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

How do I create or edit a Vim macro as a plain string without re-recording it?

Answer

:let @q = "dd"

Explanation

Macros are just strings stored in named registers. Using :let @q = "..." you can create, edit, and combine macros programmatically without touching the keyboard recorder. This unlocks techniques that are impossible with q{register}...q.

How it works

Vim's named registers store their content as strings. When you run @q, Vim replays the string as keystrokes. You can write any valid keypress sequence directly:

:let @q = "A,\<Esc>j"

This creates a macro that appends a comma, escapes to Normal mode, and moves down — the same as qaqA,<Esc>jq but never risking a mis-key.

Double-quoted Vim strings support \<Key> escape sequences for any special key:

Sequence Meaning
\<Esc> Escape
\<CR> Enter
\<C-a> Ctrl+A
\<Tab> Tab

Practical uses

Edit an existing macro without re-recording:

:let @q = substitute(@q, 'old_keys', 'new_keys', '')

Combine two macros into one:

:let @q = @a . @b

Define reusable macros in your vimrc:

autocmd VimEnter * let @q = ":%s/\\s\\+$//g\<CR>"

Inspect a macro by printing it:

:echo @q

Tips

  • Use qaq (record an immediately-stopped empty macro) to clear a register before redefining it with :let.
  • To include a literal backslash in the macro string, use \\.
  • This technique also works with the setreg() function: call setreg('q', 'dd', 'c') to set a characterwise register.

Next

How do I navigate quickfix entries, buffers, and conflicts with consistent bracket mappings?