How do I save a recorded macro permanently so it survives Vim restarts?
Answer
let @q = 'keystrokes'
Explanation
Macros recorded with q{register} are stored in registers and lost when Vim exits. To make a macro permanent, add a let @{register} = '...' assignment to your vimrc—Vim will pre-load the register on startup so @q is always ready to use.
How it works
- Record your macro normally:
qq, perform actions,q - Inspect the register content:
:reg q - Copy the keystrokes from
:reg qoutput into yourvimrc:
let @q = 'keystrokes'
Special keys must be written in their literal escape sequences. The easiest method is to yank the register content directly into the vimrc file:
:put q
This inserts the raw bytes (including ^M for <CR>, ^[ for <Esc>) which Vim reads correctly when the file is sourced.
Example
A macro that wraps the current word in double quotes:
" In vimrc (literal ^[ is inserted with <C-v><Esc>):
let @q = 'ciw"^[pa"'
Where ^[ is the literal escape character (byte 0x1b). In Neovim you can use:
let @q = "ciw\<Esc>pa\""
Tips
- Use
:reg qto see the exact content you need to copy before editing vimrc - In Neovim, prefer storing macros with
\<Key>notation for readability:let @q = "dd\<C-d>p" - Group persistent macros together in a
" Macrossection in your vimrc for easy management - If the macro uses the
"character, wrap theletvalue in single quotes and escape the register name carefully