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

How do I create a macro by typing it out instead of recording it interactively?

Answer

:let @q = "dwelp"

Explanation

Recording macros with q works well for simple sequences, but complex macros with special keys can be hard to get right in one take. Using :let @{reg} = "..." you can write a macro as a string, using Vim's special key notation. This makes it easy to construct precise macros, include escape sequences, and share macros in your vimrc.

How it works

  • :let @q = "dwelp" — sets register q to the keystrokes dwelp (delete word, move to end of next word, paste)
  • Special keys use \<...> notation inside double quotes: "\<Esc>", "\<CR>", "\<C-w>"
  • The macro can then be run with @q as normal
  • Use \<Esc> for Escape, \<CR> for Enter, \<C-a> for Ctrl-A, etc.

Example

Create a macro that wraps a word in double quotes:

:let @q = "ciw\"\<C-r>\"\"\<Esc>"

Or a simpler example — a macro that deletes to the end of line and joins with the next:

:let @q = "DgJ"

Run it with @q.

Tips

  • Inspect a macro's contents with :echo @q or :reg q
  • Store macros permanently in your vimrc: let @q = "..." in your config
  • Use single quotes to avoid backslash escaping: :let @q = 'dwelp' (but single quotes cannot encode special keys)
  • Combine with :execute for dynamic macro construction

Next

How do I use PCRE-style regex in Vim without escaping every special character?