January 16, 2007 — jao

Code folding, the ability to hide code or text blocks in source or text files, is a feature present in most editors nowadays. Emacs has several modes providing this functionality with various degrees of sophistication: outline-mode, allout, hide-show or folding-mode come to mind. One can even use Emacs narrowing capabilities to cook up custom folding.

Over the years, i’ve used several of these packages (and perhaps i’ll share some tips on them in future postings). But i’ve noticed that, at the end of the day, i have usually little use for folding. I strive for short functions (whenever a function body extends a half-page, i feel a strong refactoring urge), and as a consequence i seldom need to hide their bodies, nor to mention blocks within them.

There is however one folding trick that i use all the time. I often want to hide all function bodies in a file, to get a quick summary of it contents. As it happens, you don’t need any package or extra configuration for that. Just go to any source file, type

M-1 C-x $

and magic happens! As usual, it’s white magic: C-x $ will bring your code back.

We can use Emacs’ help system to discover what’s going on: C-h k C-x $ tells us that the above key combination is calling set-selective-display , a function that takes one numerical argument (the M-1 prefix passes 1 as the value of that argument) and, unsurprisingly, sets the variable selective-display to the value of that argument. I’ll let you read about the details in Emacs help itself, although i’m sure that by now you get the idea.

If you find yourself setting and unsetting selective-display as often as i do, next thing will be defining a handy keyboard shortcut, right?

(defun jao-toggle-selective-display () (interactive) (set-selective-display (if selective-display nil 1))) (global-set-key [f1] 'jao-toggle-selective-display)

or we can also use an optional numerical prefix (with 1 as default) with a little modification:

(defun jao-toggle-selective-display (column) (interactive "P") (set-selective-display (if selective-display nil (or column 1))))

Happy folding!