Code Folding with Emacs

Skip to first unread message

May 30, 2002, 5:39:15 PM5/30/02
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.


;; 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)
(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)
(skip-chars-forward "\t ")
; 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
; 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)

Thomas Sicheritz-Ponten

May 31, 2002, 4:40:04 AM5/31/02
to writes:

Have you looked at folding.el?
(fold-add-to-marks-list 'python-mode "# {{{ " "# }}}" nil t)
(load "folding.el" 'nomessage 'noerror)

Sicheritz-Ponten Thomas, Ph.D, (
Center for Biological Sequence Analysis \
BioCentrum-DTU, Technical University of Denmark )
CBS: +45 45 252485 Building 208, DK-2800 Lyngby ##----->
Fax: +45 45 931585 )
... damn arrow eating trees ... (

Jun 1, 2002, 7:32:35 AM6/1/02
Thomas Sicheritz-Ponten <> writes:

> Have you looked at folding.el?
> (fold-add-to-marks-list 'python-mode "# {{{ " "# }}}" nil t)
> (load "folding.el" 'nomessage 'noerror)

Yes, I looked at it but I didn't want to have to mark up my
files. Outline.el works really nicely with Python though I think
outline has a minor bug with respect to handling empty lines....


Reply all
Reply to author
0 new messages