Visual Studio Code, rebuilt in Rust
Rust
//! debugANSIHandling.ts `handleANSIOutput`: output text split into runs with the styles of its SGR sequences.
use std::sync::LazyLock;
use regex::Regex;
/// A run's color: an `RGBA` of the 8-bit and 24-bit codes, or the index of an `ansiColorIdentifiers` theme color.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnsiColor {
Rgb(u8, u8, u8),
Theme(usize),
}
/// The `code-*` classes and custom colors a run carries. Overline, blink, the alternative fonts and
/// super/subscript are parsed upstream but have no GPUI text run style, so they are not kept.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AnsiStyle {
pub bold: bool,
pub dim: bool,
pub italic: bool,
/// `code-underline` or `code-double-underline`.
pub underline: bool,
pub hidden: bool,
pub strike_through: bool,
pub foreground: Option<AnsiColor>,
pub background: Option<AnsiColor>,
pub underline_color: Option<AnsiColor>,
}
static SGR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(?:[34][0-8]|9[0-7]|10[0-7]|[0-9]|2[1-5,7-9]|[34]9|5[8,9]|1[0-9])(?:;[349][0-7]|10[0-7]|[013]|[245]|[34]9)?(?:;[012]?[0-9]?[0-9])*;?m$").unwrap());
/// The text's runs in order, without the escape sequences; empty runs are left out.
pub fn parse(text: &str) -> Vec<(String, AnsiStyle)> {
let mut runs = Vec::new();
let mut style = AnsiStyle::default();
let mut inverted = false;
let mut buffer = String::new();
let chars: Vec<char> = text.chars().collect();
let mut position = 0;
while position < chars.len() {
if chars[position] == '\u{1b}' && chars.get(position + 1) == Some(&'[') {
let end = (position + 2..chars.len()).find(|&index| "ABCDHIJKfhmpsu".contains(chars[index]));
if let Some(end) = end {
if !buffer.is_empty() {
runs.push((std::mem::take(&mut buffer), style.clone()));
}
let sequence: String = chars[position + 2..=end].iter().collect();
if SGR.is_match(&sequence) {
let codes: Vec<u32> = sequence[..sequence.len() - 1].split(';').filter(|code| !code.is_empty()).filter_map(|code| code.parse().ok()).collect();
apply(&codes, &mut style, &mut inverted);
}
position = end + 1;
continue;
}
}
buffer.push(chars[position]);
position += 1;
}
if !buffer.is_empty() {
runs.push((buffer, style));
}
runs
}
fn apply(codes: &[u32], style: &mut AnsiStyle, inverted: &mut bool) {
if let Some(&kind @ (38 | 48 | 58)) = codes.first() {
let color = match codes.get(1) {
Some(5) => eight_bit_color(codes.get(2).copied(), kind, style),
Some(2) if codes.len() >= 5 && codes[2..5].iter().all(|channel| *channel <= 255) => Some(AnsiColor::Rgb(codes[2] as u8, codes[3] as u8, codes[4] as u8)),
_ => None,
};
if let Some(color) = color {
set_color(style, kind, Some(color));
}
return;
}
for &code in codes {
match code {
0 => {
*style = AnsiStyle { underline_color: style.underline_color, ..AnsiStyle::default() };
}
1 => style.bold = true,
2 => style.dim = true,
3 => style.italic = true,
4 | 21 => style.underline = true,
7 if !*inverted => {
*inverted = true;
(style.foreground, style.background) = (style.background, style.foreground);
}
8 => style.hidden = true,
9 => style.strike_through = true,
22 => (style.bold, style.dim) = (false, false),
23 => style.italic = false,
24 => style.underline = false,
27 if *inverted => {
*inverted = false;
(style.foreground, style.background) = (style.background, style.foreground);
}
28 => style.hidden = false,
29 => style.strike_through = false,
39 => style.foreground = None,
49 => style.background = None,
59 => style.underline_color = None,
_ => set_basic_color(style, code),
}
}
}
fn set_color(style: &mut AnsiStyle, kind: u32, color: Option<AnsiColor>) {
match kind {
38 => style.foreground = color,
48 => style.background = color,
_ => style.underline_color = color,
}
}
/// `set8BitColor`: the cube and grays as RGB, the first 16 as the theme's colors.
fn eight_bit_color(number: Option<u32>, kind: u32, style: &mut AnsiStyle) -> Option<AnsiColor> {
let number = number?;
if let Some(color) = ansi_8bit_color(number) {
return Some(color);
}
if number > 15 {
return None;
}
if kind == 58 {
return Some(AnsiColor::Theme(number as usize));
}
let mut code = number + 30;
if code >= 38 {
code += 52;
}
if kind == 48 {
code += 10;
}
set_basic_color(style, code);
None
}
fn set_basic_color(style: &mut AnsiStyle, code: u32) {
match code {
30..=37 => style.foreground = Some(AnsiColor::Theme((code - 30) as usize)),
90..=97 => style.foreground = Some(AnsiColor::Theme((code - 90 + 8) as usize)),
40..=47 => style.background = Some(AnsiColor::Theme((code - 40) as usize)),
100..=107 => style.background = Some(AnsiColor::Theme((code - 100 + 8) as usize)),
_ => {}
}
}
/// `calcANSI8bitColor`.
fn ansi_8bit_color(number: u32) -> Option<AnsiColor> {
let level = |step: u32| (step as f64 * 255. / 5.).round() as u8;
match number {
16..=231 => {
let cube = number - 16;
Some(AnsiColor::Rgb(level(cube / 36), level(cube / 6 % 6), level(cube % 6)))
}
232..=255 => {
let gray = ((number - 232) as f64 / 23. * 255.).round() as u8;
Some(AnsiColor::Rgb(gray, gray, gray))
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sgr_codes_style_the_runs_and_other_sequences_drop() {
let runs = parse("a\u{1b}[1;31mb\u{1b}[2Kc\u{1b}[0md\u{1b}[38;5;196me\u{1b}[48;2;1;2;3mf\u{1b}[7mg");
let texts: Vec<&str> = runs.iter().map(|(text, _)| text.as_str()).collect();
assert_eq!(texts, ["a", "b", "c", "d", "e", "f", "g"]);
assert_eq!(runs[0].1, AnsiStyle::default());
assert_eq!(runs[1].1, AnsiStyle { bold: true, foreground: Some(AnsiColor::Theme(1)), ..Default::default() });
assert_eq!(runs[2].1, runs[1].1, "an erase sequence keeps the style");
assert_eq!(runs[3].1, AnsiStyle::default());
assert_eq!(runs[4].1.foreground, Some(AnsiColor::Rgb(255, 0, 0)));
assert_eq!(runs[5].1.background, Some(AnsiColor::Rgb(1, 2, 3)));
assert_eq!((runs[6].1.foreground, runs[6].1.background), (Some(AnsiColor::Rgb(1, 2, 3)), Some(AnsiColor::Rgb(255, 0, 0))), "7 swaps the colors");
}
#[test]
fn eight_bit_codes_below_16_are_the_theme_colors_and_an_unterminated_escape_stays_text() {
let runs = parse("\u{1b}[38;5;9mx\u{1b}[48;5;2my\u{1b}[q");
assert_eq!(runs[0].1.foreground, Some(AnsiColor::Theme(9)));
assert_eq!(runs[1].1.background, Some(AnsiColor::Theme(2)));
assert_eq!(runs[1].0, "y\u{1b}[q");
}
}