Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I automatically fold a long C code in Vim?

Tags:

c

vim

folding

I regularly run into C-codes without folding. It is irritating to read them if there is no folding, particularly with long files. How can I fold them?

like image 578
Léo Léopold Hertz 준영 Avatar asked Apr 17 '09 21:04

Léo Léopold Hertz 준영


People also ask

How do I collapse a line of code in Vim?

Opening and closing foldsThe command zc will close a fold (if the cursor is in an open fold), and zo will open a fold (if the cursor is in a closed fold). It's easier to just use za which will toggle the current fold (close it if it was open, or open it if it was closed).

How do I create a fold in Vim?

Vim uses the same movement commands to define folds. Folding also works in visual mode. If you enter visual mode using v or V , then select a few lines of text using the movement keys, and type zf , Vim will create a fold comprising those lines. Another option is to specify a range in command mode.

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.

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.


1 Answers

To fold according to syntax

:set foldmethod=syntax

If you want to do it manually on the bits you want to fold away

:set foldmethod=manual

then create new folds by selecting / moving and pressing zf e.g.

shift-v j j zf

(ignoring the spaces)

Edit: Also see the comments of this answer for indent and marker foldmethods.

like image 186
Andy Avatar answered Sep 28 '22 04:09

Andy