Vim Tips for Java #4: Use 'Tab' for Syntax Completion

Note: This tip has been updated, please see Tab Completion for Vim (Updated) instead.

If you have used my previous tip for automatic syntax completion, you might find that using the <CTRL-X><CTRL-U> keystrokes to perform omni-completion can sometimes get quite frustrating after a while. To help address this annoyance, I wrote a little vim function to use the <tab> button to perform syntax completion instead.

The nice thing about that, is the function does contextual scanning to see if you actually want a <tab> or omni-completion to be performed by scanning the token at immediately before the cursor when the <tab> button is pressed.

Put these lines into your .vimrc:

function! My_TabComplete()
 let substr = strpart(getline('.'), col('.'))
 let result = match(substr, '\w\+\(\.\w*\)$')
 if (result!=-1)
     return "\<C-X>\<C-U>"
 else
     return "\<tab>"
endfunction
autocmd FileType java inoremap <tab> <C-R>=My_TabComplete()<CR>

The specific pattern I’m looking for in this case is ‘objectOrClass.' or ‘objectOrClass.incompleteMethodName’, but do feel free to change to fit your own needs. Also, if you are using the keyword replacement keystroke <CTRL-P> rather than vjde, you should modify the script to return '\<C-P>' instead.

If you like reading this, you may also enjoy: