2

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.

Phro
  • 375
  • 2
  • 11

2 Answers2

2

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.

FDinoff
  • 30,689
  • 5
  • 75
  • 96
  • Would `` be equivalent to `` in this case? It seems more elegant to use just one sequence, but are there side effects, like [not executing `InsertLeave`](http://unix.stackexchange.com/questions/40086/exiting-block-insert-mode-with-ctrl-c/42419#42419)? I would need to split the mapping into separate `inoremap` and `cnoremap` maps as well (since deleting the line you just inserted and hitting backspace both doesn't leave insert mode and is quite counter-productive). – Phro Jun 25 '14 at 05:31
1

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)
Community
  • 1
  • 1
grubs
  • 181
  • 2
  • 4