Skip to content

Instantly share code, notes, and snippets.

@kulp
Last active August 29, 2015 14:01
Show Gist options
  • Save kulp/c1a62687d0ff8ac06f01 to your computer and use it in GitHub Desktop.
Save kulp/c1a62687d0ff8ac06f01 to your computer and use it in GitHub Desktop.
Map ansi16 colours to ansi256 colours
#!/usr/bin/env perl
# export PAGER="ansi16_to_ansi256.pl | ${PAGER:-less -R}"
use strict;
use Color::ANSI::Util qw(ansi16_to_rgb rgb_to_ansi256);
my $esc = qr/\x1b\[/;
my $fg = qr/3\d/;
my $bg = qr/4\d/;
my $seq = qr/$esc((?:$fg|$bg)(?:;(?:$fg|$bg))*)m/o;
my %colour_map = (
# foreground colours
3 => {
#ansi16_to_rgb( 'black' ) => '000000',
ansi16_to_rgb( 'red' ) => 'df8787',
ansi16_to_rgb( 'green' ) => '5fdf5f',
ansi16_to_rgb( 'yellow' ) => 'ffffaf',
#ansi16_to_rgb( 'blue' ) => '000080',
#ansi16_to_rgb( 'magenta' ) => '800080',
#ansi16_to_rgb( 'cyan' ) => '008080',
#ansi16_to_rgb( 'white' ) => '808080',
},
# background colours
4 => {
ansi16_to_rgb( 'black' ) => '1c1c1c',
#ansi16_to_rgb( 'red' ) => 'ff0000',
#ansi16_to_rgb( 'green' ) => '00ff00',
#ansi16_to_rgb( 'yellow' ) => 'ffff00',
#ansi16_to_rgb( 'blue' ) => '0000ff',
#ansi16_to_rgb( 'magenta' ) => 'ff00ff',
#ansi16_to_rgb( 'cyan' ) => '00ffff',
#ansi16_to_rgb( 'white' ) => 'ffffff',
},
);
while (<>) {
s/$seq/translate_escapes($1)/eg;
print;
}
sub translate_single_escape
{
my ($incoming) = @_;
my ($type, $colour) = (split //, $incoming)[0, 1];
my $test = $colour_map{$type}{ansi16_to_rgb($colour)};
my $mapped = defined($test) ? rgb_to_ansi256($test) : $colour;
"${type}8;5;${mapped}";
}
sub translate_escapes
{
my ($incoming) = @_;
my @parts = split ';' => $incoming;
return "\x1b[" . (join ';' => map translate_single_escape($_), @parts) . 'm';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment