use std::borrow::Cow;
enum State {
Ground,
Esc,
EscIntermediate,
Csi,
EscString,
EscStringEsc,
}
pub fn strip_ansi(text: &str) -> Cow<'_, str> {
let needs_stripping = text
.bytes()
.any(|b| (b < 0x20 && b != b'\t' && b != b'\n' && b != b'\r') || b == 0x7f);
if !needs_stripping {
return Cow::Borrowed(text);
}
let after_esc = |ch: char| match ch {
'[' => State::Csi,
']' | 'P' | 'X' | '^' | '_' => State::EscString,
'\x20'..='\x2f' => State::EscIntermediate,
_ => State::Ground,
};
let mut out = String::with_capacity(text.len());
let mut state = State::Ground;
for ch in text.chars() {
state = match state {
State::Ground => match ch {
'\x1b' => State::Esc,
'\t' | '\n' | '\r' => {
out.push(ch);
State::Ground
}
'\x00'..='\x1f' | '\x7f' => State::Ground,
_ => {
out.push(ch);
State::Ground
}
},
State::Esc => after_esc(ch),
State::EscIntermediate => match ch {
'\x20'..='\x2f' => State::EscIntermediate,
_ => State::Ground, },
State::Csi => match ch {
'\x40'..='\x7e' => State::Ground, _ => State::Csi, },
State::EscString => match ch {
'\x07' => State::Ground, '\x1b' => State::EscStringEsc,
_ => State::EscString,
},
State::EscStringEsc => match ch {
'\\' => State::Ground, _ => after_esc(ch),
},
};
}
Cow::Owned(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_text_is_borrowed() {
assert!(matches!(
strip_ansi("hello world\nwith\ttabs\r\n"),
Cow::Borrowed(_)
));
}
#[test]
fn strips_sgr() {
assert_eq!(strip_ansi("a \x1b[31mred\x1b[0m word"), "a red word");
}
#[test]
fn strips_cursor_movement() {
assert_eq!(strip_ansi("\x1b[2J\x1b[10;20Htext\x1b[1A"), "text");
}
#[test]
fn strips_osc_with_bel_terminator() {
assert_eq!(strip_ansi("\x1b]0;window title\x07after"), "after");
}
#[test]
fn strips_osc_with_st_terminator() {
assert_eq!(
strip_ansi("\x1b]8;;http://x\x1b\\link\x1b]8;;\x1b\\"),
"link"
);
}
#[test]
fn strips_dcs_string() {
assert_eq!(strip_ansi("\x1bPq#0;2;0;0;0\x1b\\after"), "after");
}
#[test]
fn esc_aborts_unterminated_osc() {
assert_eq!(strip_ansi("\x1b]0;title\x1b[31mred"), "red");
}
#[test]
fn strips_two_byte_escapes() {
assert_eq!(strip_ansi("\x1b7saved\x1b8restored\x1bc"), "savedrestored");
}
#[test]
fn strips_nf_sequences() {
assert_eq!(strip_ansi("\x1b(Btext"), "text");
}
#[test]
fn strips_control_chars_keeps_whitespace() {
assert_eq!(strip_ansi("a\x00b\x08c\td\ne\rf\x7fg"), "abc\td\ne\rfg");
}
#[test]
fn keeps_unicode() {
assert_eq!(strip_ansi("\x1b[1m✓ naïve 日本語\x1b[m"), "✓ naïve 日本語");
}
}