How do I programmatically set a register's content or pre-load a macro using setreg()?
Answer
:call setreg('q', 'dd')
Explanation
The setreg() VimScript function lets you populate any register with arbitrary content directly from the command line or a script — no recording required. This is especially useful for loading complex macros from your vimrc, resetting registers in scripts, or constructing macros dynamically.
How it works
setreg('{reg}', '{content}')assigns the string{content}to register{reg}.- The content is interpreted as keystrokes when the register is executed with
@{reg}. - An optional third argument controls the register type:
'c'for characterwise,'l'for linewise,'b'for blockwise. - Special keys use the same notation as in macros:
\<CR>for Enter,\<Esc>for Escape,\<C-a>for Ctrl+A.
Example
To load a macro that deletes a blank line and moves to the next:
:call setreg('q', 'dd')
Now @q will execute dd. For a more complex example, pre-load it in your vimrc:
" Macro to append a semicolon to the end of a line
call setreg('s', 'A;\<Esc>')
Then :source $MYVIMRC and @s appends ; to any line.
Tips
- Use
getreg('q')to inspect the current content of a register. - To clear a register:
:call setreg('q', ''). - To reset register
qbefore appending in a loop:qaqin normal mode also clears it, butsetregis scriptable. - Combine with
:let @q = '...'(the assignment form) for a cleaner vimrc syntax:let @q = 'A;\<Esc>'