Vim: Fold top level folds only

13.1k Views Asked by At

I have a long code file with syntax folding in Vim.

I know how to open all folds (zR) or close all folds (zM), and I know how to increase or decrease the foldlevel (zm, zr).

However when I increase the foldlevel the inner most folds are closed; instead I want the outer most folds closed while the inner most are unfolded. It is possible to do this manually by opening all folds and the closing each top level fold by hand it's incredible tedious specially with long files that I open quickly to get an overview of the code.

Is there any key shortcut to do this? Or do I need to make some sort of Vim function to do this? And if so, how?

3

There are 3 best solutions below

2
On BEST ANSWER

Yes, you can type

:%foldc

Which closes one level of folds (outside in).

1
On

I think you want to add set foldnestmax=1 to your $MYVIMRC.

0
On

As Karl says, the foldnestmax setting is probably what you want.

zO (i.e., capital-letter-o) opens all nested folds.

I also find zx and zv very helpful.

When I use foldmethod=expr with a custom fold expression, I'll often modify the expression so that it only folds what I want it to fold.