Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way to use Vim folding for Python code

People also ask

How do I fold a python code in Vim?

It maps alt+1 to fold the first python indent level (class definitions and functions), alt+2 to fold the second level (class methods), and alt+0 to unfold everything. It makes sure it only folds one level and doesn't fold any of the nested sub levels. You can still use za to toggle folding for the current block.

What is code folding in Vim?

Yanis. March 15, 2020. Folding is a way to hide a chunk of text, and thus unclutter the view. That comes handy when you need to focus on some other part of code, or if you want to get a quick overview of the whole file.

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.


Personally I can't convince myself to litter my code with the markers. I've become pretty used to (and efficient) at using indent-folding. Together with my mapping of space bar (see below) to open/close folds and the zR and zM commands, I'm right at home. Perfect for Python!

set foldmethod=indent
nnoremap <space> za
vnoremap <space> zf

I use this syntax file for Python. It sets the folding method to syntax and folds all classes and functions, but nothing else.


Yet another plugin for folding Python code. Rather simple, handling docstrings, and on the GitHub:

SimpylFold

Enjoy!


Python is well suited for folding on indent, bit for writing my own code I use markers as they can crunch a document down the way you want it and can serve as a kind of a table of contents. I have this in my vimrc to flip between the two when I'm viewing someone elses code.

#Toggle fold methods \fo
let g:FoldMethod = 0
map <leader>fo :call ToggleFold()<cr>
fun! ToggleFold()
    if g:FoldMethod == 0
        exe 'set foldmethod=indent'
        let g:FoldMethod = 1
    else
        exe 'set foldmethod=marker'
        let g:FoldMethod = 0
    endif
endfun
#Add markers (trigger on class Foo line)
nnoremap ,f2 ^wywO#<c-r>0 {{{2<esc>
nnoremap ,f3 ^wywO#<c-r>0 {{{3<esc> 
nnoremap ,f4 ^wywO#<c-r>0 {{{4<esc>
nnoremap ,f1 ^wywO#<c-r>0 {{{1<esc>

I think that indent folding is fine for python. I'm making a multi-branched git repo for vim-config python/django IDE ideas. Fork away!

http://github.com/skyl/vim-config-python-ide