Jamis Charles
Jamis Charles

Reputation: 6039

In a vim expression, how can I return back to normal mode?

I'm using the CoC plugin for which works great.

This command remaps the enter key so we can use enter to confirm selection of the suggestion popover.

This mapping works great, except that it stays in insert mode after accepting the selection:

inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"`

From https://github.com/neoclide/coc.nvim/wiki/Completion-with-sources#use-cr-to-confirm-completion

How can I modify this to return back to normal mode after I hit enter?

Any ideas? Thanks!

Upvotes: 0

Views: 322

Answers (1)

romainl
romainl

Reputation: 196566

First, let's deconstruct the mapping you got from that page:

inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
  • inoremap makes it a non-recursive insert mode mapping. i means "insert mode" and nore means "non-recursive". I know the remap at the end makes it tempting to call those things "remaps" or "remappings" but they are not. They are just "mappings".

  • <expr> makes it an expression mapping. It means that the right-hand side is an expression that is going to be evaluated at runtime to produce the actual RHS.

  • pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>" is what Vim calls a "trinary operator" (AKA ternary operator): :help trinary. In plain english, it reads like this: "if the popup menu is visible, return <C-y>, if not, return <C-g>u<CR>".

    :help complete_ctrl-y accepts the current suggestion in the popup menu.

    :help ctrl-g_u prevents Vim from inserting an undo point before <CR>. It is not strictly necessary but good practice.

You want to adjust the mapping's behaviour when you accept a suggestion so it is the "\<C-y>" part that must be changed.

Now…

  • you already know what key to press to leave insert mode,
  • you can take a look at :help key-notation if you are unsure how to represent that key,
  • you know what part of the mapping you need to change,
  • you should get an idea of how to proceed just by looking at the two last parts of the "trinary" operator.

Upvotes: 1

Related Questions