vimtricks.wiki Concise Vim tricks, one at a time.

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 register a
  • q -- 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:

  1. First, clear register a: qaq
  2. Now record the recursive macro: qa then /TODO then Enter then dd then @a then q
  3. 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.

Next

How do you yank a single word into a named register?