Folding in vim

Aug 24, 2007

If you work with large files, in particular large markup documents vim’s folding feature can make your day a whole lot better. Just like the fancy folding that IDEs like Eclipse and Visual Studio provide, vim can reduce whole sections of text to a single line making it easy to skip around and keep your attention focused on what is important. There are a number of different methods that vim can automatically figure out where to fold your file but I’ve found that indent does what I want most of the time. To turn folding on and off easily, I wrote the following function in my ~/.vimrc

set foldmethod=indent
set nofoldenable
function ToggleFolding()
    if &foldenable
        set nofoldenable
    else
        set foldenable
    endif
endfunction

I bound this to <F2> with the following:

nmap  <F3> :call ToggleFolding()<CR>

You can open and close folds using zo & zc and jump between them with zk & zj.