uncurses/ansi/strip.rs
1//! ANSI escape stripping built on the byte tokenizer.
2//!
3//! ## Category
4//!
5//! [`strip`] removes ANSI escape/string/control sequences while preserving
6//! printable text and non-ESC control bytes such as newlines and tabs.
7//!
8//! ## Parser conventions
9//!
10//! Tokenization recognizes CSI, OSC, DCS, SOS, PM, APC, and two-byte ESC
11//! sequences in 7-bit, raw C1, and UTF-8 C1 forms. Escape tokens contribute no output.
12//!
13//! ## Mode interaction
14//!
15//! Stripping does not emulate terminal modes. It is a byte-stream transformation
16//! suitable for display-width and plain-text extraction paths.
17//!
18//! Sequence boundaries and widths come from [`crate::ansi::text`];
19//! which byte ends a control string, and when a byte in `0x80..=0x9F`
20//! is a C1 control rather than part of a character, are documented there.
21
22use super::text::{TokenKind, WidthMode, tokenize};
23
24/// Return `s` with ANSI escape sequences removed.
25///
26/// CSI, OSC, DCS, SOS, PM, APC, and short ESC sequences are dropped. Printable
27/// UTF-8 text and non-ESC control bytes such as `\n`, `\r`, and `\t` are
28/// preserved.
29pub fn strip(s: &str) -> String {
30 let mut out = String::with_capacity(s.len());
31 for tok in tokenize(s.as_bytes(), WidthMode::default(), false) {
32 match tok.kind {
33 TokenKind::Text | TokenKind::Control => out.push_str(bs(tok.bytes)),
34 TokenKind::Escape => {}
35 }
36 }
37 out
38}
39
40#[inline]
41fn bs(b: &[u8]) -> &str {
42 // The tokenizer never splits a character: text tokens are whole grapheme
43 // clusters, and every sequence scanner steps a whole UTF-8 character at a
44 // time. Nothing enforced that, and when a scanner did split one - 0x9C is
45 // 8-bit ST and also a continuation byte, so an OSC title containing a
46 // check mark ended mid-character - the ill-formed bytes arrived here and
47 // this was undefined behaviour. Checked where checking is free.
48 debug_assert!(
49 std::str::from_utf8(b).is_ok(),
50 "token split a UTF-8 character: {b:?}"
51 );
52 // SAFETY: `b` is a token slice of `&str` input, taken on character
53 // boundaries, as asserted above.
54 unsafe { std::str::from_utf8_unchecked(b) }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn strip_sgr() {
63 assert_eq!(strip("\x1b[31mhello\x1b[0m"), "hello");
64 }
65
66 #[test]
67 fn strip_osc() {
68 assert_eq!(strip("\x1b]0;title\x07hello"), "hello");
69 assert_eq!(strip("\x1b]0;title\x1b\\hello"), "hello");
70 }
71
72 #[test]
73 fn strip_preserves_newlines() {
74 assert_eq!(strip("a\nb\tc"), "a\nb\tc");
75 }
76
77 #[test]
78 fn strip_unicode() {
79 assert_eq!(strip("\x1b[1m中文\x1b[m"), "中文");
80 }
81
82 #[test]
83 fn strip_empty() {
84 assert_eq!(strip(""), "");
85 }
86
87 #[test]
88 fn strip_only_escapes() {
89 assert_eq!(strip("\x1b[31m\x1b[m"), "");
90 }
91
92 #[test]
93 fn strip_nested_csi() {
94 assert_eq!(strip("a\x1b[1;2;3;4mb\x1b[0;1mc"), "abc");
95 }
96
97 #[test]
98 fn strip_two_byte_esc() {
99 // ESC = (DECKPAM)
100 assert_eq!(strip("a\x1b=b"), "ab");
101 }
102}