Python folding in Vim

2009-05-22 12:59; Tags: ,

There are several ftplugins at www.vim.org that fold python code. I could have used one of them and be happy but the burden of my ex-prog-life leads me to my own wheel to be reinvented.

Brief description

  • Folds are created for:
    • let g:python_fold_block = "all" — all python code blocks;
    • let g:python_fold_block = "def" — defs and classes. [DEFAULT]
  • The way empty lines are folded controlled by g:python_fold_keep_empty_lines variable:
    • let g:python_fold_keep_empty_lines = "all" — keep empty lines between code blocks; [DEFAULT]
    • let g:python_fold_keep_empty_lines = "top" — keep empty lines between top level code blocks;
    • let g:python_fold_keep_empty_lines = "top-one" — keep one empty line between top level code blocks;
    • let g:python_fold_keep_empty_lines = "one" — keep one empty line between code blocks.
  • Comment’s folding:
    • let g:python_fold_comments = 1 — fold comments; [DEFAULT]
    • let g:python_fold_comments = 0 — do not fold comments.
  • Import’s folding:
    • let g:python_fold_imports = 1 — fold imports; [DEFAULT]
    • let g:python_fold_imports = 0 — do not fold imports.
  • Docstring’s folding:
    • let g:python_fold_docstrings = 1 — fold docstrings; [DEFAULT]
    • let g:python_fold_docstrings = 0 — do not fold docstrings.

Screenshots

p_fold_all
let g:python_fold_keep_empty_lines = "all"
p_fold_top
let g:python_fold_keep_empty_lines = "top"
p_fold_top-one
let g:python_fold_keep_empty_lines = "top-one"
p_fold_one
let g:python_fold_keep_empty_lines = "one"

Install

  1. Download python.vim
  2. Place python.vim to
    • Windows: ~/vimfiles/ftplugin/
    • Linux: ~/.vim/ftplugin/

Note: Folding is shiftwidth dependent. If a code indented with 2 spaces make sure shiftwidth is 2 spaces too.

PS: It works for me and it may work for you too despite evil bugs that could live in it. ;)

2 Responses to “Python folding in Vim”

  1. christian says:

    Thanks for this great plugin! I’ve been using some of the other Python folding plugins over at http://www.vim.org, but none of them have ever really fit the bill. The one that I had settled on worked pretty well, except things went crazy as soon as docstrings came up in the code.

    Thanks again!

  2. Maxim Kim says:

    You are welcome.

Leave a Reply

Powered by WordPress