Vim's folding commands start with the letter
Let's get started. To practice as you learn, open a lengthy text file in Vim editor.
Creating Vim Folds
In Vim, folding text is quite simple. You use the following syntax to create a fold in Vim.
zffollowed by the number of lines to fold giving direction in which to fold.
zf5j- This Vim command folds the next five lines of text from the cursor position.
zf5k- folds the five lines above the cursor from the cursor position.
Move your cursor a few lines below and create a marker there using the Vim command
ma. Where 'a' is the name of the marker, just like how you name a tag.
Next move your cursor to a different location in the text file opened in Vim. To fold text between the marker and the cursor position you can use the Vim command
Folding also works in visual mode. Press the key
v to enter the visual mode in Vim. Then select a few lines of text by moving the cursor. Now use the Vim command
zf to fold the selected lines.
Suppose you want to create a fold including all the text between line number 10 and 25. This is easily done by using the Vim command
:10,21fold. The beauty of this command is it works even if your cursor is not on the line number.
Of course, to fold from the cursor position to a particular line number, you can use the Vim command
:.,21fold. Where the dot (
.) indicates the current line.
You can fold from your cursor position to the first search result of a word. For this, you use the Vim command
As you can see from the examples above, Vim folding is quite powerful and can be used in many flexible ways.
You can nest folds. ie. have folds within folds in Vim.
Opening and Closing Vim Folds
To open a folding in Vim, place the cursor on the fold and press the Vim command
zcVim command will close an already open fold.
zo doesn't open all the nested folds. To do that, you need to use the Vim command
zc will close all the nested open folds.
To open all the Vim foldings, use the command
zR. However, to open only first level folds you can use
zMwill close all open folds and
zmwill re-fold the first level folds.
Moving between folds
The same way as you use
kto move between lines, you can use
zkto move between Vim folds.
To move between start and end of a fold, use the Vim commands
zEwill delete all the folds you have created in your file. However, if you just want to delete the Vim fold below your cursor, you can use
There is a lot more you can do with Vim folds. For the detailed documentation, refer Vim Fold @ Official Vim Documentation.