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

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 register q
  • 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 @q or replay it with @@
  • You can read the current contents of a macro register with :echo @q or paste it into a buffer with "qp for 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 @q or 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 a j (move down) to whatever is already in q
  • For complex key sequences, use \' for a literal single quote inside the string or switch to double-quoted strings with proper escaping

Next

How do I visually select a double-quoted string including the quotes themselves?