How to save a Vim macro that contains “Escape” key

2019-02-02 09:29发布

问题:

I use the following Vim macro a lot (it puts the current line inside XML tags):

I<e>^[A</e>

So I saved it into my .vimrc

let @e='I<e>^[A</e>'

But it does not work.
The ^[ part means "Escape" but it is not understood as such in .vimrc

How can I save this macro, or any macro that contains "Escape" ?

回答1:

Try entering the escape with <Ctrl-v><Esc> in insert mode. See :help i_CTRL-V in vim.



回答2:

<ESC> is your friend here. Literally type <ESC>, thus :

let @e=I<e><ESC>A</e>

See :help key-notation in Vim for more info.

Update:

Ah... <ESC> works in key mappings (such as :map <Leader>e <ESC>I<e><ESC>A</e> [tested]) but not in macros, which are expanded literally. I have just tried and tested this:

:let @e='^[I<e>^[A</e>'

Where ^[ is just one char formed by hitting CTRL+VESC. Note the escape right at the beginning of the macro.



回答3:

If you're using Windows behavior for vim where Ctrl+V is the Paste command, the equivalent sequence is Ctrl+Q



回答4:

Today I discovered a vim plug-in called MARVIM (http://www.vim.org/scripts/script.php?script_id=2154).

It is capable of storing macros and executing them later using shortcuts.



回答5:

Saving macros in plain file without plugins.

Having for example macro m . In insert mode, at e.g beginning of new line, then type 3 keys

ctrl-r ctrl-r m

the macro with escapes will be put in that line. (editable as needed) In another line name/comment it. Add other macros if you wish - then save this file as e.g. :w my_vim_macros

When you want to reuse such saved macro(s): place cursor on the beginning of macro string, then 4keys

"xy$

and your macro (this line) will be yanked to register x.



回答6:

I'm answering what I do to add Escape in macro.

Using in vim editor

:let @a='iabcjj'

here I map <ESC> to jj by

.vimrc file

imap jj <esc> 


标签: vim macros