Saturday, November 01, 2008

Vim Easy Folding Tip

for me the most easiest way to use folding in vim is to use
:set foldmethod=indent
intuitive and simple.

when you use foldmethod=indent the folding will be based on indent (why of course :p), meaning the fold start and fold end is marked by line indentation (can be a tab, spaces, etc..)
and these are the command I use the most.
  • zm : reduce fold level
  • zM : fold level to zero, aka fold'em all !
  • zr : increase fold level
  • zR : fold level to the max, aka remove all fold
  • za : toogle fold open/close on current cursor
  • zA : same as above, but recursively
  • zX : undo previous fold command
what is a fold level ?
the higher fold level means less folded text, the lower fold level means more folded text. Consider this snippet of code
when i used indent as foldmethod, indentation level is a fold level. The higher indentation level would have more foldlevel available on that window, when i type zm, foldlevel are reduce to 1, the line start from
$account->publish($... 
is folded, when I type zm again foldlevel are reduce to 0(this is minimum value), then the line
$docs = new... 
is folded, and so on. And viceversa, when I type zr foldlevel are increased, and the line in coresponding foldlevel is unfolded or opened

what if I dont use indentation in my files ?
u can use manual (the default foldmethod) or marker
:set foldmethod=manual
:set foldmethod=marker
note: that when you tried to open a fold recursively (using zA on a closed fold), it work like the way you expected, but when you tried to close a fold recursively it doesnt(well at least I didn't get it at first). It because zA on open fold, close a fold starting from the cursor as the bottom! not the top!, so how to close fold from the cursor to the bottom/deepest foldlevel, my current workaround is to visually select those region an use zC

find out more bout vim's folding feature..
:help folding
happy vimming !!

2 comments:

Scrooloose said...

Hi! i find foldnestmax handy for some filetypes.

For example, in java you might have :set foldnestmax=2. Then the first fold level would be the class, and the second fold level would be for the methods.

This can be handy if you dont want all your if statements etc folded, just classes and functions.

Zeft said...

very cool! I didn't know bout that before, see you always get new thing with this editor..

thx the tip scrooloose!!