1

I would like to populate a register with the text inside quotes for a range of lines. The register should contain all yanked text separated with new line characters. Example lines:

The "black" cat
A "tall" tree
A long "tail"

Intuitively I tried to clear my q register with qqq, select the lines in visual mode and run:

:'<,'>norm "Qyi"

But then all the text is on the same line which is not what I want. I would not want to use regular expressions because it is very easy to build a normal mode set of commands to do this.

My next attempt was:

:'<,'>g/.*/execute 'normal "Qyi"' | let @q .= "\n"

I used the global command matching all line of the selection because the execute command doesn't accept a range. After the yank of text in the normal command I attempt to add a new line character but my q register ends up like this:

black^Jtall^J^Jtail^J^J

which has a mix of one and two new line characters between the yanked words.

What is the right way to do this? Ideally still using the normal mode commands to yank the text.

1 Answer 1

2

Include the > flag in 'cpoptions', so that Vim automatically adds a new line before appending to a register:

set cpo+=>

See :h cpo->.


I would like a more general solution so that I can understand how to solve future problems.

Try this:

let @q = '' | *g/^/exe 'norm! "Qyi"' | call setreg('q', "\n", 'ac')

Your command didn't work because appending a newline with :let changes the type of the register from characterwise to linewise. See :h :let-register:

If the result of {expr1} ends in a <CR> or <NL>, the register will be linewise, otherwise it will be set to characterwise.


For instance, what if I wanted to separate each yanked text by commas?

Try this:

let @q = '' | *g/^/exe 'norm! "Qyi"' | let @q .= ','
2
  • While this does work it requires changing vims behaviour (or at the very least setting and unsetting the flag before and after the command). I would like a more general solution so that I can understand how to solve future problems. For instance, what if I wanted to separate each yanked text by commas? Commented Apr 17, 2020 at 15:48
  • Thank you! This is very helpful. Commented Apr 17, 2020 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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