Eashwar Gadanchi
Eashwar Gadanchi

Reputation: 305

Search a pattern and fold the matching lines in gvim


Hi ,

I want to fold set of lines after search as follows,

The mouse can also be used to open and close folds by following steps:

  • Click on a '+' to open the closed fold at this row.

  • Click on any other non-blank character to close the open fold at this row

I want to search click and collapse all matching lines.

The mouse can also be used to open and close folds by followingsteps:

+--

There is a method to collapse the patterns which are not matching in vim , after searching a pattern we can collapse non matching patterns by "\z" key .

nnoremap \z :setlocal foldexpr=(getline(v:lnum)=~@/)?0:(getline(v:lnum-1)=~@/)\\|\\|(getline(v:lnum+1)=~@/)?1:2 foldmethod=expr foldlevel=0 foldcolumn=2<CR> Is there any option to do the opposite? Just find a pattern and collapse?

Upvotes: 0

Views: 1235

Answers (2)

user3905644
user3905644

Reputation:

I'm using below configuration with neovim I think should work with regular vim as well:

nnoremap \Z :setlocal foldexpr=(getline(v:lnum)=~@/)?0:1 foldmethod=expr foldlevel=0 foldcolumn=2 foldminlines=0<CR><CR>
nnoremap \z :setlocal foldexpr=(getline(v:lnum)=~@/)?1:0 foldmethod=expr foldlevel=0 foldcolumn=2 foldminlines=0<CR><CR>

\z: Fold matching expression from last search
\Z: Fold anything that's NOT matching from last search

It's quite useful when I want to see all comments or no comments at all, First do \ and search for ^# (If that's your language's comment start symbol) hit return, then do the folding as above.

Edit: You might want to add below to reset the folding back to manual if you want:
nnoremap \F :setlocal foldmethod=manual<CR><CR>

Upvotes: 2

Eashwar Gadanchi
Eashwar Gadanchi

Reputation: 305

I got an answer to this question from reddit user on reddit vim forum.

https://www.reddit.com/r/vim/comments/91qz90/search_a_pattern_and_fold_the_matching_lines_in/

function! FoldSearchPattern() abort
    if !exists('w:foldpatterns')
        let w:foldpatterns=[]
        setlocal foldmethod=expr foldlevel=0 foldcolumn=2
    endif
    if index(w:foldpatterns, @/) == -1
        call add(w:foldpatterns, @/)
        setlocal foldexpr=SetFolds(v:lnum)
    endif
endfunction

function! SetFolds(lnum) abort
    for pattern in w:foldpatterns
        if getline(a:lnum) =~ pattern
            if getline(a:lnum + 1) !~ pattern
                return 's1'
            else
                return 1
            endif
        endif
    endfor
endfunction

nnoremap \z :call FoldSearchPattern()<CR>

Hope it is helpful.

Upvotes: 0

Related Questions