Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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:

share|improve this question
add comment

1 Answer

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

share|improve this answer
    
set foldnestmax=2 will work for now, thanks. –  ipartola Jul 26 '11 at 13:36
    
Actually, nevermind. For some reason having a function in the middle of a class method still doesn't work. –  ipartola Jul 26 '11 at 13:47
    
@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. –  pydave Jul 26 '11 at 23:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.