Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to fold code in Vim

📅 2014-Sep-02 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ code folding, folding, vim ⬩ 📚 Archive

Vim ships with support to perform code folding. It supports many methods of code folding.

Manual code folding

By default, Vim will be in the manual code folding method. So, when you open a file you will find that no code is folded. In the manual code folding methd, you specify which lines form a fold and then you open or close that fold. I find this a tedious exercise and never use it.

Indent code folding

The code folding method that I find most useful is indent. When this method is enabled, Vim uses the indentation of the code to figure out automatically the block of code that needs to be folded.

To have code folding by indent by default, add this to your vimrc:

set foldmethod=indent

Enable code folding

When you have chosen a code folding method and open a file, code folding is already enabled. What this means is that all the folds will be closed, because by default the foldenable option is enabled.

If you wish to keep code folding disabled by default:

set nofoldenable

Note that the first code folding command you use will enable this option and also close all the folds.

Folding commands

There are many commands to open and close folds. These commands can be invoked at any line and it affects the fold that the line belongs to.

The commands I commonly use are:

Like I mentioned above, if you had foldenable disabled, then the first use of any of these commands will enable that and close all folds. This is why I choose to keep foldenable enabled (its default option).

Keep folds open by default

With code folding enabled, when I open a file, all the code is folded up. I would rather have all folds be open when I open a file.

To do this, I added these lines to my vimrc:

" Keep all folds open when a file is opened
augroup OpenAllFoldsOnFileOpen
    autocmd!
    autocmd BufRead * normal zR
augroup END

Tried with: Vim 7.4 and Ubuntu 14.04


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧