Tab Completion for Vim (Updated)
As I’ve said
before,
I wasn’t really satisfied with the original tab completion script, which
didn’t perform all the possible search completion combinations vim is
capable of. After accidentally overwriting my existing .vimrc
file, I
just thought it was high time I remedied the incomplete implementation
of tab completion for vim to work properly with Java.
As with before, the script has to utilize existing auto-completion
script,
and the additional changes on my script now makes tab ‘intelligently’ to
perform completion on incomplete methods and fields, rather than having
only to be able to do so only at the start of the dot ('.')
. Also, if
tab occurs at locations where it doesn’t fit the profile of a method or
field (i.e, it’s not in the pattern of
'package.class.methodname_or_fieldname'
, where package
is optional),
it will try to use vim’s built-in keyword completion (<C-X><C-P>
)
instead.
Here’s the script that you’ll need to copy and paste into your
.vimrc
:
" Modified tab completion. It works fine now.
function! My_TabComplete()
let line = getline('.') " curline
let substr = strpart(line, -1, col('.')+1) " from start to cursor
let substr = matchstr(substr, "[^ \t]*$") " word till cursor
if (strlen(substr)==0) " nothing to match on empty string
return "\<tab>"
endif
let bool = match(substr, '\.') " position of period, if any
if (bool==-1)
return "\<C-X>\<C-P>" " existing text matching
else
return "\<C-X>\<C-U>" " plugin matching
endif
endfunction
autocmd BufNew,BufRead *.java inoremap <tab> <C-R>=My_TabComplete()<CR>
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 exuberant-ctags
- Vim Tips for Java #3: Use Omni-Completion (or Intellisense) for Automatic Syntax Completion
- Vim Tips for Java #5: Folding Code Blocks to Prevent Visual Blindness
- Vim Tips for Java #6: Auto Bracketing for Java