Search code examples
vimomnicomplete

omnicomplete in vim with shift-tab not working?


Im trying to get vim to allow me to circle through the autocomplete popup list with the tab key. It works fine for tab but not for s-tab (shift-tab). It seems like shift-tab somehow canceles the autocomplete menu before applying C-P

Anyone got any ideas?

function InsertTabWrapper(direction)
  if pumvisible()
    if "forward" == a:direction
      return "\<C-N>"
    else
      return "\<C-P>"
    endif
  endif
  let col = col('.') - 1
  if !col || getline('.')[col - 1] !~ '\k' 
    return "\<tab>"
  else
    return "\<c-x>\<c-o>"
  endif
endfunction

inoremap <tab> <c-r>=InsertTabWrapper("forward")<cr>
inoremap <s-tab> <c-r>InsertTabWrapper("backward")<cr>

Solution

  • You missed the equal sign "=" after <c-r> for the <s-tab> mapping.

    However, I would suggest doing it like this:

    function! InsertTabWrapper()
      if pumvisible()
        return "\<c-n>"
      endif
      let col = col('.') - 1
      if !col || getline('.')[col - 1] !~ '\k'
        return "\<tab>"
      else
        return "\<c-x>\<c-o>"
      endif
    endfunction
    inoremap <expr><tab> InsertTabWrapper()
    inoremap <expr><s-tab> pumvisible()?"\<c-p>":"\<c-d>"
    
    1. Use <expr> mapping. It's nicer to see and clearer (many people don't know about <c-r>= things.
    2. Mapping <s-tab> like this and you can do unindent in insertmode.