How to achieve code folding effects in Emacs?

Folding is generally unnecessary with emacs, as it has tools that explicitly implement the actions people do manually when folding code.

Most people have good success with simple incremental searches. See “foo” mentioned somewhere? Type C-sfoo, find the definition, press enter, read it, and then press C-x C-x to go back to where you were. Simple and very useful.

Most modes support imenu. M-ximenu will let you jump to a function definition (etc.) by name. You can also bind it to a mouse click to get a menu of functions (or add it to the menubar; see the Info page for more detail). It provides data for which-function-mode, which will let you see which function you are currently inside in the modeline. (Why are your functions this long, though?)

There is also speedbar, which displays the imenu information (and other things) graphically.

If you want to get an overview of your file, try M-xoccur“. Given a regex, it will create a new buffer with each match in the current buffer. You can search for “(defun” to get an overview of the functions the current file implements. Clicking on the result will move you to that position in the file.

So anyway, think about what you really want to achieve, and Emacs probably implements that. Don’t fight with imperfect tools that make you fold and unfold things constantly.

Leave a Comment