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
I really like this little vim script i wrote for .vimrc. 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. Note that in ^[0
, the ^[
is alt
for my terminal. Don't have a lot of experience in vim script so feel free to make suggestions on the function :)
" Python folding
nnoremap ^[0 zR<CR>
nnoremap ^[1 :call Fold(0)<CR>
nnoremap ^[2 :call Fold(1)<CR>
function Fold(level)
:let b:max = a:level + 1
:set foldmethod=indent
:execute 'set foldnestmax='.b:max
:execute 'set foldlevel='.a:level
endfunction
Try this plugin:
http://vim.sourceforge.net/scripts/script.php?script_id=515
I really like the python_ifold plugin.
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
Yet another plugin for folding Python code. Rather simple, handling docstrings, and on the GitHub:
SimpylFold
Enjoy!