vim macros

vim macros

Deliberate Software

Vim Refactoring Patterns

 22 Jun, 2016 · Read in about 5 min · (990 Words)

 technical skills vim refactoring

Editor macros are a secret weapon for editing text. While they are hard to learn, no other tool offers such broad speed and power for automating changes. A skilled macro wielder can make huge changes to a codebase with ease.

Here are some inspirational patterns to demonstrate major structural refactorings using Vim macros and search/replace commands.

Reorder A List Of Numbers

A change left me with a file with unordered numbers. The numbers needed to be increasing, without changing the actual order of the lines. Macros are my first choice to accomplish a repeated action.

The commands:

/; – Search for ‘;’n – Go to next ‘;’qq – Start macro in ‘q’ registerdb – Delete backwardsN – Search for previous ‘;’yb – Yank backwardsn – Search for next ‘;’P – Paste backwardsCtrl+a – Increment numbern – Go to next ‘;’n – Go to next ‘;’q – Stop Recording macro33@q – Replay 33 times the ‘q’ macro

This only took me a few seconds to type! I was able to run this across the whole file by replaying it the number of lines minus one. Because I saved it in the ‘q’ register, I was able to keep it saved for the whole session, which involved refactoring several dozen similar files. I got to re-use the saved macro at least 20 more times in that three hour session!

I don’t think this macro is very complex. I would only leave it in the register for a single session, and remake it in the future if needed. But if I wanted to save it, running “qp spits out: dbNybnP^ann.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s