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

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

  • :let is Vim's variable assignment command
  • @a refers to register a in 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, @a executes 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 @a or paste it into a buffer with "ap
  • Put :let @q="..." in your ~/.vimrc to 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: "qp pastes it as plain text so you can read the escape sequences

Next

How do I navigate quickfix entries, buffers, and conflicts with consistent bracket mappings?