Colorized perl code snippets on ANSI terminals

Ever wanted to do a quick diff on some perl code and see it colored like in in vim ?

Fortunately, the Kate editor has a good colorizer and Gabor Szabo ported it to Perl. We can join that up with Term::ANSIColor to create a filter program to colorize perl code snippets on the fly:

#!/usr/bin/perl
# hilite.pl - perl code colorizer on an ANSI terminal (xterm / putty session)
# place this script in your path and make executable, e.g.
#   $ cp hilite.pl ~/bin/hilite
#   $ chmod 755 ~/bin/hilite
# then run it to colorize text output that contains perl, e.g.
#   $ svn diff /some/path/MyModule.pm | hilite
# and you get syntax colored text

use strict;
use warnings;
use utf8; # ار
use open ':utf8';

use Syntax::Highlight::Engine::Kate;
use Term::ANSIColor qw(:constants);
use IO::File;

my $hl = new Syntax::Highlight::Engine::Kate(
    language => 'Perl',
    substitutions => {},
    format_table => {
        Alert => [RED, RESET],
        BaseN => [RED, RESET],
        BString => [YELLOW, RESET],
        Char => [YELLOW, RESET],
        Comment => [CYAN, RESET],
        DataType => [GREEN, RESET],
        DecVal => [RED, RESET],
        Error => [RED, RESET],
        Float => [BRIGHT_RED, RESET],
        Function => [MAGENTA, RESET],
        IString => [MAGENTA, RESET],
        Keyword => [YELLOW, RESET],
        Normal => ["", ""],
        Operator => [BRIGHT_GREEN, RESET],
        Others => [MAGENTA, RESET],
        RegionMarker => [ON_GREEN, RESET],
        Reserved => [BLACK ON_BLUE, RESET],
        String => [MAGENTA, RESET],
        Variable => [BRIGHT_GREEN, RESET],
        Warning => [RED, RESET],
    },
);

my $fh;
my $file = shift @ARGV;
if ( !$file || $file eq '-' ) {
    binmode STDIN;
    $fh = \*STDIN;
}
else {
    $fh = IO::File->new($file)
        || die "Cannot open file: $file: $!";
}

while ( my $line = <$fh> ) {
    print $hl->highlightText($line);
};

3 Comments

Very nice! Thanks.

Excellent!

Github? CPAN application?

Thanks, Peter. Almost exactly what I was looking for! I've made a few changes to handle svn's diff formatting. Patch below (hopefully not too mangled):


16c16
---
> use Term::ANSIColor qw(:constants colored);
57a58,62
> my $exception_color = exceptions($line);
> if ($exception_color) {
> print colored [ $exception_color ], $line;
> next;
> }
59a65,71
>
> sub exceptions {
> my $line = shift;
> if ($line =~ /^\-/) { return 'white on_red' }
> if ($line =~ /^\+/) { return 'white on_blue' }
> if ($line =~ /^@@|^===|^Index:/) { return 'black on_white' }
> }

Leave a comment

About Peter Edwards

user-pic Freelance Perl contractor.