[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) ;-)

Cheers,
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)
      (python-mode))
    buf))

(defun ipython-newline-and-indent ()
  (interactive)
  (if ipython-autoindent
      (let ((indention "")
            (after-prompt))
        (save-excursion
          (let ((line (buffer-substring (line-beginning-position) (point)))
                (after-prompt1))
            (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
              (erase-buffer))
            (when after-prompt
              (delete-region (line-beginning-position) (point))
              (insert line)
              (newline-and-indent)
              (setq indention (buffer-substring (line-beginning-position) (point))))))
        (comint-send-input)
        (when after-prompt
          (insert indention)))
    (comint-send-input)))

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




More information about the IPython-user mailing list