vendredi 28 novembre 2014

Code folding in Vim

An intresting feature that a use from time to time in Vim is code folding. It allows you to fold and unfold parts of your code soure using za in normal mode.

To use it, you have to choose a fold method, which is the strategy that vim will use to fold the code. Vim knows following methods:

  • manual
  • indent
  • expr
  • marker
  • syntax
  • diff

Check :h foldmethod for details. The methods I use the most are indent which uses the indentation level to decide when to fold (it can be useful on large xml document) and marker.

Marker is a bit particuliar since it fold using a marker on a comment line. By default, the marker is

[inline comment mark] {{{ Label
some folded code
[inline comment mark] }}}

Last trick: it's cumbersome to set foldmethod=marker every time we open a file that use marker foldmethod. To avoid that, you can pass vim set command in a comment at the end of your file:

[inline comment mark] vim: foldmethod=marker

Then reopen your buffer et voilà!

Folding is interesting when your dealing with great amount of data. Please remember that it is not a good idea to make regions within a function. If you think that you fonction is too big, be courageous and split it in smaller ones.