[IPython-user] autoindentation problem in emacs

Liu Jin m.liu.jin at gmail.com
Sun Mar 26 07:19:30 CST 2006

>>>>> "Fernando" == Fernando Perez <Fernando.Perez at colorado.edu> writes:
    > If the ipython terminal could just use python-mode's facilities,
    > I guess that would be great. But I don't know if that is
    > possible.

Fernando, you enlightened me! I've thought about the problem for a
while. Now the solution is so obvious... Just put the attached elisp
code in ipython.el. You may need to disable ipython's autoindent under
linux. (no need for windows, unsure why)

It works by copying anything after IPython's prompt into a hidden
buffer and let python-mode take care of the indentation. You can see
how it works by open the buffer named "*IPython Indentation
Calculation*" side by side with you python shell buffer.

Briefly tested under NTEmacs22 & SVN IPython. Feel free to bug me if
anything goes wrong (quite likely) ;-)

Liu Jin

<elisp code below>

(defvar ipython-autoindent t
  "If non-nil, enable autoindent for IPython shell through python-mode.")

(defvar ipython-indenting-buffer-name "*IPython Indentation Calculation*"
  "Temporary buffer for indenting multiline statement.")

(defun ipython-get-indenting-buffer ()
  "Return a temporary buffer set in python-mode. Create one if necessary."
  (let ((buf (get-buffer-create ipython-indenting-buffer-name)))
    (set-buffer buf)
    (unless (eq major-mode 'python-mode)

(defun ipython-newline-and-indent ()
  (if ipython-autoindent
      (let ((indention "")
          (let ((line (buffer-substring (line-beginning-position) (point)))
            (comint-bol t)
            (setq after-prompt
                  (if (looking-at py-shell-input-prompt-1-regexp)
                      (setq after-prompt1 t)
                    (looking-at py-shell-input-prompt-2-regexp)))
            (set-buffer (ipython-get-indenting-buffer))
            (when after-prompt1
            (when after-prompt
              (delete-region (line-beginning-position) (point))
              (insert line)
              (setq indention (buffer-substring (line-beginning-position) (point))))))
        (when after-prompt
          (insert indention)))

(define-key py-shell-map (kbd "RET") 'ipython-newline-and-indent)

More information about the IPython-user mailing list