On-The-Fly Macros in Vim
A macro is a series of commands that you can record and play back. Vim provides a simple interface for creating and using macros that can automate all of your repetitive tasks.
To record a macro in vim:
- Go into normal mode
- Press
qand then any letter to start recording (your macro will be saved to this letter) - Enter the commands you want to record
- Press
qto stop recording
To playback a macro in vim:
- Go into normal mode
- Enter the number of times you want to repeat the action
- Press
@ - Enter the letter that your macro was saved to
That's it! The next time you find yourself wrapping things in quotes, adding spaces after separators, or converting something between formats, consider recording your actions as a macro.
Some tips:
- Macros can call other macros
- Recording to a capital letter will let you append, rather than overwrite a macro
- You can call ex commands from macros (eg.
:wnext) - Be mindful of where your cursor starts and ends
@@repeats your last playback- You can use
:nnoremap <Space> @qto allow you to run the macro inqwith spacebar in normal mode :regwill show you the contents of all your saved macros, while:reg qwill show you the contents of the macro inq- Macros are saved between vim sessions
- You can save a macro in your .vimrc (to prevent overwriting or allow portability) by adding `let @
=' ' - To edit the macro in
q, type:let @q=', pressctrl+rctrl+rq, edit your commands, then type'to close the expression