13

Imagine you want to quote the word below. If | is the cursor position you can easily quote the word with cw""<Esc>P from Normal mode.

|below

I want to achieve the same behaviour in Command-line mode. My question is how can I say to the Command-line mode that I want to type an <Esc>. I tried :norm cw""<Esc>P and some other variations but I just get ""<Esc>P instead of "below".

Still related to this I would like to know how can I make Command-line mode type Ctrl commands. For example I could quote the aforementioned word with cw"<C-r>""<Esc> instead. But then I would need Command-line to type <C-r> for me. How can I do this?

Gonçalo Ribeiro
  • 1,991
  • 1
  • 18
  • 28
  • 1
    Just like there is <C-x><C-e> in readline to edit the command-line in $EDITOR, you have <C-f> in Vim to open the command-line window. See :help cmdline-window. – romainl Mar 22 '15 at 18:09

3 Answers3

13

<C-v> is what you are looking for. It allows you to enter literal characters (e.g., a literal Esc instead of the string "Esc") without requiring you to escape anything.

:norm cw""<C-v><Esc>P

displays as:

:norm cw""^[P

and will do what you want (i.e., quote the word). You can also use this with other <C-?> mappings. For example, your second request:

:norm cw"<C-v><C-r>""

displays as:

:norm cw"^R""

And will result in the same as the above. There's no need to include the extra Esc at the end.

muru
  • 24,838
  • 8
  • 82
  • 143
Zach Ingbretsen
  • 1,313
  • 7
  • 13
11

This is because special keys like <Esc> are not translated in normal commands, and are treated like you pressed <Esc>. To remedy this, you can use an exec command. Like so:

:exec "norm cw\"\"\<Esc>P"

Note that you must put a backslash before the quotes and the <Esc>, and using single quotes instead of double quotes will not work.

EvergreenTree
  • 8,180
  • 2
  • 37
  • 59
2

Command-line mode is different; you cannot use the same (normal mode) editing commands there. You can find a list of commands at :help c_CTRL-V.

Now, there's the command-line window (:help command-line-window), which can be entered via q: from normal- and <C-F> from command-line mode. In that window, you can use all normal commands and mappings, so that would be option 1.

Option 2 is special mappings for command-line mode. As I said, you cannot use the approach via :normal et al. Key to defining those is the :help c_CTRL-\_e mapping, which "evaluate[s] {expr} and replace[s] the whole command line with the result." Here's a simple example that only works correctly at the end of the command-line:

:cnoremap <F1> <C-\>esubstitute(getcmdline(), '\w\+$', '"&"', '')<CR>
Ingo Karkat
  • 17,819
  • 1
  • 45
  • 61