6

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!

2 Answers 2

12

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

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

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.

2
  • Thank you, I did not know about Ctrl-T. That does what I need. Thanks!
    – dotancohen
    May 12, 2012 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, 2012 at 19:23

You must log in to answer this question.

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