Vim 101: Folding

Programming is all about focus. It's hard to focus when the phone's ringing, other people are talking about the latest terrible TV talent show, and there's a crazy busker outside attempting to cover Oasis - Wonderwall after several cans of Special Brew. But that's life, and we can't do much about it (other than invest in a seriously good quality pair of headphones). When it comes to code, however, we have to deal with a lot of noise -- implementation details that aren't relevant to the task at hand. One way of mitigating this is folding -- hiding parts of files based on various rules to help claw back some precious neurological capacity.

Vim supports six folding methods: manual, indent, expr, syntax, diff, and marker. Let's look at manual and indent to introduce the basics.

Manually Folding

Select a folding method by setting foldmethod, abbreviated to the more convenient fdm. The default value is manual, so no folding occurs. There are several ways to add folds:

  • zf{motion}: Create a fold based on motion
  • Visual selection, zf: Make a selection by first pressing v (or by using the mouse), then typing zf will fold the entire selection

Once a fold has been added, typing zo will open it, and zc will close it. It's pretty easy to remember these fold-related commands because they start with z. Another useful command is zE which will elimate all folds in the current window.

Folds are specific to the current window and buffer, and all of these manual folds will be lost when the file is closed. Folds can be saved by typing :mkview, then loaded again with :loadview. These view files are saved to viewdir -- try it out and have a look at ~/.vim/view/.

Indentation

Typing :set fdm=indent will change the fold method to an indentation-based algorithm. The basic way to configure this is to set foldlevel which controls the level of indentation where folding will occur.

To better visualise folding, setting foldcolumn (or fdc) will display a sidebar that indicates what will be folded. Try :set foldcolumn=2 to see it in action.

Folding

In the screenshot above I'm editing the software that powers this blog, and I'm using the following settings:

set fdm=indent
set fdc=4
set fdl=1
blog comments powered by Disqus