Vim Recipes ‣ Navigation ‣ Manually Creating Folds
You want to fold a file, then navigate it in outline mode.
Enabling Folding
Folding is very likely already enabled in your Vim. If not, check it has been compiled with the +folding option, and that foldenable is true, i.e. :set foldenable.
Use Vim's folding feature to treat a file hierarchically, expanding and collapsing its sections as necessary.
Fold commands start with z. Vim's help makes the spurious case that this, kinda', if you squint, looks like a folded piece of paper.
| Command | Action |
|---|---|
| zf | Fold the selected text. |
| zf#j | Create a fold from the cursor down # lines. |
| zf/string | Create a fold from the cursor to string. |
| zfaB | Fold the current block delimited by bracket BB can be any of ()[]{}<>. This feature understands nested blocks, too, so will usually do the right thing. |
For instance, zf4j creates a fold from the current line to the forth line down. Or, if you've selected text in Visual mode, then zf will fold the selection.
How you use folds will depend very much on the type of file you are editing. They are particularly useful for long papers or essays, for instance, where you fold each section so as to navigate the document hierarchically. When editing program source code they can be used with function/method/class declarations.
This recipe is entitled Manually Creating Folds, because there are other approaches to folding which are automatic. A particularly useful method, indentation folding, is described below. In addition, most programming languages support syntax folding. Try it out by opening some source code in Vim then executing :set foldmethod=syntax.
Indentation Folding
If you're working with structured, indented text you may prefer to use indentation folding.
Enable it with :set foldmethod=indent. Folds are now automatically created for each level of indented text. (To indent simply start a line with a <Tab>Each shiftwidth of indent corresponds to one fold. See the Indenting Lines recipe for details. So, for example, zM folds all indented text.
To expand, collapse, and otherwise navigate folds see Navigating Folds.