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 registerqto the keystrokesdwelp(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
@qas 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 @qor: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
:executefor dynamic macro construction