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>"
let bool = match(substr, '\.')                  " position of period, if any  
if (bool==-1)
 return "\<C-X>\<C-P>"                         " existing text matching
 return "\<C-X>\<C-U>"                         " plugin matching 
autocmd BufNew,BufRead *.java inoremap <tab> <C-R>=My_TabComplete()<CR>

If you like reading this, you may also enjoy: