Culip
Culip

Reputation: 589

Vim: Easy way to convert recorded macro into let

I want to save a certain macro permanently so that I can replay it in future sessions.

For instance, I record the macro which surrounds selected words with ** (like **this text is strong**):

  1. Switch to the visual mode
  2. Select some words
  3. Start recording "a"
  4. Press c, **, Ctrl-r, ", **, Ctrl-; (to switch to the normal mode); and
  5. Stop recording.

From the next time, I can just select words and press @a to replay these actions.

Now I enter :reg a and see this output:

--- Registers ---
"a   c**^R"**^[

How can I define this using the :let function so that I can add this to .vimrc and make this macro permanent?

:let @a='c**^R"**^['

didn't work.

Upvotes: 0

Views: 287

Answers (1)

romainl
romainl

Reputation: 196536

The ^R and ^[ in the output of :reg a are literal control codes, not ^ followed by R or by [. Usually, Vim uses a special color to hint at that difference.

You can do either of two things…

  • In your vimrc, type out the macro directly, using :help i_ctrl-v to insert the literal control codes. That is, press <C-v> then <C-r> to insert a literal ^R:

    let @a = 'c**    " type this out
    <C-v><C-r>       " press <C-v><C-r> to insert ^R
    "**              " type this out
    <C-v><Esc>       " press <C-v><Esc> to insert ^[
    '                " type this out
    <Esc>            " leave insert mode
    

    result

  • In your vimrc, insert the register directly between the quotes with :help i_ctrl-r:

    let @a = '
    <C-r>a
    '
    <Esc>
    

Note that it doesn't protect the register in any way so @a can be overwritten accidentally. A mapping, the right hand side of which is a macro, seems safer to me:

" again, use <C-v><C-r> to insert `^R`
xnoremap <key> c**^R"**^[

" or use the angled brackets notation
xnoremap <key> c**<C-r>"**<Esc>

Upvotes: 2

Related Questions