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

How do I edit the contents of a macro using Vimscript string functions without re-recording it?

Answer

:let @q = substitute(@q, 'from', 'to', 'g')

Explanation

Macros are stored as plain text in named registers, so you can manipulate them with any Vimscript string function. The :let @q = ... form assigns a new value to a register, and substitute(@q, 'from', 'to', 'g') replaces text within it — effectively editing the macro without re-recording.

This is far faster than re-recording a long macro when you only need to fix a small part, and is essential when the macro is too complex to reproduce easily.

How it works

  • @q — the current contents of register q (the macro)
  • substitute(@q, 'from', 'to', 'g') — Vimscript's substitute() function applies a string replacement on the register contents
  • :let @q = ... — writes the modified string back into register q

Example

Suppose you recorded a macro in q that renames a variable oldVar. You later realize the variable is actually named oldVarName. Instead of re-recording:

:let @q = substitute(@q, 'oldVar', 'oldVarName', 'g')

Or to add a missing ! to a :write inside a macro:

:let @q = substitute(@q, ':w', ':w!', 'g')

Tips

  • Use :echo @q first to inspect the raw macro text before modifying it
  • To view a macro in a readable form, yank it into the buffer with "qp on a blank line, edit it, then yank it back with "qyy
  • The same technique works for any named register: @a, @b, etc.
  • Use escape() if the macro contains special characters you need to match literally: substitute(@q, escape('a.b', '.'), 'axb', 'g')

Next

How do I highlight all occurrences of a yanked word without typing a search pattern?