Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fold to a specific level in Vim across an entire file at once?

Tags:

vim

I want to push one button in Vim and fold all the code so only code up to a specific (and variable) indent level is showing. Very useful when I want to only see method names for example and not their indented routines.

The “Vim: Fold top level folds only” question has a solution to an indent level, but it requires an environment set each time you change levels.

When my cursor is at an indent level (say level 2), I want the entire file to fold to that indent level across all methods.

Is this built into Vim somewhere? Does anyone know of a good plugin that does this?

like image 352
Evan Avatar asked Sep 17 '11 06:09

Evan


People also ask

How do I collapse a line of code in Vim?

Opening and closing foldsThe command zc will close a fold (if the cursor is in an open fold), and zo will open a fold (if the cursor is in a closed fold). It's easier to just use za which will toggle the current fold (close it if it was open, or open it if it was closed).

How do I fold text in Vim?

If you enter visual mode using v or V , then select a few lines of text using the movement keys, and type zf , Vim will create a fold comprising those lines.

How does folding work in Vim?

Marker. Vim folds your code based on characters in the actual text. Usually these characters are put in comments (like // {{{ ), but in some languages you can get away with using something in the language's syntax itself, like { and } in Javascript files.

How do I save a fold in Vim?

The problem is that when you close Vim, your artfully folded code returns to its unfolded state. The solution is quite simple - when you are ready to save your folds run the :mkview command. This will save your folds in the current buffer to your viewdir ( :h viewdir ) depending on your environment.


2 Answers

Configure folding to be defined by indentation:

:setl foldmethod=indent

and try the following 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>
like image 135
ib. Avatar answered Oct 23 '22 04:10

ib.


No need of a plugin, it is builtin in Vim.

'foldlevel' (or shorter 'fdl') and 'foldnestmax' ('fdn') seems to be what we were looking for. You only have to set the 'foldmethod' (or shorter 'fdm') and a 'foldnestmax' (or 'fdn') in you .vimrc file:

set foldmethod=indent foldlevelstart=2 foldnestmax=2

OR the shorter version:

set fdm=indent fdls=2 fdn=2

Then you can change the fold level with direct commands: zm or zr.

like image 25
PixEye Avatar answered Oct 23 '22 05:10

PixEye