Saturday, December 01, 2012

Folding something semi-automatically, on demand

Simple functions to fold in a file blocks which have beginning and ending markers.

Since custom folding functions can cause VIM's performance to degrade, the trick is: after applying the folding, disable it immediately back. For that work I found that I have to call 'redraw' before disabling the 'foldmethod=expr'.

The snippet below folds all lines enclosed between '<binary' and '</binary>'.

function! FoldWhateverFunc(mstart,mend,ln)
 let t = getline(a:ln)
 if t =~ a:mstart
  return '>1'
 elseif t =~ a:mend
  return '<1'
 return '='

function! FoldWhatever()
 set foldexpr=FoldWhateverFunc('<binary','</binary>',v:lnum)
 set foldmethod=expr
 set foldmethod=manual

Hint: one can replace the hardcoded 'binary' tag with call to the 'input()' function. Though I prefer non-interactive approach, something I can plug into the ':au'.

Edit1 BTW ':h fold-expr' contains several useful one-line examples of folding expressions.

No comments: