Blog

It's minimal, but I'm posting things.


[Vim] Proper code folding for Python files

It's surprisingly difficult to get Vim to do code folding just right in Python.
The language is delimited by indentations, and most code folding scripts will almost do what you want, but not quite1.

After some digging, I found the following plugin which :

  • folds things properly
  • gives you total control over what is folded by default when you load a file.

kalekundert's vim-coiled-snake plugin 🐍

Installation is easy and there is zero configuration needed out of the box.
And vim-coiled-snake allows you to configure a specific function called :

function! g:CoiledSnakeConfigureFold(fold)

It's goal is to let you, the user, decide what is folded automatically when a Python file is loaded into a vim buffer.

As for me, I decided to automatically fold import statements, as well as class constructors : this often folds close to 100 lines of code and helps me see what's important immediately.

      function! g:CoiledSnakeConfigureFold(fold)
          if a:fold.type == 'import'
            " Fold imports.
            let a:fold.min_lines = 3
          endif
          if stridx(a:fold.opening_line.text, 'def __init(') >= 0
            " Fold the class constructors.
            let a:fold.max_level = 1
          endif
          if line('$') < 30
            " Do not fold files with less than n lines.
            let a:fold.ignore = 1
          endif
      endfunction

Have fun!


  1. Some don't even seem to work properly!


Published on 2025-10-01T21:33:37.154176Z
Last updated on 2025-10-01T21:33:37.154176Z