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
acallsbandbcallsa
Example
Suppose you frequently need to (a) format a word as uppercase and (b) wrap it in brackets. Record these as separate macros:
- Record helper macro
bto uppercase a word:qbgUiwq - Record macro
athat callsband then wraps in brackets:qa@bbi[<Esc>ea]<Esc>q
Breaking down macro a:
@b-- call macrobto uppercase the wordbi[<Esc>-- insert opening bracket before the wordea]<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.