Skip to content

Instantly share code, notes, and snippets.

@pmorch
Created August 12, 2021 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmorch/157630b2de838c29ea14b5a62f263931 to your computer and use it in GitHub Desktop.
Save pmorch/157630b2de838c29ea14b5a62f263931 to your computer and use it in GitHub Desktop.
very incomplete and likely buggy ansi decoder

In order to investigate a bug, I needed an ansi escape code decoder.

This is it.

I just wrote exactly what was required for the bug analysis, so it is bad.

#!/usr/bin/perl -w
use strict;
use 5.010;
my %modes = (
0 => 'reset all modes',
);
my $escape = chr(0x1b);
while (my $line = <>) {
chomp $line;
# printf qq(Line: "%s"\n), quotemeta($line);
while ($line ne '') {
if ($line =~ s/^([\x20-\xFF]+)//) {
printf qq(Normal chars: "%s"\n), $1;
} elsif ($line =~ s/^$escape\[(\d+)([ABGm])//) {
my ($n, $command) = ($1, $2);
if ($command eq 'A') {
print "Move cursor up $n lines\n";
} elsif ($command eq 'B') {
print "Move cursor down $n lines\n";
} elsif ($command eq 'G') {
print "Move cursor to column $n\n";
} elsif ($command eq 'm') {
my $mode = $modes{$n} // "unknown mode: $n";
printf "Mode: %s\n", $mode;
} else {
}
} elsif ($line =~ s/^$escape\[K//) {
print "Clear current line\n";
} else {
# $line =~ s/$escape/↑/g;
$line =~ s/([^\x20-\x7F])/sprintf "0x%0x", ord($1)/ge;
printf qq(Remainder: "%s"\n), $line;
$line = '';
}
}
printf "line done\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment