What is the VIM way to copy a list of variables (a list of words vertically aligned with different widths)?

Viewed 61
let(:aaaaa)   { 123 }
let(:bb)      { true }
let(:ccc_ccc) { "foo bar" }

I want to copy all variable names (:aaaaa, :bb, :ccc_ccc).
In VsCode, for example, I would use a multi-line selection.
How can I do it in VIM?

Block selection didn't work, once the variable names have a different length.

2 Answers

You could use the command :%norm f:"Qyt) to make your 'q register' contain the following:

:aaaaa:bb:ccc_ccc

The way it works is as follows:

  • :%norm means 'to all lines, apply the following normal commands'
  • f: moves the cursor to the first colon on the line
  • "Qy appends yanked text to the 'q' register
  • t) is a motion 'till the next closing parenthesis

This assumes that the 'q' register is already empty (you can use qqq to clear it). If you only want to do this for a subset of lines, you'd replace the % with a range (or visual selection).

What you do with the register's contents after that is up to you.

"qp will put them into the buffer, and maybe you'd then do :s/:/\r:/g to split the lines at the colons like this:

:aaaaa
:bb
:ccc_ccc

If your immediate goal is to have something like this in the default register:

:aaaaa
:bb
:ccc_ccc

then it won't be easy to achieve without the ability to visually select multiple non-contiguous pieces of text of arbitrary length, which Vim doesn't have out of the box.

This means that, if we don't want to use a multiple cursors plugin, we are left with more pedestrian ways involving substitutions, macros, etc.

Assuming the cursor is on the first line, you could do something like:

:,+2t+2                  " copy the block below itself
:'[,s/.*(\(.*\)).*/\1    " remove everything you don't need
:'[,d                    " cut the three lines to the unnamed register

But Vim works best when it is used with intent. "Copy this" is rarely a goal in and of itself: it generally is one of the several low-level steps necessary to complete a higher-level task (which itself might be one of the steps of another even higher-level task). What one intends to do with the copied text often plays an important role in choosing the best strategy. Here, your actual goal may have been to get the three variable names on three lines right below their definition, something that actually doesn't imply copying them, so the two first steps would have been enough.

Related