0

So I have the following example text:

##1##
many text
and lines
##z##
##1##
many text
and lines
##z##
##2##
more text
##z##

And after doing :set incsearch, and running :g/^##1##\n.*/+,/##z##/- (which is supposed to match the middle content of ##1## and ##z##) it somehow only highlight this much:

##1##
many text

instead of

many text
and lines

Now to test if :g/^##1##\n.*/+,/##z##/- work, i appended y to yank the selection like so :g/^##1##\n.*/+,/##z##/- y. And the result when pasting:

many text
and lines

Is totally different from how set incsearch highlight it.

How come the result are different between yanking/pasting and using incsearch?

3

The incsearch option is very specific to highlight the text that matches a pattern used in a search (which is defined as a /.../ or a ?...? block.)

When you're using :g/^##1##\n.*/+,/##z##/- y, it will only highlight the text that matches the first search pattern, /^##1##\n.*/, which matches the header line and the following line.

(The reason why only the first pattern is showed by incsearch is a bit complicated... But it boils down to the second pattern is part of the command that :g executes for each match of the first pattern, so it doesn't get evaluated until :g starts executing the command for each line that matches the first pattern.)

How come the result are different between yanking/pasting and using incsearch?

This is not unusual at all! In fact, if you search for a pattern, it's not trivial to find a yank or delete command that will act on exactly that region... (Well, there's the gn motion, but it's somewhat unique in that respect.) For instance, if you use y/pattern/ Vim will not yank the text matching the pattern, but the text in between the current cursor position and the start of the next match for the pattern...

If you want to search (and have incsearch or hlsearch highlight) the text in between the ##1## header and the ##z## terminator, then use a pattern that will match that block in between:

/^##1##\n\zs\_.\{-}\ze\n##z##$/

But here again, note how having the block highlighted isn't really necessarily helping you yank or delete it... (But, then, look into the gn motion if you'd like to act on the matches themselves.)

2
  • 1
    I see! Second time I'm seeing the gn motion being mentioned, guess I'll look into it :) – Nordine Lotfi Sep 10 '20 at 5:24
  • Re: yanking, I think /pattern<CR>y//e<CR> should do it. – D. Ben Knoble Sep 10 '20 at 13:09

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.