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:
- Vim Tips for Java #1: Build Java files with Ant Automatically
- Vim Tips for Java #2: Using exhuberant-ctags
- Vim Tips for Java #3: Use Omni-Completion (or Intellisense) for Automatic Syntax Completion
- Vim Tips for Java #4: Using 'tab' for Syntax Completion
- Vim Tips for Java #6: Auto-Bracketing Within Vim
1 comments:
Thanks very much for your codes presented here. Well, the SimpleFold plugin uses Leader-f to trigger its action, and my suggestion is that you can remap it to "zx"(without double quotes), cause its action seems the same as that of the normal command "zx" in Vim. So you could use this command consistently.
Now I have some problems in the integration of Vim with java debuggers(like jdb or other IDE), but I cann't find out your email in this blog. Would you kindly send me an email to "xell.liu at gmail.com"? BTW, you could write it in Chinese if you like:-) Thanks for any reply.
Post a Comment