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

How do I define or modify a macro directly as a string without recording it?

Answer

:let @q='commands'

Explanation

Macros in Vim are stored in registers as plain text. Using :let @q='...' you can define a macro directly as a string — no recording required. This is useful for saving macros to your vimrc, constructing them programmatically, or inspecting and modifying an existing macro.

How it works

  • :let @q='dd' — set register q to the keystrokes dd
  • :echo @q — inspect the current contents of register q
  • :let @q = @q . 'j' — append j to the existing macro
  • Special keys use Vim's internal notation: \<CR> for Enter, \<Esc> for Escape, \<C-a> for Ctrl+A

Example

A macro that duplicates the current line and increments the first number:

:let @q = 'yyp\<C-a>'

This is equivalent to recording qqyyp<C-a>q but is readable and can be placed in vimrc. Run it with @q.

To persist a macro across sessions, add to vimrc:

let @q = 'dd'

Tips

  • Use double quotes " instead of single quotes to allow special escape sequences: :let @q = "dd\<CR>"
  • Check what a recorded macro actually contains: :echo @q or :reg q
  • :let @q = @q . @r concatenates two macros — run macro r after macro q
  • :let @+ = @q copies a macro to the clipboard so you can paste it as text for documentation
  • setreg('q', 'dd') is the Vimscript function equivalent, with a third argument for register type

Next

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