How to enable and use code folding in Vim?

Fold by default

Vim's default folding method is manual meaning that the folds are created manually; otherwise, there is no fold to be closed or opened using za, zo, or zc as you described. But, you can create a fold by zf{motion} in Normal mode or zf in Visual mode; e.g. zfj creates a fold for current line and the next following one in Normal mode.

Fold by indent

The accepted answer, by @Anthon, describes how to set folding method to indent; i.e. folding are defined by the level of indentations.

Fold by syntax

In a more convenient way, folds can be created automatically based on the language syntax of the current buffer. If you are using a programming language, let's call it L, and you have folding definition of L (e.g. you have installed a Vim plugin in which the folding information of L is defined; such as c.vim for C/C++, or python-mode for Python), you just need to set folding method to syntax:

set foldmethod=syntax

That's it. The most useful commands for working with folds are:

  • zo opens a fold at the cursor.
  • zShift+o opens all folds at the cursor.
  • zc closes a fold at the cursor.
  • zm increases the foldlevel by one.
  • zShift+m closes all open folds.
  • zr decreases the foldlevel by one.
  • zShift+r decreases the foldlevel to zero -- all folds will be open.

No you don't have to put the command from the page you linked to in your ~/.vimrc, you can just type them after issuing : in vim to get the command prompt.

However if you put the lines:

set foldmethod=indent   
set foldnestmax=10
set nofoldenable
set foldlevel=2

as indicated in the link you gave, in your ~/.vimrc, you don't have to type them every time you want to use folding in a file. The set nofoldenable makes sure that when opening, files are "normal", i.e. not folded.


You don't have to use it systematically: I usually manually select folds by the motion or section. For example, folding a paragraph is zfip and folding the next 20 lines is zf20j. Use za to toggle and zd to remove.

This requires a little more work but allows your folding to reflect the task at hand.

Tags:

Vim