Best code folding plugin for Python in vim?

5

2

I use vim for all the code I write. My biggest issue is that I cannot find a good Python code folding plugin. I've found two-three popular ones that use indentation but they tend to either fold too little or too much. Ideally, this is what I'd like for it to fold:

  1. Fold all top level classes.
  2. Fold all top level functions.
  3. Fold all class methods

And nothing more. The plugin I am using currently is not bad, but it tends to fold functions within methods. It also gets confused about blocks of code within a class method that have different indentation levels (e.g.: a for loop followed by more code would result in folding of the code after the for loop).

Does anyone know of a plugin that satisfies these requirements or should I just figure out how to write my own?

These are the things I've tried in the past:

ipartola

Posted 2011-04-06T14:55:13.473

Reputation: 151

Question was closed 2017-01-01T18:38:40.703

Answers

3

SimpylFold

I consider this the best folding plugin for python in vim.

It's nothing more than it needs to be: it properly folds class and function/method definitions, and leaves your loops and conditional blocks untouched.

https://github.com/tmhedberg/SimpylFold

Hotschke

Posted 2011-04-06T14:55:13.473

Reputation: 255

2

While they don't have a plugin for you, there are some useful answers on this stackoverflow question.

In particular, you might try setting set foldnestmax=2. This will do unwanted folding in top level functions, but otherwise satisfies your requirements. foldnestmax says don't fold anything deeper than x (as opposed to foldlevel, which says fold everything deeper than x). If you want folding to be smart enough to find functions wherever they are, then you'll need to set foldexpr.

If you use foldexpr, your best bet would be to play with basic folding in vimscript until you get the hang of it and then tinker with code for one of the plug-ins you provided. Be sure to set foldcolumn=1 (or greater) so you can see the folds you're setting. I think you'll essentially increment your fold only if you see class or def, but you might need v:foldstart and v:foldlevel for determining when folds end.

Also, try using zO to recursively open a fold (so if you unfold a top-level function, everything in it is unfolded).

idbrii

Posted 2011-04-06T14:55:13.473

Reputation: 682

set foldnestmax=2 will work for now, thanks. – ipartola – 2011-07-26T13:36:56.270

Actually, nevermind. For some reason having a function in the middle of a class method still doesn't work. – ipartola – 2011-07-26T13:47:26.043

@ipartola: I amended my answer with more detail about foldnestmax, but it sounds like you need to set a foldexpr. What you really want is to fold all functions and classes (not just top level ones) and nothing else. – idbrii – 2011-07-26T23:27:04.217