Refactoring with Vim Macro - Vimspired Series 1
Let’s say you have this code, which is Angular unittest code, and you have many more lines like this. You want to refactor this, to make it more try like in Example 2. Then typing it all, is not very efficient, but that’s when (Idea-)Vims Makro come in handy.
Example 1
function getSubmitHarness() {
return loader.getHarness(MatButtonHarness.with({selector: '[data-id="submit"]'}));
}
function getUsernameHarness() {
return loader.getHarness(MatInputHarness.with({selector: '[data-id="username"]'}));
}
function getPasswordHarness() {
return loader.getHarness(MatInputHarness.with({selector: '[data-id="password"]'}));
}
Example 2
function dataId(name: string) {
return {
selector: `[data-id="${name}]"`
}
}
function getSubmitHarness() {
return loader.getHarness(MatButtonHarness.with(dataId('submit')));
}
function getUsernameHarness() {
return loader.getHarness(MatInputHarness.with(dataId('username')));
}
function getPasswordHarness() {
return loader.getHarness(MatInputHarness.with(dataId('password')));
}
Let’s see how it works in a small gif first before, explaining the solution.
The Commands
- Place your cursor on a line top the first loader word
- Record macro
qx
(x
is just one possible macro register, you can use others to) - Search for loader
/loader
and jump there (ENTER) - Jump to
{
on the same line by typingf
followed by{
- Enter visual mode
v
and jump to"
usingf"
- Press
s
for substitute (you’re in input mode now) typedataId('
- Leave input mode and jump to next
"
withf"
- Enter visual mode and jump to
}
byvf}
- Press
s
(substitute) and enter the text')
- Goto normal mode
- Stop macro record with
q
- Replay macro n-times typing
@x
- Or jump to all occurrence of loader by typing
n
and use@@
to repeat last macro - Equipped with this, you can go through your files and refactor many occurrences in no time
Written on November 19, 2022