Vim Tips for Java #5: Folding Code Blocks to prevent Visual Blindness

When dealing with large source files, there is a tendency for visual blindness to kick in, where there is just too much code everywhere for you to find things like the start of a method or a particular important segment of code, in a sea of random visual clutter.

With Vim (6.0 onwards I think), there is support for concept of folding, which helps to segregate your code into meaningful chunks visually, expanding and collapsing the folds as you work. There are a number of keystrokes to learn, so if you are new to folding you might want to read a tutorial like
this one (link to linux.com).


Initially I wanted a way to automatically generate folds for me based on the type of source code I’m working on, and a nice answer I have found is the SimpleFold plugin from Eigenclass, which helps in creating folds automatically for you by matching the source file with certain patterns.

I believe that it does automatic folding for Ruby quite well, but because of the syntax structure of Java, folding using plain regex probably doesn’t fully match my requirements (it doesn’t handle the treatment of inner classes and methods that well, and mistakes certain variable declarations as methods) so I tend to use manual folding instead, which is done by using the command:

:set foldmethod=manual

While folding by default on vim looks alright, but I find SimpleFold’s display with brackets and indentation much better for differentiation between class definitions and methods, so I decided to shamelessly copy the formatting part of SimpleFold’s code for my own nefarious use instead (Copy to .vimrc):

function! Num2S(num, len)
    let filler = "                                                            "
    let text = '' . a:num
    return strpart(filler, 1, a:len - strlen(text)) . text
endfunction

function! FoldText()
    let sub = substitute(getline(v:foldstart), '/\*\|\*/\|{{{\d\=', '', 'g')
    let diff = v:foldend - v:foldstart + 1
    return  '+' . v:folddashes . '[' . Num2S(diff,3) . ']' . sub
endfunction

set foldtext=FoldText()

With the change, you’ll see a difference between the indentation of the methods within the folds, and the number of lines within square brackets. And now, it looks much better!

If you like reading this, you may also enjoy: