1 2 3 4
Now let’s convert that to the following:
1 2 3 4 5 6 7
Here are the macros I used to do this:
Note that if you copy paste the above into your vimrc it will not work. The
^M found are actually single characters, not two. To input this properly you will need to chord it in input mode with
<Ctrl-V>. So for
<Esc> you would chord
So, when I’m inside the parameters of the function, I can hit
@r and it will perform the refactoring. Now let’s break it down step by step.
@q The first macro
This is a recursive macro which takes something like
a,b,c and turns it into
var a = p.a,var b = p.b,var c = p.c. Let’s see how that’s done.
pYanks the word and enter insert mode, type var, exit insert mode and paste the just yanked word.
a = parameters.Append and fill in parameters.
lExit insert mode, find the next
@qAdjust the cursor position and recursively call itself.
Recursive macros terminate when the first error occurs. In this macro, that error is when there are no more commas left.
@r The second macro
The is the macro that should be invoked, and references the
di(Deletes everything inside the brackets.
iparameters Enter insert mode and type parameters.
<CR>Leaves insert mode and finds the next brace.
pCreates two empty lines and pastes what we deleted into the first line.
JVisually select what we just pasted and join them all into a single line.
<CR>Reselect the visually and delete all whitespace.
0Move to the beginning of the line.
:try|exe "norm! @q"|endtry
<CR>Macros will terminate on the first error, even if referencing another macro. Wrapping the other macro with try|endtry swallows the error and lets the current macro continue.
<Esc>Append ; to the end of the line.
<CR>Visually select the line, replace with carriage returns.
v=``Visually select from the current cursor position back to where it was originally was, and format.
Now is this the best way to do it? Probably not. I would not be surprised if someone was able to do it with less keystrokes or a single macro. But hey, it was fun learning experience, and ultimately I turned all of that into two keystrokes that can be reused many times.
I posted this on vimgolf so let’s see how other people solved the same refactoring!