How to remap CoC VIM autocomplete key?

10.8k Views Asked by At

I am trying to remap the autocomplete key from the "Enter" key to "TAB" because I keep autocompleting when I intend to go to the next line. The code below is the default option for coc, and I think this is where I should be able to remap the key.

" make <CR> auto-select the first completion item and notify coc.nvim to
" format on enter, <cr> could be remapped by other vim plugin
inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm()
                              \: "\<c-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"

I thought that changing the <cr> in the beginning to <TAB> would work. However, although it does allow me to autocomplete using TAB, it creates weird auto indentations in some cases. For example:

//normal behavior
someFunction(){
    //cursor here appropriately indented
}


//behavior after I made the changes mentioned above
someFunction(){
//cursor here}

I assume I just fundamentally don't understand something about coc or remapping keys in VIM.

Why can't I simply change that <cr> to <TAB>? How can I go about remapping the autocomplete key from "Enter" to "TAB"?

2

There are 2 best solutions below

3
On BEST ANSWER

I don't understand vimscript too well, but I managed to get something working by trial and error.

Default Setting:

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

Autocompleting on Tab:

"This expression seems to be responsible for coc formatting on enter
inoremap <silent><expr> <cr> "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
"I this just says autocomplete with the first option if pop up menu is open.
"If it is not open, just do a regular tab.
inoremap <silent><expr> <tab> pumvisible() ? coc#select_confirm() : "\<C-g>u\<tab>"

Note: Using coc#pum#confirm() instead of coc#select_confirm() works and is what the coc official documentation in git uses (reviewed on May-2023)

0
On

Replace the following line from the example coc config

inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm()
                              \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"

with this:

inoremap <silent><expr> <TAB> coc#pum#visible() ? coc#pum#confirm() : "\<C-g>u\<TAB>"

This was based on @christofuy's answer but updated after this line changed.