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

How do I call one macro from inside another macro in Vim?

Answer

[email protected]

Explanation

When recording a macro, you can execute another macro inside it by pressing @b (or any register) during the recording. This lets you compose complex operations from reusable building blocks. The outer macro will pause, run the inner macro to completion, and then continue recording.

How it works

  • Record a utility macro first (e.g., qb to start recording into register b)
  • Then record a second macro (e.g., qa) and call @b within it
  • When you replay @a, it will execute @b at the appropriate point
  • You can chain as many macros as you need

Example

Suppose you have a macro in register b that wraps a word in quotes: qbciw""<Esc>Pq

Now record macro a to move to the next line and wrap the first word:

qa j 0 @b q

Before running 5@a:

hello
world
foo
bar
baz

After:

hello
"world"
"foo"
"bar"
"baz"

Tips

  • Record small, focused macros first, then compose them into larger ones
  • If the inner macro fails (e.g., motion hits end of file), the outer macro stops too
  • This is the macro equivalent of calling a function from another function

Next

How do I run a search and replace only within a visually selected region?