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
- Record your macro into register
q - Open your vimrc
- Type
nnoremap <leader>mand then paste the register:- In insert mode:
<C-r>q - In normal mode:
"qp
- In insert mode:
- 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>mto verify it's set correctly