I’ve always found vim folding to be somewhat mysterious. No matter which of the foldmethods I used, it seemed like it was always too tedious or too manual.
Today, while editing a python file over a remote connection that has high enough latency to interfere with rapidly scrolling through the file, I finally set out to solve this problem. My goal was to get an overview of the file. Yes, there are plugins or ctags to do this, but I don’t have ctags installed and have tried different plugins that didn’t really work as I wanted.
Indent folding does essentially what I want; when all folds are closed, I can see the overview of classes and module-level methods in the python module. When they are open, I see the whole file. I always felt that Indent mode should be ideal with whitespace-driven python, but in the past, I found that the default settings left far too many folds to work with.
I already new about the
foldminlines setting which only creates a fold if more than a specific number of lines is displayed. But today, I discovered
This setting is the maximum number of folds in the file. In a python file, if I set it to 1, folding happens only at the classes or module-level functions in the module. If I set it to two, it happens at each method in each class. I don’t get a bunch of internal folds that I don’t want.
Another setting that I discovered today is
foldlevelstart. If set to
99, opening a new file will always have all the folds expanded, which is what I want.
So now I have exactly what I want: a few top-level folds are created automatically based on indentation, but I don’t have to fuss with interior indentation in other folds. Now I needed a refresher on how best to interact with these folds.
- zM Close All Folds Switch to “overview” mode
- zR Open All Folds Switch to normal editing
- zo Open Fold Open the class or method under the cursor
- zc Close Fold Close the class method I’m currently editing
The last one is the most useful, because it works from anywhere in the method. If I’m done with that method, I just
zc and it’s hidden from site. I don’t have to worry about collapsing multiple levels of indentation or creating manual folds. It just works.
There are other fold commands; see
:help fold for an overview, but just using these settings and memorizing these four commands seems to be all I need.