forked from beyondgrep/ack3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ack
executable file
·2462 lines (1821 loc) · 72.9 KB
/
ack
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
use strict;
use warnings;
our $VERSION = 'v3.5.0'; # Check https://beyondgrep.com/ for updates
use 5.010001;
use File::Spec ();
use File::Next ();
use Getopt::Long ();
use App::Ack ();
use App::Ack::ConfigLoader ();
use App::Ack::File ();
use App::Ack::Files ();
use App::Ack::Filter ();
use App::Ack::Filter::Default ();
use App::Ack::Filter::Extension ();
use App::Ack::Filter::FirstLineMatch ();
use App::Ack::Filter::Inverse ();
use App::Ack::Filter::Is ();
use App::Ack::Filter::IsPath ();
use App::Ack::Filter::Match ();
use App::Ack::Filter::Collection ();
# Global command-line options
our $opt_1;
our $opt_A;
our $opt_B;
our $opt_break;
our $opt_color;
our $opt_column;
our $opt_debug;
our $opt_c;
our $opt_f;
our $opt_g;
our $opt_heading;
our $opt_L;
our $opt_l;
our $opt_m;
our $opt_output;
our $opt_passthru;
our $opt_p;
our $opt_range_start;
our $opt_range_end;
our $opt_range_invert;
our $opt_regex;
our $opt_show_filename;
our $opt_show_types;
our $opt_underline;
our $opt_v;
# Flag if we need any context tracking.
our $is_tracking_context;
# The regex that we search for in each file.
our $search_re;
# Special /m version of our $search_re.
our $scan_re;
our @special_vars_used_by_opt_output;
our $using_ranges;
# Internal stats for debugging.
our %stats;
MAIN: {
$App::Ack::ORIGINAL_PROGRAM_NAME = $0;
$0 = join(' ', 'ack', $0);
$App::Ack::ors = "\n";
if ( $App::Ack::VERSION ne $main::VERSION ) {
App::Ack::die( "Program/library version mismatch\n\t$0 is $main::VERSION\n\t$INC{'App/Ack.pm'} is $App::Ack::VERSION" );
}
# Do preliminary arg checking;
my $env_is_usable = 1;
for my $arg ( @ARGV ) {
last if ( $arg eq '--' );
# Get the --thpppt, --bar, --cathy and --man checking out of the way.
$arg =~ /^--th[pt]+t+$/ and App::Ack::thpppt($arg);
$arg eq '--bar' and App::Ack::ackbar();
$arg eq '--cathy' and App::Ack::cathy();
# See if we want to ignore the environment. (Don't tell Al Gore.)
$arg eq '--env' and $env_is_usable = 1;
$arg eq '--noenv' and $env_is_usable = 0;
}
if ( $env_is_usable ) {
if ( $ENV{ACK_OPTIONS} ) {
App::Ack::warn( 'WARNING: ack no longer uses the ACK_OPTIONS environment variable. Use an ackrc file instead.' );
}
}
else {
my @keys = ( 'ACKRC', grep { /^ACK_/ } keys %ENV );
delete @ENV{@keys};
}
# Load colors
my $modules_loaded_ok = eval 'use Term::ANSIColor 1.10 (); 1;';
if ( $modules_loaded_ok && $App::Ack::is_windows ) {
$modules_loaded_ok = eval 'use Win32::Console::ANSI; 1;';
}
if ( $modules_loaded_ok ) {
$ENV{ACK_COLOR_MATCH} ||= 'black on_yellow';
$ENV{ACK_COLOR_FILENAME} ||= 'bold green';
$ENV{ACK_COLOR_LINENO} ||= 'bold yellow';
$ENV{ACK_COLOR_COLNO} ||= 'bold yellow';
}
App::Ack::ConfigLoader::configure_parser( 'no_auto_abbrev', 'pass_through' );
Getopt::Long::GetOptions(
help => sub { App::Ack::show_help(); exit; },
version => sub { App::Ack::print( App::Ack::get_version_statement() ); exit; },
man => sub { App::Ack::show_man(); },
);
if ( !@ARGV ) {
App::Ack::show_help();
exit 1;
}
my @arg_sources = App::Ack::ConfigLoader::retrieve_arg_sources();
my $opt = App::Ack::ConfigLoader::process_args( @arg_sources );
$opt_1 = $opt->{1};
$opt_A = $opt->{A};
$opt_B = $opt->{B};
$opt_break = $opt->{break};
$opt_c = $opt->{c};
$opt_color = $opt->{color};
$opt_column = $opt->{column};
$opt_debug = $opt->{debug};
$opt_f = $opt->{f};
$opt_g = $opt->{g};
$opt_heading = $opt->{heading};
$opt_L = $opt->{L};
$opt_l = $opt->{l};
$opt_m = $opt->{m};
$opt_output = $opt->{output};
$opt_p = $opt->{p};
$opt_passthru = $opt->{passthru};
$opt_range_start = $opt->{range_start};
$opt_range_end = $opt->{range_end};
$opt_range_invert = $opt->{range_invert};
$opt_regex = $opt->{regex};
$opt_show_filename = $opt->{show_filename};
$opt_show_types = $opt->{show_types};
$opt_underline = $opt->{underline};
$opt_v = $opt->{v};
if ( $opt_show_types && not( $opt_f || $opt_g ) ) {
App::Ack::die( '--show-types can only be used with -f or -g.' );
}
if ( $opt_range_start ) {
($opt_range_start, undef) = build_regex( $opt_range_start, {} );
}
if ( $opt_range_end ) {
($opt_range_end, undef) = build_regex( $opt_range_end, {} );
}
$using_ranges = $opt_range_start || $opt_range_end;
$App::Ack::report_bad_filenames = !$opt->{s};
$App::Ack::ors = $opt->{print0} ? "\0" : "\n";
if ( !defined($opt_color) && !$opt_g ) {
my $windows_color = 1;
if ( $App::Ack::is_windows ) {
$windows_color = eval { require Win32::Console::ANSI; };
}
$opt_color = !App::Ack::output_to_pipe() && $windows_color;
}
$opt_heading //= !App::Ack::output_to_pipe();
$opt_break //= !App::Ack::output_to_pipe();
if ( defined($opt->{H}) || defined($opt->{h}) ) {
$opt_show_filename = $opt->{show_filename} = $opt->{H} && !$opt->{h};
}
if ( defined $opt_output ) {
# Expand out \t, \n and \r.
$opt_output =~ s/\\n/\n/g;
$opt_output =~ s/\\r/\r/g;
$opt_output =~ s/\\t/\t/g;
my @supported_special_variables = ( 1..9, qw( _ . ` & ' + f ) );
@special_vars_used_by_opt_output = grep { $opt_output =~ /\$$_/ } @supported_special_variables;
# If the $opt_output contains $&, $` or $', those vars won't be
# captured until they're used at least once in the program.
# Do the eval to make this happen.
for my $i ( @special_vars_used_by_opt_output ) {
if ( $i eq q{&} || $i eq q{'} || $i eq q{`} ) {
no warnings; # They will be undef, so don't warn.
eval qq{"\$$i"}; ## no critic ( ErrorHandling::RequireCheckingReturnValueOfEval )
}
}
}
# Set up file filters.
my $files;
if ( $App::Ack::is_filter_mode && !$opt->{files_from} ) { # probably -x
$files = App::Ack::Files->from_stdin();
$opt_regex //= shift @ARGV;
($search_re, $scan_re) = build_regex( $opt_regex, $opt );
$stats{search_re} = $search_re;
$stats{scan_re} = $scan_re;
}
else {
if ( $opt_f ) {
# No need to check for regex, since mutex options are handled elsewhere.
}
else {
$opt_regex //= shift @ARGV;
($search_re, $scan_re) = build_regex( $opt_regex, $opt );
$stats{search_re} = $search_re;
$stats{scan_re} = $scan_re;
}
# XXX What is this checking for?
if ( $search_re && $search_re =~ /\n/ ) {
App::Ack::exit_from_ack( 0 );
}
my @start;
if ( not defined $opt->{files_from} ) {
@start = @ARGV;
}
if ( !exists($opt->{show_filename}) ) {
unless(@start == 1 && !(-d $start[0])) {
$opt_show_filename = $opt->{show_filename} = 1;
}
}
if ( defined $opt->{files_from} ) {
$files = App::Ack::Files->from_file( $opt, $opt->{files_from} );
exit 1 unless $files;
}
else {
@start = ('.') unless @start;
foreach my $target (@start) {
if ( !-e $target && $App::Ack::report_bad_filenames) {
App::Ack::warn( "$target: No such file or directory" );
}
}
$opt->{file_filter} = _compile_file_filter($opt, \@start);
$opt->{descend_filter} = _compile_descend_filter($opt);
$files = App::Ack::Files->from_argv( $opt, \@start );
}
}
App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager};
my $nmatches;
if ( $opt_f || $opt_g ) {
$nmatches = file_loop_fg( $files );
}
elsif ( $opt_c ) {
$nmatches = file_loop_c( $files );
}
elsif ( $opt_l || $opt_L ) {
$nmatches = file_loop_lL( $files );
}
else {
$nmatches = file_loop_normal( $files );
}
if ( $opt_debug ) {
require List::Util;
my @stats = qw( search_re scan_re prescans linescans filematches linematches );
my $width = List::Util::max( map { length } @stats );
for my $stat ( @stats ) {
App::Ack::warn( sprintf( '%-*.*s = %s', $width, $width, $stat, $stats{$stat} // 'undef' ) );
}
}
close $App::Ack::fh;
App::Ack::exit_from_ack( $nmatches );
}
# End of MAIN
sub file_loop_fg {
my $files = shift;
my $nmatches = 0;
while ( defined( my $file = $files->next ) ) {
if ( $opt_show_types ) {
App::Ack::show_types( $file );
}
elsif ( $opt_g ) {
print_line_with_options( undef, $file->name, 0, $App::Ack::ors );
}
else {
App::Ack::say( $file->name );
}
++$nmatches;
last if defined($opt_m) && ($nmatches >= $opt_m);
}
return $nmatches;
}
sub file_loop_c {
my $files = shift;
my $total_count = 0;
while ( defined( my $file = $files->next ) ) {
my $matches_for_this_file = count_matches_in_file( $file );
if ( not $opt_show_filename ) {
$total_count += $matches_for_this_file;
next;
}
if ( !$opt_l || $matches_for_this_file > 0 ) {
if ( $opt_show_filename ) {
my $display_filename = $file->name;
if ( $opt_color ) {
$display_filename = Term::ANSIColor::colored($display_filename, $ENV{ACK_COLOR_FILENAME});
}
App::Ack::say( $display_filename, ':', $matches_for_this_file );
}
else {
App::Ack::say( $matches_for_this_file );
}
}
}
if ( !$opt_show_filename ) {
App::Ack::say( $total_count );
}
return;
}
sub file_loop_lL {
my $files = shift;
my $nmatches = 0;
while ( defined( my $file = $files->next ) ) {
my $is_match = count_matches_in_file( $file, 1 );
if ( $opt_L ? !$is_match : $is_match ) {
App::Ack::say( $file->name );
++$nmatches;
last if $opt_1;
last if defined($opt_m) && ($nmatches >= $opt_m);
}
}
return $nmatches;
}
sub _compile_descend_filter {
my ( $opt ) = @_;
my $idirs = 0;
my $dont_ignore_dirs = 0;
for my $filter (@{$opt->{idirs} || []}) {
if ($filter->is_inverted()) {
$dont_ignore_dirs++;
}
else {
$idirs++;
}
}
# If we have one or more --noignore-dir directives, we can't ignore
# entire subdirectory hierarchies, so we return an "accept all"
# filter and scrutinize the files more in _compile_file_filter.
return if $dont_ignore_dirs;
return unless $idirs;
$idirs = $opt->{idirs};
return sub {
my $file = App::Ack::File->new($File::Next::dir);
return !grep { $_->filter($file) } @{$idirs};
};
}
sub _compile_file_filter {
my ( $opt, $start ) = @_;
my $ifiles_filters = $opt->{ifiles};
my $filters = $opt->{'filters'} || [];
my $direct_filters = App::Ack::Filter::Collection->new();
my $inverse_filters = App::Ack::Filter::Collection->new();
foreach my $filter (@{$filters}) {
if ($filter->is_inverted()) {
# We want to check if files match the uninverted filters
$inverse_filters->add($filter->invert());
}
else {
$direct_filters->add($filter);
}
}
my %is_member_of_starting_set = map { (get_file_id($_) => 1) } @{$start};
my @ignore_dir_filter = @{$opt->{idirs} || []};
my @is_inverted = map { $_->is_inverted() } @ignore_dir_filter;
# This depends on InverseFilter->invert returning the original filter (for optimization).
@ignore_dir_filter = map { $_->is_inverted() ? $_->invert() : $_ } @ignore_dir_filter;
my $dont_ignore_dir_filter = grep { $_ } @is_inverted;
my $previous_dir = '';
my $previous_dir_ignore_result;
return sub {
if ( $opt_g ) {
if ( $File::Next::name =~ /$search_re/o ) {
return 0 if $opt_v;
}
else {
return 0 if !$opt_v;
}
}
# ack always selects files that are specified on the command
# line, regardless of filetype. If you want to ack a JPEG,
# and say "ack foo whatever.jpg" it will do it for you.
return 1 if $is_member_of_starting_set{ get_file_id($File::Next::name) };
if ( $dont_ignore_dir_filter ) {
if ( $previous_dir eq $File::Next::dir ) {
if ( $previous_dir_ignore_result ) {
return 0;
}
}
else {
my @dirs = File::Spec->splitdir($File::Next::dir);
my $is_ignoring = 0;
for ( my $i = 0; $i < @dirs; $i++) {
my $dir_rsrc = App::Ack::File->new(File::Spec->catfile(@dirs[0 .. $i]));
my $j = 0;
for my $filter (@ignore_dir_filter) {
if ( $filter->filter($dir_rsrc) ) {
$is_ignoring = !$is_inverted[$j];
}
$j++;
}
}
$previous_dir = $File::Next::dir;
$previous_dir_ignore_result = $is_ignoring;
if ( $is_ignoring ) {
return 0;
}
}
}
# Ignore named pipes found in directory searching. Named
# pipes created by subprocesses get specified on the command
# line, so the rule of "always select whatever is on the
# command line" wins.
return 0 if -p $File::Next::name;
# We can't handle unreadable filenames; report them.
if ( not -r _ ) {
use filetest 'access';
if ( not -R $File::Next::name ) {
if ( $App::Ack::report_bad_filenames ) {
App::Ack::warn( "${File::Next::name}: cannot open file for reading" );
}
return 0;
}
}
my $file = App::Ack::File->new($File::Next::name);
if ( $ifiles_filters && $ifiles_filters->filter($file) ) {
return 0;
}
my $match_found = $direct_filters->filter($file);
# Don't bother invoking inverse filters unless we consider the current file a match.
if ( $match_found && $inverse_filters->filter( $file ) ) {
$match_found = 0;
}
return $match_found;
};
}
# Returns a (fairly) unique identifier for a file.
# Use this function to compare two files to see if they're
# equal (ie. the same file, but with a different path/links/etc).
sub get_file_id {
my ( $filename ) = @_;
if ( $App::Ack::is_windows ) {
return File::Next::reslash( $filename );
}
else {
# XXX Is this the best method? It always hits the FS.
if ( my ( $dev, $inode ) = (stat($filename))[0, 1] ) {
return join(':', $dev, $inode);
}
else {
# XXX This could be better.
return $filename;
}
}
}
# Returns a regex object based on a string and command-line options.
# Dies when the regex $str is undefined (i.e. not given on command line).
sub build_regex {
my $str = shift;
my $opt = shift;
defined $str or App::Ack::die( 'No regular expression found.' );
if ( !$opt->{Q} ) {
# Compile the regex to see if it dies or throws warnings.
local $SIG{__WARN__} = sub { die @_ }; # Anything that warns becomes a die.
my $scratch_regex = eval { qr/$str/ };
if ( not $scratch_regex ) {
my $err = $@;
chomp $err;
if ( $err =~ m{^(.+?); marked by <-- HERE in m/(.+?) <-- HERE} ) {
my ($why, $where) = ($1,$2);
my $pointy = ' ' x (6+length($where)) . '^---HERE';
App::Ack::die( "Invalid regex '$str'\nRegex: $str\n$pointy $why" );
}
else {
App::Ack::die( "Invalid regex '$str'\n$err" );
}
}
}
# Check for lowercaseness before we do any modifications.
my $regex_is_lc = App::Ack::is_lowercase( $str );
$str = quotemeta( $str ) if $opt->{Q};
my $scan_str = $str;
# Whole words only.
if ( $opt->{w} ) {
my $ok = 1;
if ( $str =~ /^\\[wd]/ ) {
# Explicit \w is good.
}
else {
# Can start with \w, (, [ or dot.
if ( $str !~ /^[\w\(\[\.]/ ) {
$ok = 0;
}
}
# Can end with \w, }, ), ], +, *, or dot.
if ( $str !~ /[\w\}\)\]\+\*\?\.]$/ ) {
$ok = 0;
}
# ... unless it's escaped.
elsif ( $str =~ /\\[\}\)\]\+\*\?\.]$/ ) {
$ok = 0;
}
if ( !$ok ) {
App::Ack::die( '-w will not do the right thing if your regex does not begin and end with a word character.' );
}
if ( $str =~ /^\w+$/ ) {
# No need for fancy regex if it's a simple word.
$str = sprintf( '\b(?:%s)\b', $str );
}
else {
$str = sprintf( '(?:^|\b|\s)\K(?:%s)(?=\s|\b|$)', $str );
}
}
if ( $opt->{i} || ($opt->{S} && $regex_is_lc) ) {
$_ = "(?i)$_" for ( $str, $scan_str );
}
my $scan_regex = undef;
my $regex = eval { qr/$str/ };
if ( $regex ) {
if ( $scan_str !~ /\$/ ) {
# No line_scan is possible if there's a $ in the regex.
$scan_regex = eval { qr/$scan_str/m };
}
}
else {
my $err = $@;
chomp $err;
App::Ack::die( "Invalid regex '$str':\n $err" );
}
return ($regex, $scan_regex);
}
my $match_colno;
{
# Number of context lines
my $n_before_ctx_lines;
my $n_after_ctx_lines;
# Array to keep track of lines that might be required for a "before" context
my @before_context_buf;
# Position to insert next line in @before_context_buf
my $before_context_pos;
# Number of "after" context lines still pending
my $after_context_pending;
# Number of latest line that got printed
my $printed_lineno;
my $is_first_match;
state $has_printed_from_any_file = 0;
sub file_loop_normal {
my $files = shift;
$n_before_ctx_lines = $opt_output ? 0 : ($opt_B || 0);
$n_after_ctx_lines = $opt_output ? 0 : ($opt_A || 0);
@before_context_buf = (undef) x $n_before_ctx_lines;
$before_context_pos = 0;
$is_tracking_context = $n_before_ctx_lines || $n_after_ctx_lines;
$is_first_match = 1;
my $nmatches = 0;
while ( defined( my $file = $files->next ) ) {
if ($is_tracking_context) {
$printed_lineno = 0;
$after_context_pending = 0;
if ( $opt_heading ) {
$is_first_match = 1;
}
}
my $needs_line_scan = 1;
if ( !$opt_passthru && !$opt_v ) {
$stats{prescans}++;
if ( $file->may_be_present( $scan_re ) ) {
$file->reset();
}
else {
$needs_line_scan = 0;
}
}
if ( $needs_line_scan ) {
$stats{linescans}++;
$nmatches += print_matches_in_file( $file );
}
last if $opt_1 && $nmatches;
}
return $nmatches;
}
sub print_matches_in_file {
my $file = shift;
my $max_count = $opt_m || -1; # Go negative for no limit so it can never reduce to 0.
my $nmatches = 0;
my $filename = $file->name;
my $has_printed_from_this_file = 0;
my $fh = $file->open;
if ( !$fh ) {
if ( $App::Ack::report_bad_filenames ) {
App::Ack::warn( "$filename: $!" );
}
return 0;
}
my $display_filename = $filename;
if ( $opt_show_filename && $opt_heading && $opt_color ) {
$display_filename = Term::ANSIColor::colored($display_filename, $ENV{ACK_COLOR_FILENAME});
}
# Check for context before the main loop, so we don't pay for it if we don't need it.
if ( $is_tracking_context ) {
local $_ = undef;
$after_context_pending = 0;
my $in_range = range_setup();
while ( <$fh> ) {
chomp;
$match_colno = undef;
$in_range = 1 if ( $using_ranges && !$in_range && $opt_range_start && /$opt_range_start/o );
my $does_match;
if ( $in_range ) {
if ( $opt_v ) {
$does_match = !/$search_re/o;
}
else {
if ( $does_match = /$search_re/o ) {
# @- = @LAST_MATCH_START
# @+ = @LAST_MATCH_END
$match_colno = $-[0] + 1;
}
}
}
if ( $does_match && $max_count ) {
if ( !$has_printed_from_this_file ) {
$stats{filematches}++;
if ( $opt_break && $has_printed_from_any_file ) {
App::Ack::print_blank_line();
}
if ( $opt_show_filename && $opt_heading ) {
App::Ack::say( $display_filename );
}
}
print_line_with_context( $filename, $_, $. );
$has_printed_from_this_file = 1;
$stats{linematches}++;
$nmatches++;
$max_count--;
}
else {
if ( $after_context_pending ) {
# Disable $opt_column since there are no matches in the context lines.
local $opt_column = 0;
print_line_with_options( $filename, $_, $., '-' );
--$after_context_pending;
}
elsif ( $n_before_ctx_lines ) {
# Save line for "before" context.
$before_context_buf[$before_context_pos] = $_;
$before_context_pos = ($before_context_pos+1) % $n_before_ctx_lines;
}
}
$in_range = 0 if ( $using_ranges && $in_range && $opt_range_end && /$opt_range_end/o );
last if ($max_count == 0) && ($after_context_pending == 0);
}
}
elsif ( $opt_passthru ) {
local $_ = undef;
my $in_range = range_setup();
while ( <$fh> ) {
chomp;
$in_range = 1 if ( $using_ranges && !$in_range && $opt_range_start && /$opt_range_start/o );
$match_colno = undef;
if ( $in_range && ($opt_v xor /$search_re/o) ) {
if ( !$opt_v ) {
$match_colno = $-[0] + 1;
}
if ( !$has_printed_from_this_file ) {
if ( $opt_break && $has_printed_from_any_file ) {
App::Ack::print_blank_line();
}
if ( $opt_show_filename && $opt_heading ) {
App::Ack::say( $display_filename );
}
}
print_line_with_options( $filename, $_, $., ':' );
$has_printed_from_this_file = 1;
$nmatches++;
$max_count--;
}
else {
if ( $opt_break && !$has_printed_from_this_file && $has_printed_from_any_file ) {
App::Ack::print_blank_line();
}
print_line_with_options( $filename, $_, $., '-', 1 );
$has_printed_from_this_file = 1;
}
$in_range = 0 if ( $using_ranges && $in_range && $opt_range_end && /$opt_range_end/o );
last if $max_count == 0;
}
}
elsif ( $opt_v ) {
local $_ = undef;
$match_colno = undef;
my $in_range = range_setup();
while ( <$fh> ) {
chomp;
$in_range = 1 if ( $using_ranges && !$in_range && $opt_range_start && /$opt_range_start/o );
if ( $in_range ) {
if ( !/$search_re/o ) {
if ( !$has_printed_from_this_file ) {
if ( $opt_break && $has_printed_from_any_file ) {
App::Ack::print_blank_line();
}
if ( $opt_show_filename && $opt_heading ) {
App::Ack::say( $display_filename );
}
}
print_line_with_context( $filename, $_, $. );
$has_printed_from_this_file = 1;
$nmatches++;
$max_count--;
}
}
$in_range = 0 if ( $using_ranges && $in_range && $opt_range_end && /$opt_range_end/o );
last if $max_count == 0;
}
}
else { # Normal search: No context, no -v, no --passthru
local $_ = undef;
my $last_match_lineno;
my $in_range = range_setup();
while ( <$fh> ) {
chomp;
$in_range = 1 if ( $using_ranges && !$in_range && $opt_range_start && /$opt_range_start/o );
if ( $in_range ) {
$match_colno = undef;
if ( /$search_re/o ) {
$match_colno = $-[0] + 1;
if ( !$has_printed_from_this_file ) {
$stats{filematches}++;
if ( $opt_break && $has_printed_from_any_file ) {
App::Ack::print_blank_line();
}
if ( $opt_show_filename && $opt_heading ) {
App::Ack::say( $display_filename );
}
}
if ( $opt_p ) {
if ( $last_match_lineno ) {
if ( $. > $last_match_lineno + $opt_p ) {
App::Ack::print_blank_line();
}
}
elsif ( !$opt_break && $has_printed_from_any_file ) {
App::Ack::print_blank_line();
}
}
s/[\r\n]+$//;
print_line_with_options( $filename, $_, $., ':' );
$has_printed_from_this_file = 1;
$nmatches++;
$stats{linematches}++;
$max_count--;
$last_match_lineno = $.;
}
}
$in_range = 0 if ( $using_ranges && $in_range && $opt_range_end && /$opt_range_end/o );
last if $max_count == 0;
}
}
return $nmatches;
}
sub print_line_with_options {
my ( $filename, $line, $lineno, $separator, $skip_coloring ) = @_;
$has_printed_from_any_file = 1;
$printed_lineno = $lineno;
my @line_parts;
if ( $opt_show_filename && defined($filename) ) {
my $colno;
$colno = get_match_colno() if $opt_column;
if ( $opt_color ) {
$filename = Term::ANSIColor::colored( $filename, $ENV{ACK_COLOR_FILENAME} );
$lineno = Term::ANSIColor::colored( $lineno, $ENV{ACK_COLOR_LINENO} );
$colno = Term::ANSIColor::colored( $colno, $ENV{ACK_COLOR_COLNO} ) if $opt_column;
}
if ( $opt_heading ) {
push @line_parts, $lineno;
}
else {
push @line_parts, $filename, $lineno;
}
push @line_parts, $colno if $opt_column;
}
if ( $opt_output ) {
while ( $line =~ /$search_re/og ) {
my $output = $opt_output;
if ( @special_vars_used_by_opt_output ) {
no strict;
# Stash copies of the special variables because we can't rely
# on them not changing in the process of doing the s///.
my %keep = map { ($_ => ${$_} // '') } @special_vars_used_by_opt_output;
$keep{_} = $line if exists $keep{_}; # Manually set it because $_ gets reset in a map.
$keep{f} = $filename if exists $keep{f};
my $special_vars_used_by_opt_output = join( '', @special_vars_used_by_opt_output );
$output =~ s/\$([$special_vars_used_by_opt_output])/$keep{$1}/ego;
}
App::Ack::say( join( $separator, @line_parts, $output ) );
}
}
else {
my $underline = '';
# We have to do underlining before any highlighting because highlighting modifies string length.
if ( $opt_underline && !$skip_coloring ) {
while ( $line =~ /$search_re/og ) {
my $match_start = $-[0] // next;
my $match_end = $+[0];
my $match_length = $match_end - $match_start;
last if $match_length <= 0;
my $spaces_needed = $match_start - length $underline;
$underline .= (' ' x $spaces_needed);
$underline .= ('^' x $match_length);
}
}
if ( $opt_color && !$skip_coloring ) {
my $highlighted = 0; # If highlighted, need to escape afterwards.
while ( $line =~ /$search_re/og ) {
my $match_start = $-[0] // next;
my $match_end = $+[0];
my $match_length = $match_end - $match_start;
last if $match_length <= 0;
my $substring = substr( $line, $match_start, $match_length );
my $substitution = Term::ANSIColor::colored( $substring, $ENV{ACK_COLOR_MATCH} );
# Fourth argument replaces the string specified by the first three.
substr( $line, $match_start, $match_length, $substitution );
# Move the offset of where /g left off forward the number of spaces of highlighting.
pos($line) = $match_end + (length( $substitution ) - length( $substring ));
$highlighted = 1;
}
# Reset formatting and delete everything to the end of the line.
$line .= "\e[0m\e[K" if $highlighted;
}
push @line_parts, $line;
App::Ack::say( join( $separator, @line_parts ) );
# Print the underline, if appropriate.
if ( $underline ne '' ) {
# Figure out how many spaces are used per line for the ANSI coloring.
state $chars_used_by_coloring;
if ( !defined($chars_used_by_coloring) ) {
$chars_used_by_coloring = 0;
if ( $opt_color ) {
my $len_fn = sub { length( Term::ANSIColor::colored( 'x', $ENV{$_[0]} ) ) - 1 };
$chars_used_by_coloring += $len_fn->('ACK_COLOR_FILENAME') unless $opt_heading;
$chars_used_by_coloring += $len_fn->('ACK_COLOR_LINENO');
$chars_used_by_coloring += $len_fn->('ACK_COLOR_COLNO') if $opt_column;
}
}
pop @line_parts; # Leave only the stuff on the left.
if ( @line_parts ) {