Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


share|improve this question
up vote 11 down vote accepted

I have been using this for some time now:

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

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.]

share|improve this answer
Thank you, this is exactly what I was looking for! Apparently I am not the first! – dotancohen May 12 '12 at 19:22
What is the \k? – dotancohen May 12 '12 at 19:24
It matches a 'keyword' character. See ":help /\k". – Heptite May 12 '12 at 23:51
Thank you, I have never seen the Character Classes help section. – dotancohen May 13 '12 at 7:30
I don't know why it doesn't work for me!! Can you help? – Islam Wazery May 20 '14 at 7:48

I can think of somewhat convoluted functions that go back one step, compare characters and act accordingly, but I'd rather address the old "what are you really trying to do?" question:

I suggest you use Ctrl+T to indent a line in insert mode instead, if that is all you want the tab button for. I personally find it semantically very confusing to have a position dependent key like that.

share|improve this answer
Thank you, I did not know about Ctrl-T. That does what I need. Thanks! – dotancohen May 12 '12 at 14:34
Daniel, thank you. I do believe that you had taught me the proper way to use VIM, but Heptite did post the funtion that does what I was looking for. – dotancohen May 12 '12 at 19:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .