[Tutor] was What IDE do you prefer? - now folding python in emacs

Anthony Barker abarker@xminc.com
Mon, 23 Sep 2002 23:13:41 -0400


>>
>> emacs has a folding add-in module- have you tried it?
>> fte has folding - but I am not crazy about it.
> 
> 
> I never really used emacs a lot. I know that there is
> a folding mode that is based on some special notation
> in the text. Can it fold python purely based on indentation?


Yes it is fairly simple - I picked up the script from google groups. It 
doesn't require the fancy script Anders Lindgren wrote.

taken from:
http://groups.google.ca/groups?q=emacs+folding+python&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=uelftqprw.fsf%40cs.unc.edu&rnum=2


Just use the builtin outline-minor-mode and set up the
outline-regexp and outline-level to work with Python.

Here is what you put in your .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)
	    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)
)