A fantastically efficient way to repeat a series of actions is to use a macro. You may be familiar with macros from common products like Microsoft Word. They are quite easy to create and use.
The simple steps we are going to follow are:
- Assign macro to a key
- Start recording
- Do a bunch of stuff
- Tell VIM we are done recording
- Use the macro!
To assign the macro to a key and start recording in one shot, what we do is type "q
" followed by whatever key we want to set the macro to. Let's say here we will use "s
". So typing "qs
" will cause a message "recording
" to appear in the bottom left, indicating that we have started recording a macro to store in "s
". Don't worry, you won't accidentally run the macro, by typing "s
" since macros are run by typing the "@
" symbol first.
Now that we are recording, it is time to do some stuff. Let us say that we need to add a semicolon to the end of the line, and then move the cursor to the next line to prepare for running the macro again. Here is what you do:
- Type "
i
" to go into insert mode - Press <end> key to go to end of line
- Type "
;
" since we are in the right place - Press the down arrow key to move to the next line
- Press Escape <esc> key to tell VIM we are done inserting text
- Press "
q
" one more time to stop recording (the "recording
" message goes away)
Now the macro is set. Type "@s
" to run the macro. Now, let's say we want to run it on 20 lines of code... Use the trick learned in a previous post to repeat the macro 20 times: "20@s
". Viola!
CodeProject