Subscribe for free with iTunes, Twitter, or RSS (Ogg or Quicktime).

Vimcasts

How to fold

#37

Vim’s folding feature enables us to expand and collapse regions of a document. Not only does this allow us to organize our workspace, it also makes it easy to navigate around the document, and to rearrange entire sections as though they were single lines.

Download

OGG 17 MB

Quicktime 26.1 MB

Methods of folding

Vim has several different methods for folding a document. You can read more about them by looking up :help fold-methods. I don’t want to go into much detail about these different methods, except to say that I’ve found using a custom expression to be the most useful method by far.

For the purposes of the demonstration in this video, I used a markdown file, with the markdown-folding providing the fold expression. Episode 38 will look at how the markdown folding expression is implemented, here we focus on how to use folding.

Essential folding commands

Top of any Vim folding cheat sheet should be the zi command, which turns the folding functionality on and off. Here are the folding commands which I use most frequently:

command effect
zi switch folding on or off
za toggle current fold open/closed
zc close current fold
zR open all folds
zM close all folds
zv expand folds to reveal cursor

I recommend learning these commands first. The za command is so useful that you may want to consider mapping it to a single keystroke. Steve Losh suggests using this mapping:

nnoremap <Space> za

While za is great for opening folds, the zc command is often more suitable when you want to close a fold. If the current fold is already closed, then zc will close the parent fold.

Navigating the unfolded document

Even when the document is fully unfolded, the fact that Vim knows where the folds start and finish gives us an additional method for moving around.

command effect
zj move down to top of next fold
zk move up to bottom of previous fold

The custom fold expression adds a whole new layer of semantics, which allows us to rapidly navigate the sections of the document.

More folding commands

Here are some more folding commands:

command effect
zo open current fold
zO recursively open current fold
zc close current fold
zC recursively close current fold
za toggle current fold
zA recursively open/close current fold
zm reduce `foldlevel` by one
zM close all folds
zr increase `foldlevel` by one
zR open all folds

Chaining folding commands

Vim’s folding commands operate at a low level. Sometimes, we have to chain a couple of these low level commands together to produce the desired result. For example, pressing zMzv has the effect of closing all open folds apart from the one that the cursor is on (see the video for a demonstration).

Further reading