Vim Tips for Java #6: Auto-Bracketing Within Vim

One of the things that I’ve learnt that Netbeans is able to do, was the ability to perform auto-bracket completion. For a while, I was missing that nifty little feature when I reverted back to using vim, and I tried tweaking around with vim to provide the same feature, only with limited success. Only after writing my tip on tab-completion had I realised that I have already a complete solution in providing for auto-brackets.

The following script I have will allow me to detect whether if I really wanted a closing bracket/brace or whether if has already been inserted previously by the auto-bracketing script, and hence I should skip it, by checking what the current character on the cursor right is. So here’s what’s needed to be added to your .vimrc in order for it to work:

autocmd Filetype java imap ( ()<left>
function! My_BracketComplete()
    let char = strpart(getline('.'), col('.')-1, 1)
    if (char == ")")
        return "\<Right>"
    else
        return ")"
    endif
endfunction
autocmd FileType java inoremap ) <C-R>=My_BracketComplete()<CR>

autocmd Filetype java imap { {}<left><cr><cr><up><tab>
function! My_BraceComplete()
    let char = strpart(getline('.'), col('.')-1, 1)
    if (char == ")")
        return "\<Right>"
    else
        return "}"
    endif
endfunction
autocmd FileType java inoremap } <C-R>=My_BraceComplete()<CR>

While it is neither the cleanest nor the most elegant way, but it replicates faithfully with what Netbeans does. Unfortunately, this solution will still not work for quotes and double-quotes because of the nature of the 'imap' command, which will make vim go into a non-terminating loop. So if some of you have thought of a better way to do this, do share it with me by posting your solution on my blog.

If you like reading this, you may also enjoy: