How do I define or modify a macro without recording keystrokes?
Answer
:let @q =
Explanation
Instead of recording a macro with q, you can assign any string directly to a named register using :let @{register} = 'keys'. This lets you write macros as readable strings, compose them from other registers, or fix a single wrong keystroke without re-recording from scratch.
How it works
:let @q = 'dd'— assigns the stringddto registerq, making it a macro that deletes a line- The string follows Vim's register notation: use
\nfor newline (Enter),\<Esc>for Escape, etc. - Access the current contents of a register at any time with
:echo @q - Concatenate registers:
:let @q = @q . 'j'appendsjto the existing macro inq
Example
You recorded a macro qa to add a semicolon at the end of a line:
qa A;<Esc>j q
Instead, you can define it directly:
:let @a = 'A;\<Esc>j'
To append a dd to an existing macro in register b:
:let @b = @b . 'dd'
Run it as usual with @a or @b.
Tips
- Use
:echo @qto inspect a macro before running it — you will see the literal control characters - This approach pairs well with
:sourceto save frequently-used macros in your.vimrcand load them on startup:let @q = 'Iprefix: \<Esc>j' - To clear a macro:
:let @q = ''