简体   繁体   中英

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

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.

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
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.

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 {{{ ).

Try :%g/\\(function\\_.\\{-}\\)\\@<={/ normal! f{zf% :%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% normal! f{zf% - execute forward to '{' f{ and make fold with move '%' zf% on that string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM