Friday, September 18, 2015

Re: Execute command on multiple ranges found by regex

On 2015-09-18 19:58, BPJ wrote:
> > :g/^beginfoo/+,/^endfoo/-!somefilter
>
> It has worked fine for me since Tim showed it to me,
> but I'm afraid that I need to take it to the next level:
> Is there a way to have the output of the external program be
> appended below the /^endfoo/- line rather than overwriting the
> input range?

The general idea would be to copy the range contents to where you
want them, then run the resulting (copied) data through the filter
instead of the initial source data.

Hacking around, and taking advantage of the fact that the
":t" (":copy") command places the cursor at the end of the block, you
might try something like

:g/^begin/+,/^end/-t/^end/|?^end?+,.! somefilter

Which, while ugly, translates to

:g/^begin/ # on every line matching "^begin"
+ # start a range on the following line
, # through
/^end/ # the following line matching "^end"
- # only back up one line
t # copy that range contained by "begin".."end"
/^end/ # after the line matching "^end"

At this point, we've copied the data we want to pipe, the cursor is
on the last line of that data, and we know that it's preceded by the
"^end" line, so on this grouping we then execute

| # another command
?^end? # search backwards to the "^end"
+ # and start a range on the line after it
, # through
. # the current line (where :t left the cursor)
! somefilter # pipe that range through "somefilter",
# replacing the copied data with the output

And, to make it delightfully more obscure (or Perl-like in
legibility), since the first "^end" sets the current search pattern,
it can be reduced by cutting out the repeated end-patterns to just

:g/^begin/+,/^end/-t//|??+,.!somefilter

or if you want it to be less chatty:

:g/^begin/+,/^end/-t//|sil! ??+,.!somefilter

And *BOOM*, that's how a *real* editor works. ;-)

Hope this helps,

-tim



--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments: