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

How do I record a macro that uses text objects and complex motions?

Answer

qa ci"replacement<Esc> /next<CR> q

Explanation

Macros can contain any Vim command including text objects, searches, and multi-key motions. The key is designing the macro to be repeatable regardless of exact text.

How it works

  • Record the macro with text objects that adapt to context
  • Use search (/pattern) to navigate to the next target
  • Use text objects (iw, i", i() for context-aware editing
  • The macro works on different text because text objects adapt

Example

Change the string inside each href="..." attribute:

qa /href="<CR>ci"https://new-url.com<Esc>q

This macro finds the next href=, changes the content inside quotes, and is ready for the next iteration.

Tips

  • Prefer text objects over fixed motions (they adapt to content)
  • Use search to find the next target rather than fixed line counts
  • Test with @a on the next occurrence before running with count
  • Design macros to leave the cursor ready for the next iteration

Next

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