vimtricks.wiki Concise Vim tricks, one at a time.

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

  1. Record your macro normally: qq, perform actions, q
  2. Inspect the register content: :reg q
  3. Copy the keystrokes from :reg q output into your vimrc:
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 q to 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 " Macros section in your vimrc for easy management
  • If the macro uses the " character, wrap the let value in single quotes and escape the register name carefully

Next

How do I scroll the view left and right when lines are wider than the screen?