How to collapse to a certain level in Vim all over the file at once

I want to press one button in Vim and add all the code to show only code up to a certain (and variable) indent level. Very useful when I want to see only the names of methods, for example, and not their indentation.

This question is SO: Vim: collapses only the folds of the top level has a solution to the indent level, but for each level, setting the environment is required.

When my cursor is at the indent level (e.g. level 2), I want the whole file to reset to that indent level in all methods.

Is it built into Wim? Does anyone know a good plugin that does this?

+4
source share
3 answers

Set indentation folding

:setl foldmethod=indent 

and try to run the command

 :let &l:foldlevel = indent('.') / &shiftwidth 

To quickly access this command, create a mapping for it as follows.

 :nnoremap <silent> <leader>z :let&l:fdl=indent('.')/&sw<cr> 
+3
source

Since foldnestmax does not apply when foldmethod is expr, I was looking for something else when I came across your question. Here is what I came up with that can undoubtedly be improved:

 function! <sid>CloseFoldOpens(opens_level) let lineno = 2 let last = line("$") while lineno < last if foldclosed(lineno) != -1 let lineno = foldclosedend(lineno) + 1 elseif foldlevel(lineno) > foldlevel(lineno - 1) \ && foldlevel(lineno) == a:opens_level execute lineno."foldclose" let lineno = foldclosedend(lineno) + 1 else let lineno = lineno + 1 end endwhile endfunction nnoremap <silent> z1 :%foldclose<cr> nnoremap <silent> z2 :call <sid>CloseFoldOpens(2)<cr> nnoremap <silent> z3 :call <sid>CloseFoldOpens(3)<cr> nnoremap <silent> z4 :call <sid>CloseFoldOpens(4)<cr> nnoremap <silent> z5 :call <sid>CloseFoldOpens(5)<cr> 

I prefer numbered maps, but for you based on the indentation of the current line, something like these lines:

 nnoremap <silent> z. :call <sid>CloseFoldOpens(foldlevel('.'))<cr>zv 
0
source

There is no need for a plugin, it is built into Vim.

'foldlevel' (or shorter 'fdl') and 'foldnestmax' ('fdn'), it looks like we're looking. You only need to set "foldmethod" (or shorter "fdm") and "foldnestmax" (or "fdn") in the .vimrc file:

 set foldmethod=indent foldlevelstart=2 foldnestmax=2 

OR shorter version:

 set fdm=indent fdls=2 fdn=2 

Then you can change the merge level using direct commands: zm or zr.

0
source

All Articles