Vim is my favourite text editor, because it is minimalist while also being insanely configurable. While I may describe my ideal Vim setup sometime in the future, I do want to share some tips and tricks that make Vim so damn efficient for certain tasks. Today, I shall focus on macros.
Here’s the key idea to keep in mind when discussing about Vim. Vim is not just an editor, it is a text manipulation program. Inserting text is just one of the many tasks that Vim can accomplish. A macro is a small Vim program that the user can record in order to make text editing more efficient.
Consider a simple use case. Let’s say that I have a CSV file that looks like this
New York,NY,USA
Seattle,WA,USA
Mumbai,MH,India
Let’s say that I want to add another column at the beginning of each line that is sequentially numbered, like so
1,New York,NY,USA
2,Seattle,WA,USA
3,Mumbai,MH,India
I could go down each line and manually add each column, but there’s a better way. The solution is to program a Vim macro that does the following tasks in order.
-
Assuming that the first column of a certain line is the required number for this line (row), we copy the first column to the next line.
-
Increment the line number by one so that it is one more than the previous line (row).
So, I edit the first line, in order to manually add the new column to the first line.
1,New York,NY,USA
Seattle,WA,USA
Mumbai,MH,India
Next, I ensure that I’m not executing any Vim command. I can verify this by pressing ESC a couple of times. Then I press q followed by a letter to identify this macro, e.g.: a. The macro then consists of the following keystrokes
- 0: Move to the beginning of the line.
- v: Visual mode.
- /,: Find the first
,
to match. - y: Yank (copy) the highlighted text.
- j0: Go to the beginning of the next line.
- P: Paste the copied text. At this point, the cursor should
be on the
,
. - h: Move the cursor one position to the left so that it is on the last digit of the number.
- Ctrla: Increment the number.
- q: Stop recording the macro.
Now, pressing @a would perform the nine steps
outlined with just two key-presses. Let’s say the file had 50 more lines
to be edited. In this case, I could use another powerful trick that Vim
offers – the ability to repeat a command multiple times. So, ensure
that I’m out of executing any command, I could type in a number followed
by a command that would execute the specified command a certain number
of times. So, pressing 50@a
would execute the macro a
fifty times, which is an insanely powerful
technique for modifying multiple lines with a single command.
That’s all for Vim macros for today. I hope you found this post useful. Macros were one of the things I learnt relatively late as a Vim user, but now that I do know about this trick, I use it all the time, and it has saved me countless hours and a lot of headache when modifying code or text. Until the next time, when I take some time to write some more about cool Vim tricks and tips.