Editing macros easily in Vim

If you use vim a lot, you probably use macros a lot too. They’re great for repetitive editing tasks and can be immensely powerful. However, making a typo in the middle of recording a long macro can be painful. Your macro could do the wrong thing or could stop executing halfway through if it runs into an error, and you’ll have to type the whole thing out again!

If this sounds familiar, the following mapping may well make a useful addition to your vimrc:

nnoremap <leader>... :<c-u><c-r><c-r>='let @q = '. string(getreg('q'))<cr><c-f><left>

This mapping will let you edit the contents of your q register with a few keypresses (q because it’s often chosen by vim users as a ‘scratch’ register for quick one-shot macros, as qq is the quickest way to start recording).

Let’s break that down:

" Enter command line mode and clear any existing text
:<c-u>

" Insert the result of the following literally from Vim's expression register
<c-r><c-r>=

" Insert 'let @q = [Q's CONTENTS]'
'let @q = '. string(getreg('q'))<cr>

" Open the command line history window, with the above expression populated
<c-f>

" Move a single character to the left
" (otherwise, the cursor will start off the end of the line)
<left>

Executing this will leave you in Vim’s command line history window with the contents of your macro already populated, making it very easy to correct your errant keystrokes! After editing, you can just hit Enter to submit the change and use your corrected macro.