How do I write and edit a macro as text instead of recording it live?
Answer
Write keystrokes in buffer, then "qy$
Explanation
Instead of recording a macro in real-time (where mistakes mean starting over), you can write the keystrokes as text in a buffer, edit them visually, and then yank the line into a register to use as a macro.
How it works
- Open a scratch line or buffer
- Type the macro keystrokes as text
- For special keys, use
<C-v>to insert literal characters:<C-v><Esc>inserts^[(Escape)<C-v><CR>inserts^M(Enter)<C-v><C-w>inserts^W(Ctrl-W)
- Yank the line into the target register:
"qy$or"q0y$ - Execute with
@q
Example
Type this line in your buffer:
0f:dt;A,^[j
(Where ^[ is a literal Escape character inserted with <C-v><Esc>)
Then yank it: "q0y$
Now @q executes: go to column 0, find :, delete to ;, append ,, escape, move down.
Why this is better than recording
- You can see the entire macro before running it
- Editing is trivial — just modify the text
- No need to re-record for small changes
- You can copy macros between files or share them
- Complex macros with many special characters are easier to debug
Using :let for readability
" Set a register using Vim notation (more readable)
:let @q = "0f:dt;A,\<Esc>j"
Tips
<C-v>is your friend for inserting literal control characters- Use
"qpto paste an existing macro for editing, then"qy$to save it back - This technique is recommended for any macro longer than a few keystrokes
:let @q = "..."syntax uses\<Esc>,\<CR>etc. for special keys- Documented under
:help i_CTRL-Vand:help let-register