Vim logo vim online Vim Book Ad

basic Tip #282: Folding with Regular Expression

 tip karma   Rating 16/12, Viewed by 1372 

created:   July 11, 2002 20:55      complexity:   basic
author:   Chris Butler ([email protected])      as of Vim:   6.0

Well, I've tried to understand some of the folding scripts, but life's
too short. Instead, I added the following lines to my vimrc file.

set foldexpr=(getline(v:lnum)=~@/)?0:(getline(v:lnum-1)=~@/)\|\|(getline(v:lnum+1)=~@/)?1:2
map \z :set foldmethod=expr foldlevel=0 foldcolumn=2<CR>

The first line is an extension of foldexpr=(getline(v:lnum)=~@/)?0:1
The second line (re)sets the foldmethod to expr(ession) plus.

First search for /regexp/, then fold everything else with \z
Use zr to reveal more context (before/after) lines.

You could add (getline(v:lnum-2)=~@/)\|\|(getline(v:lnum+2)=~@/)?2:3
but it will take longer as folded lines (the majority) evaluate the full expression.

What could be easier?

 rate this tip  Life Changing Helpful Unfulfilling 

<<Stateful zz | Turn on syntax coloring in Mac OS X >>

Additional Notes

hari_vim at yahoo.com, July 17, 2002 15:38
This is a simple but powerful idea. If you want more control on the amount of context to show around the matching lines, try the following script:

http://vim.sourceforge.net/scripts/script.php?script_id=158

Hari
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
SourceForge Logo