2
votes

I'm having some trouble successfully remapping a key to <Esc>. I have tried this with multiple characters, so let's say I want to remap 1 to <Esc>. In my .vimrc file, I added the following line:

noremap! 1 <Esc>

This works fine for exiting insert mode, but when I'm in command mode, the command is executed rather than escaped from. For instance, in normal mode, if I type:

/searchtext1

Rather than exiting back to normal mode without searching, the search results for 'searchtext' appear. Likewise for commands beginning with :. Is there a workaround for this? Am I using the wrong map function?

I am using Vim from the Terminal, although after testing it on the MacVim GUI, it also has this problem.

2
What happens when you try it?merlin2011
The command is executed as though I hit <cr>.Phro

2 Answers

2
votes

This is expected behavior according to the documentation. It part of vi compatability.

If you look at :h i_esc | /*3 Go you will see the following paragraph.

*3 Go from Command-line mode to Normal mode by:
   - Hitting <CR> or <NL>, which causes the entered command to be executed.
   - Deleting the complete line (e.g., with CTRL-U) and giving a final <BS>.
   - Hitting CTRL-C or <Esc>, which quits the command-line without executing
     the command.
   In the last case <Esc> may be the character defined with the 'wildchar'
   option, in which case it will start command-line completion.  You can
   ignore that and type <Esc> again.  {Vi: when hitting <Esc> the command-line
   is executed.  This is unexpected for most people; therefore it was changed
   in Vim.  But when the <Esc> is part of a mapping, the command-line is
   executed.  If you want the Vi behaviour also when typing <Esc>, use ":cmap
   ^V<Esc> ^V^M"}

The part that starts with {Vi: ... } is talking about the vi compatibility and explains behavior you are seeing.

The mapping :noremap! 1 <c-u><bs> would do what you want. Which is completely delete the current line. This is Bullet 2 in the list.

1
votes

My favorite is to map Alt-Space to Escape in all modes. To accomplish this I put this in my vimrc:

noremap <a-space> <esc>
inoremap <a-space> <esc>
cnoremap <a-space> <c-u><bs>

There are 6 sets of mappings in Vim, the break-down is like this:

  • noremap gets normal, visual, select, and operator-pending modes.
  • inoremap gets insert mode
  • cnoremap gets command-line mode (but circumvents the "vi-compatibiliy" issue using the solution presented by FDinoff)