Vim Refactoring Patterns
22 Jun, 2016 · Read in about 5 min · (990 Words)
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.
/; – 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.