-
-
Save emdeeeks/eef12f6f705dcde53e3d8b92d7e2fd25 to your computer and use it in GitHub Desktop.
ANSI Escape Sequences
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class String | |
def seq | |
gsub(%r{ | |
%% | | |
% (?<bg> B )? (?<sgr> black|red|green|yellow|blue|magenta|cyan|white|[0bu!_]|clr ) | | |
% (?<n1> \d+ )? (?<c> [\^v><\|\-!fb]<? ) (?<n2> \d+ )? | |
}x) { | |
match, bg, sgr, n1, c, n2 = *$~ | |
if sgr #Select Graphic Rendition (reset, bold, underline, negative, colors) TODO: xterm colors | |
next "\e[2J" if sgr == 'clr' | |
n = { | |
?0 => 0, | |
?b => 1, ?u => 4, ?_ => 4, ?! => 7, | |
'black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'white' => 37 | |
}[sgr] | |
n += 10 if bg and n >= 30 | |
"\e[#{n}m" | |
elsif c #Other codes (cursor movement) and colors | |
codes = { | |
?^ => ?A, ?v => ?B, ?> => ?C, ?< => ?D, | |
'v<' => ?E, '^<' => ?F, | |
?| => ?G | |
} | |
if c == ?f #Foreground | |
"\e[#{30 + n1.to_i}m" | |
elsif c == ?b #Background | |
"\e[#{40 + n1.to_i}m" | |
elsif n2 #Set cursor position | |
"\e[#{n1 || 1};#{n2}H" | |
else #Other codes | |
"\e[#{n1 || 0}#{codes[c]}" | |
end | |
else | |
?% | |
end | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment