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

How do I debug a Vim macro one command at a time?

Answer

:debug normal @q

Explanation

Recorded macros are powerful, but when one keystroke goes wrong they can fail fast and leave confusing state behind. Instead of guessing, you can run a macro under Vim's debugger and inspect each step as it executes. This is particularly useful for long macros with searches, text objects, and conditional control-flow via motions.

How it works

  • :debug starts command execution in debug mode.
  • normal @q executes register q as a normal-mode macro.
  • In debug mode, Vim pauses so you can inspect state and continue deliberately.
  • You can examine context (:echo, :registers, cursor position) before stepping again.

The key advantage is visibility: you see exactly where the macro diverges from expectation, then fix the register content instead of repeatedly rerunning a broken sequence.

Example

Suppose @q should rename fields across many lines but starts failing after the third occurrence. Run:

:debug normal @q

At each breakpoint prompt, inspect the current line and register contents, then continue. Once you identify the problematic motion or search, update the macro and rerun.

:let @q = "...fixed keystrokes..."

This turns macro debugging from trial-and-error into a controlled, inspectable workflow.

Tips

  • Use :display q (or :reg q) before running to confirm exactly what is stored.
  • Pair with :set hlsearch so failing search steps are easier to spot visually.
  • After fixing, test the macro on a small range with :.,.+5normal! @q before full-buffer execution.

Next

How do I open and edit a file directly inside a tar archive in Vim?