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

How do I debug a macro by stepping through it command by command?

Answer

:let g:debug_macro=1 | normal @a

Explanation

When a macro doesn't work as expected, debugging it step by step is essential. While Vim doesn't have a built-in macro debugger, you can use verbose mode, register inspection, and manual stepping to diagnose issues in macro recordings.

How it works

  • :registers a — view the exact keystrokes stored in the macro
  • Put the macro in a buffer: "ap — see and edit the raw keystrokes
  • Run one command at a time by re-recording partial macros
  • Use :verbose normal @a for additional output

Example

" Step 1: View the macro contents
:echo @a
" Output: /TODO^Mdd (^M is <CR>)

" Step 2: Put macro in a buffer to see all keystrokes
"ap
" Shows: /TODO<CR>dd

" Step 3: Test individual parts
/TODO<CR>     " Does the search work?
dd            " Does the deletion work?
Common issues:
- Missing <Esc> before mode switches
- Search wrapping unexpectedly
- Wrong register used
- Cursor position assumptions failing

Tips

  • ga shows the character code under cursor — useful for identifying control characters in macros
  • Edit the macro in a buffer, then yank it back: 0"ay$ updates register a
  • Use let @a = "keystrokes" with explicit \<Esc>, \<CR> for clarity
  • Recursive macros: check @a is empty before recording with qaq first

Next

How do I return to normal mode from absolutely any mode in Vim?