I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.
Does anyone have a preferred way to do Python code folding in Vim? I.e,
- Do you have a particular Vim plugin that you use and like?
- Do you use manual folding or do you place markers in comments?
- Any other recommended ways to do code folding for Python in Vim?
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!
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.
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
I really like the python_ifold
plugin.
Try this plugin:
http://vim.sourceforge.net/scripts/script.php?script_id=515
Yet another plugin for folding Python code. Rather simple, handling docstrings, and on the GitHub:
SimpylFold
Enjoy!
The Python source comes with a vim syntax plugin along with a custom vimrc file. Check the python FAQ on vim
For me the ideal folding is to fold just the class
and def
blocks, indent folding is too much for my taste. I think one elegant solution is to use the syntax system like this one mentioned by Tomas. However, this one is meant to replace the original syntax file and it may end being older than the original (i.e. that script doesn't mention Python 3 syntax).
My solution is to place in the ~/.vim/syntax
folder a file named python.vim
with just the important lines (taken from the above script):
syn match pythonDefStatement /^\s*\%(def\|class\)/
\ nextgroup=pythonFunction skipwhite
syn region pythonFunctionFold start="^\z(\s*\)\%(def\|class\)\>"
\ end="\ze\%(\s*\n\)\+\%(\z1\s\)\@!." fold transparent
hi link pythonDefStatement Statement
Then simply activate the folding with :set foldmethod=syntax
.