How do I assign a macro to a register directly from the command line without recording it?
Answer
:let @q = '{keystrokes}'
Explanation
You can assign a string directly to any register using :let @{reg} = '...'. This lets you compose, fix, or share macros as readable text from the command line — no recording session needed.
How it works
:let @q = '...'assigns the string to registerq- The string uses Vim's internal key notation:
\<Esc>for Escape,\<CR>for Enter,\<C-a>for Ctrl+A, etc. - After assignment, run the macro normally with
@qor replay it with@@ - You can read the current contents of a macro register with
:echo @qor paste it into a buffer with"qpfor inspection and editing - This technique is useful for scripting: build the macro string in a variable, then assign it
Example
Assign a macro that appends a semicolon to the end of a line:
:let @q = 'A;\<Esc>'
Now run it on 10 lines:
10@q
Or assign a macro sourced from a script:
:let @q = 'Iconsole.log(\<Esc>A)\<Esc>'
Tips
- To inspect a macro after recording:
:echo @qor put it into a scratch buffer with"qp, edit it, then yank back with"qyy - Macros are just register strings — you can concatenate them:
:let @q = @q . 'j'appends aj(move down) to whatever is already inq - For complex key sequences, use
\'for a literal single quote inside the string or switch to double-quoted strings with proper escaping