Vim Tips Wiki
Advertisement

Duplicate tip

This tip is very similar to the following:

These tips need to be merged – see the merge guidelines.

Previous TipNext Tip

Tip: #282 - Folding with Regular Expression

Created: July 11, 2002 20:55 Complexity: basic Author: Chris Butler (cz_butler--AT--yahoo.com) Version: 6.0 Karma: 54/23 Imported from: Tip#282

When searching with /, it would sometimes be nice to fold everything except for matches to your search. The following code does this, providing 2 levels of folding to allow you to show some context around each search match as well:

map \z :setlocal foldexpr=(getline(v:lnum)=~@/)?0:(getline(v:lnum-1)=~@/)\|\|(getline(v:lnum+1)=~@/)?1:2 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.

To add a second level of context, 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.

First search for /regexp/, then fold everything else with \z Use zr to display more context, use zm to display less context.

If no context is desired, you can do the following instead:

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

If you want to search and fold with a single command, either add the following as well:

command! -nargs=+ Foldsearch exe "normal /".<q-args>."^M\z"

Or get rid of the \z entirely:

command! -nargs=+ Foldsearch exe "normal /".<q-args>."^M" | setlocal foldexpr=(getline(v:lnum)=~@/)?0:(getline(v:lnum-1)=~@/)\|\|(getline(v:lnum+1)=~@/)?1:2 foldmethod=expr foldlevel=0 foldcolumn=2

In these last two code segments, be sure to replace the "^M" with an actual CTRL-M (carriage return) character. Type :Folds[earch] <search string>[ENTER] to use this command.

This tip combines well with VimTip108 (space bar in normal mode toggles a fold).

This script does the same thing and more: script#158

Comments

TODO: Explain better what the foldexpr string does.


Advertisement