How do I define or modify a macro directly as a string without recording it?
Answer
:let @q='commands'
Explanation
Macros in Vim are stored in registers as plain text. Using :let @q='...' you can define a macro directly as a string — no recording required. This is useful for saving macros to your vimrc, constructing them programmatically, or inspecting and modifying an existing macro.
How it works
:let @q='dd'— set registerqto the keystrokesdd:echo @q— inspect the current contents of registerq:let @q = @q . 'j'— appendjto the existing macro- Special keys use Vim's internal notation:
\<CR>for Enter,\<Esc>for Escape,\<C-a>for Ctrl+A
Example
A macro that duplicates the current line and increments the first number:
:let @q = 'yyp\<C-a>'
This is equivalent to recording qqyyp<C-a>q but is readable and can be placed in vimrc. Run it with @q.
To persist a macro across sessions, add to vimrc:
let @q = 'dd'
Tips
- Use double quotes
"instead of single quotes to allow special escape sequences::let @q = "dd\<CR>" - Check what a recorded macro actually contains:
:echo @qor:reg q :let @q = @q . @rconcatenates two macros — run macrorafter macroq:let @+ = @qcopies a macro to the clipboard so you can paste it as text for documentationsetreg('q', 'dd')is the Vimscript function equivalent, with a third argument for register type