How do I programmatically load text or a macro into a named register from the command line?
Answer
:let @a="text"
Explanation
:let @{register}="..." assigns text directly to a named register from the command line or a vimrc. This is the canonical way to create a macro as a string — useful for sharing macros in config files, inspecting register contents, or building macros that are too complex to record interactively.
How it works
:letis Vim's variable assignment command@arefers to registerain Vimscript — the@prefix denotes a register- The string value uses Vim's double-quote string escapes:
\<Esc>for Escape,\<CR>for Enter,\<C-w>for Ctrl+W, etc. - After assignment,
@aexecutes it as a macro normally
Example
Load a macro that wraps the current word in console.log():
:let @q="ciWconsole.log(\<C-r>\"\<Esc>)"
Then press @q on any word to transform:
myVariable
into:
console.log(myVariable)
Tips
- Read back a register with
:echo @aor paste it into a buffer with"ap - Put
:let @q="..."in your~/.vimrcto persist macros across sessions - Use uppercase
:let @A="..."to append to an existing register rather than overwrite it - To copy a typed macro from a register to inspect it:
"qppastes it as plain text so you can read the escape sequences