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

How do I save a macro permanently in my vimrc?

Answer

let @a = 'sequence'

Explanation

How it works

Macros recorded with q are stored in registers, but they are lost when you close Vim (unless you have the viminfo or shada file preserving them). To permanently save a macro, you can add a let command to your ~/.vimrc (or ~/.config/nvim/init.vim for Neovim) that sets the register contents at startup.

The syntax is let @a = 'your_keystrokes' where a is the register letter and the string contains the exact keystrokes. Special keys must be escaped using their notation, for example \<Esc> for Escape, \<CR> for Enter, and \<C-a> for Ctrl-A.

To extract the current contents of a macro for pasting into your vimrc, you can type :echo string(@a) which will print the register contents with proper escaping.

Example

Suppose you recorded a macro in register a that deletes trailing whitespace on a line:

  1. Record: qa then $ then diw then j then q
  2. To save it permanently, add this to your vimrc:
let @a = '$diwj'

For macros with special keys like Escape:

let @b = "I// \<Esc>j"

Note: Use double quotes when you need to include special key codes like \<Esc> or \<CR>. Single quotes treat everything as literal text.

Next

How do you yank a single word into a named register?