How to fold code in Vim

Vim ships with support to perform code folding. It supports many methods of code folding. By default, it is in manual method. So, when you open a file you will find that no code is folded. You can specify which lines form a fold and then open or close that fold. I find this useless and never use it.

The code folding method that I find most useful is indent. This 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

Some of the common commands I use to fold code:

  • za: Toggle code folding at the current line. The block that the current line belongs to is folded (closed) or unfolded (opened).
  • zo: Open fold.
  • zc: Close fold.
  • zR: Open all folds.
  • zM: Close all folds.

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

To do this, add these lines to your vimrc:

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

Tried with: Vim 7.4 and Ubuntu 14.04


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.