I was solving a problem on Vimgolf (you can take a look at this) where I stumbled upon this solution.
Could you please walk me through the meaning of this cryptic keystrokes
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.Sign up to join this community
For context I'll go over the whole thing. First I'll describe the operations generally and then how they apply to the golf problem specifically.
dj: Delete with 'one line down motion' (delete current and following line)
gJ: Join current and next line, adding no extra spaces
.: Repeat the join
V: Line-wise visual selection of the current line
"=: Prepare to store something into the expression register (
=). Unlike other registers the expression register is populated from the command line and these two keystrokes take you there.
Ctrl-R+Ctrl-Agrabs the WORD under the cursor and inserts it into the command line. So store into the expression register (
=) a string that consists of the WORD surrounded by square brackets. The
<CR>is a literal as if you hit Enter (just like
<C-R><C-A>is as if you hit those keys).
p: Overwrite the visually selected text with the contents of the register
ZZ- Save and exit Vim
djgJ.: Delete the first two lines and join the next two so you have a single line of comma-separated numbers
V: Visually select the whole line
"=[<C-R><C-A>]<CR> : insert into the expression register the bracketed, comma-separated list of numbers:
[2,3,5,7,11,13,17,19,23,29,]. The whole line is one WORD in this case which is why it all gets pulled in.
p : Overwrite the comma-separated list of numbers with all the numbers on separate lines. The expression register is special in that when you
put it its contents get evaluated as an expression first. When a comma-separated list expression is evaluated it resolves into each element on a separate line. E.g.
[a,b,c] evaluates to
ZZ- Save and exit Vim
"= refers to the expression register, which lets you evaluate a bit of vimscript and have vim act like the result of this expression was placed into a register.
<cr>p is a common idiom to put the result of an expression. It is a special case of the sequence
a is a register. The key is that this works in visual mode, replacing the existing text.
V"=[<C-R><C-A>]<CR>p is a clever (though obtuse) way to turn a comma-separated list into a set of lines. Prior to pressing
<CR> this expression looks like
[2,3,5,7,11,13,17,19,23,29,] which is just a list of numbers. When using
p to put a register that is set to a list, vim distributes the list one entry per line.
<C-R><C-A> means put the WORD under the cursor into the command line, which in this case is the entire line.