Finally happy with folding in vim (or how to get an overview of a python file)

By | August 31, 2011

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 foldnestmax.

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.

  1. zM Close All Folds Switch to “overview” mode
  2. zR Open All Folds Switch to normal editing
  3. zo Open Fold Open the class or method under the cursor
  4. 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.

I suspect that javascript would also work well using a foldnestmax of 1. HTML would probably not work as well since normally the entire body is the top level of intent. Perhaps a foldnestmax of 2 or 3 would be helpful here. Luckily, I can change these values on per filetype basis using autocmd.

Leave a Reply

Your email address will not be published. Required fields are marked *