How to remap coc.nvim autocomplete key?

7.5k Views Asked by At

I was trying to change my coc.nvim autocomplete key, and found this question in Stack Overflow, but the guy who answer this question doesn't explain really good how to customize it as you want, so I will explain it to help the NeoVim users that are racking the brain for this as I was.

2

There are 2 best solutions below

0
On BEST ANSWER

Short Answer

If you want to bind Tab for autocompletion, paste this in your .vimrc or init.vim

inoremap <silent><expr> <tab> pumvisible() ? coc#_select_confirm() : "\<C-g>u\<TAB>"
inoremap <silent><expr> <cr> "\<c-g>u\<CR>"

Detailed answer

So, you have to make 2 insert mode remaps, in this case I will remap my completion to Tab key.

inoremap <silent><expr> <tab> pumvisible() ? coc#_select_confirm() : "\<C-g>u\<TAB>"

Obs: If you want to bind other key to autocomplete:

inoremap <silent><expr> [the key that you want to autocomplete] pumvisible() ? coc#_select_confirm() : "\<C-g>u\<TAB>"

Now, CoC will autocomplete with Tab key too, but Enter is also autocompleting, I want to bind Enter by just be Enter, not an autocompletion key.

In VimScript Enter is represented by <cr>

inoremap <silent><expr> <cr> "\<c-g>u\<cr>"

Obs:

inoremap <silent><expr> [this is the current autocompletion key] "\<c-g>u\[this is the bind that I am giving to the key]"
0
On

The example vim configuration gives some very useful tips for COC.

But specifically for you this is relevant:


" Use tab for trigger completion with characters ahead and navigate.
" NOTE: There's always complete item selected by default, you may want to enable
" no select by `"suggest.noselect": true` in your configuration file.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
inoremap <silent><expr> <TAB>
      \ coc#pum#visible() ? coc#pum#next(1) :
      \ CheckBackspace() ? "\<Tab>" :
      \ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"

" Make <CR> to accept selected completion item or notify coc.nvim to format
" <C-g>u breaks current undo, please make your own choice.
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm()
                              \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"

function! CheckBackspace() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction