VIM: Tab as omnicomplete, but not at beginning of line

autocompletevim

I have configured Tab as Omnicompetion in VIM 7.3:

inoremap <Tab> <C-n>

This is convenient, but I would really like to have regular tab back at the beginning of a line! Is there any way to check if the preceding character is whitespace or a line beginning, and if so to insert a Tab character rather than omnicomplete?

Thanks!

Best Answer

I have been using this for some time now:

function! InsertTabWrapper()
    let col = col('.') - 1
    if !col || getline('.')[col - 1] !~ '\k'
        return "\<tab>"
    else
        return "\<c-p>"
    endif
endfunction

inoremap <tab> <c-r>=InsertTabWrapper()<cr>

This lets you use the tab key normally when the cursor is at the beginning of a line or not on a word, otherwise it executes the control-p completion key—you may change it to <c-n> for your use, although I find <c-p> more useful.

[Although I have modified it, the original idea for this probably came from the Vim Users' mailing list, but I did not keep any notes about where I got it.]

Related Question