Vim Code Folding
Vim has a built-in method of folding text — hiding it away visually but leaving it available for other uses like selecting or searching. Vim code folding can be useful in some cases, such as stashing away function definitions so the function names can be viewed more easily. I recently revisited folding after working with deeply nested YAML files.
Vim Fold Methods
foldmethod setting is how you tell Vim which type of folding to use for the given window. There are five you should know about:
manual– Manual folding: You must choose which specific lines you want to fold. They can be at arbitrary demarcations.
indent– Indent folding: Lines at the same indentation level are folded.
syntax– Syntax folding: The syntax highlighting of the current window defines the folds.
expr– Expressing folding: Powerful way of defining your own fold methods, often with regular expressions.
marker– Marker folding: Tell Vim where to fold your text by adding special characters to it.
There is also
diff folding but Vim sets this automatically in diff views so there’s little reason to use it yourself.
Each of these fold methods has its own unique uses and are worthy of their own future posts. For now, I’ll dive into the basics of folding and unfolding in Vim.
Vim Folding Commands
Here are the most important Vim code folding commands you should know:
za– Toggles the current fold open or closed. – The most useful command to know of all of these.
zA– Same as
zaexcept it toggles all folds beneath as well. Since folds can be nested (such as with indent folding), this will toggle the state of all the folds underneath of it, not just the current fold.
zc– Close the current fold.
zC– Same as above, but closes folds nested underneath as well.
zo– Open the current fold.
zO– Same as above, but opens folds nested underneath as well.
Disable Vim Code Folding
foldenable setting it used to enable folds. If this setting is turned off, all folds are automatically opened. You can disable folds entirely in your
.vimrc by adding
set nofoldenable. Or, to disable just for the current window, call it as a command:
:set nofoldenable. That’s quite a lot of text to type just to see your folded code, so you might appreciate the toggle command:
zi will quickly toggle code folding in Vim, giving you a quick, two-key, way of getting a look at your code.
Demo of Vim Folding Commands
In the demo below you can see some of these commands in action. First I set Vim’s folding method to indent-based folds using
:set foldmethod=indent. Then I use the
zi command to toggle folding in the whole file, then several variations of the individual commands to close, open, and toggle individual indent folds.
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?