How can I automatically fold all functions in a file with vim?

If you :set foldmethod=syntax the folds will be specified from the syntax definitions. If you prefer you can :set foldmethod=indent to have the indentation define the folds.

You can close all folds with zM. If you have nested folds and you want to fold level by level, use zm. To open folds use zR (all) and zr (level by level).


If each function has its opening brace on the first column you could do:

:%g/^{/normal! zf%

Maybe it is more clear this way:

:%g /^{/ normal! zf%

the g command selects lines according to the following pattern, and executes an ex command (here normal! to play normal mode keystrokes).

See :help :g and :help :normal


I came across this when I was searching for a similar thing. You would have obviously figured this out by now, but for the benefit of other people i'll answer it anyway.

You need to put in the following lines in your .vimrc:

set foldmethod=syntax
set foldnestmax=1