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

How do I define or modify a macro without recording keystrokes?

Answer

:let @q =

Explanation

Instead of recording a macro with q, you can assign any string directly to a named register using :let @{register} = 'keys'. This lets you write macros as readable strings, compose them from other registers, or fix a single wrong keystroke without re-recording from scratch.

How it works

  • :let @q = 'dd' — assigns the string dd to register q, making it a macro that deletes a line
  • The string follows Vim's register notation: use \n for newline (Enter), \<Esc> for Escape, etc.
  • Access the current contents of a register at any time with :echo @q
  • Concatenate registers: :let @q = @q . 'j' appends j to the existing macro in q

Example

You recorded a macro qa to add a semicolon at the end of a line:

qa A;<Esc>j q

Instead, you can define it directly:

:let @a = 'A;\<Esc>j'

To append a dd to an existing macro in register b:

:let @b = @b . 'dd'

Run it as usual with @a or @b.

Tips

  • Use :echo @q to inspect a macro before running it — you will see the literal control characters
  • This approach pairs well with :source to save frequently-used macros in your .vimrc and load them on startup: let @q = 'Iprefix: \<Esc>j'
  • To clear a macro: :let @q = ''

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?