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

How do I programmatically set the contents of a register from the command line?

Answer

:let @a = "value"

Explanation

The :let @{reg} = expr command lets you assign any string or expression directly into a named register without entering insert mode or performing a yank. This is invaluable for pre-loading a register before running a macro, or for constructing register contents dynamically in a script.

How it works

  • :let is Vim's variable assignment command
  • @a refers to register a — you can use any letter (az), or special registers like @/ (last search pattern) or @" (unnamed register)
  • The right-hand side is a Vim expression — a string literal, a function call, or a concatenation

Example

Say you want all occurrences of foo replaced with bar across 10 files, but you need a specific Ex command pre-loaded:

:let @a = ':s/foo/bar/g' . "\<CR>"

Now @a executes that substitution when the macro is invoked. You can also append to a register:

:let @a = @a . " extra text"

Or pre-fill the search register so the next n/N uses your pattern:

:let @/ = 'TODO'

Tips

  • Use :let @" = "text" to set the unnamed register directly, making a subsequent p paste that value
  • :let @+ = @% copies the current filename into the system clipboard register
  • Combine with :execute to build and run commands from computed strings

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?