Opening and Closing Folds

While most topics in this chapter focus on moving the cursor around the buffer, Vim's "folding" feature can simplify navigation by allowing the user to hide portions of the document. Folding visually collapses a group of adjacent lines down to a single line in the buffer. Folded content is then treated as a single line, which can be navigated over, yanked, deleted, etc. For example, one might fold a document so that only the section headings are visible, which allows the user to quickly navigate to a specific section, open the fold, and begin editing.

Vim supports a variety of "fold-methods", which determine where and when folds should be created. In addition to the built-in methods, Neovim's built-in Treesitter support provides improved, language-specific folding, and is generally the preferred fold method in modern setups.

However folds are configured, the focus of this section is how to navigate buffers containing folds.

The first group of commands affect all of the folds in an entire buffer. These are often useful when opening a new document to "get a feel" for the structure, locate certain sections, etc.

Folding commands start with z (which looks like a folded piece of paper), and use a lower-case / upper-case pattern to specify an action and a recursive action, respectively.

As a quick demonstration, open a file, then hit zR to quickly open all folds in a document, zM to quickly close all folds, then hit zr a few times decrease the level of folding one step at a time.

zradd one to 'foldlevel'
zRset 'foldlevel' to the deepest fold
zmsubtract one from 'foldlevel'
zMset 'foldlevel' to zero

Next, lets review commands that control the folds containing the cursor. Start by hitting zM to close all of the fold in the document, then move the cursor how to some folded content.

Now, hit zo to open the fold that contains the cursor, then zc to close it again. Toggling fold state is quite common, so there this can also be achieved by hitting za once to open the current fold, then hitting it again to toggle it closed again.

zoopen fold
zOopen folds recursively
zcclose a fold
zCclose folds recursively
zaopen a closed fold, close an open fold
zAopen a closed fold or close an open fold recursively
zvopen enough folds to view the cursor line