beyondgrep / ack2

**ack 2 is no longer being maintained. ack 3 is the latest version.**
https://github.com/beyondgrep/ack3/
Other
1.48k stars 138 forks source link

Color console cleanup on Windows (Fix included) #575

Closed PerlPotter closed 4 years ago

PerlPotter commented 8 years ago

Ack is really great, but when I run it in a Windows console (Windows 7) at the end, it leaves the console colors set to whatever the last color from the matches was. This is easily fixed with a few changes to the ack.bat Perl script. At the beginning of the main subroutine (~ line 888)

Change:

    sub main{
        my @arg_sources = App::Ack::ConfigLoader::retrieve_arg_sources();

to:

my $base_attr;
my $CONSOLE;

sub main {

    if ( $^O =~ m/Win/)
    {
     eval {require Win32::Console; Win32::Console->import('STD_OUTPUT_HANDLE'); $CONSOLE = Win32::Console->new(Win32::Console->STD_OUTPUT_HANDLE); $base_attr = $CONSOLE->Attr();};
    }
    $SIG{INT} = sub { if ( defined( $CONSOLE)) { $CONSOLE->Attr( $base_attr);} exit;};

    my @arg_sources = App::Ack::ConfigLoader::retrieve_arg_sources();

And at the end of the subroutine (~ line 1073) add the following lines before the call to close $App::Ack::fh;:

    if ( defined( $opt->{color}) && $opt->{color})
    {
        if ( defined( $CONSOLE))
        {
            $CONSOLE->Attr( $base_attr);
        }
    }

This change attempts to load Win32::Console, if the code is running on Windows, and if it loads, it sets $CONSOLE to the handle of the current console and gets the current attributes for the console. This is all wrapped in an eval, so if it fails, there is no error. Finally at the bottom of the routine, before closing up, it checks to see if color was used and if $CONSOLE got defined, and resets the attributes if they were. In addition, it sets the CTRL-C handler to reset the original console colors in the event the user presses CTRL-C in the midst of running ack.

petdance commented 7 years ago

@PerlPotter Is this fix still valid, and something I should apply?