Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

folding

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.

like image 823
Yongwei Xing Avatar asked Dec 30 '10 02:12

Yongwei Xing


People also ask

How do I create a fold in Vim?

Open it in Vim, and place the cursor at the beginning of a paragraph. Make sure you're in normal mode, and type zf2j . After you press j , Vim will create a fold covering three lines — the line you started the fold on, and the next two lines.

How do I expand all lines in Vim?

To expand the lines, put the cursor over the fold and hit spacebar (in vim terminology, this deletes the fold). (Side note: you may want to change the look of collapsed folds.

How do I save a fold in Vim?

The problem is that when you close Vim, your artfully folded code returns to its unfolded state. The solution is quite simple - when you are ready to save your folds run the :mkview command. This will save your folds in the current buffer to your viewdir ( :h viewdir ) depending on your environment.


2 Answers

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

like image 114
R. Martinho Fernandes Avatar answered Nov 02 '22 22:11

R. Martinho Fernandes


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

like image 25
Benoit Avatar answered Nov 03 '22 00:11

Benoit