[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:

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)
(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)