From 76702fc7e6879b9e271f77403485170ca32c3fc7 Mon Sep 17 00:00:00 2001 From: Tony Duckles Date: Sun, 10 Mar 2013 12:51:03 -0500 Subject: [PATCH] ack 2.00b06 (git commit 04e8986) Switch over to using Ack v2.0. * .ackrc: Eliminate --text option which is obsolete in ack2. * .ackrc: Change --type-set options to new-style --type-add options. * .bashrc: Don't need to use ack-wrapper anymore, at least for now. --- .ackrc | 10 +- .bashrc | 3 - bin/ack | 4168 ++++++++++++++++++++++++++++++++++++++----------------- 3 files changed, 2878 insertions(+), 1303 deletions(-) diff --git a/.ackrc b/.ackrc index 680d455..95be4c3 100644 --- a/.ackrc +++ b/.ackrc @@ -16,14 +16,12 @@ --pager=less # always print filename prefix --with-filename -# search *.txt files by default ---text -# Ack Type Settings +# Custom File-Types # #################################################################### ---type-set=mumps=.m,.ro,.ROU,.GLO ---type-set=markdown=.md,.mkd,.markdown ---type-set=css=.css,.scss +--type-add=mumps:ext:m,ro,ROU,GLO +--type-add=markdown:ext:md,mkd,markdown +--type-add=css:ext:css,scss # Colors # #################################################################### diff --git a/.bashrc b/.bashrc index bbbfce8..ab9fec4 100644 --- a/.bashrc +++ b/.bashrc @@ -264,9 +264,6 @@ settitle() { printf "\033k%s\033\\" "$@" } -# ack-wrapper -alias ack="ack-wrapper" - # ---------------------------------------------------------------------- # BASH COMPLETION # ---------------------------------------------------------------------- diff --git a/bin/ack b/bin/ack index f1505cc..2e0d994 100755 --- a/bin/ack +++ b/bin/ack @@ -4,21 +4,32 @@ # Please DO NOT EDIT or send patches for it. # # Please take a look at the source from -# https://github.com/petdance/ack +# http://github.com/petdance/ack2 # and submit patches against the individual files # that build ack. # -use warnings; use strict; +use warnings; + +use 5.008; + -our $VERSION = '1.96'; +# XXX Don't make this so brute force +# See also: https://github.com/petdance/ack2/issues/89 + +use Getopt::Long 2.36 (); + +use Carp 1.10 (); + +our $VERSION = '2.00b06'; # Check http://betterthangrep.com/ for updates # These are all our globals. - MAIN: { + $App::Ack::orig_program_name = $0; + $0 = join(' ', 'ack', $0); if ( $App::Ack::VERSION ne $main::VERSION ) { App::Ack::die( "Program/library version mismatch\n\t$0 is $main::VERSION\n\t$INC{'App/Ack.pm'} is $App::Ack::VERSION" ); } @@ -28,26 +39,29 @@ MAIN: { for ( @ARGV ) { last if ( $_ eq '--' ); - # Priorities! Get the --thpppt checking out of the way. + # Get the --thpppt and --bar checking out of the way. /^--th[pt]+t+$/ && App::Ack::_thpppt($_); + /^--bar$/ && App::Ack::_bar(); # See if we want to ignore the environment. (Don't tell Al Gore.) if ( /^--(no)?env$/ ) { $env_is_usable = defined $1 ? 0 : 1; } } - if ( $env_is_usable ) { - unshift( @ARGV, App::Ack::read_ackrc() ); - } - else { + if ( !$env_is_usable ) { my @keys = ( 'ACKRC', grep { /^ACK_/ } keys %ENV ); delete @ENV{@keys}; } App::Ack::load_colors(); - if ( exists $ENV{ACK_SWITCHES} ) { - App::Ack::warn( 'ACK_SWITCHES is no longer supported. Use ACK_OPTIONS.' ); - } + Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version'); + Getopt::Long::Configure('pass_through', 'no_auto_abbrev'); + Getopt::Long::GetOptions( + 'help' => sub { App::Ack::show_help(); exit; }, + 'version' => sub { App::Ack::print_version_statement(); exit; }, + 'man' => sub { App::Ack::show_man(); exit; }, + ); + Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version'); if ( !@ARGV ) { App::Ack::show_help(); @@ -57,67 +71,304 @@ MAIN: { main(); } -sub main { - my $opt = App::Ack::get_command_line_options(); +sub _compile_descend_filter { + my ( $opt ) = @_; + + my $idirs = $opt->{idirs}; + return unless $idirs && @{$idirs}; - $| = 1 if $opt->{flush}; # Unbuffer the output if flush mode + my %ignore_dirs; - if ( App::Ack::input_from_pipe() ) { - # We're going into filter mode - for ( qw( f g l ) ) { - $opt->{$_} and App::Ack::die( "Can't use -$_ when acting as a filter." ); + 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' ); + } } - $opt->{show_filename} = 0; - $opt->{regex} = App::Ack::build_regex( defined $opt->{regex} ? $opt->{regex} : shift @ARGV, $opt ); - if ( my $nargs = @ARGV ) { - my $s = $nargs == 1 ? '' : 's'; - App::Ack::warn( "Ignoring $nargs argument$s on the command-line while acting as a filter." ); + else { + Carp::croak( qq{Invalid filter specification "$_"} ); } + } + + return sub { + return !exists $ignore_dirs{$_} && !exists $ignore_dirs{$File::Next::dir}; + }; +} + +sub _compile_file_filter { + my ( $opt, $start ) = @_; - my $res = App::Ack::Resource::Basic->new( '-' ); - my $nmatches; - if ( $opt->{count} ) { - $nmatches = App::Ack::search_and_list( $res, $opt ); + my $ifiles = $opt->{ifiles}; + $ifiles ||= []; + + my @ifiles_filters = map { + my $filter; + + if ( /^(\w+):(.+)/ ) { + my ($how,$what) = ($1,$2); + $filter = App::Ack::Filter->create_filter($how, split(/,/, $what)); } else { - # normal searching - $nmatches = App::Ack::search_resource( $res, $opt ); + Carp::croak( qq{Invalid filter specification "$_"} ); + } + $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}; + + 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) }; + + # Ignore named pipes found in directory searching. Named + # pipes created by subprocesses get specified on the command + # line, so the rule of "always select whatever is on the + # command line" wins. + return 0 if -p $File::Next::name; + + 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; + + 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; + } + } + } + # 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; + } + } } - $res->close(); - App::Ack::exit_from_ack( $nmatches ); + return $match_found; + }; +} + +sub show_types { + my $resource = shift; + my $ors = shift; + + my @types = App::Ack::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(); + + my $opt = App::Ack::ConfigLoader::process_args( @arg_sources ); + + $App::Ack::report_bad_filenames = !$opt->{dont_report_bad_filenames}; + + if ( $opt->{flush} ) { + $| = 1; } - my $file_matching = $opt->{f} || $opt->{lines}; - if ( $file_matching ) { - App::Ack::die( "Can't specify both a regex ($opt->{regex}) and use one of --line, -f or -g." ) if $opt->{regex}; + if ( not defined $opt->{color} ) { + $opt->{color} = !App::Ack::output_to_pipe() && !$App::Ack::is_windows; } - else { - $opt->{regex} = App::Ack::build_regex( defined $opt->{regex} ? $opt->{regex} : shift @ARGV, $opt ); + if ( not defined $opt->{heading} and not defined $opt->{break} ) { + $opt->{heading} = $opt->{break} = !App::Ack::output_to_pipe(); } - # check that all regexes do compile fine - App::Ack::check_regex( $_ ) for ( $opt->{regex}, $opt->{G} ); + if ( defined($opt->{H}) || defined($opt->{h}) ) { + $opt->{show_filename}= $opt->{H} && !$opt->{h}; + } - my $what = App::Ack::get_starting_points( \@ARGV, $opt ); - my $iter = App::Ack::get_iterator( $what, $opt ); - App::Ack::filetype_setup(); + if ( my $output = $opt->{output} ) { + $output =~ s{\\}{\\\\}g; + $output =~ s{"}{\\"}g; + $opt->{output} = qq{"$output"}; + } - my $nmatches = 0; + 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 ); + } + 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 { + 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; + } + } - App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager}; - if ( $opt->{f} ) { - $nmatches = App::Ack::print_files( $iter, $opt ); + 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" ); + } + } + + $opt->{file_filter} = _compile_file_filter($opt, \@start); + $opt->{descend_filter} = _compile_descend_filter($opt); + + $resources = App::Ack::Resources->from_argv( $opt, \@start ); + } } - elsif ( $opt->{l} || $opt->{count} ) { - $nmatches = App::Ack::print_files_with_matches( $iter, $opt ); + App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager}; + + my $print_filenames = $opt->{show_filename}; + my $max_count = $opt->{m}; + my $ors = $opt->{print0} ? "\0" : "\n"; + my $only_first = $opt->{1}; + + 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. + + # 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 %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 $filename = $resource->name; + + local $opt->{color} = 0; + + App::Ack::iterate($resource, $opt, sub { + chomp; + + 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; + } + + 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 ); + + if ( $opt->{L} ? !$is_match : $is_match ) { + App::Ack::print( $resource->name, $ors ); + ++$nmatches; + + 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; + } + } } - else { - $nmatches = App::Ack::print_matches( $iter, $opt ); + + if ( $opt->{count} && !$opt->{show_filename} ) { + App::Ack::print( $total_count, "\n" ); } + close $App::Ack::fh; App::Ack::exit_from_ack( $nmatches ); } + =head1 NAME ack - grep-like text finder @@ -131,29 +382,40 @@ ack - grep-like text finder Ack is designed as a replacement for 99% of the uses of F. -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. +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. + +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. If you don't know +how to use regular expression but are interested in learning, you may +consult L. If you do not +need or want ack to use regular expressions, please see the +C<-Q>/C<--literal> option. -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. +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. =head1 FILE SELECTION +If files are not specified for searching, either on the command +line or piped in with the C<-x> option, I delves into +subdirectories selecting files for searching. + I 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. -With no file selections, I only searches files of types that -it recognizes. If you have a file called F, and I -doesn't know what a .wango file is, I won't search it. - -The B<-a> option tells I to select all files, regardless of -type. +With no file selection, I searches through regular files that +are not explicitly excluded by B<--ignore-dir> and B<--ignore-file> +options, either present in F files or on the command line. -Some files will never be selected by I, even with B<-a>, -including: +The default options for I ignore certain files and directories. These +include: =over 4 @@ -161,23 +423,28 @@ including: =item * Coredumps: Files matching F +=item * Version control directories like F<.svn> and F<.git>. + =back +Run I with the C<--dump> option to see what settings are set. + However, I always searches the files given on the command line, -no matter what type. Furthermore, by specifying the B<-u> option all -files will be searched. +no matter what type. If you tell I to search in a coredump, +it will search in a coredump. =head1 DIRECTORY SELECTION I descends through the directory tree of the starting directories -specified. However, it will ignore the shadow directories used by +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. For a complete list of directories that do not get searched, run -F. +C. =head1 WHEN TO USE GREP @@ -187,18 +454,13 @@ throw I 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 syntax should be quicker with I. -If your script or parent program uses I C<--quiet> or -C<--silent> or needs exit 2 on IO error, use I. +If your script or parent program uses I C<--quiet> or C<--silent> +or needs exit 2 on IO error, use I. =head1 OPTIONS =over 4 -=item B<-a>, B<--all> - -Operate on all files, regardless of type (but still skip directories -like F, F, etc.) - =item B<-A I>, B<--after-context=I> Print I lines of trailing context after matching lines. @@ -207,6 +469,11 @@ Print I lines of trailing context after matching lines. Print I lines of leading context before matching lines. +=item B<--[no]break> + +Print a break between results from different files. On by default +when used interactively. + =item B<-C [I]>, B<--context[=I]> Print I lines (default 2) of context around matching lines. @@ -218,9 +485,10 @@ 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. -If combined with B<-h> (B<--no-filename>) ack outputs only one total count. +If combined with B<-h> (B<--no-filename>) ack outputs only one total +count. -=item B<--color>, B<--nocolor> +=item B<--color>, B<--nocolor>, B<--colour>, B<--nocolour> B<--color> highlights the matching text. B<--nocolor> supresses the color. This is on by default unless the output is redirected. @@ -241,28 +509,48 @@ Sets the color to be used for matches. Sets the color to be used for line numbers. -=item B<--column> +=item B<--[no]column> -Show the column number of the first match. This is helpful for editors -that can place your cursor at a given position. +Show the column number of the first match. This is helpful for +editors that can place your cursor at a given position. + +=item B<--create-ackrc> + +Dumps the default ack options to standard output. This is useful for +when you want to customize the defaults. + +=item B<--dump> + +Writes the list of options loaded and where they came from to standard +output. Handy for debugging. =item B<--env>, B<--noenv> -B<--noenv> disables all environment processing. No F<.ackrc> is read -and all environment variables are ignored. By default, F considers -F<.ackrc> and settings in the environment. +B<--noenv> disables all environment processing. No F<.ackrc> is +read and all environment variables are ignored. By default, F +considers F<.ackrc> and settings in the environment. =item B<--flush> B<--flush> flushes output immediately. This is off by default -unless ack is running interactively (when output goes to a pipe -or file). +unless ack is running interactively (when output goes to a pipe or +file). =item B<-f> 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. +any searching. PATTERN must not be specified, or it will be taken +as a path to search. + +=item B<--files-from=I> + +The list of files to be searched is specified in I. The list of +files are seperated by newlines. If I is C<->, the list is loaded +from standard input. + +=item B<--[no]filter> + +Forces ack to act as if it were recieving input via a pipe. =item B<--follow>, B<--nofollow> @@ -271,28 +559,17 @@ or directories were specified on the command line. This is off by default. -=item B<-G I> - -Only paths matching I are included in the search. The entire -path and filename are matched against I, and I is a -Perl regular expression, not a shell glob. - -The options B<-i>, B<-w>, B<-v>, and B<-Q> do not apply to this I. - =item B<-g I> -Print files where the relative path + filename matches I. This option is -a convenience shortcut for B<-f> B<-G I>. - -The options B<-i>, B<-w>, B<-v>, and B<-Q> do not apply to this I. +Print files where the relative path + filename matches I. =item B<--group>, B<--nogroup> -B<--group> groups matches by file name with. This is the default when -used interactively. +B<--group> groups matches by file name. This is the default +when used interactively. -B<--nogroup> prints one result per line, like grep. This is the default -when output is redirected. +B<--nogroup> prints one result per line, like grep. This is the +default when output is redirected. =item B<-H>, B<--with-filename> @@ -303,34 +580,57 @@ Print the filename for each match. Suppress the prefixing of filenames on output when multiple files are searched. -=item B<--help> +=item B<--[no]heading> + +Print a filename heading above each file's results. This is the default +when used interactively. + +=item B<--help>, B<-?> Print a short help statement. +=item B<--help-types>, B<--help=types> + +Print all known types. + =item B<-i>, B<--ignore-case> Ignore case in the search strings. -This applies only to the PATTERN, not to the regexes given for the B<-g> -and B<-G> options. +=item B<--ignore-ack-defaults> -=item B<--[no]ignore-dir=I> +Tells ack to completely ignore the default definitions provided with ack. +This is useful in combination with B<--create-ackrc> if you I want +to customize ack. -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). +=item B<--[no]ignore-dir=I>, B<--[no]ignore-directory=I> -The I must always be a simple directory name. Nested directories like -F 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. +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). -=item B<--line=I> +The I must always be a simple directory name. Nested +directories like F 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 B<--ignore-file=I> + +Ignore files matching I. The filters are specified +identically to file type filters as seen in L. + +=item B<-k>, B<--known-types> + +Limit selected files to those with types that ack knows about. This is +equivalent to the default behavior found in ack 1. + +=item B<--lines=I> Only print line I of each file. Multiple lines can be given with multiple -B<--line> options or as a comma separated list (B<--line=3,5,7>). B<--line=4-7> +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. @@ -340,8 +640,7 @@ Only print the filenames of matching files, instead of the matching text. =item B<-L>, B<--files-without-matches> -Only print the filenames of files that do I match. This is equivalent -to specifying B<-l> and B<-v>. +Only print the filenames of files that do I match. =item B<--match I> @@ -374,15 +673,20 @@ highlighting) Output the evaluation of I 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">. -=item B<--pager=I> +=item B<--pager=I>, B<--nopager> -Direct ack's output through I. This can also be specified +B<--pager> directs ack's output through I. This can also be specified via the C and C environment variables. Using --pager does not suppress grouping and coloring like piping output on the command-line does. +B<--nopager> cancels any setting in ~/.ackrc, C or C. +No output will be sent through a pager. + =item B<--passthru> Prints all lines, whether or not they match the expression. Highlighting @@ -405,15 +709,17 @@ helpful when dealing with filenames that contain whitespace, e.g. Quote all metacharacters in PATTERN, it is treated as a literal. -This applies only to the PATTERN, not to the regexes given for the B<-g> -and B<-G> options. - =item B<-r>, B<-R>, B<--recurse> 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. -=item B<--smart-case>, B<--no-smart-case> +=item B<-s> + +Suppress error messages about nonexistent or unreadable files. This is taken +from fgrep. + +=item B<--[no]smart-case>, B<--no-smart-case> Ignore case in the search strings if PATTERN contains no uppercase characters. This is similar to C in vim. This option is @@ -421,12 +727,9 @@ off by default. B<-i> always overrides this option. -This applies only to the PATTERN, not to the regexes given for the -B<-g> and B<-G> options. - =item B<--sort-files> -Sorts the found files lexically. Use this if you want your file +Sorts the found files lexicographically. Use this if you want your file listings to be deterministic between runs of I. =item B<--show-types> @@ -435,12 +738,6 @@ Outputs the filetypes that ack associates with each file. Works with B<-f> and B<-g> options. -=item B<--thpppt> - -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<--type=TYPE>, B<--type=noTYPE> Specify the types of files to include or exclude from a search. @@ -456,31 +753,28 @@ Type specifications can be repeated and are ORed together. See I for a list of valid types. -=item B<--type-add I=I<.EXTENSION>[,I<.EXT2>[,...]]> +=item B<--type-add I:I:I> -Files with the given EXTENSION(s) are recognized as being of (the -existing) type TYPE. See also L. +Files with the given FILTERARGS applied to the given FILTER +are recognized as being of (the existing) type TYPE. +See also L. -=item B<--type-set I=I<.EXTENSION>[,I<.EXT2>[,...]]> +=item B<--type-set I:I:I> -Files with the given EXTENSION(s) are recognized as being of type -TYPE. This replaces an existing definition for type TYPE. See also -L. +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. -=item B<-u>, B<--unrestricted> +=item B<--type-del I> -All files and directories (including blib/, core.*, ...) are searched, -nothing is skipped. When both B<-u> and B<--ignore-dir> are used, the -B<--ignore-dir> option has no effect. +The filters associated with TYPE are removed from Ack, and are no longer considered +for searches. =item B<-v>, B<--invert-match> Invert match: select non-matching lines -This applies only to the PATTERN, not to the regexes given for the B<-g> -and B<-G> options. - =item B<--version> Display version and copyright information. @@ -490,8 +784,10 @@ Display version and copyright information. Force PATTERN to match only whole words. The PATTERN is wrapped with C<\b> metacharacters. -This applies only to the PATTERN, not to the regexes given for the B<-g> -and B<-G> options. +=item B<-x> + +An abbreviation for B<--files-from=->; the list of files to search are read +from standard input, with one line per file. =item B<-1> @@ -500,6 +796,16 @@ 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. +=item B<--thpppt> + +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<--bar> + +Check with the admiral for traps. + =back =head1 THE .ackrc FILE @@ -522,11 +828,9 @@ Note that arguments with spaces in them do not need to be quoted, as they are not interpreted by the shell. Basically, each I in the F<.ackrc> file is interpreted as one element of C<@ARGV>. -F looks in your home directory for the F<.ackrc>. You can -specify another location with the F variable, below. - -If B<--noenv> is specified on the command line, the F<.ackrc> file -is ignored. +F looks in several locations for F<.ackrc> files; the searching +process is detailed in L. These +files are not considered if B<--noenv> is specified on the command line. =head1 Defining your own types @@ -539,69 +843,97 @@ on one command line so that they can be easily copy & pasted. I searches for foo in all perl files. I 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 +files as well when searching for --perl files? I does this for you. B<--type-add> appends additional extensions to an existing type. If you want to define a new type, or completely redefine an existing -type, then use B<--type-set>. I defines the type I to include files with +type, then use B<--type-set>. I defines +the type I to include files with the extensions .e or .eiffel. So to search for all eiffel files -containing the word Bertrand use I. +containing the word Bertrand use I. 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 +all eiffel files from a search. Redefining also works: I and I<.xs> files no longer belong to the type I. When defining your own types in the F<.ackrc> file you have to use the following: - --type-set=eiffel=.e,.eiffel + --type-set=eiffel:ext:e,eiffel or writing on separate lines --type-set - eiffel=.e,.eiffel + eiffel:ext:e,eiffel The following does B work in the F<.ackrc> file: - --type-set eiffel=.e,.eiffel + --type-set eiffel:ext:e,eiffel -In order to see all currently defined types, use I<--help types>, e.g. -I +In order to see all currently defined types, use I<--help-types>, e.g. +I -Restrictions: +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 depends on the value +of I. =over 4 -=item +=item is:I + +I filters match the target filename exactly. It takes exactly one +argument, which is the name of the file to match. + +Example: + + --type-set make:is:Makefile + +=item ext:I[,I[,...]] + +I filters match the extension of the target file against a list +of extensions. No leading dot is needed for the extensions. + +Example: + + --type-set perl:ext:pl,pm,t + +=item match:I + +I filters match the target filename against a regular expression. +The regular expression is made case insensitive for the search. + +Example: + + --type-set make:match:/(gnu)?makefile/ + +=item firstlinematch:I -The types 'skipped', 'make', 'binary' and 'text' are considered "builtin" and -cannot be altered. +I matches the first line of the target file against a +regular expression. Like I, the regular expression is made +case insensitive. -=item +Example: -The shebang line recognition of the types 'perl', 'ruby', 'php', 'python', -'shell' and 'xml' cannot be redefined by I<--type-set>, it is always -active. However, the shebang line is only examined for files where the -extension is not recognised. Therefore it is possible to say -I and -only find your shiny new I<.perl> files (and all files with unrecognized extension -and perl on the shebang line). + --type-add perl:firstlinematch:/perl/ =back +More filter types may be made available in the future. + =head1 ENVIRONMENT VARIABLES -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. +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. =over 4 =item ACKRC -Specifies the location of the F<.ackrc> file. If this file doesn't +Specifies the location of the user's F<.ackrc> file. If this file doesn't exist, F looks in the default location. =item ACK_OPTIONS @@ -670,11 +1002,11 @@ If you are not on Windows, you never need to use C. F integrates easily with the Vim text editor. Set this in your F<.vimrc> to use F instead of F: - set grepprg=ack\ -a + set grepprg=ack\ -k -That examples uses C<-a> to search through all files, but you may -use other default flags. Now you can search with F and easily -step through the results in Vim: +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 and easily step through the results in Vim: :grep Dumper perllib @@ -720,11 +1052,18 @@ 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>. -=head2 Use B<-f> to see what files you're scanning +=head2 Use B<-f> to see what files have been selected + +Ack's B<-f> was originally added as a debugging tool. If ack is +not finding matches you think it should find, run 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. -The reason I created B<-f> in the first place was as a debugging -tool. If ack is not finding matches you think it should find, run -F to see what files are being checked. +=head2 Use B<--dump> + +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. =head1 TIPS @@ -746,7 +1085,7 @@ For example: or if you prefer: - perl -p -i -e's/this/thatg/' $(ack -f --perl) + perl -p -i -e's/this/that/g' $(ack -f --perl) =head2 Use F<-Q> when in doubt about metacharacters @@ -767,6 +1106,47 @@ 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. +=head2 Examples of F<--output> + +Following variables are useful in the expansion string: + +=over 4 + +=item C<$&> + +The whole string matched by PATTERN. + +=item C<$1>, C<$2>, ... + +The contents of the 1st, 2nd ... bracketed group in PATTERN. + +=item C<$`> + +The string before the match. + +=item C<$'> + +The string after the match. + +=back + +For more details and other variables see +L. + +This example shows how to add text around a particular pattern +(in this case adding _ around word with "e") + + 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 + +This shows how to pick out particular parts of a match using ( ) within regular expression. + + ack '=head(\d+)\s+(.*)' --output=' $1 : $2' + input file contains "=head1 NAME" + output "1 : NAME" + =head2 Share your knowledge Join the ack-users mailing list. Send me your tips and I may add @@ -815,8 +1195,9 @@ this from the Unix shell: =head2 Can you make ack recognize F<.xyz> files? -That's an enhancement. Please see the section in the manual about -enhancements. +Yes! Please see L. If you think +that F should recognize a type by default, please see +L. =head2 There's already a program/package called ack. @@ -836,6 +1217,14 @@ To do that, run this with F or as root: ln -s /usr/bin/ack-grep /usr/bin/ack +Alternatively, you could use a shell alias: + + # bash/zsh + alias ack=ack-grep + + # csh + alias ack ack-grep + =head2 What does F mean? Nothing. I wanted a name that was easy to type and that you could @@ -849,65 +1238,271 @@ 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. -=head1 AUTHOR +=head2 Why is ack telling me I have an invalid option when searching for C<+foo>? -Andy Lester, C<< >> +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!) -=head1 BUGS +=head1 ACKRC LOCATION SEMANTICS -Please report any bugs or feature requests to the issues list at -Github: L +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) -=head1 ENHANCEMENTS +=over 4 -All enhancement requests MUST first be posted to the ack-users -mailing list at L. I -will not consider a request without it first getting seen by other -ack users. This includes requests for new filetypes. +=item * -There is a list of enhancements I want to make to F in the ack -issues list at Github: L +Defaults are loaded from App::Ack::ConfigDefaults. This can be omitted +using C<--ignore-ack-defaults>. -Patches are always welcome, but patches with tests get the most -attention. +=item * Global ackrc -=head1 SUPPORT +Options are then loaded from the global ackrc. This is located at +C on Unix-like systems, and +C on Windows. +This can be omitted using C<--noenv>. -Support for and information about F can be found at: +=item * User ackrc + +Options are then loaded from the user's ackrc. This is located at +C<$HOME/.ackrc> on Unix-like systems, and +C. If a different +ackrc is desired, it may be overriden with the C<$ACKRC> environment +variable. +This can be omitted using C<--noenv>. + +=item * Project ackrc + +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_OPTIONS + +Options are then loaded from the enviroment variable C. This can +be omitted using C<--noenv>. + +=item * Command line + +Options are then loaded from the command line. + +=back + +=head1 DIFFERENCES BETWEEN ACK 1.X AND ACK 2.X + +A lot of changes were made for ack 2; here is a list of them. + +=head2 GENERAL CHANGES =over 4 -=item * The ack homepage +=item * -L +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. -=item * The ack issues list at Github +=item * -L +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. -=item * AnnoCPAN: Annotated CPAN documentation +=item * -L +ack now loads multiple ackrc files; see L for +details. -=item * CPAN Ratings +=item * -L +ack's default filter definitions aren't special; you may tell ack to +completely disregard them if you don't like them. -=item * Search CPAN +=back -L +=head2 REMOVED OPTIONS -=item * Git source repository +=over 4 + +=item * + +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. + +=item * + +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 * + +The B<--binary> option has been removed. + +=item * -L +The B<--skipped> option has been removed. + +=item * + +The B<--text> option has been removed. + +=item * + +The B<--invert-file-match> option has been removed. Instead, you may +use B<-v> with B<-g>. =back -=head1 ACKNOWLEDGEMENTS +=head2 CHANGED OPTIONS -How appropriate to have Inowledgements! +=over 4 -Thanks to everyone who has contributed to ack in any way, including +=item * + +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>. + +=back + +=head2 ADDED OPTIONS + +=over 4 + +=item * + +B<--files-from> was added so that a user may submit a list of filenames as +a list of files to search. + +=item * + +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 * + +B<-s> was added to tell ack to suppress error messages about non-existent or +unreadable files. + +=item * + +B<--ignore-directory> and B<--noignore-directory> were added as aliases for +B<--ignore-dir> and B<--noignore-dir> respectively. + +=item * + +B<--ignore-file> was added so that users may specify patterns of files to +ignore (ex. /.*~$/). + +=item * + +B<--dump> was added to allow users to easily find out which options are +set where. + +=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. + +=item * + +B<--type-del> was added to selectively remove file type definitions. + +=item * + +B<--ignore-ack-defaults> was added so that users may ignore ack's default +options in favor of their own. + +=item * + +B<--bar> was added so ack users may consult Admiral Ackbar. + +=back + +=head1 AUTHOR + +Andy Lester, C<< >> + +=head1 BUGS + +Please report any bugs or feature requests to the issues list at +Github: L + +=head1 ENHANCEMENTS + +All enhancement requests MUST first be posted to the ack-users +mailing list at L. 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 in the ack +issues list at Github: L + +Patches are always welcome, but patches with tests get the most +attention. + +=head1 SUPPORT + +Support for and information about F can be found at: + +=over 4 + +=item * The ack homepage + +L + +=item * The ack-users mailing list + +L + +=item * The ack issues list at Github + +L + +=item * AnnoCPAN: Annotated CPAN documentation + +L + +=item * CPAN Ratings + +L + +=item * Search CPAN + +L + +=item * Git source repository + +L + +=back + +=head1 ACKNOWLEDGEMENTS + +How appropriate to have Inowledgements! + +Thanks to everyone who has contributed to ack in any way, including +Andrew Black, +Ralph Bodenner, +Shaun Patterson, +Ryan Olson, +Shlomi Fish, +Karen Etheridge, +Olivier Mengue, Matthew Wild, Scott Kyle, Nick Hooey, @@ -970,16 +1565,20 @@ David Alan Pisoni, Adriano Ferreira, James Keenan, Leland Johnson, -Ricardo Signes -and Pete Krawczyk. +Ricardo Signes, +Pete Krawczyk and +Rob Hoelz. =head1 COPYRIGHT & LICENSE -Copyright 2005-2011 Andy Lester. +Copyright 2005-2013 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 File::Next; @@ -987,13 +1586,12 @@ use strict; use warnings; -our $VERSION = '1.06'; +our $VERSION = '1.12'; use File::Spec (); - our $name; # name of the current file our $dir; # dir of the current file @@ -1005,30 +1603,32 @@ BEGIN { 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); } sub files { - ($_[0] eq __PACKAGE__) && die 'File::Next::files must not be invoked as File::Next->files'; + die _bad_invocation() if @_ && defined($_[0]) && ($_[0] eq __PACKAGE__); my ($parms,@queue) = _setup( \%files_defaults, @_ ); my $filter = $parms->{file_filter}; return sub { while (@queue) { - my ($dir,$file,$fullpath) = splice( @queue, 0, 3 ); - if ( -f $fullpath ) { + 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 = $dir; + local $File::Next::dir = $dirname; local $File::Next::name = $fullpath; next if not $filter->(); } - return wantarray ? ($dir,$file,$fullpath) : $fullpath; + return wantarray ? ($dirname,$file,$fullpath) : $fullpath; } elsif ( -d _ ) { unshift( @queue, _candidate_files( $parms, $fullpath ) ); @@ -1044,6 +1644,63 @@ sub files { +sub from_file { + die _bad_invocation() if @_ && defined($_[0]) && ($_[0] eq __PACKAGE__); + + my ($parms,@queue) = _setup( \%files_defaults, @_ ); + my $err = $parms->{error_handler}; + my $warn = $parms->{error_handler}; + + my $filename = $queue[1]; + + if ( !defined($filename) ) { + $err->( 'Must pass a filename to from_file()' ); + return undef; + } + + my $fh; + if ( $filename eq '-' ) { + $fh = \*STDIN; + } + else { + if ( !open( $fh, '<', $filename ) ) { + $err->( "Unable to open $filename: $!" ); + return undef; + } + } + my $filter = $parms->{file_filter}; + + 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; + } + + 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; + + return; + }; # iterator +} + +sub _bad_invocation { + my $good = (caller(1))[3]; + my $bad = $good; + $bad =~ s/(.+)::/$1->/; + return "$good must not be invoked as $bad"; +} sub sort_standard($$) { return $_[0]->[1] cmp $_[1]->[1] } sub sort_reverse($$) { return $_[1]->[1] cmp $_[0]->[1] } @@ -1101,12 +1758,12 @@ sub _setup { sub _candidate_files { - my $parms = shift; - my $dir = shift; + my $parms = shift; + my $dirname = shift; my $dh; - if ( !opendir $dh, $dir ) { - $parms->{error_handler}->( "$dir: $!" ); + if ( !opendir $dh, $dirname ) { + $parms->{error_handler}->( "$dirname: $!" ); return; } @@ -1119,7 +1776,7 @@ sub _candidate_files { my $has_stat; # Only do directory checking if we have a descend_filter - my $fullpath = File::Spec->catdir( $dir, $file ); + my $fullpath = File::Spec->catdir( $dirname, $file ); if ( !$follow_symlinks ) { next if -l $fullpath; $has_stat = 1; @@ -1133,10 +1790,10 @@ sub _candidate_files { } } if ( $sort_sub ) { - push( @newfiles, [ $dir, $file, $fullpath ] ); + push( @newfiles, [ $dirname, $file, $fullpath ] ); } else { - push( @newfiles, $dir, $file, $fullpath ); + push( @newfiles, $dirname, $file, $fullpath ); } } closedir $dh; @@ -1155,14 +1812,16 @@ package App::Ack; use warnings; use strict; - +use Getopt::Long 2.36 (); our $VERSION; +our $GIT_REVISION; our $COPYRIGHT; BEGIN { - $VERSION = '1.96'; - $COPYRIGHT = 'Copyright 2005-2011 Andy Lester.'; + $VERSION = '2.00b06'; + $COPYRIGHT = 'Copyright 2005-2013 Andy Lester.'; + $GIT_REVISION = q{04e8986}; } our $fh; @@ -1177,110 +1836,20 @@ our %type_wanted; our %mappings; our %ignore_dirs; -our $input_from_pipe; +our $is_filter_mode; our $output_to_pipe; our $dir_sep_chars; our $is_cygwin; our $is_windows; -use File::Spec (); -use File::Glob ':glob'; -use Getopt::Long (); +use File::Spec 1.00015 (); +use File::Glob 1.00015 ':glob'; BEGIN { - %ignore_dirs = ( - '.bzr' => 'Bazaar', - '.cdv' => 'Codeville', - '~.dep' => 'Interface Builder', - '~.dot' => 'Interface Builder', - '~.nib' => 'Interface Builder', - '~.plst' => 'Interface Builder', - '.git' => 'Git', - '.hg' => 'Mercurial', - '.pc' => 'quilt', - '.svn' => 'Subversion', - _MTN => 'Monotone', - blib => 'Perl module building', - CVS => 'CVS', - RCS => 'RCS', - SCCS => 'SCCS', - _darcs => 'darcs', - _sgbak => 'Vault/Fortress', - 'autom4te.cache' => 'autoconf', - 'cover_db' => 'Devel::Cover', - _build => 'Module::Build', - ); - - %mappings = ( - actionscript => [qw( as mxml )], - ada => [qw( ada adb ads )], - asm => [qw( asm s )], - batch => [qw( bat cmd )], - binary => q{Binary files, as defined by Perl's -B op (default: off)}, - cc => [qw( c h xs )], - cfmx => [qw( cfc cfm cfml )], - clojure => [qw( clj )], - cpp => [qw( cpp cc cxx m hpp hh h hxx )], - csharp => [qw( cs )], - css => [qw( css )], - delphi => [qw( pas int dfm nfm dof dpk dproj groupproj bdsgroup bdsproj )], - elisp => [qw( el )], - erlang => [qw( erl hrl )], - fortran => [qw( f f77 f90 f95 f03 for ftn fpp )], - go => [qw( go )], - groovy => [qw( groovy gtmpl gpp grunit )], - haskell => [qw( hs lhs )], - hh => [qw( h )], - html => [qw( htm html shtml xhtml )], - java => [qw( java properties )], - js => [qw( js )], - jsp => [qw( jsp jspx jhtm jhtml )], - lisp => [qw( lisp lsp )], - lua => [qw( lua )], - make => q{Makefiles (including *.mk and *.mak)}, - mason => [qw( mas mhtml mpl mtxt )], - objc => [qw( m h )], - objcpp => [qw( mm h )], - ocaml => [qw( ml mli )], - parrot => [qw( pir pasm pmc ops pod pg tg )], - perl => [qw( pl pm pm6 pod t )], - php => [qw( php phpt php3 php4 php5 phtml)], - plone => [qw( pt cpt metadata cpy py )], - python => [qw( py )], - rake => q{Rakefiles}, - ruby => [qw( rb rhtml rjs rxml erb rake spec )], - scala => [qw( scala )], - scheme => [qw( scm ss )], - shell => [qw( sh bash csh tcsh ksh zsh )], - skipped => q{Files, but not directories, normally skipped by ack (default: off)}, - smalltalk => [qw( st )], - sql => [qw( sql ctl )], - tcl => [qw( tcl itcl itk )], - tex => [qw( tex cls sty )], - text => q{Text files, as defined by Perl's -T op (default: off)}, - tt => [qw( tt tt2 ttml )], - vb => [qw( bas cls frm ctl vb resx )], - verilog => [qw( v vh sv )], - vhdl => [qw( vhd vhdl )], - vim => [qw( vim )], - yaml => [qw( yaml yml )], - xml => [qw( xml dtd xsl xslt ent )], - ); - - while ( my ($type,$exts) = each %mappings ) { - if ( ref $exts ) { - for my $ext ( @{$exts} ) { - push( @{$types{$ext}}, $type ); - } - } - } - # add manually Makefile extensions - push @{$types{$_}}, 'make' for qw{ mk mak }; - # These have to be checked before any filehandle diddling. $output_to_pipe = not -t *STDOUT; - $input_from_pipe = -p STDIN; + $is_filter_mode = -p STDIN; $is_cygwin = ($^O eq 'cygwin'); $is_windows = ($^O =~ /MSWin32/); @@ -1288,282 +1857,107 @@ BEGIN { } -sub read_ackrc { - my @files = ( $ENV{ACKRC} ); - my @dirs = - $is_windows - ? ( $ENV{HOME}, $ENV{USERPROFILE} ) - : ( '~', $ENV{HOME} ); - for my $dir ( grep { defined } @dirs ) { - for my $file ( '.ackrc', '_ackrc' ) { - push( @files, bsd_glob( "$dir/$file", GLOB_TILDE ) ); - } - } - for my $filename ( @files ) { - if ( defined $filename && -e $filename ) { - open( my $fh, '<', $filename ) or App::Ack::die( "$filename: $!\n" ); - my @lines = grep { /./ && !/^\s*#/ } <$fh>; - chomp @lines; - close $fh or App::Ack::die( "$filename: $!\n" ); - - # get rid of leading and trailing whitespaces - for ( @lines ) { - s/^\s+//; - s/\s+$//; - } - - return @lines; - } - } +sub retrieve_arg_sources { + my @arg_sources; - return; -} + 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'); -sub get_command_line_options { - my %opt = ( - pager => $ENV{ACK_PAGER_COLOR} || $ENV{ACK_PAGER}, + Getopt::Long::GetOptions( + 'noenv' => \$noenv, + 'ackrc=s' => \$ackrc, ); - my $getopt_specs = { - 1 => sub { $opt{1} = $opt{m} = 1 }, - 'A|after-context=i' => \$opt{after_context}, - 'B|before-context=i' => \$opt{before_context}, - 'C|context:i' => sub { shift; my $val = shift; $opt{before_context} = $opt{after_context} = ($val || 2) }, - 'a|all-types' => \$opt{all}, - 'break!' => \$opt{break}, - c => \$opt{count}, - 'color|colour!' => \$opt{color}, - 'color-match=s' => \$ENV{ACK_COLOR_MATCH}, - 'color-filename=s' => \$ENV{ACK_COLOR_FILENAME}, - 'color-lineno=s' => \$ENV{ACK_COLOR_LINENO}, - 'column!' => \$opt{column}, - count => \$opt{count}, - 'env!' => sub { }, # ignore this option, it is handled beforehand - f => \$opt{f}, - flush => \$opt{flush}, - 'follow!' => \$opt{follow}, - 'g=s' => sub { shift; $opt{G} = shift; $opt{f} = 1 }, - 'G=s' => \$opt{G}, - 'group!' => sub { shift; $opt{heading} = $opt{break} = shift }, - 'heading!' => \$opt{heading}, - 'h|no-filename' => \$opt{h}, - 'H|with-filename' => \$opt{H}, - 'i|ignore-case' => \$opt{i}, - 'invert-file-match' => \$opt{invert_file_match}, - 'lines=s' => sub { shift; my $val = shift; push @{$opt{lines}}, $val }, - 'l|files-with-matches' => \$opt{l}, - 'L|files-without-matches' => sub { $opt{l} = $opt{v} = 1 }, - 'm|max-count=i' => \$opt{m}, - 'match=s' => \$opt{regex}, - 'n|no-recurse' => \$opt{n}, - o => sub { $opt{output} = '$&' }, - 'output=s' => \$opt{output}, - 'pager=s' => \$opt{pager}, - 'nopager' => sub { $opt{pager} = undef }, - 'passthru' => \$opt{passthru}, - 'print0' => \$opt{print0}, - 'Q|literal' => \$opt{Q}, - 'r|R|recurse' => sub { $opt{n} = 0 }, - 'show-types' => \$opt{show_types}, - 'smart-case!' => \$opt{smart_case}, - 'sort-files' => \$opt{sort_files}, - 'u|unrestricted' => \$opt{u}, - 'v|invert-match' => \$opt{v}, - 'w|word-regexp' => \$opt{w}, - - 'ignore-dirs=s' => sub { shift; my $dir = remove_dir_sep( shift ); $ignore_dirs{$dir} = '--ignore-dirs' }, - 'noignore-dirs=s' => sub { shift; my $dir = remove_dir_sep( shift ); delete $ignore_dirs{$dir} }, - - 'version' => sub { print_version_statement(); exit; }, - 'help|?:s' => sub { shift; show_help(@_); exit; }, - 'help-types'=> sub { show_help_types(); exit; }, - 'man' => sub { - require Pod::Usage; - Pod::Usage::pod2usage({ - -verbose => 2, - -exitval => 0, - }); - }, - - 'type=s' => sub { - # Whatever --type=xxx they specify, set it manually in the hash - my $dummy = shift; - my $type = shift; - my $wanted = ($type =~ s/^no//) ? 0 : 1; # must not be undef later + Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version'); - if ( exists $type_wanted{ $type } ) { - $type_wanted{ $type } = $wanted; - } - else { - App::Ack::die( qq{Unknown --type "$type"} ); - } - }, # type sub - }; + my @files; - # Stick any default switches at the beginning, so they can be overridden - # by the command line switches. - unshift @ARGV, split( ' ', $ENV{ACK_OPTIONS} ) if defined $ENV{ACK_OPTIONS}; - - # first pass through options, looking for type definitions - def_types_from_ARGV(); - - for my $i ( filetypes_supported() ) { - $getopt_specs->{ "$i!" } = \$type_wanted{ $i }; + if ( !$noenv ) { + my $finder = App::Ack::ConfigFinder->new; + @files = $finder->find_config_files; } - - - my $parser = Getopt::Long::Parser->new(); - $parser->configure( 'bundling', 'no_ignore_case', ); - $parser->getoptions( %{$getopt_specs} ) or - App::Ack::die( 'See ack --help, ack --help-types or ack --man for options.' ); - - my $to_screen = not output_to_pipe(); - my %defaults = ( - all => 0, - color => $to_screen, - follow => 0, - break => $to_screen, - heading => $to_screen, - before_context => 0, - after_context => 0, - ); - if ( $is_windows && $defaults{color} && not $ENV{ACK_PAGER_COLOR} ) { - if ( $ENV{ACK_PAGER} || not eval { require Win32::Console::ANSI } ) { - $defaults{color} = 0; + 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; } - } - if ( $to_screen && $ENV{ACK_PAGER_COLOR} ) { - $defaults{color} = 1; - } - - while ( my ($key,$value) = each %defaults ) { - if ( not defined $opt{$key} ) { - $opt{$key} = $value; + else { + die "Unable to load ackrc '$ackrc': $!" } + push( @files, $ackrc ); } - if ( defined $opt{m} && $opt{m} <= 0 ) { - App::Ack::die( '-m must be greater than zero' ); - } + push @arg_sources, Defaults => [ App::Ack::ConfigDefault::options() ]; - for ( qw( before_context after_context ) ) { - if ( defined $opt{$_} && $opt{$_} < 0 ) { - App::Ack::die( "--$_ may not be negative" ); - } + foreach my $file ( @files) { + my @lines = read_rcfile($file); + push ( @arg_sources, $file, \@lines ) if @lines; } - if ( defined( my $val = $opt{output} ) ) { - $opt{output} = eval qq[ sub { "$val" } ]; + if ( $ENV{ACK_OPTIONS} && !$noenv ) { + push( @arg_sources, 'ACK_OPTIONS' => $ENV{ACK_OPTIONS} ); } - if ( defined( my $l = $opt{lines} ) ) { - # --line=1 --line=5 is equivalent to --line=1,5 - my @lines = split( /,/, join( ',', @{$l} ) ); - # --line=1-3 is equivalent to --line=1,2,3 - @lines = map { - my @ret; - if ( /-/ ) { - my ($from, $to) = split /-/, $_; - if ( $from > $to ) { - App::Ack::warn( "ignoring --line=$from-$to" ); - @ret = (); - } - else { - @ret = ( $from .. $to ); - } - } - else { - @ret = ( $_ ); - }; - @ret - } @lines; - - if ( @lines ) { - my %uniq; - @uniq{ @lines } = (); - $opt{lines} = [ sort { $a <=> $b } keys %uniq ]; # numerical sort and each line occurs only once! - } - else { - # happens if there are only ignored --line directives - App::Ack::die( 'All --line options are invalid.' ); - } - } + push( @arg_sources, 'ARGV' => [ @ARGV ] ); - return \%opt; + return @arg_sources; } +sub read_rcfile { + my $file = shift; -sub def_types_from_ARGV { - my @typedef; + return unless defined $file && -e $file; - my $parser = Getopt::Long::Parser->new(); - # pass_through => leave unrecognized command line arguments alone - # no_auto_abbrev => otherwise -c is expanded and not left alone - $parser->configure( 'no_ignore_case', 'pass_through', 'no_auto_abbrev' ); - $parser->getoptions( - 'type-set=s' => sub { shift; push @typedef, ['c', shift] }, - 'type-add=s' => sub { shift; push @typedef, ['a', shift] }, - ) or App::Ack::die( 'See ack --help or ack --man for options.' ); + my @lines; - for my $td (@typedef) { - my ($type, $ext) = split /=/, $td->[1]; + 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 ( $td->[0] eq 'c' ) { - # type-set - if ( exists $mappings{$type} ) { - # can't redefine types 'make', 'skipped', 'text' and 'binary' - App::Ack::die( qq{--type-set: Builtin type "$type" cannot be changed.} ) - if ref $mappings{$type} ne 'ARRAY'; + next if $line eq ''; + next if $line =~ /^#/; - delete_type($type); - } - } - else { - # type-add + push( @lines, $line ); + } + close $fh; + + return @lines; +} - # can't append to types 'make', 'skipped', 'text' and 'binary' - App::Ack::die( qq{--type-add: Builtin type "$type" cannot be changed.} ) - if exists $mappings{$type} && ref $mappings{$type} ne 'ARRAY'; - App::Ack::warn( qq{--type-add: Type "$type" does not exist, creating with "$ext" ...} ) - unless exists $mappings{$type}; - } +sub create_ignore_rules { + my $what = shift; + my $where = shift; + my $opts = shift; - my @exts = split /,/, $ext; - s/^\.// for @exts; + my @opts = @{$opts}; - if ( !exists $mappings{$type} || ref($mappings{$type}) eq 'ARRAY' ) { - push @{$mappings{$type}}, @exts; - for my $e ( @exts ) { - push @{$types{$e}}, $type; + my %rules; + + 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( qq{Cannot append to type "$type".} ); + App::Ack::die( "Invalid argument for --$what: $opt" ); } } - return; -} - - -sub delete_type { - my $type = shift; - - App::Ack::die( qq{Internal error: Cannot delete builtin type "$type".} ) - unless ref $mappings{$type} eq 'ARRAY'; - - delete $mappings{$type}; - delete $type_wanted{$type}; - for my $ext ( keys %types ) { - $types{$ext} = [ grep { $_ ne $type } @{$types{$ext}} ]; - } -} - - -sub ignoredir_filter { - return !exists $ignore_dirs{$_} && !exists $ignore_dirs{$File::Next::dir}; + return \%rules; } @@ -1575,81 +1969,6 @@ sub remove_dir_sep { } -use constant TEXT => 'text'; - -sub filetypes { - my $filename = shift; - - my $basename = $filename; - $basename =~ s{.*[$dir_sep_chars]}{}; - - return 'skipped' unless is_searchable( $basename ); - - my $lc_basename = lc $basename; - return ('make',TEXT) if $lc_basename eq 'makefile' || $lc_basename eq 'gnumakefile'; - return ('rake','ruby',TEXT) if $lc_basename eq 'rakefile'; - - # If there's an extension, look it up - if ( $filename =~ m{\.([^\.$dir_sep_chars]+)$}o ) { - my $ref = $types{lc $1}; - return (@{$ref},TEXT) if $ref; - } - - # At this point, we can't tell from just the name. Now we have to - # open it and look inside. - - return unless -e $filename; - # From Elliot Shank: - # I can't see any reason that -r would fail on these-- the ACLs look - # fine, and no program has any of them open, so the busted Windows - # file locking model isn't getting in there. If I comment the if - # statement out, everything works fine - # So, for cygwin, don't bother trying to check for readability. - if ( !$is_cygwin ) { - if ( !-r $filename ) { - App::Ack::warn( "$filename: Permission denied" ); - return; - } - } - - return 'binary' if -B $filename; - - # If there's no extension, or we don't recognize it, check the shebang line - my $fh; - if ( !open( $fh, '<', $filename ) ) { - App::Ack::warn( "$filename: $!" ); - return; - } - my $header = <$fh>; - close $fh; - - if ( $header =~ /^#!/ ) { - return ($1,TEXT) if $header =~ /\b(ruby|lua|p(?:erl|hp|ython))-?(\d[\d.]*)?\b/; - return ('shell',TEXT) if $header =~ /\b(?:ba|t?c|k|z)?sh\b/; - } - else { - return ('xml',TEXT) if $header =~ /\Qto_string } @{$ext_list} ); } App::Ack::print( sprintf( " --[no]%-*.*s %s\n", $maxlen, $maxlen, $type, $ext_list ) ); } @@ -1902,18 +2268,16 @@ END_OF_HELP return; } -sub _listify { - my @whats = @_; - - return '' if !@whats; +sub show_man { + require Pod::Usage; - my $end = pop @whats; - my $str = @whats ? join( ', ', @whats ) . " and $end" : $end; + Pod::Usage::pod2usage({ + -input => $App::Ack::orig_program_name, + -verbose => 2, + -exitval => 0, + }); - no warnings 'once'; - require Text::Wrap; - $Text::Wrap::columns = 75; - return Text::Wrap::wrap( '', ' ', $str ); + return; } @@ -1928,8 +2292,10 @@ sub get_version_statement { } my $ver = sprintf( '%vd', $^V ); + my $git_revision = $GIT_REVISION ? " (git commit $GIT_REVISION)" : ''; + return <<"END_OF_VERSION"; -ack $VERSION +ack ${VERSION}${git_revision} Running under Perl $ver at $this_perl $copyright @@ -1953,7 +2319,7 @@ sub get_copyright { sub load_colors { - eval 'use Term::ANSIColor ()'; + eval 'use Term::ANSIColor 1.12 ()'; $ENV{ACK_COLOR_MATCH} ||= 'black on_yellow'; $ENV{ACK_COLOR_FILENAME} ||= 'bold green'; @@ -1963,37 +2329,16 @@ sub load_colors { } -sub is_interesting { - return if /^\./; - - my $include; - - for my $type ( filetypes( $File::Next::name ) ) { - if ( defined $type_wanted{$type} ) { - if ( $type_wanted{$type} ) { - $include = 1; - } - else { - return; - } - } - } - - return $include; -} - - - # 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} @_ } -sub print_first_filename { App::Ack::print( $_[0], "\n" ) } -sub print_blank_line { App::Ack::print( "\n" ) } -sub print_separator { App::Ack::print( "--\n" ) } -sub print_filename { App::Ack::print( $_[0], $_[1] ) } -sub print_line_no { App::Ack::print( $_[0], $_[1] ) } -sub print_column_no { App::Ack::print( $_[0], $_[1] ) } +sub print { print {$fh} @_; return; } +sub print_first_filename { App::Ack::print( $_[0], "\n" ); return; } +sub print_blank_line { App::Ack::print( "\n" ); return; } +sub print_separator { App::Ack::print( "--\n" ); return; } +sub print_filename { App::Ack::print( $_[0], $_[1] ); return; } +sub print_line_no { App::Ack::print( $_[0], $_[1] ); return; } +sub print_column_no { App::Ack::print( $_[0], $_[1] ); return; } sub print_count { my $filename = shift; my $nmatches = shift; @@ -2009,6 +2354,8 @@ sub print_count { App::Ack::print( $nmatches ) if $count; } App::Ack::print( $ors ); + + return; } sub print_count0 { @@ -2022,566 +2369,465 @@ sub print_count0 { else { App::Ack::print( '0', $ors ); } -} - + return; +} -{ - my $filename; - my $regex; - my $display_filename; +sub set_up_pager { + my $command = shift; - my $keep_context; + return if App::Ack::output_to_pipe(); - my $last_output_line; # number of the last line that has been output - my $any_output; # has there been any output for the current file yet - my $context_overall_output_count; # has there been any output at all - -sub search_resource { - my $res = shift; - my $opt = shift; - - $filename = $res->name(); - - my $v = $opt->{v}; - my $passthru = $opt->{passthru}; - my $max = $opt->{m}; - my $nmatches = 0; - - $display_filename = undef; - - # for --line processing - my $has_lines = 0; - my @lines; - if ( defined $opt->{lines} ) { - $has_lines = 1; - @lines = ( @{$opt->{lines}}, -1 ); - undef $regex; # Don't match when printing matching line - } - else { - $regex = qr/$opt->{regex}/; + my $pager; + if ( not open( $pager, '|-', $command ) ) { + App::Ack::die( qq{Unable to pipe to pager "$command": $!} ); } + $fh = $pager; - # for context processing - $last_output_line = -1; - $any_output = 0; - my $before_context = $opt->{before_context}; - my $after_context = $opt->{after_context}; - - $keep_context = ($before_context || $after_context) && !$passthru; + return; +} - my @before; - my $before_starts_at_line; - my $after = 0; # number of lines still to print after a match - while ( $res->next_text ) { - # XXX Optimize away the case when there are no more @lines to find. - # XXX $has_lines, $passthru and $v never change. Optimize. - if ( $has_lines - ? $. != $lines[0] # $lines[0] should be a scalar - : $v ? m/$regex/ : !m/$regex/ ) { - if ( $passthru ) { - App::Ack::print( $_ ); - next; - } +sub output_to_pipe { + return $output_to_pipe; +} - if ( $keep_context ) { - if ( $after ) { - print_match_or_context( $opt, 0, $., $-[0], $+[0], $_ ); - $after--; - } - elsif ( $before_context ) { - if ( @before ) { - if ( @before >= $before_context ) { - shift @before; - ++$before_starts_at_line; - } - } - else { - $before_starts_at_line = $.; - } - push @before, $_; - } - last if $max && ( $nmatches >= $max ) && !$after; - } - next; - } # not a match - ++$nmatches; +sub exit_from_ack { + my $nmatches = shift; - # print an empty line as a divider before first line in each file (not before the first file) - if ( !$any_output && $opt->{show_filename} && $opt->{break} && defined( $context_overall_output_count ) ) { - App::Ack::print_blank_line(); - } + my $rc = $nmatches ? 0 : 1; + exit $rc; +} - shift @lines if $has_lines; +{ - if ( $res->is_binary ) { - App::Ack::print( "Binary file $filename matches\n" ); - last; - } - if ( $keep_context ) { - if ( @before ) { - print_match_or_context( $opt, 0, $before_starts_at_line, $-[0], $+[0], @before ); - @before = (); - $before_starts_at_line = 0; - } - if ( $max && $nmatches > $max ) { - --$after; - } - else { - $after = $after_context; - } - } - print_match_or_context( $opt, 1, $., $-[0], $+[0], $_ ); +my @capture_indices; +my $match_column_number; - last if $max && ( $nmatches >= $max ) && !$after; - } # while +sub does_match { + my ( $opt, $line ) = @_; - return $nmatches; -} # search_resource() - - - -sub print_match_or_context { - my $opt = shift; # opts array - my $is_match = shift; # is there a match on the line? - my $line_no = shift; - my $match_start = shift; - my $match_end = shift; - - my $color = $opt->{color}; - my $heading = $opt->{heading}; - my $show_filename = $opt->{show_filename}; - my $show_column = $opt->{column}; - - if ( $show_filename ) { - if ( not defined $display_filename ) { - $display_filename = - $color - ? Term::ANSIColor::colored( $filename, $ENV{ACK_COLOR_FILENAME} ) - : $filename; - if ( $heading && !$any_output ) { - App::Ack::print_first_filename($display_filename); - } - } - } + my $re = $opt->{regex}; + my $invert = $opt->{v}; - my $sep = $is_match ? ':' : '-'; - my $output_func = $opt->{output}; - for ( @_ ) { - if ( $keep_context && !$output_func ) { - if ( ( $last_output_line != $line_no - 1 ) && - ( $any_output || ( !$heading && defined( $context_overall_output_count ) ) ) ) { - App::Ack::print_separator(); - } - # to ensure separators between different files when --noheading + return unless $re; - $last_output_line = $line_no; - } + $match_column_number = undef; + @capture_indices = (); - if ( $show_filename ) { - App::Ack::print_filename($display_filename, $sep) if not $heading; - my $display_line_no = - $color - ? Term::ANSIColor::colored( $line_no, $ENV{ACK_COLOR_LINENO} ) - : $line_no; - App::Ack::print_line_no($display_line_no, $sep); - } + if ( $invert ? $line !~ /$re/ : $line =~ /$re/ ) { + if ( not $invert ) { + # @- = @LAST_MATCH_START + # @+ = @LAST_MATCH_END + $match_column_number = $-[0] + 1; - if ( $output_func ) { - while ( /$regex/go ) { - App::Ack::print( $output_func->() . "\n" ); - } - } - else { - if ( $color && $is_match && $regex && - s/$regex/Term::ANSIColor::colored( substr($_, $-[0], $+[0] - $-[0]), $ENV{ACK_COLOR_MATCH} )/eg ) { - # At the end of the line reset the color and remove newline - s/[\r\n]*\z/\e[0m\e[K/; - } - else { - # remove any kind of newline at the end of the line - s/[\r\n]*\z//; - } - if ( $show_column ) { - App::Ack::print_column_no( $match_start+1, $sep ); + if ( @- > 1 ) { + @capture_indices = map { + [ $-[$_], $+[$_] ] + } ( 1 .. $#- ); } - App::Ack::print($_ . "\n"); } - $any_output = 1; - ++$context_overall_output_count; - ++$line_no; + return 1; + } + else { + return; } - - return; -} # print_match_or_context() - -} # scope around search_resource() and print_match_or_context() - - -TOTAL_COUNT_SCOPE: { -my $total_count; - -sub get_total_count { - return $total_count; } -sub reset_total_count { - $total_count = 0; +sub get_capture_indices { + return @capture_indices; } +sub get_match_column { + return $match_column_number; +} -sub search_and_list { - my $res = shift; - my $opt = shift; - - my $nmatches = 0; - my $count = $opt->{count}; - my $ors = $opt->{print0} ? "\0" : "\n"; # output record separator - my $show_filename = $opt->{show_filename}; - - my $regex = qr/$opt->{regex}/; +} - if ( $opt->{v} ) { - while ( $res->next_text ) { - if ( /$regex/ ) { - return 0 unless $count; - } - else { - ++$nmatches; +sub print_matches_in_resource { + my ( $resource, $opt ) = @_; + + 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; + + 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--; } - } - else { - while ( $res->next_text ) { - if ( /$regex/ ) { - ++$nmatches; - last unless $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; } - } - - if ( $opt->{show_total} ) { - $total_count += $nmatches; - } - else { - if ( $nmatches ) { - App::Ack::print_count( $res->name, $nmatches, $ors, $count, $show_filename ); - } - elsif ( $count && !$opt->{l} ) { - App::Ack::print_count0( $res->name, $ors, $show_filename ); - } - } + return $max_count != 0; + }); - return $nmatches ? 1 : 0; -} # search_and_list() + return $nmatches; +} -} # scope around $total_count +sub count_matches_in_resource { + my ( $resource, $opt ) = @_; + my $nmatches = 0; + App::Ack::iterate( $resource, $opt, sub { + ++$nmatches if App::Ack::does_match($opt, $_); + return 1; + } ); -sub filetypes_supported_set { - return grep { defined $type_wanted{$_} && ($type_wanted{$_} == 1) } filetypes_supported(); + return $nmatches; } +sub resource_has_match { + my ( $resource, $opt ) = @_; + return count_matches_in_resource($resource, $opt) > 0; +} -sub print_files { - my $iter = shift; - my $opt = shift; +{ - my $ors = $opt->{print0} ? "\0" : "\n"; +my @before_ctx_lines; +my @after_ctx_lines; +my $is_iterating; - my $nmatches = 0; - while ( defined ( my $file = $iter->() ) ) { - App::Ack::print $file, $opt->{show_types} ? " => " . join( ',', filetypes( $file ) ) : (), $ors; - $nmatches++; - last if $opt->{1}; +sub get_context { + if ( not $is_iterating ) { + Carp::croak( 'get_context() called outside of iterate()' ); } - return $nmatches; + return ( + scalar(@before_ctx_lines) ? \@before_ctx_lines : undef, + scalar(@after_ctx_lines) ? \@after_ctx_lines : undef, + ); } +sub iterate { + my ( $resource, $opt, $cb ) = @_; -sub print_files_with_matches { - my $iter = shift; - my $opt = shift; - - # if we have -l and only 1 file given on command line (this means - # show_filename is set to 0), we want to see the filename nevertheless - $opt->{show_filename} = 1 if $opt->{l}; + $is_iterating = 1; - $opt->{show_filename} = 0 if $opt->{h}; - $opt->{show_filename} = 1 if $opt->{H}; + local $opt->{before_context} = $opt->{output} ? 0 : $opt->{before_context}; + local $opt->{after_context} = $opt->{output} ? 0 : $opt->{after_context}; - # abuse options to hand in the show_total parameter to search_and_list - $opt->{show_total} = $opt->{count} && !$opt->{show_filename}; - reset_total_count(); + my $n_before_ctx_lines = $opt->{before_context} || 0; + my $n_after_ctx_lines = $opt->{after_context} || 0; + my $current_line; - my $nmatches = 0; - while ( defined ( my $filename = $iter->() ) ) { - my $repo = App::Ack::Repository::Basic->new( $filename ); - my $res; - while ( $res = $repo->next_resource() ) { - $nmatches += search_and_list( $res, $opt ); - $res->close(); - last if $nmatches && $opt->{1}; - } - $repo->close(); - } + @after_ctx_lines = @before_ctx_lines = (); - if ( $nmatches && $opt->{show_total} ) { - App::Ack::print_count('', get_total_count(), "\n", 1, 0 ) + if ( $resource->next_text() ) { + $current_line = $_; # prime the first line of input } - return $nmatches; -} + 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 print_matches { - my $iter = shift; - my $opt = shift; + last unless $cb->(); - $opt->{show_filename} = 0 if $opt->{h}; - $opt->{show_filename} = 1 if $opt->{H}; + # 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 $nmatches = 0; - while ( defined ( my $filename = $iter->() ) ) { - my $repo; - my $tarballs_work = 0; - if ( $tarballs_work && $filename =~ /\.tar\.gz$/ ) { - App::Ack::die( 'Not working here yet' ); - require App::Ack::Repository::Tar; # XXX Error checking - $repo = App::Ack::Repository::Tar->new( $filename ); + push @before_ctx_lines, $current_line; +if($n_after_ctx_lines) { + $current_line = shift @after_ctx_lines; } - else { - $repo = App::Ack::Repository::Basic->new( $filename ); + elsif($resource->next_text()) { + $current_line = $_; } - $repo or next; - - while ( my $res = $repo->next_resource() ) { - my $needs_line_scan; - if ( $opt->{regex} && !$opt->{passthru} ) { - $needs_line_scan = $res->needs_line_scan( $opt ); - if ( $needs_line_scan ) { - $res->reset(); - } - } - else { - $needs_line_scan = 1; - } - if ( $needs_line_scan ) { - $nmatches += search_resource( $res, $opt ); - } - $res->close(); + else { + undef $current_line; } - last if $nmatches && $opt->{1}; - $repo->close(); + shift @before_ctx_lines while @before_ctx_lines > $n_before_ctx_lines; } - return $nmatches; -} + $is_iterating = 0; # XXX this won't happen on an exception + # then again, do we care? ack doesn't really + # handle exceptions anyway. -sub filetype_setup { - my $filetypes_supported_set = filetypes_supported_set(); - # If anyone says --no-whatever, we assume all other types must be on. - if ( !$filetypes_supported_set ) { - for my $i ( keys %type_wanted ) { - $type_wanted{$i} = 1 unless ( defined( $type_wanted{$i} ) || $i eq 'binary' || $i eq 'text' || $i eq 'skipped' ); - } - } return; } +} -EXPAND_FILENAMES_SCOPE: { - my $filter; +my $has_printed_something; - sub expand_filenames { - my $argv = shift; +BEGIN { + $has_printed_something = 0; +} - my $attr; - my @files; +sub has_printed_something { + return $has_printed_something; +} - foreach my $pattern ( @{$argv} ) { - my @results = bsd_glob( $pattern ); +sub print_line_with_options { + my ( $opt, $filename, $line, $line_no, $separator ) = @_; - if (@results == 0) { - @results = $pattern; # Glob didn't match, pass it thru unchanged - } - elsif ( (@results > 1) or ($results[0] ne $pattern) ) { - if (not defined $filter) { - eval 'require Win32::File;'; - if ($@) { - $filter = 0; - } - else { - $filter = Win32::File::HIDDEN()|Win32::File::SYSTEM(); - } - } # end unless we've tried to load Win32::File - if ( $filter ) { - # Filter out hidden and system files: - @results = grep { not(Win32::File::GetAttributes($_, $attr) and $attr & $filter) } @results; - App::Ack::warn( "$pattern: Matched only hidden files" ) unless @results; - } # end if we can filter by file attributes - } # end elsif this pattern got expanded + $has_printed_something = 1; - push @files, @results; - } # end foreach pattern + 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}; - return \@files; - } # end expand_filenames -} # EXPAND_FILENAMES_SCOPE + my @line_parts; + if( $color ) { + $filename = Term::ANSIColor::colored($filename, + $ENV{ACK_COLOR_FILENAME}); + $line_no = Term::ANSIColor::colored($line_no, + $ENV{ACK_COLOR_LINENO}); + } + if($print_filename) { + if( $heading ) { + push @line_parts, $line_no; + } + else { + push @line_parts, $filename, $line_no; + } -sub get_starting_points { - my $argv = shift; - my $opt = shift; + 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 ); + } + } + else { + my @capture_indices = get_capture_indices(); + if( @capture_indices ) { + my $offset = 0; # additional offset for when we add stuff - my @what; + foreach my $index_pair ( @capture_indices ) { + my ( $match_start, $match_end ) = @{$index_pair}; - if ( @{$argv} ) { - @what = @{ $is_windows ? expand_filenames($argv) : $argv }; - $_ = File::Next::reslash( $_ ) for @what; + my $substring = substr( $line, + $offset + $match_start, $match_end - $match_start ); + my $substitution = Term::ANSIColor::colored( $substring, + $ENV{ACK_COLOR_MATCH} ); - # Show filenames unless we've specified one single file - $opt->{show_filename} = (@what > 1) || (!-f $what[0]); - } - else { - @what = '.'; # Assume current directory - $opt->{show_filename} = 1; - } + substr( $line, $offset + $match_start, + $match_end - $match_start, $substitution ); + + $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"; + } + } - for my $start_point (@what) { - App::Ack::warn( "$start_point: No such file or directory" ) unless -e $start_point; + push @line_parts, $line; + App::Ack::print( join( $separator, @line_parts ), $ors ); } - return \@what; + + return; } -sub _match { - my ( $target, $expression, $invert_flag ) = @_; +{ - if ( $invert_flag ) { - return $target !~ $expression; - } - else { - return $target =~ $expression; - } -} +my $is_first_match; +my $previous_file_processed; +my $previous_line_printed; +BEGIN { + $is_first_match = 1; + $previous_line_printed = -1; +} -sub get_iterator { - my $what = shift; - my $opt = shift; +sub print_line_with_context { + my ( $opt, $filename, $matching_line, $line_no ) = @_; - # Starting points are always searched, no matter what - my %starting_point = map { ($_ => 1) } @{$what}; + my $heading = $opt->{heading}; - my $g_regex = defined $opt->{G} ? qr/$opt->{G}/ : undef; - my $file_filter; + if( !defined($previous_file_processed) || + $previous_file_processed ne $filename ) { + $previous_file_processed = $filename; + $previous_line_printed = -1; - if ( $g_regex ) { - $file_filter - = $opt->{u} ? sub { _match( $File::Next::name, qr/$g_regex/, $opt->{invert_file_match} ) } # XXX Maybe this should be a 1, no? - : $opt->{all} ? sub { $starting_point{ $File::Next::name } || ( _match( $File::Next::name, qr/$g_regex/, $opt->{invert_file_match} ) && is_searchable( $_ ) ) } - : sub { $starting_point{ $File::Next::name } || ( _match( $File::Next::name, qr/$g_regex/, $opt->{invert_file_match} ) && is_interesting( @ _) ) } - ; - } - else { - $file_filter - = $opt->{u} ? sub {1} - : $opt->{all} ? sub { $starting_point{ $File::Next::name } || is_searchable( $_ ) } - : sub { $starting_point{ $File::Next::name } || is_interesting( @_ ) } - ; + if( $heading ) { + $is_first_match = 1; + } } - my $descend_filter - = $opt->{n} ? sub {0} - : $opt->{u} ? sub {1} - : \&ignoredir_filter; + 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}; - my $iter = - File::Next::files( { - file_filter => $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}, - }, @{$what} ); - return $iter; -} + chomp $matching_line; + my ( $before_context, $after_context ) = get_context(); -sub set_up_pager { - my $command = shift; + if ( $before_context ) { + my $first_line = $. - @{$before_context}; - return if App::Ack::output_to_pipe(); + 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}; - my $pager; - if ( not open( $pager, '|-', $command ) ) { - App::Ack::die( qq{Unable to pipe to pager "$command": $!} ); - } - $fh = $pager; + 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; -} + 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 input_from_pipe { - return $input_from_pipe; -} + App::Ack::print_line_with_options($opt, $filename, $matching_line, $line_no, ':'); + $previous_line_printed = $.; + } + 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++; + } + } + $is_first_match = 0; -sub output_to_pipe { - return $output_to_pipe; + return; } - -sub exit_from_ack { - my $nmatches = shift; - - my $rc = $nmatches ? 0 : 1; - exit $rc; } +# inefficient, but functional +sub filetypes { + my ( $resource ) = @_; + my @matches; -1; # End of App::Ack -package App::Ack::Repository; - + foreach my $k (keys %mappings) { + my $filters = $mappings{$k}; -use warnings; -use strict; + foreach my $filter (@{$filters}) { + # clone the resource + my $clone = $resource->clone; + if ( $filter->filter($clone) ) { + push @matches, $k; + last; + } + } + } -sub FAIL { - require Carp; - Carp::confess( 'Must be overloaded' ); + return sort @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 ) = @_; -sub new { - FAIL(); + if ( $is_windows ) { + return File::Next::reslash( $filename ); + } + else { + # XXX is this the best method? it always hits the FS + if( my ( $dev, $inode ) = (stat($filename))[0, 1] ) { + return join(':', $dev, $inode); + } + else { + # XXX this could be better + return $filename; + } + } } +sub create_ackrc { + my @lines = App::Ack::ConfigDefault::options(); -sub next_resource { - FAIL(); + print join("\n", '--ignore-ack-defaults', @lines); } -sub close { - FAIL(); -} -1; +1; # End of App::Ack package App::Ack::Resource; use warnings; use strict; +use overload + '""' => 'name'; sub FAIL { require Carp; @@ -2590,98 +2836,168 @@ sub FAIL { sub new { - FAIL(); + return FAIL(); } sub name { - FAIL(); + return FAIL(); } sub is_binary { - FAIL(); + return FAIL(); } sub needs_line_scan { - FAIL(); + return FAIL(); } sub reset { - FAIL(); + return FAIL(); } sub next_text { - FAIL(); + return FAIL(); } sub close { - FAIL(); + return FAIL(); } -1; -package App::Ack::Plugin::Basic; +sub clone { + return FAIL(); +} +1; +package App::Ack::Resources; -package App::Ack::Resource::Basic; use warnings; use strict; -our @ISA = qw( App::Ack::Resource ); - +sub from_argv { + my $class = shift; + my $opt = shift; + my $start = shift; -sub new { - my $class = shift; - my $filename = shift; + my $self = bless {}, $class; - my $self = bless { - filename => $filename, - fh => undef, - could_be_binary => undef, - opened => undef, - id => undef, - }, $class; + my $file_filter = undef; + my $descend_filter = $opt->{descend_filter}; - if ( $self->{filename} eq '-' ) { - $self->{fh} = *STDIN; - $self->{could_be_binary} = 0; - } - else { - if ( !open( $self->{fh}, '<', $self->{filename} ) ) { - App::Ack::warn( "$self->{filename}: $!" ); - return; - } - $self->{could_be_binary} = 1; + if( $opt->{n} ) { + $descend_filter = sub { + return 0; + }; } + $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} ); + return $self; } -sub name { - my $self = shift; +sub from_file { + my $class = shift; + my $opt = shift; + my $file = shift; - return $self->{filename}; + 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; + + return bless { + iter => $iter, + }, $class; } +# This is for reading input lines from STDIN, not the list of files from STDIN +sub from_stdin { + my $class = shift; + my $opt = shift; -sub is_binary { - my $self = shift; + my $self = bless {}, $class; - if ( $self->{could_be_binary} ) { - return -B $self->{filename}; + my $has_been_called = 0; + + $self->{iter} = sub { + if ( !$has_been_called ) { + $has_been_called = 1; + return '-'; + } + return; + }; + + return $self; +} + +sub next { + my $self = shift; + + my $file = $self->{iter}->() or return; + + return App::Ack::Resource::Basic->new( $file ); +} + +1; +package App::Ack::Resource::Basic; + + +use warnings; +use strict; + +BEGIN { + our @ISA = 'App::Ack::Resource'; +} + + +sub new { + my $class = shift; + my $filename = shift; + + my $self = bless { + filename => $filename, + fh => undef, + opened => undef, + }, $class; + + 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; + } } - return 0; + return $self; +} + + +sub name { + my $self = shift; + + return $self->{filename}; } @@ -2702,7 +3018,7 @@ sub needs_line_scan { my $buffer; my $rc = sysread( $self->{fh}, $buffer, $size ); - if ( not defined $rc ) { + if ( !defined($rc) && $App::Ack::report_bad_filenames ) { App::Ack::warn( "$self->{filename}: $!" ); return 1; } @@ -2716,8 +3032,9 @@ sub needs_line_scan { sub reset { my $self = shift; - seek( $self->{fh}, 0, 0 ) - or App::Ack::warn( "$self->{filename}: $!" ); + if( !seek( $self->{fh}, 0, 0 ) && $App::Ack::report_bad_filenames ) { + App::Ack::warn( "$self->{filename}: $!" ); + } return; } @@ -2726,6 +3043,8 @@ sub reset { 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; } @@ -2736,48 +3055,1309 @@ sub next_text { sub close { my $self = shift; - if ( not close $self->{fh} ) { + if ( !close($self->{fh}) && $App::Ack::report_bad_filenames ) { App::Ack::warn( $self->name() . ": $!" ); } return; } -package App::Ack::Repository::Basic; +sub clone { + my ( $self ) = @_; + + return __PACKAGE__->new($self->name); +} + + +1; +package App::Ack::Filter; + +use strict; +use warnings; +use overload + '""' => 'to_string'; + +use Carp 1.10 (); + +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 ) = @_; -our @ISA = qw( App::Ack::Repository ); + 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, + }, $class; +} + +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 = shift; - my $filename = shift; + my ( $class, $re ) = @_; - my $self = bless { + $re =~ s{^/|/$}{}g; # XXX validate? + $re = qr{$re}i; + + return bless { + regex => $re, + }, $class; +} + +# XXX This test checks the first "line" of the file, but we need +# it to be less piggy. If it's something like a .min.js file, then +# the "line" could be the entire file. Instead, it should read the +# first, say, 100 characters of the first line. + +sub filter { + my ( $self, $resource ) = @_; + + my $re = $self->{'regex'}; + + local $_; + return unless $resource->next_text; + + return /$re/; +} + +sub inspect { + my ( $self ) = @_; + + my $re = $self->{'regex'}; + + return ref($self) . " - $re"; +} + +sub to_string { + my ( $self ) = @_; + + my $re = $self->{'regex'}; + + 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, - nexted => 0, }, $class; +} - return $self; +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'}; +} + +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 ) = @_; -sub next_resource { + return bless { + filter => $filter, + }, $class; +} + +sub filter { + my ( $self, $resource ) = @_; + + my $filter = $self->{'filter'}; + return !$filter->filter( $resource ); +} + +sub invert { my $self = shift; - return if $self->{nexted}; - $self->{nexted} = 1; + return $self->{'filter'}; +} + +sub is_inverted { + return 1; +} + +sub inspect { + my ( $self ) = @_; + + my $filter = $self->{'filter'}; - return App::Ack::Resource::Basic->new( $self->{filename} ); + return "!$filter"; } +1; +package App::Ack::ConfigFinder; -sub close { + +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 find_config_files { + my @config_files; + + 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'; + } + + if ( $ENV{'ACKRC'} && -f $ENV{'ACKRC'} ) { + push @config_files, $ENV{'ACKRC'}; + } + else { + push @config_files, _check_for_ackrc($ENV{'HOME'}); + } + + 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; + } + + # 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 ); +} + +1; +package App::Ack::ConfigLoader; + +use strict; +use warnings; + +use Carp 1.10 (); +use Getopt::Long 2.36 (); +use Text::ParseWords 3.1 (); + + +my @INVALID_COMBINATIONS; + +BEGIN { + my @context = qw( -A -B -C --after-context --before-context --context ); + my @pretty = qw( --heading --group --break ); + my @filename = qw( -h -H --with-filename --no-filename ); + + @INVALID_COMBINATIONS = ( + # XXX normalize + [qw(-l)] => [@context, @pretty, @filename, qw(-L -o --passthru --output --max-count --column -f -g --show-types)], + [qw(-L)] => [@context, @pretty, @filename, qw(-l -o --passthru --output --max-count --column -f -g --show-types -c --count)], + [qw(--line)] => [@context, @pretty, @filename, qw(-l --files-with-matches --files-without-matches -L -o --passthru --match -m --max-count -1 -c --count --column --print0 -f -g --show-types)], + [qw(-o)] => [@context, qw(--output -c --count --column --column -f --show-types)], + [qw(--passthru)] => [@context, qw(--output --column -m --max-count -1 -c --count -f -g)], + [qw(--output)] => [@context, qw(-c --count -f -g)], + [qw(--match)] => [qw(-f -g)], + [qw(-m --max-count)] => [qw(-1 -f -g -c --count)], + [qw(-h --no-filename)] => [qw(-H --with-filename -f -g --group --heading)], + [qw(-H --with-filename)] => [qw(-h --no-filename -f -g)], + [qw(-c --count)] => [@context, @pretty, qw(--column -f -g)], + [qw(--column)] => [qw(-f -g)], + [@context] => [qw(-f -g)], + [qw(-f)] => [qw(-g), @pretty], + [qw(-g)] => [qw(-f), @pretty], + ); +} + +sub process_filter_spec { + my ( $spec ) = @_; + + if ( $spec =~ /^(\w+):(\w+):(.*)/ ) { + my ( $type_name, $ext_type, $arguments ) = ( $1, $2, $3 ); + + return ( $type_name, + App::Ack::Filter->create_filter($ext_type, split(/,/, $arguments)) ); + } + elsif ( $spec =~ /^(\w+)=(.*)/ ) { # Check to see if we have ack1-style argument specification. + my ( $type_name, $extensions ) = ( $1, $2 ); + + my @extensions = split(/,/, $extensions); + foreach my $extension ( @extensions ) { + $extension =~ s/^[.]//; + } + + return ( $type_name, App::Ack::Filter->create_filter('ext', @extensions) ); + } + else { + Carp::croak "invalid filter specification '$spec'"; + } +} + +sub process_filetypes { + my ( $opt, $arg_sources ) = @_; + + 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', + ); + my %additional_specs; + + my $add_spec = sub { + my ( undef, $spec ) = @_; + + my ( $name, $filter ) = process_filter_spec($spec); + + push @{ $App::Ack::mappings{$name} }, $filter; + + $additional_specs{$name . '!'} = sub { + my ( undef, $value ) = @_; + + my @filters = @{ $App::Ack::mappings{$name} }; + if ( not $value ) { + @filters = map { $_->invert() } @filters; + } + + push @{ $opt->{'filters'} }, @filters; + }; + }; + + my $set_spec = sub { + my ( undef, $spec ) = @_; + + my ( $name, $filter ) = process_filter_spec($spec); + + $App::Ack::mappings{$name} = [ $filter ]; + + $additional_specs{$name . '!'} = sub { + my ( undef, $value ) = @_; + + my @filters = @{ $App::Ack::mappings{$name} }; + if ( not $value ) { + @filters = map { $_->invert() } @filters; + } + + push @{ $opt->{'filters'} }, @filters; + }; + }; + + my $delete_spec = sub { + my ( undef, $name ) = @_; + + delete $App::Ack::mappings{$name}; + delete $additional_specs{$name . '!'}; + }; + + my %type_arg_specs = ( + 'type-add=s' => $add_spec, + 'type-set=s' => $set_spec, + 'type-del=s' => $delete_spec, + ); + + for ( my $i = 0; $i < @{$arg_sources}; $i += 2) { + my ( $source_name, $args ) = @{$arg_sources}[ $i, $i + 1]; + + if ( ref($args) ) { + # $args are modified in place, so no need to munge $arg_sources + Getopt::Long::GetOptionsFromArray($args, %type_arg_specs); + } + else { + ( undef, $arg_sources->[$i + 1] ) = + Getopt::Long::GetOptionsFromString($args, %type_arg_specs); + } + } + + $additional_specs{'k|known-types'} = sub { + my ( undef, $value ) = @_; + + my @filters = map { @{$_} } values(%App::Ack::mappings); + + push @{ $opt->{'filters'} }, @filters; + }; + + return \%additional_specs; +} + +sub removed_option { + my ( $option, $explanation ) = @_; + + $explanation ||= ''; + return sub { + warn "Option '$option' is not valid in ack 2\n$explanation"; + exit 1; + }; +} + +sub get_arg_spec { + my ( $opt, $extra_specs ) = @_; + + my $dash_a_explanation = < sub { $opt->{1} = $opt->{m} = 1 }, + 'A|after-context=i' => \$opt->{after_context}, + 'B|before-context=i' + => \$opt->{before_context}, + 'C|context:i' => sub { shift; my $val = shift; $opt->{before_context} = $opt->{after_context} = ($val || 2) }, + 'a' => removed_option('-a', $dash_a_explanation), + 'all' => removed_option('--all', $dash_a_explanation), + 'break!' => \$opt->{break}, + c => \$opt->{count}, + 'color|colour!' => \$opt->{color}, + 'color-match=s' => \$ENV{ACK_COLOR_MATCH}, + 'color-filename=s' => \$ENV{ACK_COLOR_FILENAME}, + 'color-lineno=s' => \$ENV{ACK_COLOR_LINENO}, + 'column!' => \$opt->{column}, + count => \$opt->{count}, + 'create-ackrc' => sub { App::Ack::create_ackrc(); exit; }, + 'env!' => sub { + my ( undef, $value ) = @_; + + if ( !$value ) { + $opt->{noenv_seen} = 1; + } + }, + f => \$opt->{f}, + 'files-from=s' => \$opt->{files_from}, + 'filter!' => \$App::Ack::is_filter_mode, + flush => \$opt->{flush}, + 'follow!' => \$opt->{follow}, + g => \$opt->{g}, + G => removed_option('-G'), + 'group!' => sub { shift; $opt->{heading} = $opt->{break} = shift }, + 'heading!' => \$opt->{heading}, + '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 { + my ( undef, $file ) = @_; + push @{ $opt->{ifiles} }, $file; + }, + 'lines=s' => sub { shift; my $val = shift; push @{$opt->{lines}}, $val }, + 'l|files-with-matches' + => \$opt->{l}, + 'L|files-without-matches' + => \$opt->{L}, + 'm|max-count=i' => \$opt->{m}, + 'match=s' => \$opt->{regex}, + '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} }; + }, + 'nopager' => sub { $opt->{pager} = undef }, + 'passthru' => \$opt->{passthru}, + 'print0' => \$opt->{print0}, + 'Q|literal' => \$opt->{Q}, + 'r|R|recurse' => sub { $opt->{n} = 0 }, + 's' => \$opt->{dont_report_bad_filenames}, + 'show-types' => \$opt->{show_types}, + 'smart-case!' => \$opt->{smart_case}, + 'sort-files' => \$opt->{sort_files}, + 'type=s' => sub { + my ( $getopt, $value ) = @_; + + my $cb_value = 1; + if ( $value =~ s/^no// ) { + $cb_value = 0; + } + + my $callback = $extra_specs->{ $value . '!' }; + + if ( $callback ) { + $callback->( $getopt, $cb_value ); + } + else { + Carp::croak( "Unknown type '$value'" ); + } + }, + 'u' => removed_option('-u'), + 'unrestricted' => removed_option('--unrestricted'), + 'v|invert-match' => \$opt->{v}, + 'w|word-regexp' => \$opt->{w}, + 'x' => sub { $opt->{files_from} = '-' }, + + 'version' => sub { App::Ack::print_version_statement(); exit; }, + 'help|?:s' => sub { shift; App::Ack::show_help(@_); exit; }, + 'help-types' => sub { App::Ack::show_help_types(); exit; }, + 'man' => sub { App::Ack::show_man(); exit; }, + $extra_specs ? %{$extra_specs} : (), + }; # 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 + 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 ]; + + if ( $source_name eq 'ARGV' ) { + $argv_source = $args; + last; + } + } + + if ( $argv_source ) { # this *should* always be true, but you never know... + my @copy = @{$argv_source}; + + Getopt::Long::Configure('pass_through'); + + Getopt::Long::GetOptionsFromArray( \@copy, + 'help-types' => \$is_help_types_active, + ); + + Getopt::Long::Configure('no_pass_through'); + } + + 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]; + + my $ret; + if ( ref($args) ) { + $ret = Getopt::Long::GetOptionsFromArray( $args, %{$arg_specs} ); + } + else { + ( $ret, $arg_sources->[$i + 1] ) = + Getopt::Long::GetOptionsFromString( $args, %{$arg_specs} ); + } + if ( !$ret ) { + if ( !$is_help_types_active ) { + my $where = $source_name eq 'ARGV' ? 'on command line' : "in $source_name"; + App::Ack::die( "Invalid option $where" ); + } + } + if ( $opt->{noenv_seen} ) { + App::Ack::die( "--noenv found in $source_name" ); + } + } + + # XXX We need to check on a -- in the middle of a non-ARGV source + + return; +} + +sub should_dump_options { + my ( $sources ) = @_; + + for(my $i = 0; $i < @{$sources}; $i += 2) { + my ( $name, $options ) = @{$sources}[$i, $i + 1]; + if($name eq 'ARGV') { + my $dump; + Getopt::Long::Configure('default', 'pass_through', 'no_auto_help', 'no_auto_version'); + Getopt::Long::GetOptionsFromArray($options, + 'dump' => \$dump, + ); + return $dump; + } + } + return; +} + +sub explode_sources { + my ( $sources ) = @_; + + my @new_sources; + + Getopt::Long::Configure('default', 'pass_through', 'no_auto_help', 'no_auto_version'); + + my %opt; + my $arg_spec = get_arg_spec(\%opt); + + my $add_type = sub { + my ( undef, $arg ) = @_; + + # XXX refactor? + if ( $arg =~ /(\w+)=/) { + $arg_spec->{$1} = sub {}; + } + else { + ( $arg ) = split /:/, $arg; + $arg_spec->{$arg} = sub {}; + } + }; + + my $del_type = sub { + my ( undef, $arg ) = @_; + + delete $arg_spec->{$arg}; + }; + + for(my $i = 0; $i < @{$sources}; $i += 2) { + my ( $name, $options ) = @{$sources}[$i, $i + 1]; + if ( ref($options) ne 'ARRAY' ) { + $sources->[$i + 1] = $options = + [ Text::ParseWords::shellwords($options) ]; + } + for ( my $j = 0; $j < @{$options}; $j++ ) { + 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, + 'type-add=s' => $add_type, + 'type-set=s' => $add_type, + 'type-del=s' => $del_type, + ); + Getopt::Long::GetOptionsFromArray(\@chunk, %{$arg_spec}); + + splice @copy, -1 * @chunk if @chunk; # XXX explain this + push @new_sources, $name, \@copy; + } + } + + return \@new_sources; +} + +sub compare_opts { + my ( $a, $b ) = @_; + + my $first_a = $a->[0]; + my $first_b = $b->[0]; + + $first_a =~ s/^--?//; + $first_b =~ s/^--?//; + + return $first_a cmp $first_b; +} + +sub dump_options { + my ( $sources ) = @_; + + $sources = explode_sources($sources); + + my %opts_by_source; + my @source_names; + + for(my $i = 0; $i < @{$sources}; $i += 2) { + my ( $name, $contents ) = @{$sources}[$i, $i + 1]; + if ( not $opts_by_source{$name} ) { + $opts_by_source{$name} = []; + push @source_names, $name; + } + push @{$opts_by_source{$name}}, $contents; + } + + foreach my $name (@source_names) { + my $contents = $opts_by_source{$name}; + + print $name, "\n"; + print '=' x length($name), "\n"; + print ' ', join(' ', @{$_}), "\n" foreach sort { compare_opts($a, $b) } @{$contents}; + } + + return; +} + +sub remove_default_options_if_needed { + my ( $sources ) = @_; + + my $default_index; + + foreach my $index ( 0 .. $#$sources ) { + if ( $sources->[$index] eq 'Defaults' ) { + $default_index = $index; + last; + } + } + + return $sources unless defined $default_index; + + my $should_remove = 0; + + 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', + ); + + foreach my $index ( $default_index + 2 .. $#$sources ) { + next if $index % 2 != 0; + + my ( $name, $args ) = @{$sources}[ $index, $index + 1 ]; + + 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, + ); + } + } + + 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, 2; + 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_name, $args ) = splice @copy, 0, 2; + $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; + + 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_name, $args ) = splice( @{$arg_sources}, 0, 2 ); + + # 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; +} + +1; # End of App::Ack::ConfigLoader +package App::Ack::ConfigDefault; + +use warnings; +use strict; + +sub options { + my @options = split( /\n/, _options_block() ); + @options = grep { /./ && !/^#/ } @options; + + return @options; +} + +sub _options_block { + return <<'HERE'; +# This is the default ackrc for ack 2.0 + +# 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 80 characters of the first line +# of text against a Perl regular expression. This is only for +# the --type-add option. + + +# Directories to ignore +# Bazaar +--ignore-directory=is:.bzr + +# Codeville +--ignore-directory=is:.cdv + +# Interface Builder +--ignore-directory=is:~.dep +--ignore-directory=is:~.dot +--ignore-directory=is:~.nib +--ignore-directory=is:~.plst + +# Git +--ignore-directory=is:.git + +# Mercurial +--ignore-directory=is:.hg + +# quilt +--ignore-directory=is:.pc + +# Subversion +--ignore-directory=is:.svn + +# Monotone +--ignore-directory=is:_MTN + +# CVS +--ignore-directory=is:CVS + +# RCS +--ignore-directory=is:RCS + +# SCCS +--ignore-directory=is:SCCS + +# darcs +--ignore-directory=is:_darcs + +# Vault/Fortress +--ignore-directory=is:_sgbak + +# autoconf +--ignore-directory=is:autom4te.cache + +# Perl module building +--ignore-directory=is:blib +--ignore-directory=is:_build + +# Perl Devel::Cover module's output directory +--ignore-directory=is:cover_db + + + +# Files to ignore +# Backup files +--ignore-file=ext:bak +--ignore-file=match:/~$/ + +# Emacs swap files +--ignore-file=match:/^#.+#$/ + +# vi/vim swap files +--ignore-file=match:/[._].*\.swp$/ + +# core dumps +--ignore-file=match:/core\.\d+$/ + +# minified Javascript +--ignore-file=match:/[.]min[.]js$/ + + +# Filetypes defined + +# Perl http://perl.org/ +--type-add=perl:ext:pl,pm,pod,t +--type-add=perl:firstlinematch:/#!.*\bperl/ + +# 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 + +# Rakefiles http://rake.rubyforge.org/ +--type-add=rake:is:Rakefile + +# CMake http://www.cmake.org/ +--type-add=cmake:is:CMakeLists.txt +--type-add=cmake:ext:cmake + +# Actionscript +--type-add=actionscript:ext:as,mxml + +# Ada http://www.adaic.org/ +--type-add=ada:ext:ada,adb,ads + +# 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 + +# Batch +--type-add=batch:ext:bat,cmd + +# ColdFusion http://en.wikipedia.org/wiki/ColdFusion +--type-add=cfmx:ext:cfc,cfm,cfml + +# Clojure http://clojure.org/ +--type-add=clojure:ext:clj + +# C +# .xs are Perl C files +--type-add=cc:ext:c,h,xs + +# C header files +--type-add=hh:ext:h + +# C++ +--type-add=cpp:ext:cpp,cc,cxx,m,hpp,hh,h,hxx + +# C# +--type-add=csharp:ext:cs + +# CSS http://www.w3.org/Style/CSS/ +--type-add=css:ext:css + +# 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 + +# Haskell http://www.haskell.org/ +--type-add=haskell:ext:hs,lhs + +# HTML +--type-add=html:ext:htm,html + +# Java http://www.oracle.com/technetwork/java/index.html +--type-add=java:ext:java,properties + +# JavaScript +--type-add=js:ext:js + +# JSP http://www.oracle.com/technetwork/java/javaee/jsp/index.html +--type-add=jsp:ext:jsp,jspx,jhtm,jhtml + +# Common Lisp http://common-lisp.net/ +--type-add=lisp:ext:lisp,lsp + +# Lua http://www.lua.org/ +--type-add=lua:ext:lua + +# Objective-C +--type-add=objc:ext:m,h + +# Objective-C++ +--type-add=objcpp:ext:mm,h + +# OCaml http://caml.inria.fr/ +--type-add=ocaml:ext:ml,mli + +# 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/ + +# Plone http://plone.org/ +--type-add=plone:ext:pt,cpt,metadata,cpy,py + +# 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/ + +# Scala http://www.scala-lang.org/ +--type-add=scala:ext:scala + +# Scheme http://groups.csail.mit.edu/mac/projects/scheme/ +--type-add=scheme:ext:scm,ss + +# Shell +--type-add=shell:ext:sh,bash,csh,tcsh,ksh,zsh +--type-add=shell:firstlinematch:/(?:ba|t?c|k|z)?sh\b/ + +# Smalltalk http://www.smalltalk.org/ +--type-add=smalltalk:ext:st + +# SQL http://www.iso.org/iso/catalogue_detail.htm?csnumber=45498 +--type-add=sql:ext:sql,ctl + +# 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 + +# Template Toolkit http://template-toolkit.org/ +--type-add=tt:ext:tt,tt2,ttml + +# Visual Basic +--type-add=vb:ext:bas,cls,frm,ctl,vb,resx + +# Verilog +--type-add=verilog:ext:v,vh,sv + +# VHDL http://www.eda.org/twiki/bin/view.cgi/P1076/WebHome +--type-add=vhdl:ext:vhd,vhdl + +# Vim http://www.vim.org/ +--type-add=vim:ext:vim + +# 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 +} 1; -- 2.47.1