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

How do I append additional keystrokes to a recorded macro using Vimscript without re-recording it?

Answer

:let @q .= "keys"

Explanation

The string concatenation assignment :let @q .= "keys" appends new keystrokes directly to the contents of a named register. Because macros are stored as plain strings in registers, you can extend an existing macro without touching a keystroke.

How it works

  • @q accesses the raw string content of register q
  • .= is Vimscript's string concatenation-and-assign operator, equivalent to @q = @q . "keys"
  • Any characters appended become part of the macro and run when you invoke @q
  • To embed special keys, use Vim key notation inside a double-quoted string: "\<CR>", "\<Esc>", "\<C-w>"

Example

You recorded macro q that deletes a word with dw. Now you want it to also move to the next word with w:

:echo @q
" → dw

:let @q .= "w"

:echo @q
" → dww

Append a newline and Enter to make a macro that creates a new line after each deletion:

:let @q .= "\<CR>"

You can also prepend, using standard string concatenation:

:let @q = "gg" . @q    " jump to top of file before running macro

Tips

  • Inspect any register's current macro with :echo @q before modifying
  • To replace a macro entirely from scratch, use :let @q = "allkeys"
  • For complex insertions in the middle of a macro, paste it into a buffer with "qp, edit in-place, then yank it back with 0"qy$ and delete the line with dd
  • This approach is especially useful in a script or plugin where you want to dynamically extend a user's macro based on context

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?