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

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 @q replays those characters as keystrokes
  • :let @a = 'string' sets register a to 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:

  1. I — enter Insert mode at the beginning of the line
  2. // — type the comment prefix
  3. \<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 vimrc so they survive restarts
  • Uppercase register names like @A are not valid on the left-hand side of :let; use the lowercase name with .= to append

Next

How do I execute Ctrl-W window commands from the command line or a Vimscript function?