Published .

rgedit.tar

rgedit.raku

#!/usr/bin/env raku

my sub tmp-edit(Str $s) {
  my $tmp = "/tmp/rged-{('a'..'z').roll(8).join}".IO;
  $tmp.spurt: $s;
  shell("%*ENV<EDITOR> $tmp");
  my $new = $tmp.slurp;
  shell("rm $tmp");
  $new
}

my regex Location { ^^ $<file>=(\S+) [':'|'-'] $<line>=(\d+) [':'|'-'] }

my sub blocks(Str $input) {
  $input
    .split(/^^'--'$$/)
    .map({
      .split(&Location, :v)
      .skip
      .rotor(2)
      .map(<start text> Z=> *)
      .rotor(2 => -1)
      .map({ (|$_[0], "end" => %($_[1].cache)<start>).Hash })
    })
}

sub MAIN($search) {
  my $input = run(<rg --engine=auto -n -C5>, $search, :out).out.slurp(:close);

  for blocks(tmp-edit($input)).reverse -> @bs {
    my $f = @bs[0]<start><file>.IO;
    my @l = $f.IO.slurp.lines;
    for @bs -> %b {
      @l.splice(%b<start><line> - 1, %b<end><line> - %b<start><line>, %b<text>.lines)
    }
    say "Writing $f...";
    $f.spurt(@l.join("\n") ~ "\n");
  }
}