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

How do I create nested macros where one macro calls another?

Answer

qa{edits}@bq

Explanation

How it works

Vim macros can call other macros, creating a modular system of reusable building blocks. When macro a contains @b, executing @a will perform its own edits and then run macro b as a subroutine.

This is useful when you have a common operation that is shared among multiple workflows. Instead of duplicating keystrokes in every macro, you record the shared part once and call it from other macros.

The key principles for nested macros:

  • Record the inner (helper) macro first, since the outer macro needs it to exist
  • The inner macro executes completely before the outer macro continues
  • You can nest multiple levels deep, though keeping it to 2-3 levels is recommended for clarity
  • Be careful not to create infinite loops where macro a calls b and b calls a

Example

Suppose you frequently need to (a) format a word as uppercase and (b) wrap it in brackets. Record these as separate macros:

  1. Record helper macro b to uppercase a word: qbgUiwq
  2. Record macro a that calls b and then wraps in brackets: qa@bbi[<Esc>ea]<Esc>q

Breaking down macro a:

  • @b -- call macro b to uppercase the word
  • bi[<Esc> -- insert opening bracket before the word
  • ea]<Esc> -- append closing bracket after the word

Given the text hello, running @a produces [HELLO].

Now you can also record macro c that uses @b differently, perhaps uppercasing and adding a colon: qc@bA:<Esc>q. The gUiw logic lives only in macro b, keeping your macros DRY.

Next

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