Vim (The editor) is able to record and replay macros; unfortunately, this feature is often unknown. Since I learned about it, I'm not afraid any more to do large and monotonous editing tasks as Vim can do most of the work for me.
OK, but, what is a macro? A macro is a list of prerecorded actions that can be executed (replayed) at any time in an automated fashion. Macros are identified by a single letter and can be recorded while Vim is running — that they are volatile in the sense that they are forgotten when the editor is closed. I'm sure there is a way to store them in the configuration file but I haven't looked for it (yet).
In order to record a macro, press q followed by the name — a single letter — you want to assign to it. The most commonly used name is q (because it's quick to type after the recording command), so simply press this key twice, qq, to start recording a macro named q. You will see that the status line changes to recording so that you know what is going on.
With the editor in recording mode, do changes to the document as you'd usually do. The macro will remember everything; even changing the current document to another one (e.g., :wn) will be stored (useful in multifile edits). When you are done, simply press q again to stop recording.
So, now that you have your macro recorded, how do you replay it? Simply press @q and watch Vim redo your actions! Note that @ stands for the replay command and q indicates the macro's name.
Be careful when recoding macros, though. It is useful to stick to generic movements around the text rather than simple ones; that is, instead of moving letter by letter, move word by word, go to the beginning/end of the line, move X lines forward/backward, etc. This way, the macro will be applicable even if the text you are currently editing does not match the one you used to record the macro.
Want more posts like this one? Take a moment to subscribe!
Enjoyed this article? Spread the word or join the ongoing discussion!