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

VimFolding

Vim Problem Overview


At first, I use the set foldmethod=marker, and move the cursor to the { of one function, use the zf% to fold current function. But there are a lot of functions in this file. How can I fold all functions in this file? And I don't want to fold {} in the functions.

Vim Solutions


Solution 1 - 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).

Solution 2 - Vim

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

Solution 3 - Vim

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

Solution 4 - Vim

I was trying to do the same and ended up simply doing:

setlocal foldmethod=marker
setlocal foldmarker={,}

It uses the marker fold method and changes the marker to a single curly brace (by default the marker is {{{).

Solution 5 - Vim

set foldlevel=0

will fold everything from the start, what is ment to be folded. Depending on the language, and your fold function, the contents of fold will vary.

Solution 6 - Vim

Try :%g/\(function\_.\{-}\)\@<={/ normal! f{zf%

Explain bit by bit:

:%g - search globaly in a whole file

/\(function\_.\{-}\)\@<={/ - pattern to find first '{' after any 'function' and put cursor on begin of string with that '{'

normal! f{zf% - execute forward to '{' f{ and make fold with move '%' zf% on that string

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYongwei XingView Question on Stackoverflow
Solution 1 - VimR. Martinho FernandesView Answer on Stackoverflow
Solution 2 - VimBenoitView Answer on Stackoverflow
Solution 3 - VimcrimsonView Answer on Stackoverflow
Solution 4 - VimmrtnmgsView Answer on Stackoverflow
Solution 5 - VimRookView Answer on Stackoverflow
Solution 6 - VimZansheeView Answer on Stackoverflow