6

The following mapping doesn't work as expected:

cnoremap $ <esc>

I would expect that when I press $ in command line mode, it cancels the current command line and returns to normal mode.

But instead of that, it runs the current command line, and returns to normal mode (as if I had pressed the Return key).

For example:

 :echo "Hello"$

will echo Hello before exiting the command line.

Is it a normal behaviour, and how can I map a key to cancel the command line mode?

9

I don't know why <esc> doesn't work, but you can use <C-c>. I.e.:

cnoremap $ <C-c>

Edit:

Found the reason for this behavior in :h c_<Esc>:

In macros or when 'x' present in 'cpoptions', start entered command.

  • I read that, but for some reason didn't link 'macros' with 'mappings'. Thanks! – Antony Jun 14 '16 at 20:17
  • 3
    Nice, thanks for your edit! Oh, yet another completely irrationnal/historical feature in Vim... That's why i love/hate Vim.. – yolenoyer Jun 14 '16 at 20:51
5

I'm not sure what causes this behavior, but I do know a way you could get around it.

Try this:

cnoremap $ <C-u><esc>

<C-u> clears the current command. From :help c_CTRL-U

                            *c_CTRL-U*
CTRL-U      Remove all characters between the cursor position and
        the beginning of the line.  Previous versions of vim
        deleted all characters on the line.  If that is the
        preferred behavior, add the following to your .vimrc: >
            :cnoremap <C-U> <C-E><C-U>
  • 1
    Thank you, but Tumbler41's answer is better, because it doesn't forget the last line history (standard <esc> behaviour) – yolenoyer Jun 14 '16 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.