Code Folding with Emacs

gb at cs.unc.edu gb at cs.unc.edu
Thu May 30 17:39:15 EDT 2002


It is really easy to get code folding going with Python mode in
Emacs. Just use the builtin outline-minor-mode and set up the
outline-regexp and outline-level to work with Python. It really works
well for me and has a nice menu or keyboard interface as well.

Here is what I put in my .emacs to make it work.

gb

;; setup python mode
(setq auto-mode-alist ; trigger python mode automatically
      (cons '("\\.py$" . python-mode) auto-mode-alist))
(setq interpreter-mode-alist
      (cons '("python" . python-mode)
	    interpreter-mode-alist))
(autoload 'python-mode "python-mode" "Python editing mode." t)
; add my customization
(add-hook 'python-mode-hook 'my-python-hook)
; this gets called by outline to deteremine the level. Just use the length of the whitespace
(defun py-outline-level ()
  (let (buffer-invisibility-spec)
    (save-excursion
      (skip-chars-forward "\t ")
      (current-column))))
; this get called after python mode is enabled
(defun my-python-hook ()
  ; outline uses this regexp to find headers. I match lines with no indent and indented "class"
  ; and "def" lines.
  (setq outline-regexp "[^ \t]\\|[ \t]*\\(def\\|class\\) ")
  ; enable our level computation
  (setq outline-level 'py-outline-level)
  ; do not use their \C-c@ prefix, too hard to type. Note this overides some python mode bindings
  (setq outline-minor-mode-prefix "\C-c")
  ; turn on outline mode
  (outline-minor-mode t)
  ; initially hide all but the headers
  (hide-body)
  ; I use CUA mode on the PC so I rebind these to make the more accessible
  (local-set-key [?\C-\t] 'py-shift-region-right)
  (local-set-key [?\C-\S-\t] 'py-shift-region-left)
  ; make paren matches visible
  (show-paren-mode 1)
)



More information about the Python-list mailing list