How do I clear or empty a macro register in Vim?
Answer
qaq
Explanation
How it works
To clear a macro register, you simply start recording into that register and immediately stop. The command qaq breaks down as:
qa-- start recording a macro into registeraq-- stop recording immediately
Since no keystrokes were recorded between start and stop, register a is now empty. This effectively clears whatever was previously stored in that register.
This technique is particularly useful before using recursive macros. A recursive macro calls itself with @a at the end, and it will keep running until it encounters an error. If register a already contains old macro contents, a recursive macro might behave unexpectedly. Clearing the register first ensures a clean slate.
You can also clear a register using :let @a = '' in command mode, which has the same effect.
Example
Suppose you want to set up a recursive macro that deletes lines containing TODO:
- First, clear register
a:qaq - Now record the recursive macro:
qathen/TODOthenEnterthenddthen@athenq - Run it with
@a
The recursive macro will keep finding and deleting TODO lines until no more matches are found. Without clearing the register first, old contents could interfere with the recursion.