Collapse comments and all functions in vim/gvim

Andrew Redd picture Andrew Redd · Nov 16, 2009 · Viewed 17.6k times · Source

I'm a novice user to vim and I haven't been able to find in the internet how to collapse functions and I've figured out how to collapse the argument list in C with zfa} and zfa). but I can't figure out how to collapse the comments sections. How do I do that?

Second question but related, is there a way to collapse all functions/argument lists/comments in a file at the same time?

Answer

jamessan picture jamessan · Nov 16, 2009

The functionality you're referring to is called "folding" (see :help usr_28). The zf command is used to manually create a fold and is only used if the foldmethod option is set to either "marker" or "manual". In the examples you gave, you're creating folds over the regions specified by the a} and a) text objects (see :help usr_4.8).

For C, you can setlocal foldmethod=syntax and the folding regions will be automatically determined by the syntax rules. This should only be done for C files by either putting the setting in ~/.vim/ftplugin/c.vim or putting the following autocmd in your ~/.vimrc.

autocmd FileType c setlocal foldmethod=syntax

N.B. both of those require that filetype detection is enabled (filetype on), and the ftplugin solution requires that filetype plugins are enabled (filetype plugin on). The latter is a superset of the former, so you don't need both commands in your ~/.vimrc.

As for opening/closing all folds in the current buffer, those are the zR and zM commands respectively.