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
:letis Vim's variable assignment command@arefers to registera— you can use any letter (a–z), 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 subsequentppaste that value :let @+ = @%copies the current filename into the system clipboard register- Combine with
:executeto build and run commands from computed strings