3

I was solving a problem on Vimgolf (you can take a look at this) where I stumbled upon this solution.

djgJ.V"=[<C-R><C-A>]<CR>pZZ

Could you please walk me through the meaning of this cryptic keystrokes "=[<C-R><C-A>]<CR>p?

6

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.

General Description:

  • 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.
  • [<C-R><C-A>]<CR> : Ctrl-R+Ctrl-A grabs 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

Golf Problem:

  • 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

    a
    b
    c

  • ZZ - Save and exit Vim
3

"= 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. "=expression<cr>p is a common idiom to put the result of an expression. It is a special case of the sequence "ap where 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.