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

How do I convert a recorded macro into a permanent key mapping?

Answer

:let @q then use in nnoremap

Explanation

Macros are stored in registers as plain keystroke strings. You can copy a register's contents directly into a nnoremap command in your vimrc, making a throwaway macro into a permanent mapping.

Method 1: Paste from the register

  1. Record your macro into register q
  2. Open your vimrc
  3. Type nnoremap <leader>m and then paste the register:
    • In insert mode: <C-r>q
    • In normal mode: "qp
  4. Escape special characters as needed

Method 2: Use :let to inspect

" View the exact keystrokes
:echo @q

" Or see it with special keys shown
:let @q

This outputs something like 0f:dt;A,^[j where ^[ is Escape.

Method 3: Set from Vimscript

" Define the macro as a mapping in vimrc
nnoremap <leader>m 0f:dt;A,<Esc>j

" Or set the register directly for use with @q
let @q = "0f:dt;A,\<Esc>j"

Example

Recorded macro that wraps a word in backticks:

" Register q contains: ciw`<C-r>"`<Esc>
" Convert to mapping:
nnoremap <leader>` ciw`<C-r>"`<Esc>

Tips

  • Special keys in mappings use <Esc>, <CR>, <C-w> notation
  • In :let @q = "..." strings, escape with \<Esc>, \<CR>, etc.
  • Use :nnoremap (not :nmap) to avoid recursive mapping issues
  • Test the mapping with :verbose nmap <leader>m to verify it's set correctly

Next

How do I always access my last yanked text regardless of deletes?