How do I programmatically set a register's content in Vimscript to pre-load a macro?
Answer
:let @q = 'content'
Explanation
:let @{reg} = 'string' directly assigns content to any named register from Vimscript. This lets you pre-load useful macros in your vimrc so they are instantly available on every Vim startup — no interactive recording required. It also enables constructing macros programmatically using string operations, which is far more maintainable than recording complex key sequences by hand.
How it works
- Vim registers store literal character sequences; running
@qreplays those characters as keystrokes :let @a = 'string'sets registerato the given text- Inside double-quoted strings, Vimscript special-key escapes work:
\<Esc>,\<CR>,\<BS>,\<Tab>, etc. - The assigned string is interpreted as raw keypresses when the register is executed with
@{reg}
Example
Pre-load a macro in ~/.vimrc that comments the current line with //:
let @c = "I//\<Esc>"
When you press @c in any buffer:
I— enter Insert mode at the beginning of the line//— type the comment prefix\<Esc>— return to Normal mode
You can also transform an existing macro register using substitute():
" Remove all trailing spaces from macro in register a
let @a = substitute(@a, ' \+$', '', '')
Or build a macro by concatenating strings:
" A macro that duplicates the current line and appends " -- copy"
let @d = "yypA -- copy\<Esc>"
Tips
- Use double-quoted strings to get special-key expansion (
\<Esc>,\<CR>, etc.); single-quoted strings are literal and will NOT expand these sequences - Inspect a register's current content with
:echo @a - Append to a register without overwriting:
:let @a .= 'more' - This technique is especially useful for macros you use daily — define them in
vimrcso they survive restarts - Uppercase register names like
@Aare not valid on the left-hand side of:let; use the lowercase name with.=to append