Debian Codegraph @

suser/pegrep

raw
1 #!/usr/bin/perl
2 # SPDX-License-Identifier: MIT
3
4 use strict;
5 use warnings;
6 our($grepcolor, $filecolor, $coloncolor, $linenocolor, $stopcolor) = ($ENV{"GREP_COLOR"});
7
8 &main();
9
10 sub goback
11 {
12 my($s, $start) = @_;
13 if ($start == 0) {
14 return 0;
15 }
16 my $of = rindex($$s, "\n", $start - 1);
17 if ($of <= 0) {
18 return 0;
19 }
20 $of = rindex($$s, "\n", $of - 1);
21 return ($of <= 0) ? 0 : $of;
22 }
23
24 sub gofwd
25 {
26 my($s, $start) = @_;
27 my $max = length($$s);
28 if ($start >= $max) {
29 return $max;
30 }
31 my $of = index($$s, "\n", $start);
32 if ($of < 0 || $of >= $max) {
33 return $max;
34 }
35 $of = index($$s, "\n", $of + 1);
36 return ($of < 0 || $of >= $max) ? $max : $of;
37 }
38
39 sub nlcount
40 {
41 my $tmp = shift @_;
42 return $tmp =~ tr/\n//;
43 }
44
45 sub main
46 {
47 my $pattern = shift @ARGV;
48 if (defined($grepcolor) && length($grepcolor) > 0) {
49 $grepcolor = "\x1b\x5b${grepcolor}m";
50 $filecolor = "\x1b\x5b35m";
51 $coloncolor = "\x1b\x5b1;30m";
52 $linenocolor = "\x1b\x5b36m";
53 $stopcolor = "\x1b\x5b0m";
54 } else {
55 $grepcolor = $filecolor = $coloncolor = $linenocolor = $stopcolor = "";
56 }
57 foreach my $file (@ARGV) {
58 &dofile($file, $pattern);
59 }
60 }
61
62 sub dofile
63 {
64 my($file, $pattern) = @_;
65 local *FH;
66
67 open(FH, "< $file");
68 my @lines = <FH>;
69 close FH;
70 my $data = join("", @lines);
71 while ($data =~ m{$pattern}gs) {
72 my $mainofs = $-[0];
73 my $postofs = $+[0];
74 my $mainlen = $postofs - $mainofs;
75 my $leadofs = &goback(\$data, $mainofs);
76 my $endofs = &gofwd(\$data, $postofs);
77 my $linestart = 1 + &nlcount(substr($data, 0, $mainofs));
78 my $lineend = $linestart + &nlcount(substr($data, $mainofs, $mainlen));
79 print "$filecolor$file$stopcolor";
80 print "$coloncolor:$stopcolor";
81 print "$linenocolor$linestart$stopcolor";
82 print "$coloncolor→$stopcolor";
83 print "$linenocolor$lineend$stopcolor";
84 print "$coloncolor:$stopcolor";
85 print substr($data, $leadofs, $mainofs - $leadofs);
86 # because less -R does not support color across \n
87 my $main = substr($data, $mainofs, $mainlen);
88 $main =~ s{\n}{$stopcolor\n$grepcolor}g;
89 print $grepcolor, $main, $stopcolor;
90 print substr($data, $postofs, $endofs - $postofs);
91 print "\n";
92 }
93 }