# Please DO NOT EDIT or send patches for it.
#
# Please take a look at the source from
-# http://github.com/petdance/ack2
+# https://github.com/petdance/ack2
# and submit patches against the individual files
# that build ack.
#
+package main;
+
use strict;
use warnings;
-use 5.008;
+our $VERSION = '2.15_01'; # Check http://beyondgrep.com/ for updates
+use 5.008008;
+use Getopt::Long 2.38 ();
+use Carp 1.04 ();
-# XXX Don't make this so brute force
-# See also: https://github.com/petdance/ack2/issues/89
+use File::Spec ();
-use Getopt::Long 2.36 ();
-use Carp 1.04 ();
+# XXX Don't make this so brute force
+# See also: https://github.com/petdance/ack2/issues/89
-our $VERSION = '2.02';
-# Check http://beyondgrep.com/ for updates
+our $opt_after_context;
+our $opt_before_context;
+our $opt_output;
+our $opt_print0;
+our $opt_color;
+our $opt_heading;
+our $opt_show_filename;
+our $opt_regex;
+our $opt_break;
+our $opt_count;
+our $opt_v;
+our $opt_m;
+our $opt_g;
+our $opt_f;
+our $opt_lines;
+our $opt_L;
+our $opt_l;
+our $opt_passthru;
+our $opt_column;
+# flag if we need any context tracking
+our $is_tracking_context;
# These are all our globals.
# Do preliminary arg checking;
my $env_is_usable = 1;
- for ( @ARGV ) {
- last if ( $_ eq '--' );
+ for my $arg ( @ARGV ) {
+ last if ( $arg eq '--' );
- # Get the --thpppt and --bar checking out of the way.
- /^--th[pt]+t+$/ && App::Ack::_thpppt($_);
- /^--bar$/ && App::Ack::_bar();
+ # Get the --thpppt, --bar, --cathy checking out of the way.
+ $arg =~ /^--th[pt]+t+$/ and App::Ack::_thpppt($arg);
+ $arg eq '--bar' and App::Ack::_bar();
+ $arg eq '--cathy' and App::Ack::_cathy();
# See if we want to ignore the environment. (Don't tell Al Gore.)
- if ( /^--(no)?env$/ ) {
- $env_is_usable = defined $1 ? 0 : 1;
- }
+ $arg eq '--env' and $env_is_usable = 1;
+ $arg eq '--noenv' and $env_is_usable = 0;
}
+
if ( !$env_is_usable ) {
my @keys = ( 'ACKRC', grep { /^ACK_/ } keys %ENV );
delete @ENV{@keys};
}
- App::Ack::load_colors();
+ load_colors();
Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
Getopt::Long::Configure('pass_through', 'no_auto_abbrev');
sub _compile_descend_filter {
my ( $opt ) = @_;
- my $idirs = $opt->{idirs};
- my $dont_ignore_dirs = $opt->{no_ignore_dirs};
+ 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};
-
- my %ignore_dirs;
+ return unless $idirs;
- foreach my $idir (@{$idirs}) {
- if ( $idir =~ /^(\w+):(.*)/ ) {
- if ( $1 eq 'is') {
- $ignore_dirs{$2} = 1;
- }
- else {
- Carp::croak( 'Non-is filters are not yet supported for --ignore-dir' );
- }
- }
- else {
- Carp::croak( qq{Invalid filter specification "$idir"} );
- }
- }
+ $idirs = $opt->{idirs};
return sub {
- return !exists $ignore_dirs{$_} && !exists $ignore_dirs{$File::Next::dir};
+ my $resource = App::Ack::Resource::Basic->new($File::Next::dir);
+ return !grep { $_->filter($resource) } @{$idirs};
};
}
sub _compile_file_filter {
my ( $opt, $start ) = @_;
- my $ifiles = $opt->{ifiles};
- $ifiles ||= [];
+ my $ifiles_filters = $opt->{ifiles};
- my @ifiles_filters = map {
- my $filter;
+ my $filters = $opt->{'filters'} || [];
+ my $direct_filters = App::Ack::Filter::Collection->new();
+ my $inverse_filters = App::Ack::Filter::Collection->new();
- if ( /^(\w+):(.+)/ ) {
- my ($how,$what) = ($1,$2);
- $filter = App::Ack::Filter->create_filter($how, split(/,/, $what));
+ foreach my $filter (@{$filters}) {
+ if ($filter->is_inverted()) {
+ # We want to check if files match the uninverted filters
+ $inverse_filters->add($filter->invert());
}
else {
- Carp::croak( qq{Invalid filter specification "$_"} );
+ $direct_filters->add($filter);
}
- $filter
- } @{$ifiles};
-
- my $filters = $opt->{'filters'} || [];
- my $inverse_filters = [ grep { $_->is_inverted() } @{$filters} ];
- @{$filters} = grep { !$_->is_inverted() } @{$filters};
-
- my %is_member_of_starting_set = map { (App::Ack::get_file_id($_) => 1) } @{$start};
+ }
- my $ignore_dir_list = $opt->{idirs};
- my $dont_ignore_dir_list = $opt->{no_ignore_dirs};
+ my %is_member_of_starting_set = map { (get_file_id($_) => 1) } @{$start};
- my %ignore_dir_set;
- my %dont_ignore_dir_set;
+ 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;
- foreach my $filter (@{ $ignore_dir_list }) {
- if ( $filter =~ /^(\w+):(.*)/ ) {
- if ( $1 eq 'is' ) {
- $ignore_dir_set{ $2 } = 1;
- } else {
- Carp::croak( 'Non-is filters are not yet supported for --ignore-dir' );
+ return sub {
+ if ( $opt_g ) {
+ if ( $File::Next::name =~ /$opt_regex/ && $opt_v ) {
+ return;
}
- } else {
- Carp::croak( qq{Invalid filter specification "$filter"} );
- }
- }
- foreach my $filter (@{ $dont_ignore_dir_list }) {
- if ( $filter =~ /^(\w+):(.*)/ ) {
- if ( $1 eq 'is' ) {
- $dont_ignore_dir_set{ $2 } = 1;
- } else {
- Carp::croak( 'Non-is filters are not yet supported for --ignore-dir' );
+ if ( $File::Next::name !~ /$opt_regex/ && !$opt_v ) {
+ return;
}
- } else {
- Carp::croak( qq{Invalid filter specification "$filter"} );
}
- }
-
- return sub {
# 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{ App::Ack::get_file_id($File::Next::name) };
+ 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);
- if ( $dont_ignore_dir_list ) {
- my ( undef, $dirname ) = File::Spec->splitpath($File::Next::name);
- my @dirs = File::Spec->splitdir($dirname);
+ my $is_ignoring = 0;
- my $is_ignoring = 0;
+ for ( my $i = 0; $i < @dirs; $i++) {
+ my $dir_rsrc = App::Ack::Resource::Basic->new(File::Spec->catfile(@dirs[0 .. $i]));
- foreach my $dir ( @dirs ) {
- if ( $ignore_dir_set{ $dir } ) {
- $is_ignoring = 1;
+ my $j = 0;
+ for my $filter (@ignore_dir_filter) {
+ if ( $filter->filter($dir_rsrc) ) {
+ $is_ignoring = !$is_inverted[$j];
+ }
+ $j++;
+ }
}
- elsif ( $dont_ignore_dir_set{ $dir } ) {
- $is_ignoring = 0;
+
+ $previous_dir = $File::Next::dir;
+ $previous_dir_ignore_result = $is_ignoring;
+
+ if ( $is_ignoring ) {
+ return 0;
}
}
- if ( $is_ignoring ) {
- return 0;
- }
}
# Ignore named pipes found in directory searching. Named
# command line" wins.
return 0 if -p $File::Next::name;
- foreach my $filter (@ifiles_filters) {
- my $resource = App::Ack::Resource::Basic->new($File::Next::name);
- return 0 if ! $resource || $filter->filter($resource);
- }
- my $match_found = 1;
- if ( @{$filters} ) {
- $match_found = 0;
+ # We can't handle unreadable filenames; report them.
+ if ( not -r _ ) {
+ use filetest 'access';
- foreach my $filter (@{$filters}) {
- my $resource = App::Ack::Resource::Basic->new($File::Next::name);
- return 0 if ! $resource;
- if ($filter->filter($resource)) {
- $match_found = 1;
- last;
+ 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 $resource = App::Ack::Resource::Basic->new($File::Next::name);
+
+ if ( $ifiles_filters && $ifiles_filters->filter($resource) ) {
+ return 0;
+ }
+
+ my $match_found = $direct_filters->filter($resource);
+
# Don't bother invoking inverse filters unless we consider the current resource a match
- if ( $match_found && @{$inverse_filters} ) {
- foreach my $filter ( @{$inverse_filters} ) {
- my $resource = App::Ack::Resource::Basic->new($File::Next::name);
- return 0 if ! $resource;
- if ( not $filter->filter( $resource ) ) {
- $match_found = 0;
- last;
- }
- }
+ if ( $match_found && $inverse_filters->filter( $resource ) ) {
+ $match_found = 0;
}
return $match_found;
};
my $resource = shift;
my $ors = shift;
- my @types = App::Ack::filetypes( $resource );
+ my @types = filetypes( $resource );
my $types = join( ',', @types );
my $arrow = @types ? ' => ' : ' =>';
App::Ack::print( $resource->name, $arrow, join( ',', @types ), $ors );
return;
}
-sub main {
- my @arg_sources = App::Ack::retrieve_arg_sources();
+# Set default colors, load Term::ANSIColor
+sub load_colors {
+ eval 'use Term::ANSIColor 1.10 ()';
+ eval 'use Win32::Console::ANSI' if $App::Ack::is_windows;
- my $opt = App::Ack::ConfigLoader::process_args( @arg_sources );
+ $ENV{ACK_COLOR_MATCH} ||= 'black on_yellow';
+ $ENV{ACK_COLOR_FILENAME} ||= 'bold green';
+ $ENV{ACK_COLOR_LINENO} ||= 'bold yellow';
- $App::Ack::report_bad_filenames = !$opt->{dont_report_bad_filenames};
+ return;
+}
- if ( $opt->{flush} ) {
- $| = 1;
- }
+sub filetypes {
+ my ( $resource ) = @_;
- if ( not defined $opt->{color} ) {
- $opt->{color} = !App::Ack::output_to_pipe() && !$App::Ack::is_windows;
- }
- if ( not defined $opt->{heading} and not defined $opt->{break} ) {
- $opt->{heading} = $opt->{break} = !App::Ack::output_to_pipe();
- }
+ my @matches;
- if ( defined($opt->{H}) || defined($opt->{h}) ) {
- $opt->{show_filename}= $opt->{H} && !$opt->{h};
- }
+ foreach my $k (keys %App::Ack::mappings) {
+ my $filters = $App::Ack::mappings{$k};
- if ( my $output = $opt->{output} ) {
- $output =~ s{\\}{\\\\}g;
- $output =~ s{"}{\\"}g;
- $opt->{output} = qq{"$output"};
+ foreach my $filter (@{$filters}) {
+ # clone the resource
+ my $clone = $resource->clone;
+ if ( $filter->filter($clone) ) {
+ push @matches, $k;
+ last;
+ }
+ }
}
- my $resources;
- if ( $App::Ack::is_filter_mode && !$opt->{files_from} ) { # probably -x
- $resources = App::Ack::Resources->from_stdin( $opt );
- my $regex = $opt->{regex};
- $regex = shift @ARGV if not defined $regex;
- $opt->{regex} = App::Ack::build_regex( $regex, $opt );
+ # http://search.cpan.org/dist/Perl-Critic/lib/Perl/Critic/Policy/Subroutines/ProhibitReturnSort.pm
+ @matches = sort @matches;
+ return @matches;
+}
+
+# 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 {
- if ( $opt->{f} || $opt->{lines} ) {
- if ( $opt->{regex} ) {
- App::Ack::warn( "regex ($opt->{regex}) specified with -f or --lines" );
- App::Ack::exit_from_ack( 0 ); # XXX the 0 is misleading
- }
+ # XXX is this the best method? it always hits the FS
+ if( my ( $dev, $inode ) = (stat($filename))[0, 1] ) {
+ return join(':', $dev, $inode);
}
else {
- my $regex = $opt->{regex};
- $regex = shift @ARGV if not defined $regex;
- $opt->{regex} = App::Ack::build_regex( $regex, $opt );
- }
- my @start;
- if ( not defined $opt->{files_from} ) {
- @start = @ARGV;
- }
- if ( !exists($opt->{show_filename}) ) {
- unless(@start == 1 && !(-d $start[0])) {
- $opt->{show_filename} = 1;
- }
+ # XXX this could be better
+ return $filename;
}
+ }
+}
- if ( defined $opt->{files_from} ) {
- $resources = App::Ack::Resources->from_file( $opt, $opt->{files_from} );
- exit 1 unless $resources;
- }
- 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" );
- }
- }
+# 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).
- $opt->{file_filter} = _compile_file_filter($opt, \@start);
- $opt->{descend_filter} = _compile_descend_filter($opt);
+sub build_regex {
+ my $str = shift;
+ my $opt = shift;
- $resources = App::Ack::Resources->from_argv( $opt, \@start );
- }
- }
- App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager};
+ defined $str or App::Ack::die( 'No regular expression found.' );
- my $print_filenames = $opt->{show_filename};
- my $max_count = $opt->{m};
- my $ors = $opt->{print0} ? "\0" : "\n";
- my $only_first = $opt->{1};
+ $str = quotemeta( $str ) if $opt->{Q};
+ if ( $opt->{w} ) {
+ my $pristine_str = $str;
- my $nmatches = 0;
- my $total_count = 0;
-RESOURCES:
- while ( my $resource = $resources->next ) {
- # XXX this variable name combined with what we're trying
- # to do makes no sense.
+ $str = "(?:$str)";
+ $str = "\\b$str" if $pristine_str =~ /^\w/;
+ $str = "$str\\b" if $pristine_str =~ /\w$/;
+ }
- # XXX Combine the -f and -g functions
- if ( $opt->{f} ) {
- # XXX printing should probably happen inside of App::Ack
- if ( $opt->{show_types} ) {
- show_types( $resource, $ors );
- }
- else {
- App::Ack::print( $resource->name, $ors );
- }
- ++$nmatches;
- last RESOURCES if defined($max_count) && $nmatches >= $max_count;
- }
- elsif ( $opt->{g} ) {
- my $is_match = ( $resource->name =~ /$opt->{regex}/o );
- if ( $opt->{v} ? !$is_match : $is_match ) {
- if ( $opt->{show_types} ) {
- show_types( $resource, $ors );
- }
- else {
- App::Ack::print( $resource->name, $ors );
- }
- ++$nmatches;
- last RESOURCES if defined($max_count) && $nmatches >= $max_count;
- }
- }
- elsif ( $opt->{lines} ) {
- my $print_filename = $opt->{show_filename};
- my $passthru = $opt->{passthru};
+ my $regex_is_lc = $str eq lc $str;
+ if ( $opt->{i} || ($opt->{smart_case} && $regex_is_lc) ) {
+ $str = "(?i)$str";
+ }
- my %line_numbers;
- foreach my $line ( @{ $opt->{lines} } ) {
- my @lines = split /,/, $line;
- @lines = map {
- /^(\d+)-(\d+)$/
- ? ( $1 .. $2 )
- : $_
- } @lines;
- @line_numbers{@lines} = (1) x @lines;
- }
+ my $re = eval { qr/$str/m };
+ if ( !$re ) {
+ die "Invalid regex '$str':\n $@";
+ }
- my $filename = $resource->name;
+ return $re;
- local $opt->{color} = 0;
+}
- App::Ack::iterate($resource, $opt, sub {
- chomp;
+my $match_column_number;
- if ( $line_numbers{$.} ) {
- App::Ack::print_line_with_context($opt, $filename, $_, $.);
- }
- elsif ( $passthru ) {
- App::Ack::print_line_with_options($opt, $filename, $_, $., ':');
- }
- return 1;
- });
- }
- elsif ( $opt->{count} ) {
- my $matches_for_this_file = App::Ack::count_matches_in_resource( $resource, $opt );
+{
- unless ( $opt->{show_filename} ) {
- $total_count += $matches_for_this_file;
- next RESOURCES;
- }
+# number of context lines
+my $n_before_ctx_lines;
+my $n_after_ctx_lines;
- if ( !$opt->{l} || $matches_for_this_file > 0) {
- if ( $print_filenames ) {
- App::Ack::print( $resource->name, ':', $matches_for_this_file, $ors );
- }
- else {
- App::Ack::print( $matches_for_this_file, $ors );
- }
- }
- }
- elsif ( $opt->{l} || $opt->{L} ) {
- my $is_match = App::Ack::resource_has_match( $resource, $opt );
+# 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;
- if ( $opt->{L} ? !$is_match : $is_match ) {
- App::Ack::print( $resource->name, $ors );
- ++$nmatches;
+# number of "after" context lines still pending
+my $after_context_pending;
- last RESOURCES if $only_first;
- last RESOURCES if defined($max_count) && $nmatches >= $max_count;
- }
- }
- else {
- $nmatches += App::Ack::print_matches_in_resource( $resource, $opt );
- if ( $nmatches && $only_first ) {
- last RESOURCES;
- }
- }
- }
+# number of latest line that got printed
+my $printed_line_no;
- if ( $opt->{count} && !$opt->{show_filename} ) {
- App::Ack::print( $total_count, "\n" );
- }
+my $is_iterating;
- close $App::Ack::fh;
- App::Ack::exit_from_ack( $nmatches );
+my $is_first_match;
+my $has_printed_something;
+
+BEGIN {
+ $has_printed_something = 0;
}
+# setup context tracking variables
+sub setup_line_context {
-=head1 NAME
+ $n_before_ctx_lines = $opt_output ? 0 : ($opt_before_context || 0);
+ $n_after_ctx_lines = $opt_output ? 0 : ($opt_after_context || 0);
-ack - grep-like text finder
+ @before_context_buf = (undef) x $n_before_ctx_lines;
+ $before_context_pos = 0;
-=head1 SYNOPSIS
+ $is_tracking_context = $n_before_ctx_lines || $n_after_ctx_lines;
- ack [options] PATTERN [FILE...]
- ack -f [options] [DIRECTORY...]
+ $is_first_match = 1;
-=head1 DESCRIPTION
+ return;
+}
-Ack is designed as a replacement for 99% of the uses of F<grep>.
+# adjust context tracking variables when entering a new file
+sub setup_line_context_for_file {
-Ack searches the named input FILEs (or standard input if no files
-are named, or the file name - is given) for lines containing a match
-to the given PATTERN. By default, ack prints the matching lines.
+ $printed_line_no = 0;
+ $after_context_pending = 0;
+ if ( $opt_heading && !$opt_lines ) {
+ $is_first_match = 1;
+ }
-PATTERN is a Perl regular expression. Perl regular expressions
-are commonly found in other programming languages, but for the particulars
-of their behavior, please consult
-L<http://perldoc.perl.org/perlreref.html|perlreref>. If you don't know
-how to use regular expression but are interested in learning, you may
-consult L<http://perldoc.perl.org/perlretut.html|perlretut>. If you do not
-need or want ack to use regular expressions, please see the
-C<-Q>/C<--literal> option.
+ return;
+}
-Ack can also list files that would be searched, without actually
-searching them, to let you take advantage of ack's file-type filtering
-capabilities.
+=for Developers
-=head1 FILE SELECTION
+This subroutine jumps through a number of optimization hoops to
+try to be fast in the more common use cases of ack. For one thing,
+in non-context tracking searches (not using -A, -B, or -C),
+conditions that normally would be checked inside the loop happen
+outside, resulting in three nearly identical loops for -v, --passthru,
+and normal searching. Any changes that happen to one should propagate
+to the others if they make sense. The non-context branches also inline
+does_match for performance reasons; any relevant changes that happen here
+must also happen there.
-If files are not specified for searching, either on the command
-line or piped in with the C<-x> option, I<ack> delves into
-subdirectories selecting files for searching.
+=cut
-I<ack> is intelligent about the files it searches. It knows about
-certain file types, based on both the extension on the file and,
-in some cases, the contents of the file. These selections can be
-made with the B<--type> option.
+sub print_matches_in_resource {
+ my ( $resource, $opt ) = @_;
-With no file selection, I<ack> searches through regular files that
-are not explicitly excluded by B<--ignore-dir> and B<--ignore-file>
-options, either present in F<ackrc> files or on the command line.
+ my $max_count = $opt_m || -1;
+ my $nmatches = 0;
+ my $filename = $resource->name;
+ my $ors = $opt_print0 ? "\0" : "\n";
-The default options for I<ack> ignore certain files and directories. These
-include:
+ my $has_printed_for_this_resource = 0;
-=over 4
+ $is_iterating = 1;
-=item * Backup files: Files matching F<#*#> or ending with F<~>.
+ my $fh = $resource->open();
+ if ( !$fh ) {
+ if ( $App::Ack::report_bad_filenames ) {
+ App::Ack::warn( "$filename: $!" );
+ }
+ return 0;
+ }
-=item * Coredumps: Files matching F<core.\d+>
+ my $display_filename = $filename;
+ if ( $opt_show_filename && $opt_heading && $opt_color ) {
+ $display_filename = Term::ANSIColor::colored($display_filename, $ENV{ACK_COLOR_FILENAME});
+ }
-=item * Version control directories like F<.svn> and F<.git>.
+ # check for context before the main loop, so we don't
+ # pay for it if we don't need it
+ if ( $is_tracking_context ) {
+ $after_context_pending = 0;
+ while ( <$fh> ) {
+ if ( does_match($opt, $_) && $max_count ) {
+ if ( !$has_printed_for_this_resource ) {
+ if ( $opt_break && $has_printed_something ) {
+ App::Ack::print_blank_line();
+ }
+ if ( $opt_show_filename && $opt_heading ) {
+ App::Ack::print_filename( $display_filename, $ors );
+ }
+ }
+ print_line_with_context($opt, $filename, $_, $.);
+ $has_printed_for_this_resource = 1;
+ $nmatches++;
+ $max_count--;
+ }
+ elsif ( $opt_passthru ) {
+ chomp; # XXX proper newline handling?
+ # XXX inline this call?
+ if ( $opt_break && !$has_printed_for_this_resource && $has_printed_something ) {
+ App::Ack::print_blank_line();
+ }
+ print_line_with_options($opt, $filename, $_, $., ':');
+ $has_printed_for_this_resource = 1;
+ }
+ else {
+ chomp; # XXX proper newline handling?
+ print_line_if_context($opt, $filename, $_, $., '-');
+ }
-=back
+ last if ($max_count == 0) && ($after_context_pending == 0);
+ }
+ }
+ else {
+ local $_;
+
+ if ( $opt_passthru ) {
+ while ( <$fh> ) {
+ $match_column_number = undef;
+ if ( $opt_v ? !/$opt_regex/o : /$opt_regex/o ) {
+ if ( !$opt_v ) {
+ $match_column_number = $-[0] + 1;
+ }
+ if ( !$has_printed_for_this_resource ) {
+ if ( $opt_break && $has_printed_something ) {
+ App::Ack::print_blank_line();
+ }
+ if ( $opt_show_filename && $opt_heading ) {
+ App::Ack::print_filename( $display_filename, $ors );
+ }
+ }
+ print_line_with_context($opt, $filename, $_, $.);
+ $has_printed_for_this_resource = 1;
+ $nmatches++;
+ $max_count--;
+ }
+ else {
+ chomp; # XXX proper newline handling?
+ if ( $opt_break && !$has_printed_for_this_resource && $has_printed_something ) {
+ App::Ack::print_blank_line();
+ }
+ print_line_with_options($opt, $filename, $_, $., ':');
+ $has_printed_for_this_resource = 1;
+ }
+ last unless $max_count != 0;
+ }
+ }
+ elsif ( $opt_v ) {
+ $match_column_number = undef;
+ while ( <$fh> ) {
+ if ( !/$opt_regex/o ) {
+ if ( !$has_printed_for_this_resource ) {
+ if ( $opt_break && $has_printed_something ) {
+ App::Ack::print_blank_line();
+ }
+ if ( $opt_show_filename && $opt_heading ) {
+ App::Ack::print_filename( $display_filename, $ors );
+ }
+ }
+ print_line_with_context($opt, $filename, $_, $.);
+ $has_printed_for_this_resource = 1;
+ $nmatches++;
+ $max_count--;
+ }
+ last unless $max_count != 0;
+ }
+ }
+ else {
+ # XXX unroll first match check ($has_printed_for_this_resource)
+ # XXX what if this is a *huge* file? (see also -l)
+ my $contents = do {
+ local $/;
+ <$fh>;
+ };
+
+ my $prev_match_end = 0;
+ my $line_no = 1;
+
+ $match_column_number = undef;
+ while ( $contents =~ /$opt_regex/og ) {
+ my $match_start = $-[0];
+ my $match_end = $+[0];
+
+ pos($contents) = $prev_match_end;
+ $prev_match_end = $match_end;
+
+ while ( $contents =~ /\n/og && $-[0] < $match_start ) {
+ $line_no++;
+ }
-Run I<ack> with the C<--dump> option to see what settings are set.
+ my $start_line = rindex($contents, "\n", $match_start);
+ my $end_line = index($contents, "\n", $match_end);
-However, I<ack> always searches the files given on the command line,
-no matter what type. If you tell I<ack> to search in a coredump,
-it will search in a coredump.
+ if ( $start_line == -1 ) {
+ $start_line = 0;
+ }
+ else {
+ $start_line++;
+ }
-=head1 DIRECTORY SELECTION
+ if ( $end_line == -1 ) {
+ $end_line = length($contents);
+ }
+ else {
+ $end_line--;
+ }
+ $match_column_number = $match_start - $start_line + 1;
+ if ( !$has_printed_for_this_resource ) {
+ if ( $opt_break && $has_printed_something ) {
+ App::Ack::print_blank_line();
+ }
+ if ( $opt_show_filename && $opt_heading ) {
+ App::Ack::print_filename( $display_filename, $ors );
+ }
+ }
+ my $line = substr($contents, $start_line, $end_line - $start_line + 1);
+ $line =~ s/[\r\n]+$//g;
+ print_line_with_options($opt, $filename, $line, $line_no, ':');
-I<ack> descends through the directory tree of the starting directories
-specified. If no directories are specified, the current working directory is
-used. However, it will ignore the shadow directories used by
-many version control systems, and the build directories used by the
-Perl MakeMaker system. You may add or remove a directory from this
-list with the B<--[no]ignore-dir> option. The option may be repeated
-to add/remove multiple directories from the ignore list.
+ pos($contents) = $end_line + 1;
-For a complete list of directories that do not get searched, run
-C<ack --dump>.
+ $has_printed_for_this_resource = 1;
+ $nmatches++;
+ $max_count--;
-=head1 WHEN TO USE GREP
+ last unless $max_count != 0;
+ }
+ }
-I<ack> trumps I<grep> as an everyday tool 99% of the time, but don't
-throw I<grep> away, because there are times you'll still need it.
+ }
-E.g., searching through huge files looking for regexes that can be
-expressed with I<grep> syntax should be quicker with I<grep>.
+ $is_iterating = 0; # XXX this won't happen on an exception
+ # then again, do we care? ack doesn't really
+ # handle exceptions anyway.
-If your script or parent program uses I<grep> C<--quiet> or C<--silent>
-or needs exit 2 on IO error, use I<grep>.
+ return $nmatches;
+}
-=head1 OPTIONS
+sub print_line_with_options {
+ my ( $opt, $filename, $line, $line_no, $separator ) = @_;
-=over 4
+ $has_printed_something = 1;
+ $printed_line_no = $line_no;
-=item B<-A I<NUM>>, B<--after-context=I<NUM>>
+ my $ors = $opt_print0 ? "\0" : "\n";
-Print I<NUM> lines of trailing context after matching lines.
+ my @line_parts;
-=item B<-B I<NUM>>, B<--before-context=I<NUM>>
+ if( $opt_color ) {
+ $filename = Term::ANSIColor::colored($filename,
+ $ENV{ACK_COLOR_FILENAME});
+ $line_no = Term::ANSIColor::colored($line_no,
+ $ENV{ACK_COLOR_LINENO});
+ }
-Print I<NUM> lines of leading context before matching lines.
+ if($opt_show_filename) {
+ if( $opt_heading ) {
+ push @line_parts, $line_no;
+ }
+ else {
+ push @line_parts, $filename, $line_no;
+ }
-=item B<--[no]break>
+ if( $opt_column ) {
+ push @line_parts, get_match_column();
+ }
+ }
+ if( $opt_output ) {
+ while ( $line =~ /$opt_regex/og ) {
+ # XXX We need to stop using eval() for --output. See https://github.com/petdance/ack2/issues/421
+ my $output = eval $opt_output;
+ App::Ack::print( join( $separator, @line_parts, $output ), $ors );
+ }
+ }
+ else {
+ if ( $opt_color ) {
+ $line =~ /$opt_regex/o; # this match is redundant, but we need
+ # to perfom it in order to get if
+ # capture groups are set
-Print a break between results from different files. On by default
-when used interactively.
+ if ( @+ > 1 ) { # if we have captures
+ while ( $line =~ /$opt_regex/og ) {
+ my $offset = 0; # additional offset for when we add stuff
+ my $previous_match_end = 0;
-=item B<-C [I<NUM>]>, B<--context[=I<NUM>]>
+ for ( my $i = 1; $i < @+; $i++ ) {
+ my ( $match_start, $match_end ) = ( $-[$i], $+[$i] );
-Print I<NUM> lines (default 2) of context around matching lines.
+ next unless defined($match_start);
+ next if $match_start < $previous_match_end;
-=item B<-c>, B<--count>
+ my $substring = substr( $line,
+ $offset + $match_start, $match_end - $match_start );
+ my $substitution = Term::ANSIColor::colored( $substring,
+ $ENV{ACK_COLOR_MATCH} );
-Suppress normal output; instead print a count of matching lines for
-each input file. If B<-l> is in effect, it will only show the
-number of lines for each file that has lines matching. Without
-B<-l>, some line counts may be zeroes.
+ substr( $line, $offset + $match_start,
+ $match_end - $match_start, $substitution );
-If combined with B<-h> (B<--no-filename>) ack outputs only one total
-count.
+ $previous_match_end = $match_end; # offsets do not need to be applied
+ $offset += length( $substitution ) - length( $substring );
+ }
-=item B<--[no]color>, B<--[no]colour>
+ pos($line) = $+[0] + $offset;
+ }
+ }
+ else {
+ my $matched = 0; # flag; if matched, need to escape afterwards
-B<--color> highlights the matching text. B<--nocolor> supresses
-the color. This is on by default unless the output is redirected.
+ while ( $line =~ /$opt_regex/og ) {
-On Windows, this option is off by default unless the
-L<Win32::Console::ANSI> module is installed or the C<ACK_PAGER_COLOR>
-environment variable is used.
+ $matched = 1;
+ my ( $match_start, $match_end ) = ($-[0], $+[0]);
+ next unless defined($match_start);
-=item B<--color-filename=I<color>>
+ my $substring = substr( $line, $match_start,
+ $match_end - $match_start );
+ my $substitution = Term::ANSIColor::colored( $substring,
+ $ENV{ACK_COLOR_MATCH} );
-Sets the color to be used for filenames.
+ substr( $line, $match_start, $match_end - $match_start,
+ $substitution );
-=item B<--color-match=I<color>>
+ pos($line) = $match_end +
+ (length( $substitution ) - length( $substring ));
+ }
+ # XXX why do we do this?
+ $line .= "\033[0m\033[K" if $matched;
+ }
+ }
-Sets the color to be used for matches.
+ push @line_parts, $line;
+ App::Ack::print( join( $separator, @line_parts ), $ors );
+ }
-=item B<--color-lineno=I<color>>
+ return;
+}
-Sets the color to be used for line numbers.
+sub iterate {
+ my ( $resource, $opt, $cb ) = @_;
-=item B<--[no]column>
+ $is_iterating = 1;
-Show the column number of the first match. This is helpful for
-editors that can place your cursor at a given position.
+ my $fh = $resource->open();
+ if ( !$fh ) {
+ if ( $App::Ack::report_bad_filenames ) {
+ App::Ack::warn( $resource->name . ': ' . $! );
+ }
+ return;
+ }
-=item B<--create-ackrc>
+ # Check for context before the main loop, so we don't pay for it if we don't need it.
+ if ( $is_tracking_context ) {
+ $after_context_pending = 0;
-Dumps the default ack options to standard output. This is useful for
-when you want to customize the defaults.
+ while ( <$fh> ) {
+ last unless $cb->();
+ }
+ }
+ else {
+ local $_;
-=item B<--dump>
+ while ( <$fh> ) {
+ last unless $cb->();
+ }
+ }
-Writes the list of options loaded and where they came from to standard
-output. Handy for debugging.
+ $is_iterating = 0; # XXX this won't happen on an exception
+ # then again, do we care? ack doesn't really
+ # handle exceptions anyway.
-=item B<--[no]env>
+ return;
+}
-B<--noenv> disables all environment processing. No F<.ackrc> is
-read and all environment variables are ignored. By default, F<ack>
-considers F<.ackrc> and settings in the environment.
+sub print_line_with_context {
+ my ( $opt, $filename, $matching_line, $line_no ) = @_;
-=item B<--flush>
+ my $ors = $opt_print0 ? "\0" : "\n";
+ my $is_tracking_context = $opt_after_context || $opt_before_context;
-B<--flush> flushes output immediately. This is off by default
-unless ack is running interactively (when output goes to a pipe or
-file).
+ $matching_line =~ s/[\r\n]+$//g;
-=item B<-f>
+ # check if we need to print context lines first
+ if( $is_tracking_context ) {
+ my $before_unprinted = $line_no - $printed_line_no - 1;
+ if ( !$is_first_match && ( !$printed_line_no || $before_unprinted > $n_before_ctx_lines ) ) {
+ App::Ack::print('--', $ors);
+ }
-Only print the files that would be searched, without actually doing
-any searching. PATTERN must not be specified, or it will be taken
-as a path to search.
+ # We want at most $n_before_ctx_lines of context
+ if ( $before_unprinted > $n_before_ctx_lines ) {
+ $before_unprinted = $n_before_ctx_lines;
+ }
-=item B<--files-from=I<FILE>>
+ while ( $before_unprinted > 0 ) {
+ my $line = $before_context_buf[($before_context_pos - $before_unprinted + $n_before_ctx_lines) % $n_before_ctx_lines];
-The list of files to be searched is specified in I<FILE>. The list of
-files are seperated by newlines. If I<FILE> is C<->, the list is loaded
-from standard input.
+ chomp $line;
-=item B<--[no]filter>
+ # Disable $opt->{column} since there are no matches in the context lines
+ local $opt_column = 0;
-Forces ack to act as if it were recieving input via a pipe.
+ print_line_with_options($opt, $filename, $line, $line_no-$before_unprinted, '-');
+ $before_unprinted--;
+ }
+ }
-=item B<--[no]follow>
+ print_line_with_options($opt, $filename, $matching_line, $line_no, ':');
-Follow or don't follow symlinks, other than whatever starting files
-or directories were specified on the command line.
+ # We want to get the next $n_after_ctx_lines printed
+ $after_context_pending = $n_after_ctx_lines;
-This is off by default.
+ $is_first_match = 0;
-=item B<-g I<PATTERN>>
+ return;
+}
-Print files where the relative path + filename matches I<PATTERN>.
+# print the line only if it's part of a context we need to display
+sub print_line_if_context {
+ my ( $opt, $filename, $line, $line_no, $separator ) = @_;
-=item B<--[no]group>
+ if ( $after_context_pending ) {
+ # Disable $opt->{column} since there are no matches in the context lines
+ local $opt_column = 0;
+ print_line_with_options( $opt, $filename, $line, $line_no, $separator );
+ --$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;
+ }
-B<--group> groups matches by file name. This is the default
-when used interactively.
+ return;
+}
-B<--nogroup> prints one result per line, like grep. This is the
-default when output is redirected.
+}
-=item B<-H>, B<--with-filename>
+# does_match() MUST have an $opt_regex set.
-Print the filename for each match. This is the default unless searching
-a single explicitly specified file.
+=for Developers
-=item B<-h>, B<--no-filename>
+This subroutine is inlined a few places in print_matches_in_resource
+for performance reasons, so any changes here must be copied there as
+well.
-Suppress the prefixing of filenames on output when multiple files are
-searched.
+=cut
-=item B<--[no]heading>
+sub does_match {
+ my ( $opt, $line ) = @_;
-Print a filename heading above each file's results. This is the default
-when used interactively.
+ $match_column_number = undef;
-=item B<--help>, B<-?>
+ if ( $opt_v ) {
+ return ( $line !~ /$opt_regex/o );
+ }
+ else {
+ if ( $line =~ /$opt_regex/o ) {
+ # @- = @LAST_MATCH_START
+ # @+ = @LAST_MATCH_END
+ $match_column_number = $-[0] + 1;
+ return 1;
+ }
+ else {
+ return;
+ }
+ }
+}
-Print a short help statement.
+sub get_match_column {
+ return $match_column_number;
+}
-=item B<--help-types>, B<--help=types>
+sub resource_has_match {
+ my ( $resource, $opt ) = @_;
-Print all known types.
+ my $has_match = 0;
+ my $fh = $resource->open();
+ if ( !$fh ) {
+ if ( $App::Ack::report_bad_filenames ) {
+ App::Ack::warn( $resource->name . ': ' . $! );
+ }
+ }
+ else {
+ if ( $opt_v ) {
+ while ( <$fh> ) {
+ if (!/$opt_regex/o) {
+ $has_match = 1;
+ last;
+ }
+ }
+ }
+ else {
+ # XXX read in chunks
+ # XXX only do this for certain file sizes?
+ my $content = do {
+ local $/;
+ <$fh>;
+ };
+ $has_match = $content =~ /$opt_regex/o;
+ }
+ close $fh;
+ }
-=item B<-i>, B<--ignore-case>
+ return $has_match;
+}
-Ignore case distinctions in PATTERN
+sub count_matches_in_resource {
+ my ( $resource, $opt ) = @_;
-=item B<--ignore-ack-defaults>
+ my $nmatches = 0;
+ my $fh = $resource->open();
+ if ( !$fh ) {
+ if ( $App::Ack::report_bad_filenames ) {
+ App::Ack::warn( $resource->name . ': ' . $! );
+ }
+ }
+ else {
+ if ( $opt_v ) {
+ while ( <$fh> ) {
+ ++$nmatches if (!/$opt_regex/o);
+ }
+ }
+ else {
+ my $content = do {
+ local $/;
+ <$fh>;
+ };
+ $nmatches =()= ($content =~ /$opt_regex/og);
+ }
+ close $fh;
+ }
-Tells ack to completely ignore the default definitions provided with ack.
-This is useful in combination with B<--create-ackrc> if you I<really> want
-to customize ack.
+ return $nmatches;
+}
-=item B<--[no]ignore-dir=I<DIRNAME>>, B<--[no]ignore-directory=I<DIRNAME>>
+sub main {
+ my @arg_sources = App::Ack::ConfigLoader::retrieve_arg_sources();
-Ignore directory (as CVS, .svn, etc are ignored). May be used
-multiple times to ignore multiple directories. For example, mason
-users may wish to include B<--ignore-dir=data>. The B<--noignore-dir>
-option allows users to search directories which would normally be
-ignored (perhaps to research the contents of F<.svn/props> directories).
+ my $opt = App::Ack::ConfigLoader::process_args( @arg_sources );
-The I<DIRNAME> must always be a simple directory name. Nested
-directories like F<foo/bar> are NOT supported. You would need to
-specify B<--ignore-dir=foo> and then no files from any foo directory
-are taken into account by ack unless given explicitly on the command
-line.
+ $opt_after_context = $opt->{after_context};
+ $opt_before_context = $opt->{before_context};
+ $opt_output = $opt->{output};
+ $opt_print0 = $opt->{print0};
+ $opt_color = $opt->{color};
+ $opt_heading = $opt->{heading};
+ $opt_show_filename = $opt->{show_filename};
+ $opt_regex = $opt->{regex};
+ $opt_break = $opt->{break};
+ $opt_count = $opt->{count};
+ $opt_v = $opt->{v};
+ $opt_m = $opt->{m};
+ $opt_g = $opt->{g};
+ $opt_f = $opt->{f};
+ $opt_lines = $opt->{lines};
+ $opt_L = $opt->{L};
+ $opt_l = $opt->{l};
+ $opt_passthru = $opt->{passthru};
+ $opt_column = $opt->{column};
-=item B<--ignore-file=I<FILTERTYPE:FILTERARGS>>
+ $App::Ack::report_bad_filenames = !$opt->{dont_report_bad_filenames};
-Ignore files matching I<FILTERTYPE:FILTERARGS>. The filters are specified
-identically to file type filters as seen in L</"Defining your own types">.
+ if ( $opt->{flush} ) {
+ $| = 1;
+ }
-=item B<-k>, B<--known-types>
+ 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;
+ }
+ if ( not defined $opt_heading and not defined $opt_break ) {
+ $opt_heading = $opt_break = $opt->{break} = !App::Ack::output_to_pipe();
+ }
-Limit selected files to those with types that ack knows about. This is
-equivalent to the default behavior found in ack 1.
+ if ( defined($opt->{H}) || defined($opt->{h}) ) {
+ $opt_show_filename = $opt->{show_filename} = $opt->{H} && !$opt->{h};
+ }
-=item B<--lines=I<NUM>>
+ if ( my $output = $opt_output ) {
+ $output =~ s{\\}{\\\\}g;
+ $output =~ s{"}{\\"}g;
+ $opt_output = qq{"$output"};
+ }
-Only print line I<NUM> of each file. Multiple lines can be given with multiple
-B<--lines> options or as a comma separated list (B<--lines=3,5,7>). B<--lines=4-7>
-also works. The lines are always output in ascending order, no matter the
-order given on the command line.
+ my $resources;
+ if ( $App::Ack::is_filter_mode && !$opt->{files_from} ) { # probably -x
+ $resources = App::Ack::Resources->from_stdin( $opt );
+ $opt_regex = shift @ARGV if not defined $opt_regex;
+ $opt_regex = $opt->{regex} = build_regex( $opt_regex, $opt );
+ }
+ else {
+ if ( $opt_f || $opt_lines ) {
+ if ( $opt_regex ) {
+ App::Ack::warn( "regex ($opt_regex) specified with -f or --lines" );
+ App::Ack::exit_from_ack( 0 ); # XXX the 0 is misleading
+ }
+ }
+ else {
+ $opt_regex = shift @ARGV if not defined $opt_regex;
+ $opt_regex = $opt->{regex} = build_regex( $opt_regex, $opt );
+ }
+ if ( $opt_regex && $opt_regex =~ /\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;
+ }
+ }
-=item B<-l>, B<--files-with-matches>
+ if ( defined $opt->{files_from} ) {
+ $resources = App::Ack::Resources->from_file( $opt, $opt->{files_from} );
+ exit 1 unless $resources;
+ }
+ 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" );
+ }
+ }
-Only print the filenames of matching files, instead of the matching text.
+ $opt->{file_filter} = _compile_file_filter($opt, \@start);
+ $opt->{descend_filter} = _compile_descend_filter($opt);
-=item B<-L>, B<--files-without-matches>
+ $resources = App::Ack::Resources->from_argv( $opt, \@start );
+ }
+ }
+ App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager};
-Only print the filenames of files that do I<NOT> match.
+ my $ors = $opt_print0 ? "\0" : "\n";
+ my $only_first = $opt->{1};
-=item B<--match I<PATTERN>>
+ my $nmatches = 0;
+ my $total_count = 0;
-Specify the I<PATTERN> explicitly. This is helpful if you don't want to put the
-regex as your first argument, e.g. when executing multiple searches over the
-same set of files.
+ setup_line_context( $opt );
- # search for foo and bar in given files
- ack file1 t/file* --match foo
- ack file1 t/file* --match bar
+RESOURCES:
+ while ( my $resource = $resources->next ) {
+ if ($is_tracking_context) {
+ setup_line_context_for_file($opt);
+ }
-=item B<-m=I<NUM>>, B<--max-count=I<NUM>>
+ # XXX Combine the -f and -g functions
+ if ( $opt_f ) {
+ # XXX printing should probably happen inside of App::Ack
+ if ( $opt->{show_types} ) {
+ show_types( $resource, $ors );
+ }
+ else {
+ App::Ack::print( $resource->name, $ors );
+ }
+ ++$nmatches;
+ last RESOURCES if defined($opt_m) && $nmatches >= $opt_m;
+ }
+ elsif ( $opt_g ) {
+ if ( $opt->{show_types} ) {
+ show_types( $resource, $ors );
+ }
+ else {
+ local $opt_show_filename = 0; # XXX Why is this local?
-Stop reading a file after I<NUM> matches.
+ print_line_with_options($opt, '', $resource->name, 0, $ors);
+ }
+ ++$nmatches;
+ last RESOURCES if defined($opt_m) && $nmatches >= $opt_m;
+ }
+ elsif ( $opt_lines ) {
+ my %line_numbers;
+ foreach my $line ( @{ $opt_lines } ) {
+ my @lines = split /,/, $line;
+ @lines = map {
+ /^(\d+)-(\d+)$/
+ ? ( $1 .. $2 )
+ : $_
+ } @lines;
+ @line_numbers{@lines} = (1) x @lines;
+ }
-=item B<--man>
+ my $filename = $resource->name;
-Print this manual page.
+ local $opt_color = 0;
-=item B<-n>, B<--no-recurse>
+ iterate($resource, $opt, sub {
+ chomp;
-No descending into subdirectories.
+ if ( $line_numbers{$.} ) {
+ print_line_with_context($opt, $filename, $_, $.);
+ }
+ elsif ( $opt_passthru ) {
+ print_line_with_options($opt, $filename, $_, $., ':');
+ }
+ elsif ( $is_tracking_context ) {
+ print_line_if_context($opt, $filename, $_, $., '-');
+ }
+ return 1;
+ });
+ }
+ elsif ( $opt_count ) {
+ my $matches_for_this_file = count_matches_in_resource( $resource, $opt );
-=item B<-o>
+ if ( not $opt_show_filename ) {
+ $total_count += $matches_for_this_file;
+ next RESOURCES;
+ }
-Show only the part of each line matching PATTERN (turns off text
-highlighting)
+ if ( !$opt_l || $matches_for_this_file > 0) {
+ if ( $opt_show_filename ) {
+ App::Ack::print( $resource->name, ':', $matches_for_this_file, $ors );
+ }
+ else {
+ App::Ack::print( $matches_for_this_file, $ors );
+ }
+ }
+ }
+ elsif ( $opt_l || $opt_L ) {
+ my $is_match = resource_has_match( $resource, $opt );
-=item B<--output=I<expr>>
+ if ( $opt_L ? !$is_match : $is_match ) {
+ App::Ack::print( $resource->name, $ors );
+ ++$nmatches;
-Output the evaluation of I<expr> for each line (turns off text
-highlighting)
-If PATTERN matches more than once then a line is output for each non-overlapping match.
-For more information please see the section L</"Examples of F<--output>">.
+ last RESOURCES if $only_first;
+ last RESOURCES if defined($opt_m) && $nmatches >= $opt_m;
+ }
+ }
+ else {
+ $nmatches += print_matches_in_resource( $resource, $opt );
+ if ( $nmatches && $only_first ) {
+ last RESOURCES;
+ }
+ }
+ }
-=item B<--pager=I<program>>, B<--nopager>
+ if ( $opt_count && !$opt_show_filename ) {
+ App::Ack::print( $total_count, "\n" );
+ }
-B<--pager> directs ack's output through I<program>. This can also be specified
-via the C<ACK_PAGER> and C<ACK_PAGER_COLOR> environment variables.
+ close $App::Ack::fh;
+ App::Ack::exit_from_ack( $nmatches );
+}
-Using --pager does not suppress grouping and coloring like piping
-output on the command-line does.
-B<--nopager> cancels any setting in ~/.ackrc, C<ACK_PAGER> or C<ACK_PAGER_COLOR>.
-No output will be sent through a pager.
-=item B<--passthru>
+=head1 NAME
-Prints all lines, whether or not they match the expression. Highlighting
-will still work, though, so it can be used to highlight matches while
-still seeing the entire file, as in:
+ack - grep-like text finder
- # Watch a log file, and highlight a certain IP address
- $ tail -f ~/access.log | ack --passthru 123.45.67.89
+=head1 SYNOPSIS
-=item B<--print0>
+ ack [options] PATTERN [FILE...]
+ ack -f [options] [DIRECTORY...]
-Only works in conjunction with -f, -g, -l or -c (filename output). The filenames
-are output separated with a null byte instead of the usual newline. This is
-helpful when dealing with filenames that contain whitespace, e.g.
+=head1 DESCRIPTION
- # remove all files of type html
- ack -f --html --print0 | xargs -0 rm -f
+Ack is designed as an alternative to F<grep> for programmers.
-=item B<-Q>, B<--literal>
+Ack searches the named input FILEs (or standard input if no files
+are named, or the file name - is given) for lines containing a match
+to the given PATTERN. By default, ack prints the matching lines.
-Quote all metacharacters in PATTERN, it is treated as a literal.
+PATTERN is a Perl regular expression. Perl regular expressions
+are commonly found in other programming languages, but for the particulars
+of their behavior, please consult
+L<http://perldoc.perl.org/perlreref.html|perlreref>. If you don't know
+how to use regular expression but are interested in learning, you may
+consult L<http://perldoc.perl.org/perlretut.html|perlretut>. If you do not
+need or want ack to use regular expressions, please see the
+C<-Q>/C<--literal> option.
-=item B<-r>, B<-R>, B<--recurse>
+Ack can also list files that would be searched, without actually
+searching them, to let you take advantage of ack's file-type filtering
+capabilities.
-Recurse into sub-directories. This is the default and just here for
-compatibility with grep. You can also use it for turning B<--no-recurse> off.
+=head1 FILE SELECTION
-=item B<-s>
+If files are not specified for searching, either on the command
+line or piped in with the C<-x> option, I<ack> delves into
+subdirectories selecting files for searching.
-Suppress error messages about nonexistent or unreadable files. This is taken
-from fgrep.
+I<ack> is intelligent about the files it searches. It knows about
+certain file types, based on both the extension on the file and,
+in some cases, the contents of the file. These selections can be
+made with the B<--type> option.
-=item B<--[no]smart-case>, B<--no-smart-case>
+With no file selection, I<ack> searches through regular files that
+are not explicitly excluded by B<--ignore-dir> and B<--ignore-file>
+options, either present in F<ackrc> files or on the command line.
-Ignore case in the search strings if PATTERN contains no uppercase
-characters. This is similar to C<smartcase> in vim. This option is
-off by default, and ignored if C<-i> is specified.
+The default options for I<ack> ignore certain files and directories. These
+include:
-B<-i> always overrides this option.
+=over 4
-=item B<--sort-files>
+=item * Backup files: Files matching F<#*#> or ending with F<~>.
-Sorts the found files lexicographically. Use this if you want your file
-listings to be deterministic between runs of I<ack>.
+=item * Coredumps: Files matching F<core.\d+>
-=item B<--show-types>
+=item * Version control directories like F<.svn> and F<.git>.
-Outputs the filetypes that ack associates with each file.
+=back
-Works with B<-f> and B<-g> options.
+Run I<ack> with the C<--dump> option to see what settings are set.
-=item B<--type=[no]TYPE>
+However, I<ack> always searches the files given on the command line,
+no matter what type. If you tell I<ack> to search in a coredump,
+it will search in a coredump.
-Specify the types of files to include or exclude from a search.
-TYPE is a filetype, like I<perl> or I<xml>. B<--type=perl> can
-also be specified as B<--perl>, and B<--type=noperl> can be done
-as B<--noperl>.
+=head1 DIRECTORY SELECTION
-If a file is of both type "foo" and "bar", specifying --foo and
---nobar will exclude the file, because an exclusion takes precedence
-over an inclusion.
+I<ack> descends through the directory tree of the starting directories
+specified. If no directories are specified, the current working directory is
+used. However, it will ignore the shadow directories used by
+many version control systems, and the build directories used by the
+Perl MakeMaker system. You may add or remove a directory from this
+list with the B<--[no]ignore-dir> option. The option may be repeated
+to add/remove multiple directories from the ignore list.
-Type specifications can be repeated and are ORed together.
+For a complete list of directories that do not get searched, run
+C<ack --dump>.
-See I<ack --help=types> for a list of valid types.
+=head1 WHEN TO USE GREP
-=item B<--type-add I<TYPE>:I<FILTER>:I<FILTERARGS>>
+I<ack> trumps I<grep> as an everyday tool 99% of the time, but don't
+throw I<grep> away, because there are times you'll still need it.
-Files with the given FILTERARGS applied to the given FILTER
-are recognized as being of (the existing) type TYPE.
-See also L</"Defining your own types">.
+E.g., searching through huge files looking for regexes that can be
+expressed with I<grep> syntax should be quicker with I<grep>.
+If your script or parent program uses I<grep> C<--quiet> or C<--silent>
+or needs exit 2 on IO error, use I<grep>.
-=item B<--type-set I<TYPE>:I<FILTER>:I<FILTERARGS>>
+=head1 OPTIONS
-Files with the given FILTERARGS applied to the given FILTER are recognized as
-being of type TYPE. This replaces an existing definition for type TYPE. See
-also L</"Defining your own types">.
+=over 4
-=item B<--type-del I<TYPE>>
+=item B<--ackrc>
-The filters associated with TYPE are removed from Ack, and are no longer considered
-for searches.
+Specifies an ackrc file to load after all others; see L</"ACKRC LOCATION SEMANTICS">.
-=item B<-v>, B<--invert-match>
+=item B<-A I<NUM>>, B<--after-context=I<NUM>>
-Invert match: select non-matching lines
+Print I<NUM> lines of trailing context after matching lines.
-=item B<--version>
+=item B<-B I<NUM>>, B<--before-context=I<NUM>>
-Display version and copyright information.
+Print I<NUM> lines of leading context before matching lines.
-=item B<-w>, B<--word-regexp>
+=item B<--[no]break>
-Force PATTERN to match only whole words. The PATTERN is wrapped with
-C<\b> metacharacters.
+Print a break between results from different files. On by default
+when used interactively.
-=item B<-x>
+=item B<-C [I<NUM>]>, B<--context[=I<NUM>]>
-An abbreviation for B<--files-from=->; the list of files to search are read
-from standard input, with one line per file.
+Print I<NUM> lines (default 2) of context around matching lines.
-=item B<-1>
+=item B<-c>, B<--count>
-Stops after reporting first match of any kind. This is different
-from B<--max-count=1> or B<-m1>, where only one match per file is
-shown. Also, B<-1> works with B<-f> and B<-g>, where B<-m> does
-not.
+Suppress normal output; instead print a count of matching lines for
+each input file. If B<-l> is in effect, it will only show the
+number of lines for each file that has lines matching. Without
+B<-l>, some line counts may be zeroes.
-=item B<--thpppt>
+If combined with B<-h> (B<--no-filename>) ack outputs only one total
+count.
-Display the all-important Bill The Cat logo. Note that the exact
-spelling of B<--thpppppt> is not important. It's checked against
-a regular expression.
+=item B<--[no]color>, B<--[no]colour>
-=item B<--bar>
+B<--color> highlights the matching text. B<--nocolor> suppresses
+the color. This is on by default unless the output is redirected.
-Check with the admiral for traps.
+On Windows, this option is off by default unless the
+L<Win32::Console::ANSI> module is installed or the C<ACK_PAGER_COLOR>
+environment variable is used.
-=back
+=item B<--color-filename=I<color>>
-=head1 THE .ackrc FILE
+Sets the color to be used for filenames.
-The F<.ackrc> file contains command-line options that are prepended
-to the command line before processing. Multiple options may live
-on multiple lines. Lines beginning with a # are ignored. A F<.ackrc>
-might look like this:
+=item B<--color-match=I<color>>
- # Always sort the files
- --sort-files
+Sets the color to be used for matches.
- # Always color, even if piping to a another program
- --color
+=item B<--color-lineno=I<color>>
- # Use "less -r" as my pager
- --pager=less -r
+Sets the color to be used for line numbers.
-Note that arguments with spaces in them do not need to be quoted,
-as they are not interpreted by the shell. Basically, each I<line>
-in the F<.ackrc> file is interpreted as one element of C<@ARGV>.
+=item B<--[no]column>
-F<ack> looks in several locations for F<.ackrc> files; the searching
-process is detailed in L</"ACKRC LOCATION SEMANTICS">. These
-files are not considered if B<--noenv> is specified on the command line.
+Show the column number of the first match. This is helpful for
+editors that can place your cursor at a given position.
-=head1 Defining your own types
+=item B<--create-ackrc>
-ack allows you to define your own types in addition to the predefined
-types. This is done with command line options that are best put into
-an F<.ackrc> file - then you do not have to define your types over and
-over again. In the following examples the options will always be shown
-on one command line so that they can be easily copy & pasted.
+Dumps the default ack options to standard output. This is useful for
+when you want to customize the defaults.
-I<ack --perl foo> searches for foo in all perl files. I<ack --help=types>
-tells you, that perl files are files ending
-in .pl, .pm, .pod or .t. So what if you would like to include .xs
-files as well when searching for --perl files? I<ack --type-add perl:ext:xs --perl foo>
-does this for you. B<--type-add> appends
-additional extensions to an existing type.
+=item B<--dump>
-If you want to define a new type, or completely redefine an existing
-type, then use B<--type-set>. I<ack --type-set eiffel:ext:e,eiffel> defines
-the type I<eiffel> to include files with
-the extensions .e or .eiffel. So to search for all eiffel files
-containing the word Bertrand use I<ack --type-set eiffel:ext:e,eiffel --eiffel Bertrand>.
-As usual, you can also write B<--type=eiffel>
-instead of B<--eiffel>. Negation also works, so B<--noeiffel> excludes
-all eiffel files from a search. Redefining also works: I<ack --type-set cc:ext:c,h>
-and I<.xs> files no longer belong to the type I<cc>.
+Writes the list of options loaded and where they came from to standard
+output. Handy for debugging.
-When defining your own types in the F<.ackrc> file you have to use
-the following:
+=item B<--[no]env>
- --type-set=eiffel:ext:e,eiffel
+B<--noenv> disables all environment processing. No F<.ackrc> is
+read and all environment variables are ignored. By default, F<ack>
+considers F<.ackrc> and settings in the environment.
-or writing on separate lines
+=item B<--flush>
- --type-set
- eiffel:ext:e,eiffel
+B<--flush> flushes output immediately. This is off by default
+unless ack is running interactively (when output goes to a pipe or
+file).
-The following does B<NOT> work in the F<.ackrc> file:
+=item B<-f>
- --type-set eiffel:ext:e,eiffel
+Only print the files that would be searched, without actually doing
+any searching. PATTERN must not be specified, or it will be taken
+as a path to search.
+=item B<--files-from=I<FILE>>
-In order to see all currently defined types, use I<--help-types>, e.g.
-I<ack --type-set backup:ext:bak --type-add perl:ext:perl --help-types>
+The list of files to be searched is specified in I<FILE>. The list of
+files are separated by newlines. If I<FILE> is C<->, the list is loaded
+from standard input.
-In addition to filtering based on extension (like ack 1.x allowed), ack 2
-offers additional filter types. The generic syntax is
-I<--type-set TYPE:FILTER:FILTERARGS>; I<FILTERARGS> depends on the value
-of I<FILTER>.
+=item B<--[no]filter>
-=over 4
+Forces ack to act as if it were receiving input via a pipe.
-=item is:I<FILENAME>
+=item B<--[no]follow>
-I<is> filters match the target filename exactly. It takes exactly one
-argument, which is the name of the file to match.
+Follow or don't follow symlinks, other than whatever starting files
+or directories were specified on the command line.
-Example:
+This is off by default.
- --type-set make:is:Makefile
+=item B<-g I<PATTERN>>
-=item ext:I<EXTENSION>[,I<EXTENSION2>[,...]]
+Print files where the relative path + filename matches I<PATTERN>.
+This option can be combined with B<--color> to make it easier to spot
+the match.
-I<ext> filters match the extension of the target file against a list
-of extensions. No leading dot is needed for the extensions.
+=item B<--[no]group>
-Example:
+B<--group> groups matches by file name. This is the default
+when used interactively.
- --type-set perl:ext:pl,pm,t
+B<--nogroup> prints one result per line, like grep. This is the
+default when output is redirected.
-=item match:I<PATTERN>
+=item B<-H>, B<--with-filename>
-I<match> filters match the target filename against a regular expression.
-The regular expression is made case insensitive for the search.
+Print the filename for each match. This is the default unless searching
+a single explicitly specified file.
-Example:
+=item B<-h>, B<--no-filename>
- --type-set make:match:/(gnu)?makefile/
+Suppress the prefixing of filenames on output when multiple files are
+searched.
-=item firstlinematch:I<PATTERN>
+=item B<--[no]heading>
-I<firstlinematch> matches the first line of the target file against a
-regular expression. Like I<match>, the regular expression is made
-case insensitive.
+Print a filename heading above each file's results. This is the default
+when used interactively.
-Example:
+=item B<--help>, B<-?>
- --type-add perl:firstlinematch:/perl/
+Print a short help statement.
-=back
+=item B<--help-types>, B<--help=types>
-More filter types may be made available in the future.
+Print all known types.
-=head1 ENVIRONMENT VARIABLES
+=item B<-i>, B<--ignore-case>
-For commonly-used ack options, environment variables can make life
-much easier. These variables are ignored if B<--noenv> is specified
-on the command line.
+Ignore case distinctions in PATTERN
-=over 4
+=item B<--ignore-ack-defaults>
-=item ACKRC
+Tells ack to completely ignore the default definitions provided with ack.
+This is useful in combination with B<--create-ackrc> if you I<really> want
+to customize ack.
-Specifies the location of the user's F<.ackrc> file. If this file doesn't
-exist, F<ack> looks in the default location.
+=item B<--[no]ignore-dir=I<DIRNAME>>, B<--[no]ignore-directory=I<DIRNAME>>
-=item ACK_OPTIONS
+Ignore directory (as CVS, .svn, etc are ignored). May be used
+multiple times to ignore multiple directories. For example, mason
+users may wish to include B<--ignore-dir=data>. The B<--noignore-dir>
+option allows users to search directories which would normally be
+ignored (perhaps to research the contents of F<.svn/props> directories).
-This variable specifies default options to be placed in front of
-any explicit options on the command line.
+The I<DIRNAME> must always be a simple directory name. Nested
+directories like F<foo/bar> are NOT supported. You would need to
+specify B<--ignore-dir=foo> and then no files from any foo directory
+are taken into account by ack unless given explicitly on the command
+line.
-=item ACK_COLOR_FILENAME
+=item B<--ignore-file=I<FILTERTYPE:FILTERARGS>>
-Specifies the color of the filename when it's printed in B<--group>
-mode. By default, it's "bold green".
+Ignore files matching I<FILTERTYPE:FILTERARGS>. The filters are specified
+identically to file type filters as seen in L</"Defining your own types">.
-The recognized attributes are clear, reset, dark, bold, underline,
-underscore, blink, reverse, concealed black, red, green, yellow,
-blue, magenta, on_black, on_red, on_green, on_yellow, on_blue,
-on_magenta, on_cyan, and on_white. Case is not significant.
-Underline and underscore are equivalent, as are clear and reset.
-The color alone sets the foreground color, and on_color sets the
-background color.
+=item B<-k>, B<--known-types>
-This option can also be set with B<--color-filename>.
+Limit selected files to those with types that ack knows about. This is
+equivalent to the default behavior found in ack 1.
-=item ACK_COLOR_MATCH
+=item B<--lines=I<NUM>>
-Specifies the color of the matching text when printed in B<--color>
-mode. By default, it's "black on_yellow".
+Only print line I<NUM> of each file. Multiple lines can be given with multiple
+B<--lines> options or as a comma separated list (B<--lines=3,5,7>). B<--lines=4-7>
+also works. The lines are always output in ascending order, no matter the
+order given on the command line.
-This option can also be set with B<--color-match>.
+=item B<-l>, B<--files-with-matches>
-See B<ACK_COLOR_FILENAME> for the color specifications.
+Only print the filenames of matching files, instead of the matching text.
-=item ACK_COLOR_LINENO
+=item B<-L>, B<--files-without-matches>
-Specifies the color of the line number when printed in B<--color>
-mode. By default, it's "bold yellow".
+Only print the filenames of files that do I<NOT> match.
-This option can also be set with B<--color-lineno>.
+=item B<--match I<PATTERN>>
-See B<ACK_COLOR_FILENAME> for the color specifications.
+Specify the I<PATTERN> explicitly. This is helpful if you don't want to put the
+regex as your first argument, e.g. when executing multiple searches over the
+same set of files.
-=item ACK_PAGER
+ # search for foo and bar in given files
+ ack file1 t/file* --match foo
+ ack file1 t/file* --match bar
-Specifies a pager program, such as C<more>, C<less> or C<most>, to which
-ack will send its output.
+=item B<-m=I<NUM>>, B<--max-count=I<NUM>>
-Using C<ACK_PAGER> does not suppress grouping and coloring like
-piping output on the command-line does, except that on Windows
-ack will assume that C<ACK_PAGER> does not support color.
+Stop reading a file after I<NUM> matches.
-C<ACK_PAGER_COLOR> overrides C<ACK_PAGER> if both are specified.
+=item B<--man>
-=item ACK_PAGER_COLOR
+Print this manual page.
-Specifies a pager program that understands ANSI color sequences.
-Using C<ACK_PAGER_COLOR> does not suppress grouping and coloring
-like piping output on the command-line does.
+=item B<-n>, B<--no-recurse>
-If you are not on Windows, you never need to use C<ACK_PAGER_COLOR>.
+No descending into subdirectories.
-=back
+=item B<-o>
-=head1 ACK & OTHER TOOLS
+Show only the part of each line matching PATTERN (turns off text
+highlighting)
-=head2 Vim integration
+=item B<--output=I<expr>>
-F<ack> integrates easily with the Vim text editor. Set this in your
-F<.vimrc> to use F<ack> instead of F<grep>:
+Output the evaluation of I<expr> for each line (turns off text
+highlighting)
+If PATTERN matches more than once then a line is output for each non-overlapping match.
+For more information please see the section L</"Examples of F<--output>">.
- set grepprg=ack\ -k
+=item B<--pager=I<program>>, B<--nopager>
-That example uses C<-k> to search through only files of the types ack
-knows about, but you may use other default flags. Now you can search
-with F<ack> and easily step through the results in Vim:
+B<--pager> directs ack's output through I<program>. This can also be specified
+via the C<ACK_PAGER> and C<ACK_PAGER_COLOR> environment variables.
- :grep Dumper perllib
+Using --pager does not suppress grouping and coloring like piping
+output on the command-line does.
-Miles Sterrett has written a Vim plugin for F<ack> which allows you to use
-C<:Ack> instead of C<:grep>, as well as several other advanced features.
+B<--nopager> cancels any setting in ~/.ackrc, C<ACK_PAGER> or C<ACK_PAGER_COLOR>.
+No output will be sent through a pager.
-L<https://github.com/mileszs/ack.vim>
+=item B<--passthru>
-=head2 Emacs integration
+Prints all lines, whether or not they match the expression. Highlighting
+will still work, though, so it can be used to highlight matches while
+still seeing the entire file, as in:
-Phil Jackson put together an F<ack.el> extension that "provides a
-simple compilation mode ... has the ability to guess what files you
-want to search for based on the major-mode."
+ # Watch a log file, and highlight a certain IP address
+ $ tail -f ~/access.log | ack --passthru 123.45.67.89
-L<http://www.shellarchive.co.uk/content/emacs.html>
+=item B<--print0>
-=head2 TextMate integration
+Only works in conjunction with -f, -g, -l or -c (filename output). The filenames
+are output separated with a null byte instead of the usual newline. This is
+helpful when dealing with filenames that contain whitespace, e.g.
-Pedro Melo is a TextMate user who writes "I spend my day mostly
-inside TextMate, and the built-in find-in-project sucks with large
-projects. So I hacked a TextMate command that was using find +
-grep to use ack. The result is the Search in Project with ack, and
-you can find it here:
-L<http://www.simplicidade.org/notes/archives/2008/03/search_in_proje.html>"
+ # remove all files of type html
+ ack -f --html --print0 | xargs -0 rm -f
-=head2 Shell and Return Code
+=item B<-Q>, B<--literal>
-For greater compatibility with I<grep>, I<ack> in normal use returns
-shell return or exit code of 0 only if something is found and 1 if
-no match is found.
+Quote all metacharacters in PATTERN, it is treated as a literal.
-(Shell exit code 1 is C<$?=256> in perl with C<system> or backticks.)
+=item B<-r>, B<-R>, B<--recurse>
-The I<grep> code 2 for errors is not used.
+Recurse into sub-directories. This is the default and just here for
+compatibility with grep. You can also use it for turning B<--no-recurse> off.
-If C<-f> or C<-g> are specified, then 0 is returned if at least one
-file is found. If no files are found, then 1 is returned.
+=item B<-s>
-=cut
+Suppress error messages about nonexistent or unreadable files. This is taken
+from fgrep.
-=head1 DEBUGGING ACK PROBLEMS
+=item B<--[no]smart-case>, B<--no-smart-case>
-If ack gives you output you're not expecting, start with a few simple steps.
+Ignore case in the search strings if PATTERN contains no uppercase
+characters. This is similar to C<smartcase> in vim. This option is
+off by default, and ignored if C<-i> is specified.
-=head2 Use B<--noenv>
+B<-i> always overrides this option.
-Your environment variables and F<.ackrc> may be doing things you're
-not expecting, or forgotten you specified. Use B<--noenv> to ignore
-your environment and F<.ackrc>.
+=item B<--sort-files>
-=head2 Use B<-f> to see what files have been selected
+Sorts the found files lexicographically. Use this if you want your file
+listings to be deterministic between runs of I<ack>.
-Ack's B<-f> was originally added as a debugging tool. If ack is
-not finding matches you think it should find, run F<ack -f> to see
-what files have been selected. You can also add the C<--show-types>
-options to show the type of each file selected.
+=item B<--show-types>
-=head2 Use B<--dump>
+Outputs the filetypes that ack associates with each file.
-This lists the ackrc files that are loaded and the options loaded
-from them.
-So for example you can find a list of directories that do not get searched or where filetypes are defined.
+Works with B<-f> and B<-g> options.
-=head1 TIPS
+=item B<--type=[no]TYPE>
-=head2 Use the F<.ackrc> file.
+Specify the types of files to include or exclude from a search.
+TYPE is a filetype, like I<perl> or I<xml>. B<--type=perl> can
+also be specified as B<--perl>, and B<--type=noperl> can be done
+as B<--noperl>.
-The F<.ackrc> is the place to put all your options you use most of
-the time but don't want to remember. Put all your --type-add and
---type-set definitions in it. If you like --smart-case, set it
-there, too. I also set --sort-files there.
+If a file is of both type "foo" and "bar", specifying --foo and
+--nobar will exclude the file, because an exclusion takes precedence
+over an inclusion.
-=head2 Use F<-f> for working with big codesets
+Type specifications can be repeated and are ORed together.
-Ack does more than search files. C<ack -f --perl> will create a
-list of all the Perl files in a tree, ideal for sending into F<xargs>.
-For example:
+See I<ack --help=types> for a list of valid types.
- # Change all "this" to "that" in all Perl files in a tree.
- ack -f --perl | xargs perl -p -i -e's/this/that/g'
+=item B<--type-add I<TYPE>:I<FILTER>:I<FILTERARGS>>
-or if you prefer:
+Files with the given FILTERARGS applied to the given FILTER
+are recognized as being of (the existing) type TYPE.
+See also L</"Defining your own types">.
- perl -p -i -e's/this/that/g' $(ack -f --perl)
-=head2 Use F<-Q> when in doubt about metacharacters
+=item B<--type-set I<TYPE>:I<FILTER>:I<FILTERARGS>>
-If you're searching for something with a regular expression
-metacharacter, most often a period in a filename or IP address, add
-the -Q to avoid false positives without all the backslashing. See
-the following example for more...
+Files with the given FILTERARGS applied to the given FILTER are recognized as
+being of type TYPE. This replaces an existing definition for type TYPE. See
+also L</"Defining your own types">.
-=head2 Use ack to watch log files
+=item B<--type-del I<TYPE>>
-Here's one I used the other day to find trouble spots for a website
-visitor. The user had a problem loading F<troublesome.gif>, so I
-took the access log and scanned it with ack twice.
+The filters associated with TYPE are removed from Ack, and are no longer considered
+for searches.
- ack -Q aa.bb.cc.dd /path/to/access.log | ack -Q -B5 troublesome.gif
+=item B<-v>, B<--invert-match>
-The first ack finds only the lines in the Apache log for the given
-IP. The second finds the match on my troublesome GIF, and shows
-the previous five lines from the log in each case.
+Invert match: select non-matching lines
-=head2 Examples of F<--output>
+=item B<--version>
-Following variables are useful in the expansion string:
+Display version and copyright information.
-=over 4
+=item B<-w>, B<--word-regexp>
-=item C<$&>
+Force PATTERN to match only whole words. The PATTERN is wrapped with
+C<\b> metacharacters.
-The whole string matched by PATTERN.
+=item B<-x>
-=item C<$1>, C<$2>, ...
+An abbreviation for B<--files-from=->; the list of files to search are read
+from standard input, with one line per file.
-The contents of the 1st, 2nd ... bracketed group in PATTERN.
+=item B<-1>
-=item C<$`>
+Stops after reporting first match of any kind. This is different
+from B<--max-count=1> or B<-m1>, where only one match per file is
+shown. Also, B<-1> works with B<-f> and B<-g>, where B<-m> does
+not.
-The string before the match.
+=item B<--thpppt>
-=item C<$'>
+Display the all-important Bill The Cat logo. Note that the exact
+spelling of B<--thpppppt> is not important. It's checked against
+a regular expression.
-The string after the match.
+=item B<--bar>
-=back
+Check with the admiral for traps.
-For more details and other variables see
-L<http://perldoc.perl.org/perlvar.html#Variables-related-to-regular-expressions|perlvar>.
+=item B<--cathy>
-This example shows how to add text around a particular pattern
-(in this case adding _ around word with "e")
+Chocolate, Chocolate, Chocolate!
- ack2.pl "\w*e\w*" quick.txt --output="$`_$&_$'"
- _The_ quick brown fox jumps over the lazy dog
- The quick brown fox jumps _over_ the lazy dog
- The quick brown fox jumps over _the_ lazy dog
+=back
-This shows how to pick out particular parts of a match using ( ) within regular expression.
+=head1 THE .ackrc FILE
- ack '=head(\d+)\s+(.*)' --output=' $1 : $2'
- input file contains "=head1 NAME"
- output "1 : NAME"
+The F<.ackrc> file contains command-line options that are prepended
+to the command line before processing. Multiple options may live
+on multiple lines. Lines beginning with a # are ignored. A F<.ackrc>
+might look like this:
-=head2 Share your knowledge
+ # Always sort the files
+ --sort-files
-Join the ack-users mailing list. Send me your tips and I may add
-them here.
+ # Always color, even if piping to a another program
+ --color
-=head1 FAQ
+ # Use "less -r" as my pager
+ --pager=less -r
-=head2 Why isn't ack finding a match in (some file)?
+Note that arguments with spaces in them do not need to be quoted,
+as they are not interpreted by the shell. Basically, each I<line>
+in the F<.ackrc> file is interpreted as one element of C<@ARGV>.
-Probably because it's of a type that ack doesn't recognize. ack's
-searching behavior is driven by filetype. B<If ack doesn't know
-what kind of file it is, ack ignores the file.>
+F<ack> looks in several locations for F<.ackrc> files; the searching
+process is detailed in L</"ACKRC LOCATION SEMANTICS">. These
+files are not considered if B<--noenv> is specified on the command line.
-Use the C<-f> switch to see a list of files that ack will search
-for you.
+=head1 Defining your own types
-If you want ack to search files that it doesn't recognize, use the
-C<-a> switch.
+ack allows you to define your own types in addition to the predefined
+types. This is done with command line options that are best put into
+an F<.ackrc> file - then you do not have to define your types over and
+over again. In the following examples the options will always be shown
+on one command line so that they can be easily copy & pasted.
-If you want ack to search every file, even ones that it always
-ignores like coredumps and backup files, use the C<-u> switch.
+I<ack --perl foo> searches for foo in all perl files. I<ack --help=types>
+tells you, that perl files are files ending
+in .pl, .pm, .pod or .t. So what if you would like to include .xs
+files as well when searching for --perl files? I<ack --type-add perl:ext:xs --perl foo>
+does this for you. B<--type-add> appends
+additional extensions to an existing type.
-=head2 Why does ack ignore unknown files by default?
+If you want to define a new type, or completely redefine an existing
+type, then use B<--type-set>. I<ack --type-set eiffel:ext:e,eiffel> defines
+the type I<eiffel> to include files with
+the extensions .e or .eiffel. So to search for all eiffel files
+containing the word Bertrand use I<ack --type-set eiffel:ext:e,eiffel --eiffel Bertrand>.
+As usual, you can also write B<--type=eiffel>
+instead of B<--eiffel>. Negation also works, so B<--noeiffel> excludes
+all eiffel files from a search. Redefining also works: I<ack --type-set cc:ext:c,h>
+and I<.xs> files no longer belong to the type I<cc>.
-ack is designed by a programmer, for programmers, for searching
-large trees of code. Most codebases have a lot files in them which
-aren't source files (like compiled object files, source control
-metadata, etc), and grep wastes a lot of time searching through all
-of those as well and returning matches from those files.
+When defining your own types in the F<.ackrc> file you have to use
+the following:
-That's why ack's behavior of not searching things it doesn't recognize
-is one of its greatest strengths: the speed you get from only
-searching the things that you want to be looking at.
+ --type-set=eiffel:ext:e,eiffel
-=head2 Wouldn't it be great if F<ack> did search & replace?
+or writing on separate lines
-No, ack will always be read-only. Perl has a perfectly good way
-to do search & replace in files, using the C<-i>, C<-p> and C<-n>
-switches.
+ --type-set
+ eiffel:ext:e,eiffel
-You can certainly use ack to select your files to update. For
-example, to change all "foo" to "bar" in all PHP files, you can do
-this from the Unix shell:
+The following does B<NOT> work in the F<.ackrc> file:
- $ perl -i -p -e's/foo/bar/g' $(ack -f --php)
+ --type-set eiffel:ext:e,eiffel
-=head2 Can you make ack recognize F<.xyz> files?
-Yes! Please see L</"Defining your own types">. If you think
-that F<ack> should recognize a type by default, please see
-L</"ENHANCEMENTS">.
+In order to see all currently defined types, use I<--help-types>, e.g.
+I<ack --type-set backup:ext:bak --type-add perl:ext:perl --help-types>
-=head2 There's already a program/package called ack.
+In addition to filtering based on extension (like ack 1.x allowed), ack 2
+offers additional filter types. The generic syntax is
+I<--type-set TYPE:FILTER:FILTERARGS>; I<FILTERARGS> depends on the value
+of I<FILTER>.
-Yes, I know.
+=over 4
-=head2 Why is it called ack if it's called ack-grep?
+=item is:I<FILENAME>
-The name of the program is "ack". Some packagers have called it
-"ack-grep" when creating packages because there's already a package
-out there called "ack" that has nothing to do with this ack.
+I<is> filters match the target filename exactly. It takes exactly one
+argument, which is the name of the file to match.
-I suggest you make a symlink named F<ack> that points to F<ack-grep>
-because one of the crucial benefits of ack is having a name that's
-so short and simple to type.
+Example:
-To do that, run this with F<sudo> or as root:
+ --type-set make:is:Makefile
- ln -s /usr/bin/ack-grep /usr/bin/ack
+=item ext:I<EXTENSION>[,I<EXTENSION2>[,...]]
-Alternatively, you could use a shell alias:
+I<ext> filters match the extension of the target file against a list
+of extensions. No leading dot is needed for the extensions.
- # bash/zsh
- alias ack=ack-grep
+Example:
- # csh
- alias ack ack-grep
+ --type-set perl:ext:pl,pm,t
-=head2 What does F<ack> mean?
+=item match:I<PATTERN>
-Nothing. I wanted a name that was easy to type and that you could
-pronounce as a single syllable.
+I<match> filters match the target filename against a regular expression.
+The regular expression is made case insensitive for the search.
-=head2 Can I do multi-line regexes?
+Example:
-No, ack does not support regexes that match multiple lines. Doing
-so would require reading in the entire file at a time.
+ --type-set make:match:/(gnu)?makefile/
-If you want to see lines near your match, use the C<--A>, C<--B>
-and C<--C> switches for displaying context.
+=item firstlinematch:I<PATTERN>
-=head2 Why is ack telling me I have an invalid option when searching for C<+foo>?
+I<firstlinematch> matches the first line of the target file against a
+regular expression. Like I<match>, the regular expression is made
+case insensitive.
-ack treats command line options beginning with C<+> or C<-> as options; if you
-would like to search for these, you may prefix your search term with C<--> or
-use the C<--match> option. (However, don't forget that C<+> is a regular
-expression metacharacter!)
+Example:
-=head1 ACKRC LOCATION SEMANTICS
+ --type-add perl:firstlinematch:/perl/
-Ack can load its configuration from many sources. This list
-specifies the sources Ack looks for configuration; each one
-that is found is loaded in the order specified here, and
-each one overrides options set in any of the sources preceding
-it. (For example, if I set --sort-files in my user ackrc, and
---nosort-files on the command line, the command line takes
-precedence)
+=back
-=over 4
+More filter types may be made available in the future.
-=item *
+=head1 ENVIRONMENT VARIABLES
-Defaults are loaded from App::Ack::ConfigDefaults. This can be omitted
-using C<--ignore-ack-defaults>.
+For commonly-used ack options, environment variables can make life
+much easier. These variables are ignored if B<--noenv> is specified
+on the command line.
-=item * Global ackrc
+=over 4
-Options are then loaded from the global ackrc. This is located at
-C</etc/ackrc> on Unix-like systems, and
-C<C:\Documents and Settings\All Users\Application Data> on Windows.
-This can be omitted using C<--noenv>.
+=item ACKRC
-=item * User ackrc
+Specifies the location of the user's F<.ackrc> file. If this file doesn't
+exist, F<ack> looks in the default location.
-Options are then loaded from the user's ackrc. This is located at
-C<$HOME/.ackrc> on Unix-like systems, and
-C<C:\Documents and Settings\$USER\Application Data>. If a different
-ackrc is desired, it may be overriden with the C<$ACKRC> environment
-variable.
-This can be omitted using C<--noenv>.
+=item ACK_OPTIONS
-=item * Project ackrc
+This variable specifies default options to be placed in front of
+any explicit options on the command line.
-Options are then loaded from the project ackrc. The project ackrc is
-the first ackrc file with the name C<.ackrc> or C<_ackrc>, first searching
-in the current directory, then the parent directory, then the grandparent
-directory, etc. This can be omitted using C<--noenv>.
+=item ACK_COLOR_FILENAME
-=item * ACK_OPTIONS
+Specifies the color of the filename when it's printed in B<--group>
+mode. By default, it's "bold green".
-Options are then loaded from the enviroment variable C<ACK_OPTIONS>. This can
-be omitted using C<--noenv>.
+The recognized attributes are clear, reset, dark, bold, underline,
+underscore, blink, reverse, concealed black, red, green, yellow,
+blue, magenta, on_black, on_red, on_green, on_yellow, on_blue,
+on_magenta, on_cyan, and on_white. Case is not significant.
+Underline and underscore are equivalent, as are clear and reset.
+The color alone sets the foreground color, and on_color sets the
+background color.
-=item * Command line
+This option can also be set with B<--color-filename>.
-Options are then loaded from the command line.
+=item ACK_COLOR_MATCH
-=back
+Specifies the color of the matching text when printed in B<--color>
+mode. By default, it's "black on_yellow".
-=head1 DIFFERENCES BETWEEN ACK 1.X AND ACK 2.X
+This option can also be set with B<--color-match>.
-A lot of changes were made for ack 2; here is a list of them.
+See B<ACK_COLOR_FILENAME> for the color specifications.
-=head2 GENERAL CHANGES
+=item ACK_COLOR_LINENO
-=over 4
+Specifies the color of the line number when printed in B<--color>
+mode. By default, it's "bold yellow".
-=item *
+This option can also be set with B<--color-lineno>.
-When no selectors are specified, ack 1.x only searches through files that
-it can map to a file type. ack 2.x, by constrast, will search through
-every regular, non-binary file that is not explicitly ignored via
-B<--ignore-file> or B<--ignore-dir>. This is similar to the behavior of the
-B<-a/--all> option in ack 1.x.
+See B<ACK_COLOR_FILENAME> for the color specifications.
-=item *
+=item ACK_PAGER
-A more flexible filter system has been added, so that more powerful file types
-may be created by the user. For details, please consult
-L</"Defining your own types">.
+Specifies a pager program, such as C<more>, C<less> or C<most>, to which
+ack will send its output.
-=item *
+Using C<ACK_PAGER> does not suppress grouping and coloring like
+piping output on the command-line does, except that on Windows
+ack will assume that C<ACK_PAGER> does not support color.
-ack now loads multiple ackrc files; see L</"ACKRC LOCATION SEMANTICS"> for
-details.
+C<ACK_PAGER_COLOR> overrides C<ACK_PAGER> if both are specified.
-=item *
+=item ACK_PAGER_COLOR
-ack's default filter definitions aren't special; you may tell ack to
-completely disregard them if you don't like them.
+Specifies a pager program that understands ANSI color sequences.
+Using C<ACK_PAGER_COLOR> does not suppress grouping and coloring
+like piping output on the command-line does.
+
+If you are not on Windows, you never need to use C<ACK_PAGER_COLOR>.
=back
-=head2 REMOVED OPTIONS
+=head1 AVAILABLE COLORS
-=over 4
+F<ack> uses the colors available in Perl's L<Term::ANSIColor> module, which
+provides the following listed values. Note that case does not matter when using
+these values.
-=item *
+=head2 Foreground colors
-Because of the change in default search behavior, the B<-a/--all> and
-B<-u/--unrestricted> options have been removed. In addition, the
-B<-k/--known-types> option was added to cause ack to behave with
-the default search behavior of ack 1.x.
+ black red green yellow blue magenta cyan white
-=item *
+ bright_black bright_red bright_green bright_yellow
+ bright_blue bright_magenta bright_cyan bright_white
-The B<-G> option has been removed. Two regular expressions on the
-command line was considered too confusing; to simulate B<-G>'s functionality,
-you may use the new B<-x> option to pipe filenames from one invocation of
-ack into another.
+=head2 Background colors
-=item *
+ on_black on_red on_green on_yellow
+ on_blue on_magenta on_cyan on_white
-The B<--binary> option has been removed.
+ on_bright_black on_bright_red on_bright_green on_bright_yellow
+ on_bright_blue on_bright_magenta on_bright_cyan on_bright_white
-=item *
+=head1 ACK & OTHER TOOLS
-The B<--skipped> option has been removed.
+=head2 Vim integration
-=item *
+F<ack> integrates easily with the Vim text editor. Set this in your
+F<.vimrc> to use F<ack> instead of F<grep>:
-The B<--text> option has been removed.
+ set grepprg=ack\ -k
-=item *
+That example uses C<-k> to search through only files of the types ack
+knows about, but you may use other default flags. Now you can search
+with F<ack> and easily step through the results in Vim:
-The B<--invert-file-match> option has been removed. Instead, you may
-use B<-v> with B<-g>.
+ :grep Dumper perllib
-=back
+Miles Sterrett has written a Vim plugin for F<ack> which allows you to use
+C<:Ack> instead of C<:grep>, as well as several other advanced features.
-=head2 CHANGED OPTIONS
+L<https://github.com/mileszs/ack.vim>
-=over 4
+=head2 Emacs integration
-=item *
+Phil Jackson put together an F<ack.el> extension that "provides a
+simple compilation mode ... has the ability to guess what files you
+want to search for based on the major-mode."
-The options that modify the regular expression's behavior (B<-i>, B<-w>,
-B<-Q>, and B<-v>) may now be used with B<-g>.
+L<http://www.shellarchive.co.uk/content/emacs.html>
-=back
+=head2 TextMate integration
-=head2 ADDED OPTIONS
+Pedro Melo is a TextMate user who writes "I spend my day mostly
+inside TextMate, and the built-in find-in-project sucks with large
+projects. So I hacked a TextMate command that was using find +
+grep to use ack. The result is the Search in Project with ack, and
+you can find it here:
+L<http://www.simplicidade.org/notes/archives/2008/03/search_in_proje.html>"
-=over 4
+=head2 Shell and Return Code
-=item *
-
-B<--files-from> was added so that a user may submit a list of filenames as
-a list of files to search.
-
-=item *
+For greater compatibility with I<grep>, I<ack> in normal use returns
+shell return or exit code of 0 only if something is found and 1 if
+no match is found.
-B<-x> was added to tell ack to accept a list of filenames via standard input;
-this list is the list of filenames that will be used for the search.
+(Shell exit code 1 is C<$?=256> in perl with C<system> or backticks.)
-=item *
+The I<grep> code 2 for errors is not used.
-B<-s> was added to tell ack to suppress error messages about non-existent or
-unreadable files.
+If C<-f> or C<-g> are specified, then 0 is returned if at least one
+file is found. If no files are found, then 1 is returned.
-=item *
+=cut
-B<--ignore-directory> and B<--noignore-directory> were added as aliases for
-B<--ignore-dir> and B<--noignore-dir> respectively.
+=head1 DEBUGGING ACK PROBLEMS
-=item *
+If ack gives you output you're not expecting, start with a few simple steps.
-B<--ignore-file> was added so that users may specify patterns of files to
-ignore (ex. /.*~$/).
+=head2 Use B<--noenv>
-=item *
+Your environment variables and F<.ackrc> may be doing things you're
+not expecting, or forgotten you specified. Use B<--noenv> to ignore
+your environment and F<.ackrc>.
-B<--dump> was added to allow users to easily find out which options are
-set where.
+=head2 Use B<-f> to see what files have been selected
-=item *
+Ack's B<-f> was originally added as a debugging tool. If ack is
+not finding matches you think it should find, run F<ack -f> to see
+what files have been selected. You can also add the C<--show-types>
+options to show the type of each file selected.
-B<--create-ackrc> was added so that users may create custom ackrc files based
-on the default settings loaded by ack, and so that users may easily view those
-defaults.
+=head2 Use B<--dump>
-=item *
+This lists the ackrc files that are loaded and the options loaded
+from them.
+So for example you can find a list of directories that do not get searched or where filetypes are defined.
-B<--type-del> was added to selectively remove file type definitions.
+=head1 TIPS
-=item *
+=head2 Use the F<.ackrc> file.
-B<--ignore-ack-defaults> was added so that users may ignore ack's default
-options in favor of their own.
+The F<.ackrc> is the place to put all your options you use most of
+the time but don't want to remember. Put all your --type-add and
+--type-set definitions in it. If you like --smart-case, set it
+there, too. I also set --sort-files there.
-=item *
+=head2 Use F<-f> for working with big codesets
-B<--bar> was added so ack users may consult Admiral Ackbar.
+Ack does more than search files. C<ack -f --perl> will create a
+list of all the Perl files in a tree, ideal for sending into F<xargs>.
+For example:
-=back
+ # Change all "this" to "that" in all Perl files in a tree.
+ ack -f --perl | xargs perl -p -i -e's/this/that/g'
-=head1 AUTHOR
+or if you prefer:
-Andy Lester, C<< <andy at petdance.com> >>
+ perl -p -i -e's/this/that/g' $(ack -f --perl)
-=head1 BUGS
+=head2 Use F<-Q> when in doubt about metacharacters
-Please report any bugs or feature requests to the issues list at
-Github: L<https://github.com/petdance/ack2/issues>
+If you're searching for something with a regular expression
+metacharacter, most often a period in a filename or IP address, add
+the -Q to avoid false positives without all the backslashing. See
+the following example for more...
-=head1 ENHANCEMENTS
+=head2 Use ack to watch log files
-All enhancement requests MUST first be posted to the ack-users
-mailing list at L<http://groups.google.com/group/ack-users>. I
-will not consider a request without it first getting seen by other
-ack users. This includes requests for new filetypes.
+Here's one I used the other day to find trouble spots for a website
+visitor. The user had a problem loading F<troublesome.gif>, so I
+took the access log and scanned it with ack twice.
-There is a list of enhancements I want to make to F<ack> in the ack
-issues list at Github: L<https://github.com/petdance/ack2/issues>
+ ack -Q aa.bb.cc.dd /path/to/access.log | ack -Q -B5 troublesome.gif
-Patches are always welcome, but patches with tests get the most
-attention.
+The first ack finds only the lines in the Apache log for the given
+IP. The second finds the match on my troublesome GIF, and shows
+the previous five lines from the log in each case.
-=head1 SUPPORT
+=head2 Examples of F<--output>
-Support for and information about F<ack> can be found at:
+Following variables are useful in the expansion string:
=over 4
-=item * The ack homepage
+=item C<$&>
-L<http://beyondgrep.com/>
+The whole string matched by PATTERN.
-=item * The ack-users mailing list
+=item C<$1>, C<$2>, ...
-L<http://groups.google.com/group/ack-users>
+The contents of the 1st, 2nd ... bracketed group in PATTERN.
-=item * The ack issues list at Github
+=item C<$`>
-L<https://github.com/petdance/ack2/issues>
+The string before the match.
-=item * AnnoCPAN: Annotated CPAN documentation
+=item C<$'>
-L<http://annocpan.org/dist/ack>
+The string after the match.
-=item * CPAN Ratings
+=back
-L<http://cpanratings.perl.org/d/ack>
+For more details and other variables see
+L<http://perldoc.perl.org/perlvar.html#Variables-related-to-regular-expressions|perlvar>.
-=item * Search CPAN
+This example shows how to add text around a particular pattern
+(in this case adding _ around word with "e")
-L<http://search.cpan.org/dist/ack>
+ ack2.pl "\w*e\w*" quick.txt --output="$`_$&_$'"
+ _The_ quick brown fox jumps over the lazy dog
+ The quick brown fox jumps _over_ the lazy dog
+ The quick brown fox jumps over _the_ lazy dog
-=item * Git source repository
+This shows how to pick out particular parts of a match using ( ) within regular expression.
-L<https://github.com/petdance/ack2>
+ ack '=head(\d+)\s+(.*)' --output=' $1 : $2'
+ input file contains "=head1 NAME"
+ output "1 : NAME"
-=back
+=head2 Share your knowledge
-=head1 ACKNOWLEDGEMENTS
+Join the ack-users mailing list. Send me your tips and I may add
+them here.
-How appropriate to have I<ack>nowledgements!
+=head1 FAQ
-Thanks to everyone who has contributed to ack in any way, including
-Michael McClimon,
-Andrew Black,
-Ralph Bodenner,
-Shaun Patterson,
-Ryan Olson,
-Shlomi Fish,
-Karen Etheridge,
-Olivier Mengue,
-Matthew Wild,
-Scott Kyle,
-Nick Hooey,
-Bo Borgerson,
-Mark Szymanski,
-Marq Schneider,
-Packy Anderson,
-JR Boyens,
-Dan Sully,
-Ryan Niebur,
-Kent Fredric,
-Mike Morearty,
-Ingmar Vanhassel,
-Eric Van Dewoestine,
-Sitaram Chamarty,
-Adam James,
-Richard Carlsson,
-Pedro Melo,
-AJ Schuster,
-Phil Jackson,
-Michael Schwern,
-Jan Dubois,
-Christopher J. Madsen,
-Matthew Wickline,
-David Dyck,
-Jason Porritt,
-Jjgod Jiang,
-Thomas Klausner,
-Uri Guttman,
-Peter Lewis,
-Kevin Riggle,
-Ori Avtalion,
-Torsten Blix,
-Nigel Metheringham,
-GE<aacute>bor SzabE<oacute>,
-Tod Hagan,
-Michael Hendricks,
-E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason,
-Piers Cawley,
-Stephen Steneker,
-Elias Lutfallah,
-Mark Leighton Fisher,
-Matt Diephouse,
-Christian Jaeger,
-Bill Sully,
-Bill Ricker,
-David Golden,
-Nilson Santos F. Jr,
-Elliot Shank,
-Merijn Broeren,
-Uwe Voelker,
-Rick Scott,
-Ask BjE<oslash>rn Hansen,
-Jerry Gay,
-Will Coleda,
-Mike O'Regan,
-Slaven ReziE<0x107>,
-Mark Stosberg,
-David Alan Pisoni,
-Adriano Ferreira,
-James Keenan,
-Leland Johnson,
-Ricardo Signes,
-Pete Krawczyk and
-Rob Hoelz.
+=head2 Why isn't ack finding a match in (some file)?
-=head1 COPYRIGHT & LICENSE
+Probably because it's of a type that ack doesn't recognize. ack's
+searching behavior is driven by filetype. B<If ack doesn't know
+what kind of file it is, ack ignores the file.>
-Copyright 2005-2013 Andy Lester.
+Use the C<-f> switch to see a list of files that ack will search
+for you. You can use the C<--show-types> switch to show which type
+ack thinks each file is.
-This program is free software; you can redistribute it and/or modify
-it under the terms of the Artistic License v2.0.
+=head2 Wouldn't it be great if F<ack> did search & replace?
-See http://www.perlfoundation.org/artistic_license_2_0 or the LICENSE.md
-file that comes with the ack distribution.
+No, ack will always be read-only. Perl has a perfectly good way
+to do search & replace in files, using the C<-i>, C<-p> and C<-n>
+switches.
-=cut
-package File::Next;
+You can certainly use ack to select your files to update. For
+example, to change all "foo" to "bar" in all PHP files, you can do
+this from the Unix shell:
-use strict;
-use warnings;
+ $ perl -i -p -e's/foo/bar/g' $(ack -f --php)
+=head2 Can I make ack recognize F<.xyz> files?
-our $VERSION = '1.12';
+Yes! Please see L</"Defining your own types">. If you think
+that F<ack> should recognize a type by default, please see
+L</"ENHANCEMENTS">.
+=head2 There's already a program/package called ack.
+Yes, I know.
-use File::Spec ();
+=head2 Why is it called ack if it's called ack-grep?
-our $name; # name of the current file
-our $dir; # dir of the current file
+The name of the program is "ack". Some packagers have called it
+"ack-grep" when creating packages because there's already a package
+out there called "ack" that has nothing to do with this ack.
-our %files_defaults;
-our %skip_dirs;
+I suggest you make a symlink named F<ack> that points to F<ack-grep>
+because one of the crucial benefits of ack is having a name that's
+so short and simple to type.
-BEGIN {
- %files_defaults = (
- file_filter => undef,
- descend_filter => undef,
- error_handler => sub { CORE::die @_ },
- warning_handler => sub { CORE::warn @_ },
- sort_files => undef,
- follow_symlinks => 1,
- nul_separated => 0,
- );
- %skip_dirs = map {($_,1)} (File::Spec->curdir, File::Spec->updir);
-}
+To do that, run this with F<sudo> or as root:
+ ln -s /usr/bin/ack-grep /usr/bin/ack
-sub files {
- die _bad_invocation() if @_ && defined($_[0]) && ($_[0] eq __PACKAGE__);
+Alternatively, you could use a shell alias:
- my ($parms,@queue) = _setup( \%files_defaults, @_ );
- my $filter = $parms->{file_filter};
+ # bash/zsh
+ alias ack=ack-grep
- return sub {
- while (@queue) {
- my ($dirname,$file,$fullpath) = splice( @queue, 0, 3 );
- if ( -f $fullpath || -p $fullpath || $fullpath =~ m{^/dev/fd} ) {
- if ( $filter ) {
- local $_ = $file;
- local $File::Next::dir = $dirname;
- local $File::Next::name = $fullpath;
- next if not $filter->();
- }
- return wantarray ? ($dirname,$file,$fullpath) : $fullpath;
- }
- elsif ( -d _ ) {
- unshift( @queue, _candidate_files( $parms, $fullpath ) );
- }
- } # while
+ # csh
+ alias ack ack-grep
- return;
- }; # iterator
-}
+=head2 What does F<ack> mean?
+Nothing. I wanted a name that was easy to type and that you could
+pronounce as a single syllable.
+=head2 Can I do multi-line regexes?
+No, ack does not support regexes that match multiple lines. Doing
+so would require reading in the entire file at a time.
+If you want to see lines near your match, use the C<--A>, C<--B>
+and C<--C> switches for displaying context.
+=head2 Why is ack telling me I have an invalid option when searching for C<+foo>?
-sub from_file {
- die _bad_invocation() if @_ && defined($_[0]) && ($_[0] eq __PACKAGE__);
+ack treats command line options beginning with C<+> or C<-> as options; if you
+would like to search for these, you may prefix your search term with C<--> or
+use the C<--match> option. (However, don't forget that C<+> is a regular
+expression metacharacter!)
- my ($parms,@queue) = _setup( \%files_defaults, @_ );
- my $err = $parms->{error_handler};
- my $warn = $parms->{error_handler};
+=head2 Why does C<"ack '.{40000,}'"> fail? Isn't that a valid regex?
- my $filename = $queue[1];
+The Perl language limits the repetition quanitifier to 32K. You
+can search for C<.{32767}> but not C<.{32768}>.
- if ( !defined($filename) ) {
- $err->( 'Must pass a filename to from_file()' );
- return undef;
- }
+=head1 ACKRC LOCATION SEMANTICS
- my $fh;
- if ( $filename eq '-' ) {
- $fh = \*STDIN;
- }
- else {
- if ( !open( $fh, '<', $filename ) ) {
- $err->( "Unable to open $filename: $!" );
- return undef;
- }
- }
- my $filter = $parms->{file_filter};
+Ack can load its configuration from many sources. The following list
+specifies the sources Ack looks for configuration files; each one
+that is found is loaded in the order specified here, and
+each one overrides options set in any of the sources preceding
+it. (For example, if I set --sort-files in my user ackrc, and
+--nosort-files on the command line, the command line takes
+precedence)
- return sub {
- local $/ = $parms->{nul_separated} ? "\x00" : $/;
- while ( my $fullpath = <$fh> ) {
- chomp $fullpath;
- next unless $fullpath =~ /./;
- if ( not ( -f $fullpath || -p _ ) ) {
- $warn->( "$fullpath: No such file" );
- next;
- }
+=over 4
- my ($volume,$dirname,$file) = File::Spec->splitpath( $fullpath );
- if ( $filter ) {
- local $_ = $file;
- local $File::Next::dir = $dirname;
- local $File::Next::name = $fullpath;
- next if not $filter->();
- }
- return wantarray ? ($dirname,$file,$fullpath) : $fullpath;
- } # while
- close $fh;
+=item *
- return;
- }; # iterator
-}
+Defaults are loaded from App::Ack::ConfigDefaults. This can be omitted
+using C<--ignore-ack-defaults>.
-sub _bad_invocation {
- my $good = (caller(1))[3];
- my $bad = $good;
- $bad =~ s/(.+)::/$1->/;
- return "$good must not be invoked as $bad";
-}
+=item * Global ackrc
-sub sort_standard($$) { return $_[0]->[1] cmp $_[1]->[1] }
-sub sort_reverse($$) { return $_[1]->[1] cmp $_[0]->[1] }
+Options are then loaded from the global ackrc. This is located at
+C</etc/ackrc> on Unix-like systems.
-sub reslash {
- my $path = shift;
+Under Windows XP and earlier, the global ackrc is at
+C<C:\Documents and Settings\All Users\Application Data\ackrc>
- my @parts = split( /\//, $path );
+Under Windows Vista/7, the global ackrc is at
+C<C:\ProgramData\ackrc>
- return $path if @parts < 2;
+The C<--noenv> option prevents all ackrc files from being loaded.
- return File::Spec->catfile( @parts );
-}
+=item * User ackrc
+Options are then loaded from the user's ackrc. This is located at
+C<$HOME/.ackrc> on Unix-like systems.
+Under Windows XP and earlier, the user's ackrc is at
+C<C:\Documents and Settings\$USER\Application Data\ackrc>.
-sub _setup {
- my $defaults = shift;
- my $passed_parms = ref $_[0] eq 'HASH' ? {%{+shift}} : {}; # copy parm hash
+Under Windows Vista/7, the user's ackrc is at
+C<C:\Users\$USER\AppData\Roaming\ackrc>.
- my %passed_parms = %{$passed_parms};
+If you want to load a different user-level ackrc, it may be specified
+with the C<$ACKRC> environment variable.
- my $parms = {};
- for my $key ( keys %{$defaults} ) {
- $parms->{$key} =
- exists $passed_parms{$key}
- ? delete $passed_parms{$key}
- : $defaults->{$key};
- }
+The C<--noenv> option prevents all ackrc files from being loaded.
- # Any leftover keys are bogus
- for my $badkey ( keys %passed_parms ) {
- my $sub = (caller(1))[3];
- $parms->{error_handler}->( "Invalid option passed to $sub(): $badkey" );
- }
+=item * Project ackrc
- # If it's not a code ref, assume standard sort
- if ( $parms->{sort_files} && ( ref($parms->{sort_files}) ne 'CODE' ) ) {
- $parms->{sort_files} = \&sort_standard;
- }
- my @queue;
+Options are then loaded from the project ackrc. The project ackrc is
+the first ackrc file with the name C<.ackrc> or C<_ackrc>, first searching
+in the current directory, then the parent directory, then the grandparent
+directory, etc. This can be omitted using C<--noenv>.
- for ( @_ ) {
- my $start = reslash( $_ );
- if (-d $start) {
- push @queue, ($start,undef,$start);
- }
- else {
- push @queue, (undef,$start,$start);
- }
- }
+=item * --ackrc
- return ($parms,@queue);
-}
+The C<--ackrc> option may be included on the command line to specify an
+ackrc file that can override all others. It is consulted even if C<--noenv>
+is present.
+=item * ACK_OPTIONS
-sub _candidate_files {
- my $parms = shift;
- my $dirname = shift;
+Options are then loaded from the environment variable C<ACK_OPTIONS>. This can
+be omitted using C<--noenv>.
- my $dh;
- if ( !opendir $dh, $dirname ) {
- $parms->{error_handler}->( "$dirname: $!" );
- return;
- }
+=item * Command line
- my @newfiles;
- my $descend_filter = $parms->{descend_filter};
- my $follow_symlinks = $parms->{follow_symlinks};
- my $sort_sub = $parms->{sort_files};
+Options are then loaded from the command line.
- for my $file ( grep { !exists $skip_dirs{$_} } readdir $dh ) {
- my $has_stat;
+=back
- # Only do directory checking if we have a descend_filter
- my $fullpath = File::Spec->catdir( $dirname, $file );
- if ( !$follow_symlinks ) {
- next if -l $fullpath;
- $has_stat = 1;
- }
+=head1 DIFFERENCES BETWEEN ACK 1.X AND ACK 2.X
- if ( $descend_filter ) {
- if ( $has_stat ? (-d _) : (-d $fullpath) ) {
- local $File::Next::dir = $fullpath;
- local $_ = $file;
- next if not $descend_filter->();
- }
- }
- if ( $sort_sub ) {
- push( @newfiles, [ $dirname, $file, $fullpath ] );
- }
- else {
- push( @newfiles, $dirname, $file, $fullpath );
- }
- }
- closedir $dh;
+A lot of changes were made for ack 2; here is a list of them.
- if ( $sort_sub ) {
- return map { @{$_} } sort $sort_sub @newfiles;
- }
+=head2 GENERAL CHANGES
- return @newfiles;
-}
+=over 4
+=item *
-1; # End of File::Next
-package App::Ack;
+When no selectors are specified, ack 1.x only searches through files that
+it can map to a file type. ack 2.x, by contrast, will search through
+every regular, non-binary file that is not explicitly ignored via
+B<--ignore-file> or B<--ignore-dir>. This is similar to the behavior of the
+B<-a/--all> option in ack 1.x.
-use warnings;
-use strict;
+=item *
-use Getopt::Long 2.36 ();
+A more flexible filter system has been added, so that more powerful file types
+may be created by the user. For details, please consult
+L</"Defining your own types">.
+=item *
-our $VERSION;
-our $GIT_REVISION;
-our $COPYRIGHT;
-BEGIN {
- $VERSION = '2.02';
- $COPYRIGHT = 'Copyright 2005-2013 Andy Lester.';
- $GIT_REVISION = q{f3c8827};
-}
+ack now loads multiple ackrc files; see L</"ACKRC LOCATION SEMANTICS"> for
+details.
-our $fh;
+=item *
-BEGIN {
- $fh = *STDOUT;
-}
+ack's default filter definitions aren't special; you may tell ack to
+completely disregard them if you don't like them.
+=back
-our %types;
-our %type_wanted;
-our %mappings;
-our %ignore_dirs;
+=head2 REMOVED OPTIONS
-our $is_filter_mode;
-our $output_to_pipe;
+=over 4
-our $dir_sep_chars;
-our $is_cygwin;
-our $is_windows;
+=item *
-use File::Spec 1.00015 ();
-use File::Glob 1.00015 ':glob';
+Because of the change in default search behavior, the B<-a/--all> and
+B<-u/--unrestricted> options have been removed. In addition, the
+B<-k/--known-types> option was added to cause ack to behave with
+the default search behavior of ack 1.x.
-BEGIN {
- # These have to be checked before any filehandle diddling.
- $output_to_pipe = not -t *STDOUT;
- $is_filter_mode = -p STDIN;
+=item *
- $is_cygwin = ($^O eq 'cygwin');
- $is_windows = ($^O =~ /MSWin32/);
- $dir_sep_chars = $is_windows ? quotemeta( '\\/' ) : quotemeta( File::Spec->catfile( '', '' ) );
-}
+The B<-G> option has been removed. Two regular expressions on the
+command line was considered too confusing; to simulate B<-G>'s functionality,
+you may use the new B<-x> option to pipe filenames from one invocation of
+ack into another.
+=item *
-sub retrieve_arg_sources {
- my @arg_sources;
+The B<--binary> option has been removed.
- my $noenv;
- my $ackrc;
+=item *
- Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
- Getopt::Long::Configure('pass_through');
- Getopt::Long::Configure('no_auto_abbrev');
+The B<--skipped> option has been removed.
- Getopt::Long::GetOptions(
- 'noenv' => \$noenv,
- 'ackrc=s' => \$ackrc,
- );
+=item *
- Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
+The B<--text> option has been removed.
- my @files;
+=item *
- if ( !$noenv ) {
- my $finder = App::Ack::ConfigFinder->new;
- @files = $finder->find_config_files;
- }
- if ( $ackrc ) {
- # we explicitly use open so we get a nice error message
- # XXX this is a potential race condition!
- if(open my $fh, '<', $ackrc) {
- close $fh;
- }
- else {
- die "Unable to load ackrc '$ackrc': $!"
- }
- push( @files, $ackrc );
- }
+The B<--invert-file-match> option has been removed. Instead, you may
+use B<-v> with B<-g>.
- push @arg_sources, Defaults => [ App::Ack::ConfigDefault::options() ];
+=back
- foreach my $file ( @files) {
- my @lines = read_rcfile($file);
- push ( @arg_sources, $file, \@lines ) if @lines;
- }
+=head2 CHANGED OPTIONS
- if ( $ENV{ACK_OPTIONS} && !$noenv ) {
- push( @arg_sources, 'ACK_OPTIONS' => $ENV{ACK_OPTIONS} );
- }
+=over 4
- push( @arg_sources, 'ARGV' => [ @ARGV ] );
+=item *
- return @arg_sources;
-}
+The options that modify the regular expression's behavior (B<-i>, B<-w>,
+B<-Q>, and B<-v>) may now be used with B<-g>.
-sub read_rcfile {
- my $file = shift;
+=back
- return unless defined $file && -e $file;
+=head2 ADDED OPTIONS
- my @lines;
+=over 4
- open( my $fh, '<', $file ) or App::Ack::die( "Unable to read $file: $!" );
- while ( my $line = <$fh> ) {
- chomp $line;
- $line =~ s/^\s+//;
- $line =~ s/\s+$//;
+=item *
- next if $line eq '';
- next if $line =~ /^#/;
+B<--files-from> was added so that a user may submit a list of filenames as
+a list of files to search.
- push( @lines, $line );
- }
- close $fh;
+=item *
- return @lines;
-}
+B<-x> was added to tell ack to accept a list of filenames via standard input;
+this list is the list of filenames that will be used for the search.
+=item *
-sub create_ignore_rules {
- my $what = shift;
- my $where = shift;
- my $opts = shift;
+B<-s> was added to tell ack to suppress error messages about non-existent or
+unreadable files.
- my @opts = @{$opts};
+=item *
- my %rules;
+B<--ignore-directory> and B<--noignore-directory> were added as aliases for
+B<--ignore-dir> and B<--noignore-dir> respectively.
- for my $opt ( @opts ) {
- if ( $opt =~ /^(is|ext|regex),(.+)$/ ) {
- my $method = $1;
- my $arg = $2;
- if ( $method eq 'regex' ) {
- push( @{$rules{regex}}, qr/$arg/ );
- }
- else {
- ++$rules{$method}{$arg};
- }
- }
- else {
- App::Ack::die( "Invalid argument for --$what: $opt" );
- }
- }
+=item *
- return \%rules;
-}
+B<--ignore-file> was added so that users may specify patterns of files to
+ignore (ex. /.*~$/).
+=item *
-sub remove_dir_sep {
- my $path = shift;
- $path =~ s/[$dir_sep_chars]$//;
+B<--dump> was added to allow users to easily find out which options are
+set where.
- return $path;
-}
+=item *
+B<--create-ackrc> was added so that users may create custom ackrc files based
+on the default settings loaded by ack, and so that users may easily view those
+defaults.
-sub build_regex {
- my $str = shift;
- my $opt = shift;
+=item *
- defined $str or App::Ack::die( 'No regular expression found.' );
+B<--type-del> was added to selectively remove file type definitions.
- $str = quotemeta( $str ) if $opt->{Q};
- if ( $opt->{w} ) {
- $str = "\\b$str" if $str =~ /^\w/;
- $str = "$str\\b" if $str =~ /\w$/;
- }
+=item *
- my $regex_is_lc = $str eq lc $str;
- if ( $opt->{i} || ($opt->{smart_case} && $regex_is_lc) ) {
- $str = "(?i)$str";
- }
+B<--ignore-ack-defaults> was added so that users may ignore ack's default
+options in favor of their own.
- my $ok = eval {
- qr/$str/
- };
+=item *
- my $error = $@;
+B<--bar> was added so ack users may consult Admiral Ackbar.
- if ( !$ok ) {
- die "Invalid regex '$str':\n $error";
- }
+=back
- return $str;
-}
+=head1 AUTHOR
+Andy Lester, C<< <andy at petdance.com> >>
-sub check_regex {
- my $regex = shift;
+=head1 BUGS
- return unless defined $regex;
+Please report any bugs or feature requests to the issues list at
+Github: L<https://github.com/petdance/ack2/issues>
- eval { qr/$regex/ };
- if ($@) {
- (my $error = $@) =~ s/ at \S+ line \d+.*//;
- chomp($error);
- App::Ack::die( "Invalid regex '$regex':\n $error" );
- }
+=head1 ENHANCEMENTS
- return;
-}
+All enhancement requests MUST first be posted to the ack-users
+mailing list at L<http://groups.google.com/group/ack-users>. I
+will not consider a request without it first getting seen by other
+ack users. This includes requests for new filetypes.
+There is a list of enhancements I want to make to F<ack> in the ack
+issues list at Github: L<https://github.com/petdance/ack2/issues>
+Patches are always welcome, but patches with tests get the most
+attention.
+=head1 SUPPORT
-sub warn {
- return CORE::warn( _my_program(), ': ', @_, "\n" );
-}
+Support for and information about F<ack> can be found at:
+=over 4
-sub die {
- return CORE::die( _my_program(), ': ', @_, "\n" );
-}
+=item * The ack homepage
-sub _my_program {
- require File::Basename;
- return File::Basename::basename( $0 );
-}
+L<http://beyondgrep.com/>
+=item * The ack-users mailing list
+L<http://groups.google.com/group/ack-users>
-sub filetypes_supported {
- return keys %mappings;
-}
+=item * The ack issues list at Github
-sub _get_thpppt {
- my $y = q{_ /|,\\'!.x',=(www)=, U };
- $y =~ tr/,x!w/\nOo_/;
- return $y;
-}
+L<https://github.com/petdance/ack2/issues>
-sub _thpppt {
- my $y = _get_thpppt();
- App::Ack::print( "$y ack $_[0]!\n" );
- exit 0;
-}
+=item * AnnoCPAN: Annotated CPAN documentation
-sub _bar {
- my $x;
- $x = <<'_BAR';
- 6?!I'7!I"?%+!
- 3~!I#7#I"7#I!?!+!="+"="+!:!
- 2?#I!7!I!?#I!7!I"+"=%+"=#
- 1?"+!?*+!=#~"=!+#?"="+!
- 0?"+!?"I"?&+!="~!=!~"=!+%="+"
- /I!+!?)+!?!+!=$~!=!~!="+!="+"?!="?!
- .?%I"?%+%='?!=#~$="
- ,,!?%I"?(+$=$~!=#:"~$:!~!
- ,I!?!I!?"I"?!+#?"+!?!+#="~$:!~!:!~!:!,!:!,":#~!
- +I!?&+!="+!?#+$=!~":!~!:!~!:!,!:#,!:!,%:"
- *+!I!?!+$=!+!=!+!?$+#=!~":!~":#,$:",#:!,!:!
- *I!?"+!?!+!=$+!?#+#=#~":$,!:",!:!,&:"
- )I!?$=!~!=#+"?!+!=!+!=!~!="~!:!~":!,'.!,%:!~!
- (=!?"+!?!=!~$?"+!?!+!=#~"=",!="~$,$.",#.!:!=!
- (I"+"="~"=!+&=!~"=!~!,!~!+!=!?!+!?!=!I!?!+"=!.",!.!,":!
- %I$?!+!?!=%+!~!+#~!=!~#:#=!~!+!~!=#:!,%.!,!.!:"
- $I!?!=!?!I!+!?"+!=!~!=!~!?!I!?!=!+!=!~#:",!~"=!~!:"~!=!:",&:" '-/
- $?!+!I!?"+"=!+"~!,!:"+#~#:#,"=!~"=!,!~!,!.",!:".!:! */! !I!t!'!s! !a! !g!r!e!p!!! !/!
- $+"=!+!?!+"~!=!:!~!:"I!+!,!~!=!:!~!,!:!,$:!~".&:"~!,# (-/
- %~!=!~!=!:!.!+"~!:!,!.!,!~!=!:$.!,":!,!.!:!~!,!:!=!.#="~!,!:" ./!
- %=!~!?!+"?"+!=!~",!.!:!?!~!.!:!,!:!,#.!,!:","~!:!=!~!=!:",!~! ./!
- %+"~":!~!=#~!:!~!,!.!~!:",!~!=!~!.!:!,!.",!:!,":!=":!.!,!:!7! -/!
- %~",!:".#:!=!:!,!:"+!:!~!:!.!,!~!,!.#,!.!,$:"~!,":"~!=! */!
- &=!~!=#+!=!~",!.!:",#:#,!.",+:!,!.",!=!+!?!
- &~!=!~!=!~!:"~#:",!.!,#~!:!.!+!,!.",$.",$.#,!+!I!?!
- &~!="~!:!~":!~",!~!=!~":!,!:!~!,!:!,&.$,#."+!?!I!?!I!
- &~!=!~!=!+!,!:!~!:!=!,!:!~&:$,!.!,".!,".!,#."~!+!?$I!
- &~!=!~!="~!=!:!~":!,!~%:#,!:",!.!,#.",#I!7"I!?!+!?"I"
- &+!I!7!:#~"=!~!:!,!:"~$.!=!.!,!~!,$.#,!~!7!I#?!+!?"I"7!
- %7#?!+!~!:!=!~!=!~":!,!:"~":#.!,)7#I"?"I!7&
- %7#I!=":!=!~!:"~$:"~!:#,!:!,!:!~!:#,!7#I!?#7)
- $7$+!,!~!=#~!:!~!:!~$:#,!.!~!:!=!,":!7#I"?#7+=!?!
- $7#I!~!,!~#=!~!:"~!:!,!:!,#:!=!~",":!7$I!?#I!7*+!=!+"
- "I!7$I!,":!,!.!=":$,!:!,$:$7$I!+!?"I!7+?"I!7!I!7!,!
- !,!7%I!:",!."~":!,&.!,!:!~!I!7$I!+!?"I!7,?!I!7',!
- !7(,!.#~":!,%.!,!7%I!7!?#I"7,+!?!7*
-7+:!,!~#,"=!7'I!?#I"7/+!7+
-77I!+!7!?!7!I"71+!7,
-_BAR
+L<http://annocpan.org/dist/ack>
- $x =~ s/(.)(.)/$1x(ord($2)-32)/eg;
- App::Ack::print( $x );
- exit 0;
-}
+=item * CPAN Ratings
+L<http://cpanratings.perl.org/d/ack>
-sub show_help {
- my $help_arg = shift || 0;
+=item * Search CPAN
- return show_help_types() if $help_arg =~ /^types?/;
+L<http://search.cpan.org/dist/ack>
- App::Ack::print( <<"END_OF_HELP" );
-Usage: ack [OPTION]... PATTERN [FILES OR DIRECTORIES]
+=item * Git source repository
-Search for PATTERN in each source file in the tree from the current
-directory on down. If any files or directories are specified, then
-only those files and directories are checked. ack may also search
-STDIN, but only if no file or directory arguments are specified,
-or if one of them is "-".
+L<https://github.com/petdance/ack2>
-Default switches may be specified in ACK_OPTIONS environment variable or
-an .ackrc file. If you want no dependency on the environment, turn it
-off with --noenv.
+=back
-Example: ack -i select
+=head1 ACKNOWLEDGEMENTS
-Searching:
- -i, --ignore-case Ignore case distinctions in PATTERN
- --[no]smart-case Ignore case distinctions in PATTERN,
- only if PATTERN contains no upper case.
- Ignored if -i is specified
- -v, --invert-match Invert match: select non-matching lines
- -w, --word-regexp Force PATTERN to match only whole words
+How appropriate to have I<ack>nowledgements!
+
+Thanks to everyone who has contributed to ack in any way, including
+Stephen Thirlwall,
+Jonah Bishop,
+Chris Rebert,
+Denis Howe,
+RaE<uacute>l GundE<iacute>n,
+James McCoy,
+Daniel Perrett,
+Steven Lee,
+Jonathan Perret,
+Fraser Tweedale,
+RaE<aacute>l GundE<aacute>n,
+Steffen Jaeckel,
+Stephan Hohe,
+Michael Beijen,
+Alexandr Ciornii,
+Christian Walde,
+Charles Lee,
+Joe McMahon,
+John Warwick,
+David Steinbrunner,
+Kara Martens,
+Volodymyr Medvid,
+Ron Savage,
+Konrad Borowski,
+Dale Sedivic,
+Michael McClimon,
+Andrew Black,
+Ralph Bodenner,
+Shaun Patterson,
+Ryan Olson,
+Shlomi Fish,
+Karen Etheridge,
+Olivier Mengue,
+Matthew Wild,
+Scott Kyle,
+Nick Hooey,
+Bo Borgerson,
+Mark Szymanski,
+Marq Schneider,
+Packy Anderson,
+JR Boyens,
+Dan Sully,
+Ryan Niebur,
+Kent Fredric,
+Mike Morearty,
+Ingmar Vanhassel,
+Eric Van Dewoestine,
+Sitaram Chamarty,
+Adam James,
+Richard Carlsson,
+Pedro Melo,
+AJ Schuster,
+Phil Jackson,
+Michael Schwern,
+Jan Dubois,
+Christopher J. Madsen,
+Matthew Wickline,
+David Dyck,
+Jason Porritt,
+Jjgod Jiang,
+Thomas Klausner,
+Uri Guttman,
+Peter Lewis,
+Kevin Riggle,
+Ori Avtalion,
+Torsten Blix,
+Nigel Metheringham,
+GE<aacute>bor SzabE<oacute>,
+Tod Hagan,
+Michael Hendricks,
+E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason,
+Piers Cawley,
+Stephen Steneker,
+Elias Lutfallah,
+Mark Leighton Fisher,
+Matt Diephouse,
+Christian Jaeger,
+Bill Sully,
+Bill Ricker,
+David Golden,
+Nilson Santos F. Jr,
+Elliot Shank,
+Merijn Broeren,
+Uwe Voelker,
+Rick Scott,
+Ask BjE<oslash>rn Hansen,
+Jerry Gay,
+Will Coleda,
+Mike O'Regan,
+Slaven ReziE<0x107>,
+Mark Stosberg,
+David Alan Pisoni,
+Adriano Ferreira,
+James Keenan,
+Leland Johnson,
+Ricardo Signes,
+Pete Krawczyk and
+Rob Hoelz.
+
+=head1 COPYRIGHT & LICENSE
+
+Copyright 2005-2015 Andy Lester.
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the Artistic License v2.0.
+
+See http://www.perlfoundation.org/artistic_license_2_0 or the LICENSE.md
+file that comes with the ack distribution.
+
+=cut
+package App::Ack;
+
+use warnings;
+use strict;
+
+
+our $VERSION;
+our $COPYRIGHT;
+BEGIN {
+ $VERSION = '2.15_01';
+ $COPYRIGHT = 'Copyright 2005-2015 Andy Lester.';
+}
+
+our $fh;
+
+BEGIN {
+ $fh = *STDOUT;
+}
+
+
+our %types;
+our %type_wanted;
+our %mappings;
+our %ignore_dirs;
+
+our $is_filter_mode;
+our $output_to_pipe;
+
+our $dir_sep_chars;
+our $is_cygwin;
+our $is_windows;
+
+use File::Spec 1.00015 ();
+
+BEGIN {
+ # These have to be checked before any filehandle diddling.
+ $output_to_pipe = not -t *STDOUT;
+ $is_filter_mode = -p STDIN;
+
+ $is_cygwin = ($^O eq 'cygwin');
+ $is_windows = ($^O eq 'MSWin32');
+ $dir_sep_chars = $is_windows ? quotemeta( '\\/' ) : quotemeta( File::Spec->catfile( '', '' ) );
+}
+
+
+
+sub remove_dir_sep {
+ my $path = shift;
+ $path =~ s/[$dir_sep_chars]$//;
+
+ return $path;
+}
+
+
+
+sub warn {
+ return CORE::warn( _my_program(), ': ', @_, "\n" );
+}
+
+
+sub die {
+ return CORE::die( _my_program(), ': ', @_, "\n" );
+}
+
+sub _my_program {
+ require File::Basename;
+ return File::Basename::basename( $0 );
+}
+
+
+
+sub filetypes_supported {
+ return keys %mappings;
+}
+
+sub _get_thpppt {
+ my $y = q{_ /|,\\'!.x',=(www)=, U };
+ $y =~ tr/,x!w/\nOo_/;
+ return $y;
+}
+
+sub _thpppt {
+ my $y = _get_thpppt();
+ App::Ack::print( "$y ack $_[0]!\n" );
+ exit 0;
+}
+
+sub _bar {
+ my $x;
+ $x = <<'_BAR';
+ 6?!I'7!I"?%+!
+ 3~!I#7#I"7#I!?!+!="+"="+!:!
+ 2?#I!7!I!?#I!7!I"+"=%+"=#
+ 1?"+!?*+!=#~"=!+#?"="+!
+ 0?"+!?"I"?&+!="~!=!~"=!+%="+"
+ /I!+!?)+!?!+!=$~!=!~!="+!="+"?!="?!
+ .?%I"?%+%='?!=#~$="
+ ,,!?%I"?(+$=$~!=#:"~$:!~!
+ ,I!?!I!?"I"?!+#?"+!?!+#="~$:!~!:!~!:!,!:!,":#~!
+ +I!?&+!="+!?#+$=!~":!~!:!~!:!,!:#,!:!,%:"
+ *+!I!?!+$=!+!=!+!?$+#=!~":!~":#,$:",#:!,!:!
+ *I!?"+!?!+!=$+!?#+#=#~":$,!:",!:!,&:"
+ )I!?$=!~!=#+"?!+!=!+!=!~!="~!:!~":!,'.!,%:!~!
+ (=!?"+!?!=!~$?"+!?!+!=#~"=",!="~$,$.",#.!:!=!
+ (I"+"="~"=!+&=!~"=!~!,!~!+!=!?!+!?!=!I!?!+"=!.",!.!,":!
+ %I$?!+!?!=%+!~!+#~!=!~#:#=!~!+!~!=#:!,%.!,!.!:"
+ $I!?!=!?!I!+!?"+!=!~!=!~!?!I!?!=!+!=!~#:",!~"=!~!:"~!=!:",&:" '-/
+ $?!+!I!?"+"=!+"~!,!:"+#~#:#,"=!~"=!,!~!,!.",!:".!:! */! !I!t!'!s! !a! !g!r!e!p!!! !/!
+ $+"=!+!?!+"~!=!:!~!:"I!+!,!~!=!:!~!,!:!,$:!~".&:"~!,# (-/
+ %~!=!~!=!:!.!+"~!:!,!.!,!~!=!:$.!,":!,!.!:!~!,!:!=!.#="~!,!:" ./!
+ %=!~!?!+"?"+!=!~",!.!:!?!~!.!:!,!:!,#.!,!:","~!:!=!~!=!:",!~! ./!
+ %+"~":!~!=#~!:!~!,!.!~!:",!~!=!~!.!:!,!.",!:!,":!=":!.!,!:!7! -/!
+ %~",!:".#:!=!:!,!:"+!:!~!:!.!,!~!,!.#,!.!,$:"~!,":"~!=! */!
+ &=!~!=#+!=!~",!.!:",#:#,!.",+:!,!.",!=!+!?!
+ &~!=!~!=!~!:"~#:",!.!,#~!:!.!+!,!.",$.",$.#,!+!I!?!
+ &~!="~!:!~":!~",!~!=!~":!,!:!~!,!:!,&.$,#."+!?!I!?!I!
+ &~!=!~!=!+!,!:!~!:!=!,!:!~&:$,!.!,".!,".!,#."~!+!?$I!
+ &~!=!~!="~!=!:!~":!,!~%:#,!:",!.!,#.",#I!7"I!?!+!?"I"
+ &+!I!7!:#~"=!~!:!,!:"~$.!=!.!,!~!,$.#,!~!7!I#?!+!?"I"7!
+ %7#?!+!~!:!=!~!=!~":!,!:"~":#.!,)7#I"?"I!7&
+ %7#I!=":!=!~!:"~$:"~!:#,!:!,!:!~!:#,!7#I!?#7)
+ $7$+!,!~!=#~!:!~!:!~$:#,!.!~!:!=!,":!7#I"?#7+=!?!
+ $7#I!~!,!~#=!~!:"~!:!,!:!,#:!=!~",":!7$I!?#I!7*+!=!+"
+ "I!7$I!,":!,!.!=":$,!:!,$:$7$I!+!?"I!7+?"I!7!I!7!,!
+ !,!7%I!:",!."~":!,&.!,!:!~!I!7$I!+!?"I!7,?!I!7',!
+ !7(,!.#~":!,%.!,!7%I!7!?#I"7,+!?!7*
+7+:!,!~#,"=!7'I!?#I"7/+!7+
+77I!+!7!?!7!I"71+!7,
+_BAR
+
+ return App::Ack::__pic($x);
+}
+
+sub _cathy {
+ my $x = <<'CATHY';
+ 0+!--+!
+ 0|! "C!H!O!C!O!L!A!T!E!!! !|!
+ 0|! "C!H!O!C!O!L!A!T!E!!! !|!
+ 0|! "C!H!O!C!O!L!A!T!E!!! !|!
+ 0|! $A"C!K!!! $|!
+ 0+!--+!
+ 6\! 1:!,!.! !
+ 7\! /.!M!~!Z!M!~!
+ 8\! /~!D! "M! !
+ 4.! $\! /M!~!.!8! +.!M# 4
+ 0,!.! (\! .~!M!N! ,+!I!.!M!.! 3
+ /?!O!.!M!:! '\! .O!.! +~!Z!=!N!.! 4
+ ..! !D!Z!.!Z!.! '\! 9=!M".! 6
+ /.! !.!~!M".! '\! 8~! 9
+ 4M!.! /.!7!N!M!.! F
+ 4.! &:!M! !N"M# !M"N!M! #D!M&=! =
+ :M!7!M#:! !~!M!7!,!$!M!:! #.! !O!N!.!M!:!M# ;
+ 8Z!M"~!N!$!D!.!N!?! !I!N!.! (?!M! !M!,!D!M".! 9
+ (?!Z!M!N!:! )=!M!O!8!.!M!+!M! !M!,! !O!M! +,!M!.!M!~!Z!N!M!:! &:!~! 0
+ &8!7!.!~!M"D!M!,! &M!?!=!8! !M!,!O! !M!+! !+!O!.!M! $M#~! !.!8!M!Z!.!M! !O!M"Z! %:!~!M!Z!M!Z!.! +
+ &:!M!7!,! *M!.!Z!M! !8"M!.!M!~! !.!M!.!=! #~!8!.!M! !7!M! "N!Z#I! !D!M!,!M!.! $."M!,! !M!.! *
+ 2$!O! "N! !.!M!I! !7" "M! "+!O! !~!M! !d!O!.!7!I!M!.! !.!O!=!M!.! !M",!M!.! %.!$!O!D! +
+ 1~!O! "M!+! !8!$! "M! "?!O! %Z!8!D!M!?!8!I!O!7!M! #M!.!M! "M",!M! 4
+ 07!~! ".!8! !.!M! "I!+! !.!M! &Z!D!.!7!=!M! !:!.!M! #:!8"+! !.!+!8! !8! 3
+ /~!M! #N! !~!M!$! !.!M! !.!M" &~!M! "~!M!O! "D! $M! !8! "M!,!M!+!D!.! 1
+ #.! #?!M!N!.! #~!O! $M!.!7!$! "?" !?!~!M! '7!8!?!M!.!+!M"O! $?"$!D! !.!O! !$!7!I!.! 0
+ $,!M!:!O!?! ".! !?!=! $=!:!O! !M! "M! !M! !+!$! (.! +.!M! !M!.! !8! !+"Z!~! $:!M!$! !.! '
+ #.!8!.!I!$! $7!I! %M" !=!M! !~!M!D! "7!I! .I!O! %?!=!,!D! !,!M! !D!~!8!~! %D!M! (
+ #.!M"?! $=!O! %=!N! "8!.! !Z!M! #M!~! (M!:! #.!M" &O! !M!.! !?!,! !8!.!N!~! $8!N!M!,!.! %
+ *$!O! &M!,! "O! !.!M!.! #M! (~!M( &O!.! !7! "M! !.!M!.!M!,! #.!M! !M! &
+ )=!8!.! $.!M!O!.! "$!.!I!N! !I!M# (7!M(I! %D"Z!M! "=!I! "M! !M!:! #~!D! '
+ )D! &8!N!:! ".!O! !M!="M! "M! (7!M) %." !M!D!."M!.! !$!=! !M!,! +
+ (M! &+!.!M! #Z!7!O!M!.!~!8! +,!M#D!?!M#D! #.!Z!M#,!Z!?! !~!N! "N!.! !M! +
+ 'D!:! %$!D! !?! #M!Z! !8!.! !M"?!7!?!7! '+!I!D! !?!O!:!M!:! ":!M!:! !M!7".!M! "8!+! !:!D! !.!M! *
+ %.!O!:! $.!O!+! !D!.! #M! "M!.!+!N!I!Z! "7!M!N!M!N!?!I!7!Z!=!M'D"~! #M!.!8!$! !:! !.!M! "N!?! !,!O! )
+ !.!?!M!:!M!I! %8!,! "M!.! #M! "N! !M!.! !M!.! !+!~! !.!M!.! ':!M! $M! $M!Z!$! !M!.! "D! "M! "?!M! (
+ !7!8! !+!I! ".! "$!=! ":!$! "+! !M!.! !O! !M!I!M".! !=!~! ",!O! '=!M! $$!,! #N!:! ":!8!.! !D!~! !,!M!.! !:!M!.! &
+ !:!,!.! &Z" #D! !.!8!."M!.! !8!?!Z!M!.!M! #Z!~! !?!M!Z!.! %~!O!.!8!$!N!8!O!I!:!~! !+! #M!.! !.!M!.! !+!M! ".!~!M!+! $
+ !.! 'D!I! #?!M!.!M!,! !.!Z! !.!8! #M&O!I!?! (~!I!M"." !M!Z!.! !M!N!.! "+!$!.! "M!.! !M!?!.! "8!M! $
+ (O!8! $M! !M!.! ".!:! !+!=! #M! #.!M! !+" *$!M":!.! !M!~! "M!7! #M! #7!Z! "M"$!M!.! !.! #
+ '$!Z! #.!7!+!M! $.!,! !+!:! #N! #.!M!.!+!M! +D!M! #=!N! ":!O! #=!M! #Z!D! $M!I! %
+ $,! ".! $.!M" %$!.! !?!~! "+!7!." !.!M!,! !M! *,!N!M!.$M!?! "D!,! #M!.! #N! +
+ ,M!Z! &M! "I!,! "M! %I!M! !?!=!.! (Z!8!M! $:!M!.! !,!M! $D! #.!M!.! )
+ +8!O! &.!8! "I!,! !~!M! &N!M! !M!D! '?!N!O!." $?!7! "?!~! #M!.! #I!D!.! (
+ 3M!,! "N!.! !D" &.!+!M!.! !M":!.":!M!7!M!D! 'M!.! "M!.! "M!,! $I! )
+ 3I! #M! "M!,! !:! &.!M" ".!,! !.!$!M!I! #.! !:! !.!M!?! "N!+! ".! /
+ 1M!,! #.!M!8!M!=!.! +~!N"O!Z"~! *+!M!.! "M! 2
+ 0.!M! &M!.! 8:! %.!M!Z! "M!=! *O!,! %
+ 0?!$! &N! )." .,! %."M! ":!M!.! 0
+ 0N!:! %?!O! #.! ..! &,! &.!D!,! "N!I! 0
+CATHY
+ return App::Ack::__pic($x);
+}
+
+sub __pic {
+ my($compressed) = @_;
+ $compressed =~ s/(.)(.)/$1x(ord($2)-32)/eg;
+ App::Ack::print( $compressed );
+ exit 0;
+}
+
+
+sub show_help {
+ my $help_arg = shift || 0;
+
+ return show_help_types() if $help_arg =~ /^types?/;
+
+ App::Ack::print( <<"END_OF_HELP" );
+Usage: ack [OPTION]... PATTERN [FILES OR DIRECTORIES]
+
+Search for PATTERN in each source file in the tree from the current
+directory on down. If any files or directories are specified, then
+only those files and directories are checked. ack may also search
+STDIN, but only if no file or directory arguments are specified,
+or if one of them is "-".
+
+Default switches may be specified in ACK_OPTIONS environment variable or
+an .ackrc file. If you want no dependency on the environment, turn it
+off with --noenv.
+
+Example: ack -i select
+
+Searching:
+ -i, --ignore-case Ignore case distinctions in PATTERN
+ --[no]smart-case Ignore case distinctions in PATTERN,
+ only if PATTERN contains no upper case.
+ Ignored if -i is specified
+ -v, --invert-match Invert match: select non-matching lines
+ -w, --word-regexp Force PATTERN to match only whole words
-Q, --literal Quote all metacharacters; PATTERN is literal
Search output:
-c, --count Show number of lines matching per file
--[no]column Show the column number of the first match
- -A NUM, --after-context=NUM Print NUM lines of trailing context after matching
- lines.
- -B NUM, --before-context=NUM Print NUM lines of leading context before matching
- lines.
+ -A NUM, --after-context=NUM Print NUM lines of trailing context after
+ matching lines.
+ -B NUM, --before-context=NUM Print NUM lines of leading context before
+ matching lines.
-C [NUM], --context[=NUM] Print NUM lines (default 2) of output context.
--print0 Print null byte as separator between filenames,
File presentation:
- --pager=COMMAND Pipes all ack output through COMMAND. For example,
- --pager="less -R". Ignored if output is redirected.
- --nopager Do not send output through a pager. Cancels any
- setting in ~/.ackrc, ACK_PAGER or ACK_PAGER_COLOR.
- --[no]heading Print a filename heading above each file's results.
- (default: on when used interactively)
- --[no]break Print a break between results from different files.
- (default: on when used interactively)
+ --pager=COMMAND Pipes all ack output through COMMAND. For
+ example, --pager="less -R". Ignored if output
+ is redirected.
+ --nopager Do not send output through a pager. Cancels
+ any setting in ~/.ackrc, ACK_PAGER or
+ ACK_PAGER_COLOR.
+ --[no]heading Print a filename heading above each file's
+ results. (default: on when used interactively)
+ --[no]break Print a break between results from different
+ files. (default: on when used interactively)
--group Same as --heading --break
--nogroup Same as --noheading --nobreak
--[no]color Highlight the matching text (default: on unless
--[no]colour Same as --[no]color
--color-filename=COLOR
--color-match=COLOR
- --color-lineno=COLOR Set the color for filenames, matches, and line numbers.
+ --color-lineno=COLOR Set the color for filenames, matches, and line
+ numbers.
--flush Flush output immediately, even when ack is used
non-interactively (when output goes to a pipe or
file).
File finding:
- -f Only print the files selected, without searching.
- The PATTERN must not be specified.
- -g Same as -f, but only select files matching PATTERN.
+ -f Only print the files selected, without
+ searching. The PATTERN must not be specified.
+ -g Same as -f, but only select files matching
+ PATTERN.
--sort-files Sort the found files lexically.
--show-types Show which types each file has.
--files-from=FILE Read the list of files to search from FILE.
-x Read the list of files to search from STDIN.
File inclusion/exclusion:
- --[no]ignore-dir=name Add/Remove directory from the list of ignored dirs
+ --[no]ignore-dir=name Add/remove directory from list of ignored dirs
--[no]ignore-directory=name Synonym for ignore-dir
--ignore-file=filter Add filter for ignoring files
- -r, -R, --recurse Recurse into subdirectories (ack's default behavior)
+ -r, -R, --recurse Recurse into subdirectories (default: on)
-n, --no-recurse No descending into subdirectories
--[no]follow Follow symlinks. Default is off.
- -k, --known-types Include only files with types that ack recognizes.
+ -k, --known-types Include only files of types that ack recognizes.
- --type=X Include only X files, where X is a recognized filetype.
+ --type=X Include only X files, where X is a recognized
+ filetype.
--type=noX Exclude X files.
See "ack --help-types" for supported filetypes.
File type specification:
--type-set TYPE:FILTER:FILTERARGS
- Files with the given FILTERARGS applied to the given
- FILTER are recognized as being of type TYPE. This
- replaces an existing definition for type TYPE.
+ Files with the given FILTERARGS applied to the
+ given FILTER are recognized as being of type
+ TYPE. This replaces an existing definition for
+ type TYPE.
--type-add TYPE:FILTER:FILTERARGS
- Files with the given FILTERARGS applied to the given
- FILTER are recognized as being of type TYPE.
+ Files with the given FILTERARGS applied to the
+ given FILTER are recognized as being type TYPE.
--type-del TYPE Removes all filters associated with TYPE.
Miscellaneous:
- --[no]env Ignore environment variables and global ackrc files. --env is legal but redundant.
+ --[no]env Ignore environment variables and global ackrc
+ files. --env is legal but redundant.
--ackrc=filename Specify an ackrc file to use
- --ignore-ack-defaults Ignore the default definitions that ack includes.
- --create-ackrc Outputs a default ackrc for your customization to standard output.
+ --ignore-ack-defaults Ignore default definitions included with ack.
+ --create-ackrc Outputs a default ackrc for your customization
+ to standard output.
--help, -? This help
--help-types Display all known types
- --dump Dump information on which options are loaded from which RC files
- --[no]filter Force ack to treat standard input as a pipe (--filter) or tty (--nofilter)
+ --dump Dump information on which options are loaded
+ from which RC files
+ --[no]filter Force ack to treat standard input as a pipe
+ (--filter) or tty (--nofilter)
--man Man page
--version Display version & copyright
--thpppt Bill the Cat
--bar The warning admiral
+ --cathy Chocolate! Chocolate! Chocolate!
Exit status is 0 if match, 1 if no match.
-This is version $VERSION of ack.
+ack's home page is at http://beyondgrep.com/
+
+The full ack manual is available by running "ack --man".
+
+This is version $VERSION of ack. Run "ack --version" for full version info.
END_OF_HELP
return;
}
my $ver = sprintf( '%vd', $^V );
- my $git_revision = $GIT_REVISION ? " (git commit $GIT_REVISION)" : '';
-
return <<"END_OF_VERSION";
-ack ${VERSION}${git_revision}
+ack ${VERSION}
Running under Perl $ver at $this_perl
$copyright
}
-sub load_colors {
- eval 'use Term::ANSIColor 1.10 ()';
-
- $ENV{ACK_COLOR_MATCH} ||= 'black on_yellow';
- $ENV{ACK_COLOR_FILENAME} ||= 'bold green';
- $ENV{ACK_COLOR_LINENO} ||= 'bold yellow';
-
- return;
-}
-
-
-# print subs added in order to make it easy for a third party
+# print*() subs added in order to make it easy for a third party
# module (such as App::Wack) to redefine the display methods
# and show the results in a different way.
sub print { print {$fh} @_; return; }
exit $rc;
}
-{
-my @capture_indices;
-my $match_column_number;
-sub does_match {
- my ( $opt, $line ) = @_;
+1; # End of App::Ack
+package App::Ack::Resource;
- my $re = $opt->{regex};
- my $invert = $opt->{v};
- return unless $re;
+use warnings;
+use strict;
+use overload
+ '""' => 'name';
- $match_column_number = undef;
- @capture_indices = ();
+sub FAIL {
+ require Carp;
+ Carp::confess( 'Must be overloaded' );
+}
- if ( $invert ? $line !~ /$re/ : $line =~ /$re/ ) {
- if ( not $invert ) {
- # @- = @LAST_MATCH_START
- # @+ = @LAST_MATCH_END
- $match_column_number = $-[0] + 1;
- if ( @- > 1 ) {
- @capture_indices = map {
- [ $-[$_], $+[$_] ]
- } ( 1 .. $#- );
- }
- }
- return 1;
- }
- else {
- return;
- }
+sub new {
+ return FAIL();
}
-sub get_capture_indices {
- return @capture_indices;
-}
-sub get_match_column {
- return $match_column_number;
+sub name {
+ return FAIL();
}
-}
-sub print_matches_in_resource {
- my ( $resource, $opt ) = @_;
+sub basename {
+ return FAIL();
+}
- my $passthru = $opt->{passthru};
- my $max_count = $opt->{m} || -1;
- my $nmatches = 0;
- my $filename = $resource->name;
- my $break = $opt->{break};
- my $heading = $opt->{heading};
- my $ors = $opt->{print0} ? "\0" : "\n";
- my $color = $opt->{color};
- my $print_filename = $opt->{show_filename};
- my $has_printed_for_this_resource = 0;
+sub is_binary {
+ return FAIL();
+}
- App::Ack::iterate($resource, $opt, sub {
- if ( App::Ack::does_match($opt, $_) ) {
- if( !$has_printed_for_this_resource ) {
- if( $break && has_printed_something() ) {
- App::Ack::print_blank_line();
- }
- if( $print_filename) {
- if( $heading ) {
- my $filename = $resource->name;
- if($color) {
- $filename = Term::ANSIColor::colored($filename,
- $ENV{ACK_COLOR_FILENAME});
- }
- App::Ack::print_filename( $filename, $ors );
- }
- }
- }
- App::Ack::print_line_with_context($opt, $filename, $_, $.);
- $has_printed_for_this_resource = 1;
- $nmatches++;
- $max_count--;
- }
- elsif ( $passthru ) {
- chomp;
- if( $break && !$has_printed_for_this_resource && has_printed_something() ) {
- App::Ack::print_blank_line();
- }
- App::Ack::print_line_with_options($opt, $filename, $_, $., ':');
- $has_printed_for_this_resource = 1;
- }
- return $max_count != 0;
- });
- return $nmatches;
+sub open {
+ return FAIL();
}
-sub count_matches_in_resource {
- my ( $resource, $opt ) = @_;
- my $nmatches = 0;
+sub needs_line_scan {
+ return FAIL();
+}
- App::Ack::iterate( $resource, $opt, sub {
- ++$nmatches if App::Ack::does_match($opt, $_);
- return 1;
- } );
- return $nmatches;
+sub reset {
+ return FAIL();
}
-sub resource_has_match {
- my ( $resource, $opt ) = @_;
- return count_matches_in_resource($resource, $opt) > 0;
+sub close {
+ return FAIL();
}
-{
-my @before_ctx_lines;
-my @after_ctx_lines;
-my $is_iterating;
+sub clone {
+ return FAIL();
+}
-sub get_context {
- if ( not $is_iterating ) {
- Carp::croak( 'get_context() called outside of iterate()' );
- }
- return (
- scalar(@before_ctx_lines) ? \@before_ctx_lines : undef,
- scalar(@after_ctx_lines) ? \@after_ctx_lines : undef,
- );
+sub firstliney {
+ return FAIL();
}
-sub iterate {
- my ( $resource, $opt, $cb ) = @_;
+1;
+package App::Ack::Resources;
- $is_iterating = 1;
- local $opt->{before_context} = $opt->{output} ? 0 : $opt->{before_context};
- local $opt->{after_context} = $opt->{output} ? 0 : $opt->{after_context};
- my $n_before_ctx_lines = $opt->{before_context} || 0;
- my $n_after_ctx_lines = $opt->{after_context} || 0;
- my $current_line;
+use warnings;
+use strict;
- @after_ctx_lines = @before_ctx_lines = ();
+sub _generate_error_handler {
+ my $opt = shift;
- if ( $resource->next_text() ) {
- $current_line = $_; # prime the first line of input
+ if ( $opt->{dont_report_bad_filenames} ) {
+ return sub {
+ my $msg = shift;
+ # XXX restricting to specific error messages for now; I would
+ # prefer a different way of doing this
+ if ( $msg =~ /Permission denied/ ) {
+ return;
+ }
+ App::Ack::warn( $msg );
+ };
+ }
+ else {
+ return sub {
+ my $msg = shift;
+ App::Ack::warn( $msg );
+ };
}
+}
- while ( defined $current_line ) {
- while ( (@after_ctx_lines < $n_after_ctx_lines) && $resource->next_text() ) {
- push @after_ctx_lines, $_;
- }
- local $_ = $current_line;
- my $former_dot_period = $.;
- $. = $. - @after_ctx_lines;
+sub from_argv {
+ my $class = shift;
+ my $opt = shift;
+ my $start = shift;
- last unless $cb->();
+ my $self = bless {}, $class;
- # I tried doing this with local(), but for some reason,
- # $. continued to have its new value after the exit of the
- # enclosing block. I'm guessing that $. has some extra
- # magic associated with it or something. If someone can
- # tell me why this happened, I would love to know!
- $. = $former_dot_period; # XXX this won't happen on an exception
+ my $file_filter = undef;
+ my $descend_filter = $opt->{descend_filter};
- push @before_ctx_lines, $current_line;
-if($n_after_ctx_lines) {
- $current_line = shift @after_ctx_lines;
- }
- elsif($resource->next_text()) {
- $current_line = $_;
- }
- else {
- undef $current_line;
- }
- shift @before_ctx_lines while @before_ctx_lines > $n_before_ctx_lines;
+ if( $opt->{n} ) {
+ $descend_filter = sub {
+ return 0;
+ };
}
- $is_iterating = 0; # XXX this won't happen on an exception
- # then again, do we care? ack doesn't really
- # handle exceptions anyway.
+ $self->{iter} =
+ File::Next::files( {
+ file_filter => $opt->{file_filter},
+ descend_filter => $descend_filter,
+ error_handler => _generate_error_handler($opt),
+ warning_handler => sub {},
+ sort_files => $opt->{sort_files},
+ follow_symlinks => $opt->{follow},
+ }, @{$start} );
- return;
+ return $self;
}
-}
-my $has_printed_something;
+sub from_file {
+ my $class = shift;
+ my $opt = shift;
+ my $file = shift;
-BEGIN {
- $has_printed_something = 0;
-}
+ my $iter =
+ File::Next::from_file( {
+ error_handler => _generate_error_handler($opt),
+ warning_handler => _generate_error_handler($opt),
+ sort_files => $opt->{sort_files},
+ }, $file ) or return undef;
-sub has_printed_something {
- return $has_printed_something;
+ return bless {
+ iter => $iter,
+ }, $class;
}
-sub print_line_with_options {
- my ( $opt, $filename, $line, $line_no, $separator ) = @_;
-
- $has_printed_something = 1;
-
- my $print_filename = $opt->{show_filename};
- my $print_column = $opt->{column};
- my $ors = $opt->{print0} ? "\0" : "\n";
- my $heading = $opt->{heading};
- my $output_expr = $opt->{output};
- my $re = $opt->{regex};
- my $color = $opt->{color};
-
- my @line_parts;
+# This is for reading input lines from STDIN, not the list of files from STDIN
+sub from_stdin {
+ my $class = shift;
+ my $opt = shift;
- if( $color ) {
- $filename = Term::ANSIColor::colored($filename,
- $ENV{ACK_COLOR_FILENAME});
- $line_no = Term::ANSIColor::colored($line_no,
- $ENV{ACK_COLOR_LINENO});
- }
+ my $self = bless {}, $class;
- if($print_filename) {
- if( $heading ) {
- push @line_parts, $line_no;
- }
- else {
- push @line_parts, $filename, $line_no;
- }
+ my $has_been_called = 0;
- if( $print_column ) {
- push @line_parts, get_match_column();
- }
- }
- if( $output_expr ) {
- # XXX avoid re-evaluation if we can
- while( $line =~ /$re/g ) {
- my $output = eval $output_expr;
- App::Ack::print( join( $separator, @line_parts, $output ), $ors );
+ $self->{iter} = sub {
+ if ( !$has_been_called ) {
+ $has_been_called = 1;
+ return '-';
}
- }
- else {
- my @capture_indices = get_capture_indices();
- if( @capture_indices ) {
- my $offset = 0; # additional offset for when we add stuff
+ return;
+ };
- foreach my $index_pair ( @capture_indices ) {
- my ( $match_start, $match_end ) = @{$index_pair};
+ return $self;
+}
- my $substring = substr( $line,
- $offset + $match_start, $match_end - $match_start );
- my $substitution = Term::ANSIColor::colored( $substring,
- $ENV{ACK_COLOR_MATCH} );
+sub next {
+ my $self = shift;
- substr( $line, $offset + $match_start,
- $match_end - $match_start, $substitution );
+ my $file = $self->{iter}->() or return;
- $offset += length( $substitution ) - length( $substring );
- }
- }
- elsif( $color ) {
- # XXX I know $& is a no-no; fix it later
- if($line =~ s/$re/Term::ANSIColor::colored($&, $ENV{ACK_COLOR_MATCH})/ge) {
- $line .= "\033[0m\033[K";
- }
- }
+ return App::Ack::Resource::Basic->new( $file );
+}
- push @line_parts, $line;
- App::Ack::print( join( $separator, @line_parts ), $ors );
- }
+1;
+package App::Ack::Resource::Basic;
- return;
-}
-{
+use warnings;
+use strict;
-my $is_first_match;
-my $previous_file_processed;
-my $previous_line_printed;
+use Fcntl ();
+use File::Spec ();
BEGIN {
- $is_first_match = 1;
- $previous_line_printed = -1;
+ our @ISA = 'App::Ack::Resource';
}
-sub print_line_with_context {
- my ( $opt, $filename, $matching_line, $line_no ) = @_;
- my $heading = $opt->{heading};
- if( !defined($previous_file_processed) ||
- $previous_file_processed ne $filename ) {
- $previous_file_processed = $filename;
- $previous_line_printed = -1;
+sub new {
+ my $class = shift;
+ my $filename = shift;
+
+ my $self = bless {
+ filename => $filename,
+ fh => undef,
+ opened => 0,
+ }, $class;
- if( $heading ) {
- $is_first_match = 1;
- }
+ if ( $self->{filename} eq '-' ) {
+ $self->{fh} = *STDIN;
+ $self->{opened} = 1;
}
- my $ors = $opt->{print0} ? "\0" : "\n";
- my $match_word = $opt->{w};
- my $re = $opt->{regex};
- my $is_tracking_context = $opt->{after_context} || $opt->{before_context};
- my $output_expr = $opt->{output};
+ return $self;
+}
- chomp $matching_line;
- my ( $before_context, $after_context ) = get_context();
+sub name {
+ return $_[0]->{filename};
+}
- if ( $before_context ) {
- my $first_line = $. - @{$before_context};
+sub basename {
+ my ( $self ) = @_;
- if ( $first_line <= $previous_line_printed ) {
- splice @{$before_context}, 0, $previous_line_printed - $first_line + 1;
- $first_line = $. - @{$before_context};
- }
- if ( @{$before_context} ) {
- my $offset = @{$before_context};
+ # XXX definedness? pre-populate the slot with an undef?
+ unless ( exists $self->{basename} ) {
+ $self->{basename} = (File::Spec->splitpath($self->name))[2];
+ }
- if( !$is_first_match && $previous_line_printed != $first_line - 1 ) {
- App::Ack::print('--', $ors);
- }
- foreach my $line (@{$before_context}) {
- my $context_line_no = $. - $offset;
- if ( $context_line_no <= $previous_line_printed ) {
- next;
- }
+ return $self->{basename};
+}
- chomp $line;
- App::Ack::print_line_with_options($opt, $filename, $line, $context_line_no, '-');
- $previous_line_printed = $context_line_no;
- $offset--;
- }
- }
- }
- if ( $. > $previous_line_printed ) {
- if( $is_tracking_context && !$is_first_match && $previous_line_printed != $. - 1 ) {
- App::Ack::print('--', $ors);
- }
+sub needs_line_scan {
+ my $self = shift;
+ my $opt = shift;
- App::Ack::print_line_with_options($opt, $filename, $matching_line, $line_no, ':');
- $previous_line_printed = $.;
- }
+ return 1 if $opt->{v};
- if($after_context) {
- my $offset = 1;
- foreach my $line (@{$after_context}) {
- # XXX improve this!
- if ( $previous_line_printed >= $. + $offset ) {
- $offset++;
- next;
- }
- chomp $line;
- my $separator = App::Ack::does_match( $opt, $line ) ? ':' : '-';
- App::Ack::print_line_with_options($opt, $filename, $line, $. + $offset, $separator);
- $previous_line_printed = $. + $offset;
- $offset++;
- }
+ my $size = -s $self->{fh};
+ if ( $size == 0 ) {
+ return 0;
+ }
+ elsif ( $size > 100_000 ) {
+ return 1;
}
- $is_first_match = 0;
+ my $buffer;
+ my $rc = sysread( $self->{fh}, $buffer, $size );
+ if ( !defined($rc) && $App::Ack::report_bad_filenames ) {
+ App::Ack::warn( "$self->{filename}: $!" );
+ return 1;
+ }
+ return 0 unless $rc && ( $rc == $size );
- return;
+ my $regex = $opt->{regex};
+ return $buffer =~ /$regex/m;
}
-}
-# inefficient, but functional
-sub filetypes {
- my ( $resource ) = @_;
+sub reset {
+ my $self = shift;
- my @matches;
-
- foreach my $k (keys %mappings) {
- my $filters = $mappings{$k};
+ # return if we haven't opened the file yet
+ if ( !defined($self->{fh}) ) {
+ return;
+ }
- foreach my $filter (@{$filters}) {
- # clone the resource
- my $clone = $resource->clone;
- if ( $filter->filter($clone) ) {
- push @matches, $k;
- last;
- }
- }
+ if( !seek( $self->{fh}, 0, 0 ) && $App::Ack::report_bad_filenames ) {
+ App::Ack::warn( "$self->{filename}: $!" );
}
- return sort @matches;
+ return;
}
-# 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 ( $is_windows ) {
- return File::Next::reslash( $filename );
+sub close {
+ my $self = shift;
+
+ # return if we haven't opened the file yet
+ if ( !defined($self->{fh}) ) {
+ return;
}
- 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;
- }
+
+ if ( !close($self->{fh}) && $App::Ack::report_bad_filenames ) {
+ App::Ack::warn( $self->name() . ": $!" );
}
-}
-sub create_ackrc {
- print "$_\n" for ( '--ignore-ack-defaults', App::Ack::ConfigDefault::options() );
+ $self->{opened} = 0;
+
+ return;
}
+sub clone {
+ my ( $self ) = @_;
-1; # End of App::Ack
-package App::Ack::Resource;
+ return __PACKAGE__->new($self->name);
+}
+sub firstliney {
+ my ( $self ) = @_;
-use warnings;
-use strict;
-use overload
- '""' => 'name';
+ my $fh = $self->open();
-sub FAIL {
- require Carp;
- Carp::confess( 'Must be overloaded' );
-}
+ if ( !exists $self->{firstliney} ) {
+ my $buffer = '';
+ my $rc = sysread( $fh, $buffer, 250 );
+ unless($rc) { # XXX handle this better?
+ $buffer = '';
+ }
+ $buffer =~ s/[\r\n].*//s;
+ $self->{firstliney} = $buffer;
+ $self->reset;
+ }
+ $self->close;
-sub new {
- return FAIL();
+ return $self->{firstliney};
}
+sub open {
+ my ( $self ) = @_;
+
+ return $self->{fh} if $self->{opened};
-sub name {
- return FAIL();
-}
+ if ( ! open $self->{fh}, '<', $self->{filename} ) {
+ return;
+ }
+ $self->{opened} = 1;
-sub is_binary {
- return FAIL();
+ return $self->{fh};
}
+1;
+package App::Ack::ConfigDefault;
+use warnings;
+use strict;
-sub needs_line_scan {
- return FAIL();
-}
-sub reset {
- return FAIL();
+sub options {
+ return split( /\n/, _options_block() );
}
-sub next_text {
- return FAIL();
+sub options_clean {
+ return grep { /./ && !/^#/ } options();
}
-sub close {
- return FAIL();
-}
+sub _options_block {
+ my $lines = <<'HERE';
+# This is the default ackrc for ack version ==VERSION==.
+# There are four different ways to match
+#
+# is: Match the filename exactly
+#
+# ext: Match the extension of the filename exactly
+#
+# match: Match the filename against a Perl regular expression
+#
+# firstlinematch: Match the first 250 characters of the first line
+# of text against a Perl regular expression. This is only for
+# the --type-add option.
-sub clone {
- return FAIL();
-}
-1;
-package App::Ack::Resources;
+### Directories to ignore
+# Bazaar
+# http://bazaar.canonical.com/
+--ignore-directory=is:.bzr
+# Codeville
+# http://freecode.com/projects/codeville
+--ignore-directory=is:.cdv
-use warnings;
-use strict;
+# Interface Builder (Xcode)
+# http://en.wikipedia.org/wiki/Interface_Builder
+--ignore-directory=is:~.dep
+--ignore-directory=is:~.dot
+--ignore-directory=is:~.nib
+--ignore-directory=is:~.plst
+# Git
+# http://git-scm.com/
+--ignore-directory=is:.git
-sub from_argv {
- my $class = shift;
- my $opt = shift;
- my $start = shift;
+# Mercurial
+# http://mercurial.selenic.com/
+--ignore-directory=is:.hg
- my $self = bless {}, $class;
+# quilt
+# http://directory.fsf.org/wiki/Quilt
+--ignore-directory=is:.pc
- my $file_filter = undef;
- my $descend_filter = $opt->{descend_filter};
+# Subversion
+# http://subversion.tigris.org/
+--ignore-directory=is:.svn
- if( $opt->{n} ) {
- $descend_filter = sub {
- return 0;
- };
- }
+# Monotone
+# http://www.monotone.ca/
+--ignore-directory=is:_MTN
- $self->{iter} =
- File::Next::files( {
- file_filter => $opt->{file_filter},
- descend_filter => $descend_filter,
- error_handler => sub { my $msg = shift; App::Ack::warn( $msg ) },
- sort_files => $opt->{sort_files},
- follow_symlinks => $opt->{follow},
- }, @{$start} );
+# CVS
+# http://savannah.nongnu.org/projects/cvs
+--ignore-directory=is:CVS
- return $self;
-}
+# RCS
+# http://www.gnu.org/software/rcs/
+--ignore-directory=is:RCS
+# SCCS
+# http://en.wikipedia.org/wiki/Source_Code_Control_System
+--ignore-directory=is:SCCS
-sub from_file {
- my $class = shift;
- my $opt = shift;
- my $file = shift;
+# darcs
+# http://darcs.net/
+--ignore-directory=is:_darcs
- my $iter =
- File::Next::from_file( {
- error_handler => sub { my $msg = shift; App::Ack::warn( $msg ) },
- warning_handler => sub { my $msg = shift; App::Ack::warn( $msg ) },
- sort_files => $opt->{sort_files},
- }, $file ) or return undef;
+# Vault/Fortress
+--ignore-directory=is:_sgbak
- return bless {
- iter => $iter,
- }, $class;
-}
+# autoconf
+# http://www.gnu.org/software/autoconf/
+--ignore-directory=is:autom4te.cache
-# This is for reading input lines from STDIN, not the list of files from STDIN
-sub from_stdin {
- my $class = shift;
- my $opt = shift;
+# Perl module building
+--ignore-directory=is:blib
+--ignore-directory=is:_build
- my $self = bless {}, $class;
+# Perl Devel::Cover module's output directory
+# https://metacpan.org/release/Devel-Cover
+--ignore-directory=is:cover_db
- my $has_been_called = 0;
+# Node modules created by npm
+--ignore-directory=is:node_modules
- $self->{iter} = sub {
- if ( !$has_been_called ) {
- $has_been_called = 1;
- return '-';
- }
- return;
- };
+# CMake cache
+# http://www.cmake.org/
+--ignore-directory=is:CMakeFiles
- return $self;
-}
+# Eclipse workspace folder
+# http://eclipse.org/
+--ignore-directory=is:.metadata
-sub next {
- my $self = shift;
+# Cabal (Haskell) sandboxes
+# http://www.haskell.org/cabal/users-guide/installing-packages.html
+--ignore-directory=is:.cabal-sandbox
- my $file = $self->{iter}->() or return;
+### Files to ignore
- return App::Ack::Resource::Basic->new( $file );
-}
+# Backup files
+--ignore-file=ext:bak
+--ignore-file=match:/~$/
-1;
-package App::Ack::Resource::Basic;
+# Emacs swap files
+--ignore-file=match:/^#.+#$/
+# vi/vim swap files http://vim.org/
+--ignore-file=match:/[._].*\.swp$/
-use warnings;
-use strict;
+# core dumps
+--ignore-file=match:/core\.\d+$/
-BEGIN {
- our @ISA = 'App::Ack::Resource';
-}
+# minified Javascript
+--ignore-file=match:/[.-]min[.]js$/
+--ignore-file=match:/[.]js[.]min$/
+# minified CSS
+--ignore-file=match:/[.]min[.]css$/
+--ignore-file=match:/[.]css[.]min$/
-sub new {
- my $class = shift;
- my $filename = shift;
+# JS and CSS source maps
+--ignore-file=match:/[.]js[.]map$/
+--ignore-file=match:/[.]css[.]map$/
- my $self = bless {
- filename => $filename,
- fh => undef,
- opened => undef,
- }, $class;
+# PDFs, because they pass Perl's -T detection
+--ignore-file=ext:pdf
- if ( $self->{filename} eq '-' ) {
- $self->{fh} = *STDIN;
- }
- else {
- if ( !open( $self->{fh}, '<', $self->{filename} ) && $App::Ack::report_bad_filenames ) {
- App::Ack::warn( "$self->{filename}: $!" );
- return;
- }
- }
+# Common graphics, just as an optimization
+--ignore-file=ext:gif,jpg,jpeg,png
- return $self;
-}
+### Filetypes defined
-sub name {
- my $self = shift;
+# Perl
+# http://perl.org/
+--type-add=perl:ext:pl,pm,pod,t,psgi
+--type-add=perl:firstlinematch:/^#!.*\bperl/
- return $self->{filename};
-}
+# Perl tests
+--type-add=perltest:ext:t
+# Makefiles
+# http://www.gnu.org/s/make/
+--type-add=make:ext:mk
+--type-add=make:ext:mak
+--type-add=make:is:makefile
+--type-add=make:is:Makefile
+--type-add=make:is:Makefile.Debug
+--type-add=make:is:Makefile.Release
+# Rakefiles
+# http://rake.rubyforge.org/
+--type-add=rake:is:Rakefile
-sub needs_line_scan {
- my $self = shift;
- my $opt = shift;
+# CMake
+# http://www.cmake.org/
+--type-add=cmake:is:CMakeLists.txt
+--type-add=cmake:ext:cmake
- return 1 if $opt->{v};
+# Actionscript
+--type-add=actionscript:ext:as,mxml
- my $size = -s $self->{fh};
- if ( $size == 0 ) {
- return 0;
- }
- elsif ( $size > 100_000 ) {
- return 1;
- }
+# Ada
+# http://www.adaic.org/
+--type-add=ada:ext:ada,adb,ads
- my $buffer;
- my $rc = sysread( $self->{fh}, $buffer, $size );
- if ( !defined($rc) && $App::Ack::report_bad_filenames ) {
- App::Ack::warn( "$self->{filename}: $!" );
- return 1;
- }
- return 0 unless $rc && ( $rc == $size );
+# ASP
+# http://msdn.microsoft.com/en-us/library/aa286483.aspx
+--type-add=asp:ext:asp
- my $regex = $opt->{regex};
- return $buffer =~ /$regex/m;
-}
+# ASP.Net
+# http://www.asp.net/
+--type-add=aspx:ext:master,ascx,asmx,aspx,svc
+# Assembly
+--type-add=asm:ext:asm,s
-sub reset {
- my $self = shift;
+# Batch
+--type-add=batch:ext:bat,cmd
- if( !seek( $self->{fh}, 0, 0 ) && $App::Ack::report_bad_filenames ) {
- App::Ack::warn( "$self->{filename}: $!" );
- }
+# ColdFusion
+# http://en.wikipedia.org/wiki/ColdFusion
+--type-add=cfmx:ext:cfc,cfm,cfml
- return;
-}
+# Clojure
+# http://clojure.org/
+--type-add=clojure:ext:clj
+# C
+# .xs are Perl C files
+--type-add=cc:ext:c,h,xs
-sub next_text {
- if ( defined ($_ = readline $_[0]->{fh}) ) {
- $. = ++$_[0]->{line};
- s/[\r\n]+$//; # chomp may not handle this
- $_ .= "\n"; # add back newline (XXX make it native)
- return 1;
- }
+# C header files
+--type-add=hh:ext:h
- return;
-}
+# CoffeeScript
+# http://coffeescript.org/
+--type-add=coffeescript:ext:coffee
+# C++
+--type-add=cpp:ext:cpp,cc,cxx,m,hpp,hh,h,hxx
-sub close {
- my $self = shift;
+# C++ header files
+--type-add=hpp:ext:hpp,hh,h,hxx
- if ( !close($self->{fh}) && $App::Ack::report_bad_filenames ) {
- App::Ack::warn( $self->name() . ": $!" );
- }
+# C#
+--type-add=csharp:ext:cs
- return;
-}
+# CSS
+# http://www.w3.org/Style/CSS/
+--type-add=css:ext:css
+# Dart
+# http://www.dartlang.org/
+--type-add=dart:ext:dart
-sub clone {
- my ( $self ) = @_;
+# Delphi
+# http://en.wikipedia.org/wiki/Embarcadero_Delphi
+--type-add=delphi:ext:pas,int,dfm,nfm,dof,dpk,dproj,groupproj,bdsgroup,bdsproj
- return __PACKAGE__->new($self->name);
-}
+# Elixir
+# http://elixir-lang.org/
+--type-add=elixir:ext:ex,exs
+# Emacs Lisp
+# http://www.gnu.org/software/emacs
+--type-add=elisp:ext:el
-1;
-package App::Ack::Filter;
+# Erlang
+# http://www.erlang.org/
+--type-add=erlang:ext:erl,hrl
-use strict;
-use warnings;
-use overload
- '""' => 'to_string';
+# Fortran
+# http://en.wikipedia.org/wiki/Fortran
+--type-add=fortran:ext:f,f77,f90,f95,f03,for,ftn,fpp
-use Carp 1.04 ();
+# Go
+# http://golang.org/
+--type-add=go:ext:go
-my %filter_types;
+# Groovy
+# http://groovy.codehaus.org/
+--type-add=groovy:ext:groovy,gtmpl,gpp,grunit,gradle
+# Haskell
+# http://www.haskell.org/
+--type-add=haskell:ext:hs,lhs
-sub create_filter {
- my ( undef, $type, @args ) = @_;
+# HTML
+--type-add=html:ext:htm,html
- if ( my $package = $filter_types{$type} ) {
- return $package->new(@args);
- }
- Carp::croak "Unknown filter type '$type'";
-}
+# Jade
+# http://jade-lang.com/
+--type-add=jade:ext:jade
+# Java
+# http://www.oracle.com/technetwork/java/index.html
+--type-add=java:ext:java,properties
-sub register_filter {
- my ( undef, $type, $package ) = @_;
+# JavaScript
+--type-add=js:ext:js
- $filter_types{$type} = $package;
+# JSP
+# http://www.oracle.com/technetwork/java/javaee/jsp/index.html
+--type-add=jsp:ext:jsp,jspx,jhtm,jhtml
- return;
-}
+# JSON
+# http://www.json.org/
+--type-add=json:ext:json
+# Less
+# http://www.lesscss.org/
+--type-add=less:ext:less
-sub invert {
- my ( $self ) = @_;
+# Common Lisp
+# http://common-lisp.net/
+--type-add=lisp:ext:lisp,lsp
- return App::Ack::Filter::Inverse->new( $self );
-}
+# Lua
+# http://www.lua.org/
+--type-add=lua:ext:lua
+--type-add=lua:firstlinematch:/^#!.*\blua(jit)?/
+# Objective-C
+--type-add=objc:ext:m,h
-sub is_inverted {
- return 0;
-}
+# Objective-C++
+--type-add=objcpp:ext:mm,h
+# OCaml
+# http://caml.inria.fr/
+--type-add=ocaml:ext:ml,mli
-sub to_string {
- my ( $self ) = @_;
+# Matlab
+# http://en.wikipedia.org/wiki/MATLAB
+--type-add=matlab:ext:m
- return '(unimplemented to_string)';
-}
+# Parrot
+# http://www.parrot.org/
+--type-add=parrot:ext:pir,pasm,pmc,ops,pod,pg,tg
+# PHP
+# http://www.php.net/
+--type-add=php:ext:php,phpt,php3,php4,php5,phtml
+--type-add=php:firstlinematch:/^#!.*\bphp/
-sub inspect {
- my ( $self ) = @_;
+# Plone
+# http://plone.org/
+--type-add=plone:ext:pt,cpt,metadata,cpy,py
- return ref($self);
-}
+# Python
+# http://www.python.org/
+--type-add=python:ext:py
+--type-add=python:firstlinematch:/^#!.*\bpython/
-1;
-package App::Ack::Filter::Extension;
+# R
+# http://www.r-project.org/
+--type-add=rr:ext:R
-use strict;
-use warnings;
-BEGIN {
- our @ISA = 'App::Ack::Filter';
-}
+# reStructured Text
+# http://docutils.sourceforge.net/rst.html
+--type-add=rst:ext:rst
-sub new {
- my ( $class, @extensions ) = @_;
+# Ruby
+# http://www.ruby-lang.org/
+--type-add=ruby:ext:rb,rhtml,rjs,rxml,erb,rake,spec
+--type-add=ruby:is:Rakefile
+--type-add=ruby:firstlinematch:/^#!.*\bruby/
- my $exts = join('|', map { "\Q$_\E"} @extensions);
- my $re = qr/[.](?:$exts)$/i;
+# Rust
+# http://www.rust-lang.org/
+--type-add=rust:ext:rs
- return bless {
- extensions => \@extensions,
- regex => $re,
- }, $class;
-}
+# Sass
+# http://sass-lang.com
+--type-add=sass:ext:sass,scss
-sub filter {
- my ( $self, $resource ) = @_;
+# Scala
+# http://www.scala-lang.org/
+--type-add=scala:ext:scala
- my $re = $self->{'regex'};
+# Scheme
+# http://groups.csail.mit.edu/mac/projects/scheme/
+--type-add=scheme:ext:scm,ss
- return $resource->name =~ /$re/;
-}
+# Shell
+--type-add=shell:ext:sh,bash,csh,tcsh,ksh,zsh,fish
+--type-add=shell:firstlinematch:/^#!.*\b(?:ba|t?c|k|z|fi)?sh\b/
-sub inspect {
- my ( $self ) = @_;
+# Smalltalk
+# http://www.smalltalk.org/
+--type-add=smalltalk:ext:st
- my $re = $self->{'regex'};
+# Smarty
+# http://www.smarty.net/
+--type-add=smarty:ext:tpl
- return ref($self) . " - $re";
-}
+# SQL
+# http://www.iso.org/iso/catalogue_detail.htm?csnumber=45498
+--type-add=sql:ext:sql,ctl
-sub to_string {
- my ( $self ) = @_;
+# Stylus
+# http://learnboost.github.io/stylus/
+--type-add=stylus:ext:styl
- my $exts = $self->{'extensions'};
+# Tcl
+# http://www.tcl.tk/
+--type-add=tcl:ext:tcl,itcl,itk
- return join(' ', map { ".$_" } @{$exts});
-}
+# LaTeX
+# http://www.latex-project.org/
+--type-add=tex:ext:tex,cls,sty
-BEGIN {
- App::Ack::Filter->register_filter(ext => __PACKAGE__);
-}
+# Template Toolkit (Perl)
+# http://template-toolkit.org/
+--type-add=tt:ext:tt,tt2,ttml
-1;
-package App::Ack::Filter::FirstLineMatch;
+# Visual Basic
+--type-add=vb:ext:bas,cls,frm,ctl,vb,resx
-use strict;
-use warnings;
-BEGIN {
- our @ISA = 'App::Ack::Filter';
-}
+# Verilog
+--type-add=verilog:ext:v,vh,sv
-sub new {
- my ( $class, $re ) = @_;
+# VHDL
+# http://www.eda.org/twiki/bin/view.cgi/P1076/WebHome
+--type-add=vhdl:ext:vhd,vhdl
- $re =~ s{^/|/$}{}g; # XXX validate?
- $re = qr{$re}i;
+# Vim
+# http://www.vim.org/
+--type-add=vim:ext:vim
- return bless {
- regex => $re,
- }, $class;
+# XML
+# http://www.w3.org/TR/REC-xml/
+--type-add=xml:ext:xml,dtd,xsl,xslt,ent
+--type-add=xml:firstlinematch:/<[?]xml/
+
+# YAML
+# http://yaml.org/
+--type-add=yaml:ext:yaml,yml
+HERE
+ $lines =~ s/==VERSION==/$App::Ack::VERSION/sm;
+
+ return $lines;
}
-# This test reads the first 250 characters of a file, then just uses the
-# first line found in that. This prevents reading something like an entire
-# .min.js file (which might be only one "line" long) into memory.
+1;
+package App::Ack::ConfigFinder;
-sub filter {
- my ( $self, $resource ) = @_;
- my $re = $self->{'regex'};
+use strict;
+use warnings;
- my $buffer;
- my $rc = sysread( $resource->{fh}, $buffer, 250 );
- return unless $rc;
- $buffer =~ s/[\r\n].*//s;
+use Cwd 3.00 ();
+use File::Spec 3.00;
- return $buffer =~ /$re/;
-}
+use if ($^O eq 'MSWin32'), 'Win32';
-sub inspect {
- my ( $self ) = @_;
- my $re = $self->{'regex'};
+sub new {
+ my ( $class ) = @_;
- return ref($self) . " - $re";
+ return bless {}, $class;
}
-sub to_string {
- my ( $self ) = @_;
-
- (my $re = $self->{regex}) =~ s{\([^:]*:(.*)\)$}{$1};
- return "first line matches /$re/";
+sub _remove_redundancies {
+ my @configs = @_;
+
+ my %seen;
+ foreach my $config (@configs) {
+ my $key = $config->{path};
+ if ( not $App::Ack::is_windows ) {
+ # On Unix, uniquify on inode.
+ my ($dev, $inode) = (stat $key)[0, 1];
+ $key = "$dev:$inode" if defined $dev;
+ }
+ undef $config if $seen{$key}++;
+ }
+ return grep { defined } @configs;
}
-BEGIN {
- App::Ack::Filter->register_filter(firstlinematch => __PACKAGE__);
-}
-1;
-package App::Ack::Filter::Is;
+sub _check_for_ackrc {
+ return unless defined $_[0];
-use strict;
-use warnings;
-BEGIN {
- our @ISA = 'App::Ack::Filter';
-}
+ my @files = grep { -f }
+ map { File::Spec->catfile(@_, $_) }
+ qw(.ackrc _ackrc);
-use File::Spec 3.00 ();
+ die File::Spec->catdir(@_) . " contains both .ackrc and _ackrc.\n" .
+ "Please remove one of those files.\n"
+ if @files > 1;
-sub new {
- my ( $class, $filename ) = @_;
+ return wantarray ? @files : $files[0];
+} # end _check_for_ackrc
- return bless {
- filename => $filename,
- }, $class;
-}
-sub filter {
- my ( $self, $resource ) = @_;
- my $filename = $self->{'filename'};
- my $base = (File::Spec->splitpath($resource->name))[2];
+sub find_config_files {
+ my @config_files;
- return $base eq $filename;
-}
+ if ( $App::Ack::is_windows ) {
+ push @config_files, map { +{ path => File::Spec->catfile($_, 'ackrc') } } (
+ Win32::GetFolderPath(Win32::CSIDL_COMMON_APPDATA()),
+ Win32::GetFolderPath(Win32::CSIDL_APPDATA()),
+ );
+ }
+ else {
+ push @config_files, { path => '/etc/ackrc' };
+ }
-sub inspect {
- my ( $self ) = @_;
- my $filename = $self->{'filename'};
+ if ( $ENV{'ACKRC'} && -f $ENV{'ACKRC'} ) {
+ push @config_files, { path => $ENV{'ACKRC'} };
+ }
+ else {
+ push @config_files, map { +{ path => $_ } } _check_for_ackrc($ENV{'HOME'});
+ }
- return ref($self) . " - $filename";
+ # XXX This should go through some untainted cwd-fetching function, and not get untainted inline like this.
+ my $cwd = Cwd::getcwd();
+ $cwd =~ /(.+)/;
+ $cwd = $1;
+ my @dirs = File::Spec->splitdir( $cwd );
+ while(@dirs) {
+ my $ackrc = _check_for_ackrc(@dirs);
+ if(defined $ackrc) {
+ push @config_files, { project => 1, path => $ackrc };
+ last;
+ }
+ pop @dirs;
+ }
+
+ # We only test for existence here, so if the file is deleted out from under us, this will fail later.
+ return _remove_redundancies( @config_files );
}
-sub to_string {
- my ( $self ) = @_;
-
- my $filename = $self->{'filename'};
-}
-
-BEGIN {
- App::Ack::Filter->register_filter(is => __PACKAGE__);
-}
-
-1;
-package App::Ack::Filter::Match;
-
-use strict;
-use warnings;
-BEGIN {
- our @ISA = 'App::Ack::Filter';
-}
-
-use File::Spec 3.00;
-
-sub new {
- my ( $class, $re ) = @_;
-
- $re =~ s{^/|/$}{}g; # XXX validate?
- $re = qr/$re/i;
-
- return bless {
- regex => $re,
- }, $class;
-}
-
-sub filter {
- my ( $self, $resource ) = @_;
-
- my $re = $self->{'regex'};
- my $base = (File::Spec->splitpath($resource->name))[2];
-
- return $base =~ /$re/;
-}
-
-sub inspect {
- my ( $self ) = @_;
-
- my $re = $self->{'regex'};
-
- print ref($self) . " - $re";
-}
-
-sub to_string {
- my ( $self ) = @_;
-
- my $re = $self->{'regex'};
-
- return "filename matches $re";
-}
-
-BEGIN {
- App::Ack::Filter->register_filter(match => __PACKAGE__);
-}
-
-1;
-package App::Ack::Filter::Default;
-
-use strict;
-use warnings;
-BEGIN {
- our @ISA = 'App::Ack::Filter';
-}
-
-sub new {
- my ( $class ) = @_;
-
- return bless {}, $class;
-}
-
-sub filter {
- my ( $self, $resource ) = @_;
-
- return -T $resource->name;
-}
-
-1;
-package App::Ack::Filter::Inverse;
-
-use strict;
-use warnings;
-BEGIN {
- our @ISA = 'App::Ack::Filter';
-}
-
-sub new {
- my ( $class, $filter ) = @_;
-
- return bless {
- filter => $filter,
- }, $class;
-}
-
-sub filter {
- my ( $self, $resource ) = @_;
-
- my $filter = $self->{'filter'};
- return !$filter->filter( $resource );
-}
-
-sub invert {
- my $self = shift;
-
- return $self->{'filter'};
-}
-
-sub is_inverted {
- return 1;
-}
-
-sub inspect {
- my ( $self ) = @_;
-
- my $filter = $self->{'filter'};
-
- return "!$filter";
-}
-
-1;
-package App::Ack::ConfigFinder;
-
-
-use strict;
-use warnings;
-
-use Cwd 3.00 ();
-use File::Spec 3.00;
-
-BEGIN {
- if ($App::Ack::is_windows) {
- require Win32;
- }
-}
-
-
-sub new {
- my ( $class ) = @_;
-
- return bless {}, $class;
-}
-
-sub _remove_redundancies {
- my ( @configs ) = @_;
-
- my %dev_and_inode_seen;
-
- foreach my $path ( @configs ) {
- my ( $dev, $inode ) = (stat $path)[0, 1];
- if( defined($dev) ) {
- if( $dev_and_inode_seen{"$dev:$inode"} ) {
- undef $path;
- }
- else {
- $dev_and_inode_seen{"$dev:$inode"} = 1;
- }
- }
- }
- return grep { defined() } @configs;
-}
-
-sub _check_for_ackrc {
- return unless defined $_[0];
-
- my @files = grep { -f }
- map { File::Spec->catfile(@_, $_) }
- qw(.ackrc _ackrc);
-
- die File::Spec->catdir(@_) . " contains both .ackrc and _ackrc.\n" .
- "Please remove one of those files.\n"
- if @files > 1;
- return wantarray ? @files : $files[0];
-} # end _check_for_ackrc
+sub read_rcfile {
+ my $file = shift;
+ return unless defined $file && -e $file;
-sub find_config_files {
- my @config_files;
+ my @lines;
- if($App::Ack::is_windows) {
- push @config_files, map { File::Spec->catfile($_, 'ackrc') } (
- Win32::GetFolderPath(Win32::CSIDL_COMMON_APPDATA()),
- Win32::GetFolderPath(Win32::CSIDL_APPDATA()),
- );
- }
- else {
- push @config_files, '/etc/ackrc';
- }
+ open( my $fh, '<', $file ) or App::Ack::die( "Unable to read $file: $!" );
+ while ( my $line = <$fh> ) {
+ chomp $line;
+ $line =~ s/^\s+//;
+ $line =~ s/\s+$//;
- if ( $ENV{'ACKRC'} && -f $ENV{'ACKRC'} ) {
- push @config_files, $ENV{'ACKRC'};
- }
- else {
- push @config_files, _check_for_ackrc($ENV{'HOME'});
- }
+ next if $line eq '';
+ next if $line =~ /^\s*#/;
- my @dirs = File::Spec->splitdir(Cwd::getcwd());
- while(@dirs) {
- my $ackrc = _check_for_ackrc(@dirs);
- if(defined $ackrc) {
- push @config_files, $ackrc;
- last;
- }
- pop @dirs;
+ push( @lines, $line );
}
+ close $fh or App::Ack::die( "Unable to close $file: $!" );
- # XXX we only test for existence here, so if the file is
- # deleted out from under us, this will fail later. =(
- return _remove_redundancies( @config_files );
+ return @lines;
}
1;
use warnings;
use Carp 1.04 ();
-use Getopt::Long 2.36 ();
+use Getopt::Long 2.35 ();
use Text::ParseWords 3.1 ();
);
}
+sub _generate_ignore_dir {
+ my ( $option_name, $opt ) = @_;
+
+ my $is_inverted = $option_name =~ /^--no/;
+
+ return sub {
+ my ( undef, $dir ) = @_;
+
+ $dir = App::Ack::remove_dir_sep( $dir );
+ if ( $dir !~ /:/ ) {
+ $dir = 'is:' . $dir;
+ }
+
+ my ( $filter_type, $args ) = split /:/, $dir, 2;
+
+ if ( $filter_type eq 'firstlinematch' ) {
+ Carp::croak( qq{Invalid filter specification "$filter_type" for option '$option_name'} );
+ }
+
+ my $filter = App::Ack::Filter->create_filter($filter_type, split(/,/, $args));
+ my $collection;
+
+ my $previous_inversion_matches = $opt->{idirs} && !($is_inverted xor $opt->{idirs}[-1]->is_inverted());
+
+ if ( $previous_inversion_matches ) {
+ $collection = $opt->{idirs}[-1];
+
+ if ( $is_inverted ) {
+ # XXX this relies on invert of an inverted filter
+ # to return the original
+ $collection = $collection->invert()
+ }
+ }
+ else {
+ $collection = App::Ack::Filter::Collection->new();
+
+ if ( $is_inverted ) {
+ push @{ $opt->{idirs} }, $collection->invert();
+ }
+ else {
+ push @{ $opt->{idirs} }, $collection;
+ }
+ }
+
+ $collection->add($filter);
+
+ if ( $filter_type eq 'is' ) {
+ $collection->add(App::Ack::Filter::IsPath->new($args));
+ }
+ };
+}
+
sub process_filter_spec {
my ( $spec ) = @_;
}
}
+
+sub uninvert_filter {
+ my ( $opt, @filters ) = @_;
+
+ return unless defined $opt->{filters} && @filters;
+
+ # Loop through all the registered filters. If we hit one that
+ # matches this extension and it's inverted, we need to delete it from
+ # the options.
+ for ( my $i = 0; $i < @{ $opt->{filters} }; $i++ ) {
+ my $opt_filter = @{ $opt->{filters} }[$i];
+
+ # XXX Do a real list comparison? This just checks string equivalence.
+ if ( $opt_filter->is_inverted() && "$opt_filter->{filter}" eq "@filters" ) {
+ splice @{ $opt->{filters} }, $i, 1;
+ $i--;
+ }
+ }
+}
+
+
sub process_filetypes {
my ( $opt, $arg_sources ) = @_;
if ( not $value ) {
@filters = map { $_->invert() } @filters;
}
+ else {
+ uninvert_filter( $opt, @filters );
+ }
push @{ $opt->{'filters'} }, @filters;
};
'type-del=s' => $delete_spec,
);
- for ( my $i = 0; $i < @{$arg_sources}; $i += 2) {
- my ( $source_name, $args ) = @{$arg_sources}[ $i, $i + 1];
+ foreach my $source (@{$arg_sources}) {
+ my ( $source_name, $args ) = @{$source}{qw/name contents/};
if ( ref($args) ) {
# $args are modified in place, so no need to munge $arg_sources
- Getopt::Long::GetOptionsFromArray($args, %type_arg_specs);
+ local @ARGV = @{$args};
+ Getopt::Long::GetOptions(%type_arg_specs);
+ @{$args} = @ARGV;
}
else {
- ( undef, $arg_sources->[$i + 1] ) =
+ ( undef, $source->{contents} ) =
Getopt::Long::GetOptionsFromString($args, %type_arg_specs);
}
}
return \%additional_specs;
}
+
sub removed_option {
my ( $option, $explanation ) = @_;
};
}
+
sub get_arg_spec {
my ( $opt, $extra_specs ) = @_;
- my $dash_a_explanation = <<EOT;
+ my $dash_a_explanation = <<'EOT';
This is because we now have -k/--known-types which makes it only select files
of known types, rather than any text file (which is the behavior of ack 1.x).
+You may have options in a .ackrc, or in the ACKRC_OPTIONS environment variable.
+Try using the --dump flag.
EOT
+
return {
1 => sub { $opt->{1} = $opt->{m} = 1 },
'A|after-context=i' => \$opt->{after_context},
'color-lineno=s' => \$ENV{ACK_COLOR_LINENO},
'column!' => \$opt->{column},
count => \$opt->{count},
- 'create-ackrc' => sub { App::Ack::create_ackrc(); exit; },
+ 'create-ackrc' => sub { print "$_\n" for ( '--ignore-ack-defaults', App::Ack::ConfigDefault::options() ); exit; },
'env!' => sub {
my ( undef, $value ) = @_;
'h|no-filename' => \$opt->{h},
'H|with-filename' => \$opt->{H},
'i|ignore-case' => \$opt->{i},
- 'ignore-directory|ignore-dir=s' # XXX Combine this version with the negated version below
- => sub {
- my ( undef, $dir ) = @_;
-
- $dir = App::Ack::remove_dir_sep( $dir );
- if ( $dir !~ /^(?:is|match):/ ) {
- $dir = 'is:' . $dir;
- }
- push @{ $opt->{idirs} }, $dir;
- },
- 'ignore-file=s' => sub {
+ 'ignore-directory|ignore-dir=s' => _generate_ignore_dir('--ignore-dir', $opt),
+ 'ignore-file=s' => sub {
my ( undef, $file ) = @_;
- push @{ $opt->{ifiles} }, $file;
+
+ my ( $filter_type, $args ) = split /:/, $file, 2;
+
+ my $filter = App::Ack::Filter->create_filter($filter_type, split(/,/, $args));
+
+ if ( !$opt->{ifiles} ) {
+ $opt->{ifiles} = App::Ack::Filter::Collection->new();
+ }
+ $opt->{ifiles}->add($filter);
},
'lines=s' => sub { shift; my $val = shift; push @{$opt->{lines}}, $val },
'l|files-with-matches'
'n|no-recurse' => \$opt->{n},
o => sub { $opt->{output} = '$&' },
'output=s' => \$opt->{output},
- 'pager=s' => \$opt->{pager},
- 'noignore-directory|noignore-dir=s'
- => sub {
- my ( undef, $dir ) = @_;
-
- # XXX can you do --noignore-dir=match,...?
- $dir = App::Ack::remove_dir_sep( $dir );
- if ( $dir !~ /^(?:is|match):/ ) {
- $dir = 'is:' . $dir;
- }
- if ( $dir !~ /^(?:is|match):/ ) {
- Carp::croak("invalid noignore-directory argument: '$dir'");
- }
-
- @{ $opt->{idirs} } = grep {
- $_ ne $dir
- } @{ $opt->{idirs} };
-
- push @{ $opt->{no_ignore_dirs} }, $dir;
- },
+ 'pager:s' => sub {
+ my ( undef, $value ) = @_;
+
+ $opt->{pager} = $value || $ENV{PAGER};
+ },
+ 'noignore-directory|noignore-dir=s' => _generate_ignore_dir('--noignore-dir', $opt),
'nopager' => sub { $opt->{pager} = undef },
'passthru' => \$opt->{passthru},
'print0' => \$opt->{print0},
}; # arg_specs
}
+
sub process_other {
my ( $opt, $extra_specs, $arg_sources ) = @_;
- Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version'); # start with default options, minus some annoying ones
+ # Start with default options, minus some annoying ones.
+ Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
Getopt::Long::Configure(
'bundling',
'no_ignore_case',
my $argv_source;
my $is_help_types_active;
- for ( my $i = 0; $i < @{$arg_sources}; $i += 2 ) {
- my ( $source_name, $args ) = @{$arg_sources}[ $i, $i + 1 ];
+ foreach my $source (@{$arg_sources}) {
+ my ( $source_name, $args ) = @{$source}{qw/name contents/};
if ( $source_name eq 'ARGV' ) {
$argv_source = $args;
}
}
- if ( $argv_source ) { # this *should* always be true, but you never know...
+ if ( $argv_source ) { # This *should* always be true, but you never know...
my @copy = @{$argv_source};
+ local @ARGV = @copy;
Getopt::Long::Configure('pass_through');
- Getopt::Long::GetOptionsFromArray( \@copy,
+ Getopt::Long::GetOptions(
'help-types' => \$is_help_types_active,
);
my $arg_specs = get_arg_spec($opt, $extra_specs);
- for ( my $i = 0; $i < @{$arg_sources}; $i += 2) {
- my ($source_name, $args) = @{$arg_sources}[$i, $i + 1];
+ foreach my $source (@{$arg_sources}) {
+ my ( $source_name, $args ) = @{$source}{qw/name contents/};
+
+ my $args_for_source = $arg_specs;
+
+ if ( $source->{project} ) {
+ my $illegal = sub {
+ die "Options --output, --pager and --match are forbidden in project .ackrc files.\n";
+ };
+
+ $args_for_source = { %$args_for_source,
+ 'output=s' => $illegal,
+ 'pager:s' => $illegal,
+ 'match=s' => $illegal,
+ };
+ }
my $ret;
if ( ref($args) ) {
- $ret = Getopt::Long::GetOptionsFromArray( $args, %{$arg_specs} );
+ local @ARGV = @{$args};
+ $ret = Getopt::Long::GetOptions( %{$args_for_source} );
+ @{$args} = @ARGV;
}
else {
- ( $ret, $arg_sources->[$i + 1] ) =
- Getopt::Long::GetOptionsFromString( $args, %{$arg_specs} );
+ ( $ret, $source->{contents} ) =
+ Getopt::Long::GetOptionsFromString( $args, %{$args_for_source} );
}
if ( !$ret ) {
if ( !$is_help_types_active ) {
return;
}
+
sub should_dump_options {
my ( $sources ) = @_;
- for(my $i = 0; $i < @{$sources}; $i += 2) {
- my ( $name, $options ) = @{$sources}[$i, $i + 1];
+ foreach my $source (@{$sources}) {
+ my ( $name, $options ) = @{$source}{qw/name contents/};
+
if($name eq 'ARGV') {
my $dump;
+ local @ARGV = @{$options};
Getopt::Long::Configure('default', 'pass_through', 'no_auto_help', 'no_auto_version');
- Getopt::Long::GetOptionsFromArray($options,
+ Getopt::Long::GetOptions(
'dump' => \$dump,
);
+ @{$options} = @ARGV;
return $dump;
}
}
return;
}
+
sub explode_sources {
my ( $sources ) = @_;
delete $arg_spec->{$arg};
};
- for(my $i = 0; $i < @{$sources}; $i += 2) {
- my ( $name, $options ) = @{$sources}[$i, $i + 1];
+ foreach my $source (@{$sources}) {
+ my ( $name, $options ) = @{$source}{qw/name contents/};
if ( ref($options) ne 'ARRAY' ) {
- $sources->[$i + 1] = $options =
+ $source->{contents} = $options =
[ Text::ParseWords::shellwords($options) ];
}
- for ( my $j = 0; $j < @{$options}; $j++ ) {
+
+ for my $j ( 0 .. @{$options}-1 ) {
next unless $options->[$j] =~ /^-/;
my @chunk = ( $options->[$j] );
push @chunk, $options->[$j] while ++$j < @{$options} && $options->[$j] !~ /^-/;
$j--;
my @copy = @chunk;
- Getopt::Long::GetOptionsFromArray(\@chunk,
+ local @ARGV = @chunk;
+ Getopt::Long::GetOptions(
'type-add=s' => $add_type,
'type-set=s' => $add_type,
'type-del=s' => $del_type,
);
- Getopt::Long::GetOptionsFromArray(\@chunk, %{$arg_spec});
+ Getopt::Long::GetOptions( %{$arg_spec} );
- splice @copy, -1 * @chunk if @chunk; # XXX explain this
- push @new_sources, $name, \@copy;
+ push @new_sources, {
+ name => $name,
+ contents => \@copy,
+ };
}
}
return \@new_sources;
}
+
sub compare_opts {
my ( $a, $b ) = @_;
return $first_a cmp $first_b;
}
+
sub dump_options {
my ( $sources ) = @_;
my %opts_by_source;
my @source_names;
- for(my $i = 0; $i < @{$sources}; $i += 2) {
- my ( $name, $contents ) = @{$sources}[$i, $i + 1];
+ foreach my $source (@{$sources}) {
+ my ( $name, $contents ) = @{$source}{qw/name contents/};
if ( not $opts_by_source{$name} ) {
$opts_by_source{$name} = [];
push @source_names, $name;
print ' ', join(' ', @{$_}), "\n" foreach sort { compare_opts($a, $b) } @{$contents};
}
- return;
+ return;
+}
+
+
+sub remove_default_options_if_needed {
+ my ( $sources ) = @_;
+
+ my $default_index;
+
+ foreach my $index ( 0 .. $#{$sources} ) {
+ if ( $sources->[$index]{'name'} eq 'Defaults' ) {
+ $default_index = $index;
+ last;
+ }
+ }
+
+ return $sources unless defined $default_index;
+
+ my $should_remove = 0;
+
+ # Start with default options, minus some annoying ones.
+ Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
+ Getopt::Long::Configure(
+ 'no_ignore_case',
+ 'no_auto_abbrev',
+ 'pass_through',
+ );
+
+ foreach my $index ( $default_index + 1 .. $#{$sources} ) {
+ my ( $name, $args ) = @{$sources->[$index]}{qw/name contents/};
+
+ if (ref($args)) {
+ local @ARGV = @{$args};
+ Getopt::Long::GetOptions(
+ 'ignore-ack-defaults' => \$should_remove,
+ );
+ @{$args} = @ARGV;
+ }
+ else {
+ ( undef, $sources->[$index]{contents} ) = Getopt::Long::GetOptionsFromString($args,
+ 'ignore-ack-defaults' => \$should_remove,
+ );
+ }
+ }
+
+ Getopt::Long::Configure('default');
+ Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
+
+ return $sources unless $should_remove;
+
+ my @copy = @{$sources};
+ splice @copy, $default_index, 1;
+ return \@copy;
+}
+
+
+sub check_for_mutually_exclusive_options {
+ my ( $arg_sources ) = @_;
+
+ my %mutually_exclusive_with;
+ my @copy = @{$arg_sources};
+
+ for(my $i = 0; $i < @INVALID_COMBINATIONS; $i += 2) {
+ my ( $lhs, $rhs ) = @INVALID_COMBINATIONS[ $i, $i + 1 ];
+
+ foreach my $l_opt ( @{$lhs} ) {
+ foreach my $r_opt ( @{$rhs} ) {
+ push @{ $mutually_exclusive_with{ $l_opt } }, $r_opt;
+ push @{ $mutually_exclusive_with{ $r_opt } }, $l_opt;
+ }
+ }
+ }
+
+ while( @copy ) {
+ my %set_opts;
+
+ my $source = shift @copy;
+ my ( $source_name, $args ) = @{$source}{qw/name contents/};
+ $args = ref($args) ? [ @{$args} ] : [ Text::ParseWords::shellwords($args) ];
+
+ foreach my $opt ( @{$args} ) {
+ next unless $opt =~ /^[-+]/;
+ last if $opt eq '--';
+
+ if( $opt =~ /^(.*)=/ ) {
+ $opt = $1;
+ }
+ elsif ( $opt =~ /^(-[^-]).+/ ) {
+ $opt = $1;
+ }
+
+ $set_opts{ $opt } = 1;
+
+ my $mutex_opts = $mutually_exclusive_with{ $opt };
+
+ next unless $mutex_opts;
+
+ foreach my $mutex_opt ( @{$mutex_opts} ) {
+ if($set_opts{ $mutex_opt }) {
+ die "Options '$mutex_opt' and '$opt' are mutually exclusive\n";
+ }
+ }
+ }
+ }
+}
+
+
+sub process_args {
+ my $arg_sources = \@_;
+
+ my %opt = (
+ pager => $ENV{ACK_PAGER_COLOR} || $ENV{ACK_PAGER},
+ );
+
+ check_for_mutually_exclusive_options($arg_sources);
+
+ $arg_sources = remove_default_options_if_needed($arg_sources);
+
+ if ( should_dump_options($arg_sources) ) {
+ dump_options($arg_sources);
+ exit(0);
+ }
+
+ my $type_specs = process_filetypes(\%opt, $arg_sources);
+ process_other(\%opt, $type_specs, $arg_sources);
+ while ( @{$arg_sources} ) {
+ my $source = shift @{$arg_sources};
+ my ( $source_name, $args ) = @{$source}{qw/name contents/};
+
+ # All of our sources should be transformed into an array ref
+ if ( ref($args) ) {
+ if ( $source_name eq 'ARGV' ) {
+ @ARGV = @{$args};
+ }
+ elsif (@{$args}) {
+ Carp::croak "source '$source_name' has extra arguments!";
+ }
+ }
+ else {
+ Carp::croak 'The impossible has occurred!';
+ }
+ }
+ my $filters = ($opt{filters} ||= []);
+
+ # Throw the default filter in if no others are selected.
+ if ( not grep { !$_->is_inverted() } @{$filters} ) {
+ push @{$filters}, App::Ack::Filter::Default->new();
+ }
+ return \%opt;
+}
+
+
+sub retrieve_arg_sources {
+ my @arg_sources;
+
+ my $noenv;
+ my $ackrc;
+
+ Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
+ Getopt::Long::Configure('pass_through');
+ Getopt::Long::Configure('no_auto_abbrev');
+
+ Getopt::Long::GetOptions(
+ 'noenv' => \$noenv,
+ 'ackrc=s' => \$ackrc,
+ );
+
+ Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
+
+ my @files;
+
+ if ( !$noenv ) {
+ my $finder = App::Ack::ConfigFinder->new;
+ @files = $finder->find_config_files;
+ }
+ if ( $ackrc ) {
+ # We explicitly use open so we get a nice error message.
+ # XXX This is a potential race condition!.
+ if(open my $fh, '<', $ackrc) {
+ close $fh;
+ }
+ else {
+ die "Unable to load ackrc '$ackrc': $!"
+ }
+ push( @files, { path => $ackrc } );
+ }
+
+ push @arg_sources, {
+ name => 'Defaults',
+ contents => [ App::Ack::ConfigDefault::options_clean() ],
+ };
+
+ foreach my $file ( @files) {
+ my @lines = App::Ack::ConfigFinder::read_rcfile($file->{path});
+
+ if(@lines) {
+ push @arg_sources, {
+ name => $file->{path},
+ contents => \@lines,
+ project => $file->{project},
+ };
+ }
+ }
+
+ if ( $ENV{ACK_OPTIONS} && !$noenv ) {
+ push @arg_sources, {
+ name => 'ACK_OPTIONS',
+ contents => $ENV{ACK_OPTIONS},
+ };
+ }
+
+ push @arg_sources, {
+ name => 'ARGV',
+ contents => [ @ARGV ],
+ };
+
+ return @arg_sources;
+}
+
+1; # End of App::Ack::ConfigLoader
+package App::Ack::Filter;
+
+use strict;
+use warnings;
+
+use Carp 1.04 ();
+
+my %filter_types;
+
+
+sub create_filter {
+ my ( undef, $type, @args ) = @_;
+
+ if ( my $package = $filter_types{$type} ) {
+ return $package->new(@args);
+ }
+ Carp::croak "Unknown filter type '$type'";
+}
+
+
+sub register_filter {
+ my ( undef, $type, $package ) = @_;
+
+ $filter_types{$type} = $package;
+
+ return;
+}
+
+
+sub invert {
+ my ( $self ) = @_;
+
+ return App::Ack::Filter::Inverse->new( $self );
+}
+
+
+sub is_inverted {
+ return 0;
+}
+
+
+sub to_string {
+ my ( $self ) = @_;
+
+ return '(unimplemented to_string)';
+}
+
+
+sub inspect {
+ my ( $self ) = @_;
+
+ return ref($self);
+}
+
+1;
+package App::Ack::Filter::Extension;
+
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
+
+
+sub new {
+ my ( $class, @extensions ) = @_;
+
+ my $exts = join('|', map { "\Q$_\E"} @extensions);
+ my $re = qr/[.](?:$exts)$/i;
+
+ return bless {
+ extensions => \@extensions,
+ regex => $re,
+ groupname => 'ExtensionGroup',
+ }, $class;
+}
+
+sub create_group {
+ return App::Ack::Filter::ExtensionGroup->new();
+}
+
+sub filter {
+ my ( $self, $resource ) = @_;
+
+ my $re = $self->{'regex'};
+
+ return $resource->name =~ /$re/;
+}
+
+sub inspect {
+ my ( $self ) = @_;
+
+ my $re = $self->{'regex'};
+
+ return ref($self) . " - $re";
+}
+
+sub to_string {
+ my ( $self ) = @_;
+
+ my $exts = $self->{'extensions'};
+
+ return join(' ', map { ".$_" } @{$exts});
+}
+
+BEGIN {
+ App::Ack::Filter->register_filter(ext => __PACKAGE__);
+}
+
+1;
+package App::Ack::Filter::FirstLineMatch;
+
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
+
+sub new {
+ my ( $class, $re ) = @_;
+
+ $re =~ s{^/|/$}{}g; # XXX validate?
+ $re = qr{$re}i;
+
+ return bless {
+ regex => $re,
+ }, $class;
+}
+
+# This test reads the first 250 characters of a file, then just uses the
+# first line found in that. This prevents reading something like an entire
+# .min.js file (which might be only one "line" long) into memory.
+
+sub filter {
+ my ( $self, $resource ) = @_;
+
+ my $re = $self->{'regex'};
+
+ my $line = $resource->firstliney;
+
+ return $line =~ /$re/;
+}
+
+sub inspect {
+ my ( $self ) = @_;
+
+ my $re = $self->{'regex'};
+
+ return ref($self) . " - $re";
+}
+
+sub to_string {
+ my ( $self ) = @_;
+
+ (my $re = $self->{regex}) =~ s{\([^:]*:(.*)\)$}{$1};
+
+ return "first line matches /$re/";
+}
+
+BEGIN {
+ App::Ack::Filter->register_filter(firstlinematch => __PACKAGE__);
+}
+
+1;
+package App::Ack::Filter::Is;
+
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
+
+use File::Spec 3.00 ();
+
+sub new {
+ my ( $class, $filename ) = @_;
+
+ return bless {
+ filename => $filename,
+ groupname => 'IsGroup',
+ }, $class;
+}
+
+sub create_group {
+ return App::Ack::Filter::IsGroup->new();
+}
+
+sub filter {
+ my ( $self, $resource ) = @_;
+
+ my $filename = $self->{'filename'};
+ my $base = (File::Spec->splitpath($resource->name))[2];
+
+ return $base eq $filename;
+}
+
+sub inspect {
+ my ( $self ) = @_;
+
+ my $filename = $self->{'filename'};
+
+ return ref($self) . " - $filename";
+}
+
+sub to_string {
+ my ( $self ) = @_;
+
+ my $filename = $self->{'filename'};
+
+ return $filename;
+}
+
+BEGIN {
+ App::Ack::Filter->register_filter(is => __PACKAGE__);
+}
+
+1;
+package App::Ack::Filter::Match;
+
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
+
+use File::Spec 3.00;
+
+sub new {
+ my ( $class, $re ) = @_;
+
+ $re =~ s{^/|/$}{}g; # XXX validate?
+ $re = qr/$re/i;
+
+ return bless {
+ regex => $re,
+ groupname => 'MatchGroup',
+ }, $class;
+}
+
+sub create_group {
+ return App::Ack::Filter::MatchGroup->new;
+}
+
+sub filter {
+ my ( $self, $resource ) = @_;
+
+ my $re = $self->{'regex'};
+
+ return $resource->basename =~ /$re/;
+}
+
+sub inspect {
+ my ( $self ) = @_;
+
+ my $re = $self->{'regex'};
+
+ print ref($self) . " - $re";
+
+ return;
+}
+
+sub to_string {
+ my ( $self ) = @_;
+
+ my $re = $self->{'regex'};
+
+ return "filename matches $re";
+}
+
+BEGIN {
+ App::Ack::Filter->register_filter(match => __PACKAGE__);
+}
+
+1;
+package App::Ack::Filter::Default;
+
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
+
+sub new {
+ my ( $class ) = @_;
+
+ return bless {}, $class;
+}
+
+sub filter {
+ my ( $self, $resource ) = @_;
+
+ return -T $resource->name;
+}
+
+1;
+package App::Ack::Filter::Inverse;
+
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
+
+sub new {
+ my ( $class, $filter ) = @_;
+
+ return bless {
+ filter => $filter,
+ }, $class;
+}
+
+sub filter {
+ my ( $self, $resource ) = @_;
+
+ my $filter = $self->{'filter'};
+ return !$filter->filter( $resource );
+}
+
+sub invert {
+ my $self = shift;
+
+ return $self->{'filter'};
+}
+
+sub is_inverted {
+ return 1;
+}
+
+sub inspect {
+ my ( $self ) = @_;
+
+ my $filter = $self->{'filter'};
+
+ return "!$filter";
+}
+
+1;
+package App::Ack::Filter::Collection;
+
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
+
+sub new {
+ my ( $class ) = @_;
+
+ return bless {
+ groups => {},
+ ungrouped => [],
+ }, $class;
+}
+
+sub filter {
+ my ( $self, $resource ) = @_;
+
+ for my $group (values %{$self->{'groups'}}) {
+ if ($group->filter($resource)) {
+ return 1;
+ }
+ }
+
+ for my $filter (@{$self->{'ungrouped'}}) {
+ if ($filter->filter($resource)) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+sub add {
+ my ( $self, $filter ) = @_;
+
+ if (exists $filter->{'groupname'}) {
+ my $group = ($self->{groups}->{$filter->{groupname}} ||= $filter->create_group());
+ $group->add($filter);
+ }
+ else {
+ push @{$self->{'ungrouped'}}, $filter;
+ }
+
+ return;
+}
+
+sub inspect {
+ my ( $self ) = @_;
+
+ return ref($self) . " - $self";
+}
+
+sub to_string {
+ my ( $self ) = @_;
+
+ my $ungrouped = $self->{'ungrouped'};
+
+ return join(', ', map { "($_)" } @{$ungrouped});
+}
+
+1;
+package App::Ack::Filter::IsGroup;
+
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
+
+use File::Spec 3.00 ();
+
+sub new {
+ my ( $class ) = @_;
+
+ return bless {
+ data => {},
+ }, $class;
}
-sub remove_default_options_if_needed {
- my ( $sources ) = @_;
+sub add {
+ my ( $self, $filter ) = @_;
- my $default_index;
+ $self->{data}->{ $filter->{filename} } = 1;
- foreach my $index ( 0 .. $#$sources ) {
- if ( $sources->[$index] eq 'Defaults' ) {
- $default_index = $index;
- last;
- }
- }
+ return;
+}
- return $sources unless defined $default_index;
+sub filter {
+ my ( $self, $resource ) = @_;
- my $should_remove = 0;
+ my $data = $self->{'data'};
+ my $base = $resource->basename;
- Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version'); # start with default options, minus some annoying ones
- Getopt::Long::Configure(
- 'no_ignore_case',
- 'no_auto_abbrev',
- 'pass_through',
- );
+ return exists $data->{$base};
+}
- foreach my $index ( $default_index + 2 .. $#$sources ) {
- next if $index % 2 != 0;
+sub inspect {
+ my ( $self ) = @_;
- my ( $name, $args ) = @{$sources}[ $index, $index + 1 ];
+ return ref($self) . " - $self";
+}
- if (ref($args)) {
- Getopt::Long::GetOptionsFromArray($args,
- 'ignore-ack-defaults' => \$should_remove,
- );
- }
- else {
- ( undef, $sources->[$index + 1] ) = Getopt::Long::GetOptionsFromString($args,
- 'ignore-ack-defaults' => \$should_remove,
- );
- }
- }
+sub to_string {
+ my ( $self ) = @_;
- Getopt::Long::Configure('default');
- Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
+ return join(' ', keys %{$self->{data}});
+}
- return $sources unless $should_remove;
+1;
+package App::Ack::Filter::ExtensionGroup;
- my @copy = @{$sources};
- splice @copy, $default_index, 2;
- return \@copy;
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
}
-sub check_for_mutually_exclusive_options {
- my ( $arg_sources ) = @_;
+sub new {
+ my ( $class ) = @_;
- my %mutually_exclusive_with;
- my @copy = @{$arg_sources};
+ return bless {
+ data => {},
+ }, $class;
+}
- for(my $i = 0; $i < @INVALID_COMBINATIONS; $i += 2) {
- my ( $lhs, $rhs ) = @INVALID_COMBINATIONS[ $i, $i + 1 ];
+sub add {
+ my ( $self, $filter ) = @_;
- foreach my $l_opt ( @{$lhs} ) {
- foreach my $r_opt ( @{$rhs} ) {
- push @{ $mutually_exclusive_with{ $l_opt } }, $r_opt;
- push @{ $mutually_exclusive_with{ $r_opt } }, $l_opt;
- }
- }
+ foreach my $ext (@{$filter->{extensions}}) {
+ $self->{data}->{lc $ext} = 1;
}
- while( @copy ) {
- my %set_opts;
+ return;
+}
- my ( $source_name, $args ) = splice @copy, 0, 2;
- $args = ref($args) ? [ @{$args} ] : [ Text::ParseWords::shellwords($args) ];
+sub filter {
+ my ( $self, $resource ) = @_;
- foreach my $opt ( @{$args} ) {
- next unless $opt =~ /^[-+]/;
- last if $opt eq '--';
+ if ($resource->name =~ /[.]([^.]*)$/) {
+ return exists $self->{'data'}->{lc $1};
+ }
- if( $opt =~ /^(.*)=/ ) {
- $opt = $1;
- }
- elsif ( $opt =~ /^(-[^-]).+/ ) {
- $opt = $1;
- }
+ return 0;
+}
- $set_opts{ $opt } = 1;
+sub inspect {
+ my ( $self ) = @_;
- my $mutex_opts = $mutually_exclusive_with{ $opt };
+ return ref($self) . " - $self";
+}
- next unless $mutex_opts;
+sub to_string {
+ my ( $self ) = @_;
- foreach my $mutex_opt ( @{$mutex_opts} ) {
- if($set_opts{ $mutex_opt }) {
- die "Options '$mutex_opt' and '$opt' are mutually exclusive\n";
- }
- }
- }
- }
+ return join(' ', map { ".$_" } sort keys %{$self->{data}});
}
-sub process_args {
- my $arg_sources = \@_;
+1;
+package App::Ack::Filter::MatchGroup;
- my %opt;
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
- check_for_mutually_exclusive_options($arg_sources);
+sub new {
+ my ( $class ) = @_;
- $arg_sources = remove_default_options_if_needed($arg_sources);
+ return bless {
+ matches => [],
+ big_re => undef,
+ }, $class;
+}
- if ( should_dump_options($arg_sources) ) {
- dump_options($arg_sources);
- exit(0);
- }
+sub add {
+ my ( $self, $filter ) = @_;
- my $type_specs = process_filetypes(\%opt, $arg_sources);
- process_other(\%opt, $type_specs, $arg_sources);
- while ( @{$arg_sources} ) {
- my ( $source_name, $args ) = splice( @{$arg_sources}, 0, 2 );
+ push @{ $self->{matches} }, $filter->{regex};
- # All of our sources should be transformed into an array ref
- if ( ref($args) ) {
- if ( $source_name eq 'ARGV' ) {
- @ARGV = @{$args};
- }
- elsif (@{$args}) {
- Carp::croak "source '$source_name' has extra arguments!";
- }
- }
- else {
- Carp::croak 'The impossible has occurred!';
- }
- }
- my $filters = ($opt{filters} ||= []);
+ my $re = join('|', map { "(?:$_)" } @{ $self->{matches} });
+ $self->{big_re} = qr/$re/;
- # throw the default filter in if no others are selected
- if ( not grep { !$_->is_inverted() } @{$filters} ) {
- push @{$filters}, App::Ack::Filter::Default->new();
- }
- return \%opt;
+ return;
}
-1; # End of App::Ack::ConfigLoader
-package App::Ack::ConfigDefault;
-
-use warnings;
-use strict;
+sub filter {
+ my ( $self, $resource ) = @_;
-sub options {
- my @options = split( /\n/, _options_block() );
- @options = grep { /./ && !/^#/ } @options;
+ my $re = $self->{big_re};
- return @options;
+ return $resource->basename =~ /$re/;
}
-sub _options_block {
- return <<'HERE';
-# This is the default ackrc for ack 2.0
+sub inspect {
+ my ( $self ) = @_;
+}
-# There are four different ways to match
-#
-# is: Match the filename exactly
-#
-# ext: Match the extension of the filename exactly
-#
-# match: Match the filename against a Perl regular expression
-#
-# firstlinematch: Match the first 250 characters of the first line
-# of text against a Perl regular expression. This is only for
-# the --type-add option.
+sub to_string {
+ my ( $self ) = @_;
+}
+1;
+package App::Ack::Filter::IsPath;
-# Directories to ignore
-# Bazaar
---ignore-directory=is:.bzr
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
-# Codeville
---ignore-directory=is:.cdv
-# Interface Builder
---ignore-directory=is:~.dep
---ignore-directory=is:~.dot
---ignore-directory=is:~.nib
---ignore-directory=is:~.plst
+sub new {
+ my ( $class, $filename ) = @_;
-# Git
---ignore-directory=is:.git
+ return bless {
+ filename => $filename,
+ groupname => 'IsPathGroup',
+ }, $class;
+}
-# Mercurial
---ignore-directory=is:.hg
+sub create_group {
+ return App::Ack::Filter::IsPathGroup->new();
+}
-# quilt
---ignore-directory=is:.pc
+sub filter {
+ my ( $self, $resource ) = @_;
-# Subversion
---ignore-directory=is:.svn
+ return $resource->name eq $self->{'filename'};
+}
-# Monotone
---ignore-directory=is:_MTN
+sub inspect {
+ my ( $self ) = @_;
-# CVS
---ignore-directory=is:CVS
+ my $filename = $self->{'filename'};
-# RCS
---ignore-directory=is:RCS
+ return ref($self) . " - $filename";
+}
-# SCCS
---ignore-directory=is:SCCS
+sub to_string {
+ my ( $self ) = @_;
-# darcs
---ignore-directory=is:_darcs
+ my $filename = $self->{'filename'};
-# Vault/Fortress
---ignore-directory=is:_sgbak
+ return $filename;
+}
-# autoconf
---ignore-directory=is:autom4te.cache
+1;
+package App::Ack::Filter::IsPathGroup;
-# Perl module building
---ignore-directory=is:blib
---ignore-directory=is:_build
+use strict;
+use warnings;
+BEGIN {
+ our @ISA = 'App::Ack::Filter';
+}
-# Perl Devel::Cover module's output directory
---ignore-directory=is:cover_db
+sub new {
+ my ( $class ) = @_;
+ return bless {
+ data => {},
+ }, $class;
+}
+sub add {
+ my ( $self, $filter ) = @_;
-# Files to ignore
-# Backup files
---ignore-file=ext:bak
---ignore-file=match:/~$/
+ $self->{data}->{ $filter->{filename} } = 1;
-# Emacs swap files
---ignore-file=match:/^#.+#$/
+ return;
+}
-# vi/vim swap files
---ignore-file=match:/[._].*\.swp$/
+sub filter {
+ my ( $self, $resource ) = @_;
-# core dumps
---ignore-file=match:/core\.\d+$/
+ my $data = $self->{'data'};
-# minified Javascript
---ignore-file=match:/[.]min[.]js$/
+ return exists $data->{$resource->name};
+}
+sub inspect {
+ my ( $self ) = @_;
-# Filetypes defined
+ return ref($self) . " - $self";
+}
-# Perl http://perl.org/
---type-add=perl:ext:pl,pm,pod,t
---type-add=perl:firstlinematch:/^#!.*\bperl/
+sub to_string {
+ my ( $self ) = @_;
-# Makefiles http://www.gnu.org/s/make/
---type-add=make:ext:mk
---type-add=make:ext:mak
---type-add=make:is:makefile
---type-add=make:is:Makefile
---type-add=make:is:GNUmakefile
+ return join(' ', keys %{$self->{data}});
+}
-# Rakefiles http://rake.rubyforge.org/
---type-add=rake:is:Rakefile
+1;
+package File::Next;
-# CMake http://www.cmake.org/
---type-add=cmake:is:CMakeLists.txt
---type-add=cmake:ext:cmake
+use strict;
+use warnings;
-# Actionscript
---type-add=actionscript:ext:as,mxml
-# Ada http://www.adaic.org/
---type-add=ada:ext:ada,adb,ads
+our $VERSION = '1.12';
-# ASP http://msdn.microsoft.com/en-us/library/aa286483.aspx
---type-add=asp:ext:asp
-# ASP.Net http://www.asp.net/
---type-add=aspx:ext:master,ascx,asmx,aspx,svc
-# Assembly
---type-add=asm:ext:asm,s
+use File::Spec ();
-# Batch
---type-add=batch:ext:bat,cmd
+our $name; # name of the current file
+our $dir; # dir of the current file
-# ColdFusion http://en.wikipedia.org/wiki/ColdFusion
---type-add=cfmx:ext:cfc,cfm,cfml
+our %files_defaults;
+our %skip_dirs;
-# Clojure http://clojure.org/
---type-add=clojure:ext:clj
+BEGIN {
+ %files_defaults = (
+ file_filter => undef,
+ descend_filter => undef,
+ error_handler => sub { CORE::die @_ },
+ warning_handler => sub { CORE::warn @_ },
+ sort_files => undef,
+ follow_symlinks => 1,
+ nul_separated => 0,
+ );
+ %skip_dirs = map {($_,1)} (File::Spec->curdir, File::Spec->updir);
+}
-# C
-# .xs are Perl C files
---type-add=cc:ext:c,h,xs
-# C header files
---type-add=hh:ext:h
+sub files {
+ die _bad_invocation() if @_ && defined($_[0]) && ($_[0] eq __PACKAGE__);
-# C++
---type-add=cpp:ext:cpp,cc,cxx,m,hpp,hh,h,hxx
+ my ($parms,@queue) = _setup( \%files_defaults, @_ );
+ my $filter = $parms->{file_filter};
-# C#
---type-add=csharp:ext:cs
+ return sub {
+ while (@queue) {
+ my ($dirname,$file,$fullpath) = splice( @queue, 0, 3 );
+ if ( -f $fullpath || -p $fullpath || $fullpath =~ m{^/dev/fd} ) {
+ if ( $filter ) {
+ local $_ = $file;
+ local $File::Next::dir = $dirname;
+ local $File::Next::name = $fullpath;
+ next if not $filter->();
+ }
+ return wantarray ? ($dirname,$file,$fullpath) : $fullpath;
+ }
+ elsif ( -d _ ) {
+ unshift( @queue, _candidate_files( $parms, $fullpath ) );
+ }
+ } # while
-# CSS http://www.w3.org/Style/CSS/
---type-add=css:ext:css
+ return;
+ }; # iterator
+}
-# Delphi http://en.wikipedia.org/wiki/Embarcadero_Delphi
---type-add=delphi:ext:pas,int,dfm,nfm,dof,dpk,dproj,groupproj,bdsgroup,bdsproj
-# Emacs Lisp http://www.gnu.org/software/emacs
---type-add=elisp:ext:el
-# Erlang http://www.erlang.org/
---type-add=erlang:ext:erl,hrl
-# Fortran http://en.wikipedia.org/wiki/Fortran
---type-add=fortran:ext:f,f77,f90,f95,f03,for,ftn,fpp
-# Google Go http://golang.org/
---type-add=go:ext:go
-# Groovy http://groovy.codehaus.org/
---type-add=groovy:ext:groovy,gtmpl,gpp,grunit,gradle
+sub from_file {
+ die _bad_invocation() if @_ && defined($_[0]) && ($_[0] eq __PACKAGE__);
-# Haskell http://www.haskell.org/
---type-add=haskell:ext:hs,lhs
+ my ($parms,@queue) = _setup( \%files_defaults, @_ );
+ my $err = $parms->{error_handler};
+ my $warn = $parms->{error_handler};
-# HTML
---type-add=html:ext:htm,html
+ my $filename = $queue[1];
-# Java http://www.oracle.com/technetwork/java/index.html
---type-add=java:ext:java,properties
+ if ( !defined($filename) ) {
+ $err->( 'Must pass a filename to from_file()' );
+ return undef;
+ }
-# JavaScript
---type-add=js:ext:js
+ my $fh;
+ if ( $filename eq '-' ) {
+ $fh = \*STDIN;
+ }
+ else {
+ if ( !open( $fh, '<', $filename ) ) {
+ $err->( "Unable to open $filename: $!" );
+ return undef;
+ }
+ }
+ my $filter = $parms->{file_filter};
-# JSP http://www.oracle.com/technetwork/java/javaee/jsp/index.html
---type-add=jsp:ext:jsp,jspx,jhtm,jhtml
+ return sub {
+ local $/ = $parms->{nul_separated} ? "\x00" : $/;
+ while ( my $fullpath = <$fh> ) {
+ chomp $fullpath;
+ next unless $fullpath =~ /./;
+ if ( not ( -f $fullpath || -p _ ) ) {
+ $warn->( "$fullpath: No such file" );
+ next;
+ }
-# Common Lisp http://common-lisp.net/
---type-add=lisp:ext:lisp,lsp
+ my ($volume,$dirname,$file) = File::Spec->splitpath( $fullpath );
+ if ( $filter ) {
+ local $_ = $file;
+ local $File::Next::dir = $dirname;
+ local $File::Next::name = $fullpath;
+ next if not $filter->();
+ }
+ return wantarray ? ($dirname,$file,$fullpath) : $fullpath;
+ } # while
+ close $fh;
-# Lua http://www.lua.org/
---type-add=lua:ext:lua
+ return;
+ }; # iterator
+}
-# Objective-C
---type-add=objc:ext:m,h
+sub _bad_invocation {
+ my $good = (caller(1))[3];
+ my $bad = $good;
+ $bad =~ s/(.+)::/$1->/;
+ return "$good must not be invoked as $bad";
+}
-# Objective-C++
---type-add=objcpp:ext:mm,h
+sub sort_standard($$) { return $_[0]->[1] cmp $_[1]->[1] }
+sub sort_reverse($$) { return $_[1]->[1] cmp $_[0]->[1] }
-# OCaml http://caml.inria.fr/
---type-add=ocaml:ext:ml,mli
+sub reslash {
+ my $path = shift;
-# Parrot http://www.parrot.org/
---type-add=parrot:ext:pir,pasm,pmc,ops,pod,pg,tg
+ my @parts = split( /\//, $path );
-# PHP http://www.php.net/
---type-add=php:ext:php,phpt,php3,php4,php5,phtml
---type-add=php:firstlinematch:/^#!.*\bphp/
+ return $path if @parts < 2;
-# Plone http://plone.org/
---type-add=plone:ext:pt,cpt,metadata,cpy,py
+ return File::Spec->catfile( @parts );
+}
-# Python http://www.python.org/
---type-add=python:ext:py
---type-add=python:firstlinematch:/^#!.*\bpython/
-# R http://www.r-project.org/
---type-add=rr:ext:R
-# Ruby http://www.ruby-lang.org/
---type-add=ruby:ext:rb,rhtml,rjs,rxml,erb,rake,spec
---type-add=ruby:is:Rakefile
---type-add=ruby:firstlinematch:/^#!.*\bruby/
+sub _setup {
+ my $defaults = shift;
+ my $passed_parms = ref $_[0] eq 'HASH' ? {%{+shift}} : {}; # copy parm hash
-# Rust http://www.rust-lang.org/
---type-add=rust:ext:rs
+ my %passed_parms = %{$passed_parms};
-# Scala http://www.scala-lang.org/
---type-add=scala:ext:scala
+ my $parms = {};
+ for my $key ( keys %{$defaults} ) {
+ $parms->{$key} =
+ exists $passed_parms{$key}
+ ? delete $passed_parms{$key}
+ : $defaults->{$key};
+ }
-# Scheme http://groups.csail.mit.edu/mac/projects/scheme/
---type-add=scheme:ext:scm,ss
+ # Any leftover keys are bogus
+ for my $badkey ( keys %passed_parms ) {
+ my $sub = (caller(1))[3];
+ $parms->{error_handler}->( "Invalid option passed to $sub(): $badkey" );
+ }
-# Shell
---type-add=shell:ext:sh,bash,csh,tcsh,ksh,zsh
---type-add=shell:firstlinematch:/^#!.*\b(?:ba|t?c|k|z)?sh\b/
+ # If it's not a code ref, assume standard sort
+ if ( $parms->{sort_files} && ( ref($parms->{sort_files}) ne 'CODE' ) ) {
+ $parms->{sort_files} = \&sort_standard;
+ }
+ my @queue;
-# Smalltalk http://www.smalltalk.org/
---type-add=smalltalk:ext:st
+ for ( @_ ) {
+ my $start = reslash( $_ );
+ if (-d $start) {
+ push @queue, ($start,undef,$start);
+ }
+ else {
+ push @queue, (undef,$start,$start);
+ }
+ }
-# SQL http://www.iso.org/iso/catalogue_detail.htm?csnumber=45498
---type-add=sql:ext:sql,ctl
+ return ($parms,@queue);
+}
-# Tcl http://www.tcl.tk/
---type-add=tcl:ext:tcl,itcl,itk
-# LaTeX http://www.latex-project.org/
---type-add=tex:ext:tex,cls,sty
+sub _candidate_files {
+ my $parms = shift;
+ my $dirname = shift;
-# Template Toolkit http://template-toolkit.org/
---type-add=tt:ext:tt,tt2,ttml
+ my $dh;
+ if ( !opendir $dh, $dirname ) {
+ $parms->{error_handler}->( "$dirname: $!" );
+ return;
+ }
-# Visual Basic
---type-add=vb:ext:bas,cls,frm,ctl,vb,resx
+ my @newfiles;
+ my $descend_filter = $parms->{descend_filter};
+ my $follow_symlinks = $parms->{follow_symlinks};
+ my $sort_sub = $parms->{sort_files};
-# Verilog
---type-add=verilog:ext:v,vh,sv
+ for my $file ( grep { !exists $skip_dirs{$_} } readdir $dh ) {
+ my $has_stat;
-# VHDL http://www.eda.org/twiki/bin/view.cgi/P1076/WebHome
---type-add=vhdl:ext:vhd,vhdl
+ # Only do directory checking if we have a descend_filter
+ my $fullpath = File::Spec->catdir( $dirname, $file );
+ if ( !$follow_symlinks ) {
+ next if -l $fullpath;
+ $has_stat = 1;
+ }
-# Vim http://www.vim.org/
---type-add=vim:ext:vim
+ if ( $descend_filter ) {
+ if ( $has_stat ? (-d _) : (-d $fullpath) ) {
+ local $File::Next::dir = $fullpath;
+ local $_ = $file;
+ next if not $descend_filter->();
+ }
+ }
+ if ( $sort_sub ) {
+ push( @newfiles, [ $dirname, $file, $fullpath ] );
+ }
+ else {
+ push( @newfiles, $dirname, $file, $fullpath );
+ }
+ }
+ closedir $dh;
-# XML http://www.w3.org/TR/REC-xml/
---type-add=xml:ext:xml,dtd,xsl,xslt,ent
---type-add=xml:firstlinematch:/<[?]xml/
+ if ( $sort_sub ) {
+ return map { @{$_} } sort $sort_sub @newfiles;
+ }
-# YAML http://yaml.org/
---type-add=yaml:ext:yaml,yml
-HERE
+ return @newfiles;
}
-1;
+
+1; # End of File::Next