9

The command is

nnoremap <leader>; :execute "normal! mqA;\<esc>`q"

If you then press <leader>;, you will E114: Missing quote: "normal! mqA;\ followed by E15: Invalid expression: "normal! mqA;\. Why is this? The command works fine if input directly into the commandline.

The command adds a ; at the end of the current line, without changing the cursors position.

I realise that I can just do nnoremap <leader>; mqA;<esc>`q which works, the question is why the above doesn't work, and what can be done to make it work in the execute-normal form.

My guess would be that some level of nested escaping is needed, but I couldn't find one that works.

3 Answers 3

10

You need to escape the < via <lt>:

nnoremap <leader>; :execute "normal! mqA;\<lt>esc>`q"<cr>

Note: added <cr> to execute the command as well.

However this can be simplified quite a bit:

nnoremap <leader>; mqA;<esc>`q

Using an expression mapping you can make your mapping conditional based on a trailing ; character:

nnoremap <expr> <leader>; getline('.') =~ ';$' ? '' : "mqA;\<esc>`q"

For more help see:

:h <lt>
:h map-<expr>
1
  • 1
    In the vim documentation. see :h <>. The relevant part is: The <> notation uses <lt> to escape the special meaning of key names. Using a backslash also works, but only when 'cpoptions' does not include the 'B' flag. So if B flag is not in cpotions, you can use \<Esc> to represent the <Esc> key.
    – jdhao
    Apr 27, 2019 at 9:19
5

You need to escape the <ESC> in command mode. This is done by prefixing it with <C-v>. You also need a trailing <CR> to actually run it. Like this:

nnoremap <silent> <leader>; :execute "normal! mqA;<C-v><ESC>`q"<CR>
0

I found that there are 3 ways to escape the key:

  1. nnoremap <silent> <leader>; :execute "normal! mqA;<C-v><esc>`q"<CR>
  2. nnoremap <silent> <leader>; :execute "normal! mqA;\<lt>esc>`q"<CR>
  3. nnoremap <silent> <leader>; :execute "normal! mqA;\e`q"<CR>

Similar for the Enter key (<cr>):

<c-v><cr> or \<lt>cr> or \r.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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