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

How do I define or edit a macro's content programmatically without re-recording it?

Answer

:let @q = 'keystrokes'

Explanation

You can assign a string directly to any register using :let, turning it into a macro instantly. This gives you full programmatic control over macros — useful for constructing them from expressions, appending to an existing macro without uppercase-recording, or modifying a recorded macro using Vimscript string functions.

How it works

  • :let @q = 'I# \<Esc>j' — creates a macro in register q that inserts # at the start of a line and moves down
  • :let @q = @q . 'j' — appends j to the current contents of q
  • :let @q = substitute(@q, 'foo', 'bar', '') — modifies the macro using a string substitution
  • :echo @q — inspect the current macro contents before or after editing

Special keys inside the string must use Vimscript double-quote escape sequences:

let @q = "I# \<Esc>j"

Example

You recorded a Python comment macro but need it to work for JavaScript (// instead of #):

" Original macro: insert '# ' at line start
let @q = "I# \<Esc>j"

" Modify it for JavaScript comments
let @q = substitute(@q, '#', '//', '')

" Run the updated macro on 5 lines
5@q

Tips

  • Use :reg q to view the register before and after to confirm your changes
  • Chain two macros: :let @q = @a . @b combines macros a and b into q
  • Copy a macro to the clipboard for sharing: :let @+ = @q
  • This technique is how Vimscript plugins programmatically create complex operations that behave like recorded macros

Next

How do I briefly highlight text after yanking it to get visual confirmation of what was copied?