Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code folding with Vim

I have tried a bunch of Python code folding plugins and I have seen this question asked once here, but they all don't seem to be too useful to achieve Python code folding in this manner:

class myClass(models.Model):
    [folded code]

    class Meta:
        [folded code]

    def __unicode__(self):
        [folded code]

    def save(self, *args, **kwargs):
        [folded code]

So my question is, Is there any Python code folding plugin that can do this? I haven't been able to find any so far and I have tried out quite a number of such Vim plugins already.

like image 933
Calvin Cheng Avatar asked Sep 15 '11 01:09

Calvin Cheng


People also ask

How do I create a fold in Vim?

Vim uses the same movement commands to define folds. Folding also works in visual mode. If you enter visual mode using v or V , then select a few lines of text using the movement keys, and type zf , Vim will create a fold comprising those lines.

How do I enable Python syntax highlighting in Vim?

The command to enable syntax highlighting in vim is :syntax on , if you want it to be active everytime you launch vim, just add a line containing syntax on in your . vimrc file. maybe your vim doesn't have filetype detection enabled, try adding filetype on to your .

How do I save a fold in Vim?

The problem is that when you close Vim, your artfully folded code returns to its unfolded state. The solution is quite simple - when you are ready to save your folds run the :mkview command. This will save your folds in the current buffer to your viewdir ( :h viewdir ) depending on your environment.


1 Answers

description

Because of its reliance on significant whitespace rather than explicit block delimiters, properly folding Python code can be tricky. The Python syntax definition that comes bundled with Vim doesn't contain any fold directives at all, and the simplest workaround is to :set foldmethod=indent, which usually ends up folding a lot more than you really want it to.

There's no shortage of Vim plugins for improved Python folding, but most seem to suffer from cobbled-together algorithms with bizarre, intractable bugs in the corner cases. SimpylFold aims to be exactly what its name suggests: simple, correct folding for Python. 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. There's no BS involved: no screwing around with unrelated options (which several of the other plugins do), no choice of algorithms to scratch your head over (because there's only one that's correct); it just works, simply.

http://www.vim.org/scripts/script.php?script_id=3723

like image 152
A T Avatar answered Oct 01 '22 22:10

A T