Code Folding in VIM
Vim is arguably one of the most awesome editors around. I use it exclusively, extending it with many plugins. As of version 6.0 Vim supports code folding, a nice way to hide blocks you don't need to see and thus reduce the visible complexity of the code you're editing.Vim accomplishes this using a foldmethod which can guess where to fold the code based on syntactic hints (defined in the syntax file of the FileType you're using), indentation and other methods, including manual mark-up of foldable regions. It then calls a function stored in foldtext that computes a text to display instead of the text region folded away. You can see vim's default foldtext in action here:
Here used to be a screenshot showing some code blocks in VIM, but omploader.org think it's funny to molest people into not using their service, rather than just telling them...
I'll try to replace it soon.
Here used to be a screenshot showing VIM's default code folding routine in action, but omploader.org think it's funny to molest people into not using their service, rather than just telling them...
I'll try to replace it soon.
Rolling your own
I find Vim's default foldtext a bit hideous. Most importantly it messes up indentation and I'm very religious abuot indentation, given I'm a horizontal reader and use 8 spaces (one traditional tab) for indentation. So I tried to came up with something minimalistic that would preserve indentation on collapsed folds, using my traditional fold method syntax. I failed, but Heptite I met in #vim on irc.freenode.net helped me out with this code:
set foldtext=MyFoldText()
" Folds preserving indentation and without clutter
function! MyFoldText()
let i = indent(v:foldstart)
return repeat(' ', i) . substitute(getline(v:foldstart), '^\s\+', '', '')
endfunction
" Reload folding
nmap <F3> :syn sync fromstart
The function MyFoldText() was his idea of approaching the problem. I had some trouble coming up with one myself because getline(v:foldstart) seems to include a leading indent which messed up the folding when a syntax element triggering folding (as defined in the syntax file) would be split across more than one line (like a bloated method declaration featuring many throws or arguments). I really think that this is a bug in Vim's folding method and eliminating leading spaces with a substitute command is just a workaround, but it works quite well for now and gives very pleasing results:
Here used to be a screenshot showing my current code folding routine in action, but omploader.org think it's funny to molest people into not using their service, rather than just telling them...
I'll try to replace it soon.
A look at a Tagger with code folding enabled.