Skip to main content

vtcode_commons/
ansi.rs

1#![expect(
2    clippy::indexing_slicing,
3    reason = "The boundary parser validates byte positions while walking escape sequences; anstream handles plain-text stripping."
4)]
5
6//! Shared ANSI escape parser and stripping utilities for VT Code.
7//!
8//! Plain-text stripping is delegated to `anstream`'s ANSI state machine, which
9//! is already a workspace dependency. The hand-rolled parser below remains for
10//! the one thing `anstream` does not expose: the byte boundaries and payloads
11//! of individual escape sequences (OSC 8 link ranges, echo suppression).
12//!
13//! See `docs/reference/ansi-in-vtcode.md` for the workspace usage map.
14
15use crate::ansi_codes::{BEL_BYTE, ESC_BYTE};
16use anstream::adapter::strip_str;
17use anstyle_parse::state::{State, state_change};
18
19const ESC: u8 = ESC_BYTE;
20const BEL: u8 = BEL_BYTE;
21const DEL: u8 = 0x7f;
22const C1_ST: u8 = 0x9c;
23const C1_DCS: u8 = 0x90;
24const C1_SOS: u8 = 0x98;
25const C1_CSI: u8 = 0x9b;
26const C1_OSC: u8 = 0x9d;
27const C1_PM: u8 = 0x9e;
28const C1_APC: u8 = 0x9f;
29const CAN: u8 = 0x18;
30const SUB: u8 = 0x1a;
31const MAX_STRING_SEQUENCE_BYTES: usize = 4096;
32const MAX_CSI_SEQUENCE_BYTES: usize = 64;
33
34#[derive(Clone, Copy)]
35enum StringSequenceTerminator {
36    StOnly,
37    BelOrSt,
38}
39
40impl StringSequenceTerminator {
41    #[inline]
42    const fn allows_bel(self) -> bool {
43        matches!(self, Self::BelOrSt)
44    }
45}
46
47#[inline]
48fn parse_c1_at(bytes: &[u8], start: usize) -> Option<(u8, usize)> {
49    let first = *bytes.get(start)?;
50    if (0x80..=0x9f).contains(&first) {
51        return Some((first, 1));
52    }
53    None
54}
55
56#[inline]
57fn parse_csi(bytes: &[u8], start: usize) -> Option<usize> {
58    // ECMA-48 / ISO 6429 CSI grammar:
59    // - parameter bytes: 0x30..0x3F
60    // - intermediate bytes: 0x20..0x2F
61    // - final byte: 0x40..0x7E
62    // (See ANSI escape code article on Wikipedia, CSI section.)
63    let mut index = start;
64    let mut phase = 0u8; // 0=parameter, 1=intermediate
65    let mut consumed = 0usize;
66
67    while index < bytes.len() {
68        let byte = bytes[index];
69        if byte == ESC {
70            // VT100: ESC aborts current control sequence and starts a new one.
71            return Some(index);
72        }
73        if byte == CAN || byte == SUB {
74            // VT100: CAN/SUB abort current control sequence.
75            return Some(index + 1);
76        }
77
78        consumed += 1;
79        if consumed > MAX_CSI_SEQUENCE_BYTES {
80            // Bound malformed or hostile input.
81            return Some(index + 1);
82        }
83
84        if phase == 0 && (0x30..=0x3f).contains(&byte) {
85            index += 1;
86            continue;
87        }
88        if (0x20..=0x2f).contains(&byte) {
89            phase = 1;
90            index += 1;
91            continue;
92        }
93        if (0x40..=0x7e).contains(&byte) {
94            return Some(index + 1);
95        }
96
97        // Invalid CSI byte: abort sequence without consuming this byte.
98        return Some(index);
99    }
100
101    None
102}
103
104#[inline]
105fn parse_string_sequence(bytes: &[u8], start: usize, terminator: StringSequenceTerminator) -> Option<usize> {
106    let mut consumed = 0usize;
107    for index in start..bytes.len() {
108        if bytes[index] == ESC && !(index + 1 < bytes.len() && bytes[index + 1] == b'\\') {
109            // VT100: ESC aborts current sequence and begins a new one.
110            return Some(index);
111        }
112        if bytes[index] == CAN || bytes[index] == SUB {
113            return Some(index + 1);
114        }
115
116        if let Some((c1, len)) = parse_c1_at(bytes, index)
117            && c1 == C1_ST
118        {
119            return Some(index + len);
120        }
121
122        match bytes[index] {
123            BEL if terminator.allows_bel() => return Some(index + 1),
124            ESC if index + 1 < bytes.len() && bytes[index + 1] == b'\\' => return Some(index + 2),
125            _ => {}
126        }
127
128        consumed += 1;
129        if consumed > MAX_STRING_SEQUENCE_BYTES {
130            // Cap unbounded strings when terminator is missing.
131            return Some(index + 1);
132        }
133    }
134    None
135}
136
137#[inline]
138fn push_visible_byte(output: &mut Vec<u8>, byte: u8) {
139    if matches!(byte, b'\n' | b'\r' | b'\t') || !(byte < 32 || byte == DEL) {
140        output.push(byte);
141    }
142}
143
144#[inline]
145fn parse_ansi_sequence_bytes(bytes: &[u8]) -> Option<usize> {
146    if bytes.is_empty() {
147        return None;
148    }
149
150    if let Some((c1, c1_len)) = parse_c1_at(bytes, 0) {
151        return match c1 {
152            C1_CSI => parse_csi(bytes, c1_len),
153            C1_OSC => parse_string_sequence(bytes, c1_len, StringSequenceTerminator::BelOrSt),
154            C1_DCS | C1_SOS | C1_PM | C1_APC => parse_string_sequence(bytes, c1_len, StringSequenceTerminator::StOnly),
155            _ => Some(c1_len),
156        };
157    }
158
159    match bytes[0] {
160        ESC => {
161            if bytes.len() < 2 {
162                return None;
163            }
164
165            match bytes[1] {
166                b'[' => parse_csi(bytes, 2),
167                b']' => parse_string_sequence(bytes, 2, StringSequenceTerminator::BelOrSt),
168                b'P' | b'^' | b'_' | b'X' => parse_string_sequence(bytes, 2, StringSequenceTerminator::StOnly),
169                // Three-byte sequences: ESC + intermediate + final
170                // ESC SP {F,G,L,M,N} — 7/8-bit controls, ANSI conformance
171                // ESC # {3,4,5,6,8} — DEC line attributes / screen alignment
172                // ESC % {@ ,G} — character set selection (ISO 2022)
173                // ESC ( C / ESC ) C / ESC * C / ESC + C — G0-G3 designation
174                b' ' | b'#' | b'%' | b'(' | b')' | b'*' | b'+' => {
175                    if bytes.len() > 2 {
176                        Some(3)
177                    } else {
178                        None
179                    }
180                }
181                next if next < 128 => Some(2),
182                _ => Some(1),
183            }
184        }
185        _ => None,
186    }
187}
188
189/// Strip ANSI escape codes from text, returning a borrowed `Cow` when the
190/// input contains no ESC byte.  This is the preferred API for call-sites that
191/// want to avoid allocation on the common "no ANSI codes" path.
192pub fn strip_ansi_codes(text: &str) -> std::borrow::Cow<'_, str> {
193    if !text.contains('\x1b') {
194        return std::borrow::Cow::Borrowed(text);
195    }
196    std::borrow::Cow::Owned(strip_ansi(text))
197}
198
199/// Remove the C0 controls that must never reach a transcript.
200///
201/// `anstream` keeps FF (`0x0C`) because it is ASCII whitespace in its state
202/// machine, and the old in-tree stripper removed every control byte except
203/// `\n`, `\r`, and `\t` (plus DEL). Keep that contract: the escape-sequence
204/// parsing is delegated, but control-byte filtering is owned here.
205#[inline]
206fn is_transcript_control(byte: u8) -> bool {
207    (byte < b' ' && !matches!(byte, b'\n' | b'\r' | b'\t')) || byte == DEL
208}
209
210/// Strip escape sequences and residual control bytes from already-valid UTF-8.
211fn strip_plain(text: &str) -> String {
212    let mut output = strip_str(text).to_string().into_bytes();
213    // Only ASCII control bytes are removed, so no multi-byte UTF-8 sequence
214    // can be broken and `from_utf8` reuses the existing allocation.
215    output.retain(|byte| !is_transcript_control(*byte));
216    // Removing ASCII control bytes never splits a multi-byte UTF-8 sequence
217    // (their continuation bytes are all non-ASCII), so the decode below
218    // always succeeds; the lossy fallback only guards against a future
219    // filter change, in exchange for never panicking on stream input.
220    String::from_utf8(output).unwrap_or_else(|error| String::from_utf8_lossy(error.as_bytes()).into_owned())
221}
222
223/// Strip ANSI escape codes from text, keeping only plain text.
224///
225/// Delegates to `anstream`'s ANSI state machine. An incomplete sequence at the
226/// end of the input is dropped rather than emitted as raw control bytes; for
227/// chunked input use [`AnsiStripStream`] so a split sequence is not lost.
228pub fn strip_ansi(text: &str) -> String {
229    strip_plain(text)
230}
231
232/// Stateful ANSI stripper for chunked input such as a PTY byte stream.
233///
234/// `anstream`'s incremental adapter resets its parser to the ground state at
235/// each call, so it cannot recover a sequence split across two chunks. This
236/// wrapper holds back only the trailing, unterminated escape sequence and
237/// re-strips it together with the next chunk. Both the boundary detector and
238/// `anstream` use `anstyle_parse`'s state machine, so they cannot disagree on
239/// where a sequence ends. The retained suffix is bounded.
240#[derive(Default)]
241pub struct AnsiStripStream {
242    /// Trailing, unterminated escape sequence held back for the next chunk.
243    /// Bounded by [`MAX_STRING_SEQUENCE_BYTES`].
244    pending: String,
245    /// Parser state while discarding an overlong, unterminated sequence.
246    ///
247    /// The bound on `pending` means a hostile or buggy child could emit an
248    /// arbitrarily long OSC string. Once the cap is hit, the rest of that
249    /// sequence is dropped until the state machine returns to `Ground`, so
250    /// output stays independent of where the PTY read landed without letting
251    /// the retained buffer grow without limit.
252    discarding: Option<State>,
253}
254
255impl AnsiStripStream {
256    /// Create a stripper with no retained bytes.
257    #[must_use]
258    pub fn new() -> Self {
259        Self::default()
260    }
261
262    /// Strip the next chunk, returning its visible text.
263    ///
264    /// A trailing escape sequence that is incomplete in `chunk` is retained
265    /// and prepended to the next call instead of leaking raw control bytes.
266    pub fn strip_chunk(&mut self, chunk: &str) -> String {
267        let chunk = self.discard_overlong(chunk);
268        if chunk.is_empty() {
269            return String::new();
270        }
271        // The common case has no held-back suffix. Avoid copying the whole
272        // chunk into `pending`'s buffer only to split it again; PTY output is
273        // chunked at high frequency and this path is allocation-sensitive.
274        if self.pending.is_empty() {
275            return self.strip_ready(chunk);
276        }
277        let mut combined = std::mem::take(&mut self.pending);
278        combined.push_str(chunk);
279        self.strip_ready(&combined)
280    }
281
282    /// Drop the continuation of an overlong sequence up to its terminator,
283    /// returning the first byte after the sequence (if the chunk contains it).
284    fn discard_overlong<'a>(&mut self, chunk: &'a str) -> &'a str {
285        let Some(mut state) = self.discarding else {
286            return chunk;
287        };
288        for (index, ch) in chunk.char_indices() {
289            if !ch.is_ascii() {
290                continue;
291            }
292            let (next, _) = state_change(state, ch as u8);
293            if next != State::Anywhere {
294                state = next;
295            }
296            if next == State::Ground {
297                self.discarding = None;
298                return chunk.split_at(index + ch.len_utf8()).1;
299            }
300        }
301        self.discarding = Some(state);
302        ""
303    }
304
305    /// Strip `text`, holding back its trailing incomplete sequence for the next call.
306    fn strip_ready(&mut self, text: &str) -> String {
307        let mut overlong = false;
308        let split_at = if text.as_bytes().contains(&ESC) {
309            let tail = sequence_tail(text);
310            overlong = tail.overlong;
311            if overlong {
312                self.discarding = Some(tail.state);
313            }
314            tail.start
315        } else {
316            text.len()
317        };
318        let (ready, pending) = text.split_at(split_at);
319        if !overlong {
320            self.pending.push_str(pending);
321        }
322        strip_plain(ready)
323    }
324}
325
326/// Where an unterminated escape sequence starts, and the parser state at EOF.
327struct SequenceTail {
328    /// Byte offset where the trailing incomplete sequence begins; `text.len()`
329    /// when the input ends in a complete sequence or was too long to retain.
330    start: usize,
331    /// Parser state after the whole input, used to resume in discard mode.
332    state: State,
333    /// Whether the trailing sequence exceeded the retention cap.
334    overlong: bool,
335}
336
337/// Locate the trailing, unterminated escape sequence.
338///
339/// Uses the same `anstyle_parse` state machine as `anstream`. A second,
340/// hand-rolled grammar here would classify sequences differently (notably a
341/// C0 control inside CSI) and make output depend on where a PTY read landed.
342fn sequence_tail(text: &str) -> SequenceTail {
343    let mut state = State::Ground;
344    let mut candidate = None;
345    for (index, ch) in text.char_indices() {
346        if !ch.is_ascii() {
347            // Validated UTF-8 bytes are printable and do not affect ANSI state.
348            continue;
349        }
350        if state == State::Ground && ch == '\x1b' {
351            candidate = Some(index);
352        }
353        let (next, _) = state_change(state, ch as u8);
354        if next != State::Anywhere {
355            state = next;
356        }
357    }
358
359    if state == State::Ground {
360        return SequenceTail { start: text.len(), state, overlong: false };
361    }
362    // A non-Ground state without an ASCII ESC start can only come from 8-bit
363    // C1 bytes, which `anstream` treats as printable UTF-8 rather than controls.
364    let Some(start) = candidate else {
365        return SequenceTail { start: text.len(), state, overlong: false };
366    };
367    if text.len() - start > MAX_STRING_SEQUENCE_BYTES {
368        return SequenceTail { start: text.len(), state, overlong: true };
369    }
370    SequenceTail { start, state, overlong: false }
371}
372
373/// Strip ANSI escape codes from arbitrary bytes, preserving non-control bytes.
374///
375/// This is the preferred API when input may contain raw C1 (8-bit) controls.
376fn strip_ansi_bytes(input: &[u8]) -> Vec<u8> {
377    let mut output = Vec::with_capacity(input.len());
378    let bytes = input;
379    let mut i = 0;
380
381    while i < bytes.len() {
382        // Pre-slice to the remaining portion so all indexing below shares one bounds edge.
383        let rest = &bytes[i..];
384
385        if (rest[0] == ESC || parse_c1_at(bytes, i).is_some())
386            && let Some(len) = parse_ansi_sequence_bytes(rest)
387        {
388            i += len;
389            continue;
390        }
391        if rest[0] == ESC || parse_c1_at(bytes, i).is_some() {
392            // Incomplete/unterminated control sequence at end of available text.
393            break;
394        }
395
396        push_visible_byte(&mut output, rest[0]);
397        i += 1;
398    }
399    output
400}
401
402/// Parse and determine the length of the ANSI escape sequence at the start of text.
403///
404/// This boundary parser is deliberately conservative: an invalid byte inside a
405/// CSI (including a C0 control other than ESC/CAN/SUB) aborts the sequence
406/// without consuming that byte. PTY echo suppression uses it to skip escape
407/// sequences without swallowing following command text on malformed input.
408/// [`strip_ansi`] follows `anstream`'s ECMA-48 state machine instead, where a
409/// C0 control inside CSI is executed and the sequence continues; the two
410/// parsers therefore disagree on that malformed input by design.
411pub fn parse_ansi_sequence(text: &str) -> Option<usize> {
412    let bytes = text.as_bytes();
413    parse_ansi_sequence_bytes(bytes)
414}
415
416/// ANSI stripping for ASCII-only text.
417///
418/// Retained for API compatibility; this now shares [`strip_ansi`]'s parser.
419/// Two deliberate contract changes from the old copy-raw-spans implementation:
420/// C0 controls and DEL are filtered (as in [`strip_ansi`]), and an unterminated
421/// escape sequence at the end of the input is dropped instead of kept — the
422/// latter would leak raw control bytes when a PTY chunk splits a sequence.
423pub fn strip_ansi_ascii_only(text: &str) -> String {
424    strip_ansi(text)
425}
426
427/// Detect if text contains unicode characters that need special handling
428#[must_use]
429pub fn contains_unicode(text: &str) -> bool {
430    text.bytes().any(|b| b >= 0x80)
431}
432
433#[cfg(test)]
434mod tests {
435    use super::{
436        AnsiStripStream, CAN, MAX_STRING_SEQUENCE_BYTES, SUB, parse_ansi_sequence_bytes, push_visible_byte, strip_ansi,
437        strip_ansi_ascii_only,
438    };
439
440    #[test]
441    fn strips_esc_csi_sequences() {
442        let input = "a\x1b[31mred\x1b[0mz";
443        assert_eq!(strip_ansi(input), "aredz");
444        assert_eq!(strip_ansi_ascii_only(input), "aredz");
445    }
446
447    #[test]
448    fn utf8_encoded_c1_is_not_reprocessed_as_control() {
449        // XTerm/ECMA-48: controls are processed once; decoded UTF-8 text is not reprocessed as C1.
450        let input = "a\u{009b}31mred";
451        assert_eq!(strip_ansi(input), input);
452    }
453
454    #[test]
455    fn strip_removes_ascii_del_control() {
456        let input = format!("a{}b", char::from(0x7f));
457        assert_eq!(strip_ansi(&input), "ab");
458    }
459
460    #[test]
461    fn strip_removes_c0_controls_except_line_whitespace() {
462        // anstream treats FF (0x0C) as printable ASCII whitespace; the shared
463        // stripper must still remove it so raw control bytes never reach a
464        // transcript. VT (0x0B) and the other C0 controls are filtered too.
465        // ESC (0x1B) is an escape-sequence introducer, not a plain control
466        // byte; its behavior is covered by the sequence tests above.
467        for code in (0x00..0x20).filter(|&code| !matches!(code, b'\n' | b'\r' | b'\t' | 0x1b)) {
468            let input = format!("a{}b", char::from(code));
469            assert_eq!(strip_ansi(&input), "ab", "control byte 0x{code:02x}");
470
471            let mut stream = AnsiStripStream::new();
472            assert_eq!(stream.strip_chunk(&input), "ab", "control byte 0x{code:02x}");
473        }
474    }
475
476    #[test]
477    fn csi_aborts_on_esc_then_new_sequence_parses() {
478        let input = "a\x1b[31\x1b[32mgreen\x1b[0mz";
479        assert_eq!(strip_ansi(input), "agreenz");
480    }
481
482    #[test]
483    fn csi_aborts_on_can_and_sub() {
484        let can = format!("a\x1b[31{}b", char::from(CAN));
485        let sub = format!("a\x1b[31{}b", char::from(SUB));
486        assert_eq!(strip_ansi(&can), "ab");
487        assert_eq!(strip_ansi(&sub), "ab");
488    }
489
490    #[test]
491    fn osc_aborts_on_esc_non_st() {
492        let input = "a\x1b]title\x1b[31mred\x1b[0mz";
493        assert_eq!(strip_ansi(input), "aredz");
494    }
495
496    #[test]
497    fn osc_program_status_reports_are_stripped() {
498        // Nested OSC 7501 from child output must never reach the terminal:
499        // VT Code re-projects children with generic labels instead. Both
500        // terminator forms apply; surrounding text survives on both sides.
501        let st = "out\x1b]7501;state=working:app=tool:msg=V29ya2luZw==\x1b\\done";
502        assert_eq!(strip_ansi(st), "outdone");
503        let bel = "out\x1b]7501;state=blocked:kind=permission\x07done";
504        assert_eq!(strip_ansi(bel), "outdone");
505    }
506
507    #[test]
508    fn incomplete_sequence_drops_tail() {
509        let input = "text\x1b[31";
510        assert_eq!(strip_ansi(input), "text");
511    }
512
513    #[test]
514    fn ascii_only_incomplete_sequence_drops_tail() {
515        // The old ASCII fast path kept the unterminated tail, which leaked raw
516        // escape bytes into transcripts when a PTY chunk split a sequence.
517        let input = "text\x1b[31";
518        assert_eq!(strip_ansi_ascii_only(input), "text");
519    }
520
521    #[test]
522    fn strips_common_progress_redraw_sequences() {
523        // Common pattern for dynamic CLI updates:
524        // carriage return + erase line + redraw text.
525        let input = "\r\x1b[2KProgress 10%\r\x1b[2KDone\n";
526        assert_eq!(strip_ansi(input), "\rProgress 10%\rDone\n");
527    }
528
529    #[test]
530    fn strips_cursor_navigation_sequences() {
531        let input = "left\x1b[1D!\nup\x1b[1Arow";
532        assert_eq!(strip_ansi(input), "left!\nuprow");
533    }
534
535    #[test]
536    fn strip_ansi_bytes_supports_raw_c1_csi() {
537        let input = [b'a', 0x9b, b'3', b'1', b'm', b'r', b'e', b'd', 0x9b, b'0', b'm', b'z'];
538        let out = super::strip_ansi_bytes(&input);
539        assert_eq!(out, b"aredz");
540    }
541
542    #[test]
543    fn strip_ansi_bytes_supports_raw_c1_osc_and_st() {
544        let mut input = b"pre".to_vec();
545        input.extend_from_slice(&[0x9d]);
546        input.extend_from_slice(b"8;;https://example.com");
547        input.extend_from_slice(&[0x9c]);
548        input.extend_from_slice(b"link");
549        input.extend_from_slice(&[0x9d]);
550        input.extend_from_slice(b"8;;");
551        input.extend_from_slice(&[0x9c]);
552        input.extend_from_slice(b"post");
553        let out = super::strip_ansi_bytes(&input);
554        assert_eq!(out, b"prelinkpost");
555    }
556
557    #[test]
558    fn csi_respects_parameter_intermediate_final_grammar() {
559        // Parameter bytes ("1;2"), intermediate bytes (" "), then final ("m")
560        let input = "a\x1b[1;2 mred\x1b[0mz";
561        assert_eq!(strip_ansi(input), "aredz");
562    }
563
564    #[test]
565    fn malformed_csi_control_byte_lets_next_final_byte_terminate() {
566        // Per the ECMA-48/DEC state machine, a C0 control inside CSI is
567        // executed but does not abort the sequence. The next byte in 0x40..=0x7e
568        // ('v') is therefore the final byte and is consumed with the sequence.
569        let malformed = format!("a\x1b[12{}visible", char::from(0x10));
570        assert_eq!(strip_ansi(&malformed), "aisible");
571    }
572
573    #[test]
574    fn boundary_parser_stays_conservative_on_malformed_csi() {
575        // Echo suppression relies on the boundary parser not swallowing text
576        // that follows a malformed CSI, so it intentionally disagrees with
577        // `strip_ansi` about where the sequence ends.
578        let malformed = format!("\x1b[12{}visible", char::from(0x10));
579        let len = super::parse_ansi_sequence(&malformed).expect("sequence length");
580        assert_eq!(malformed.split_at(len).0, "\x1b[12");
581        assert_eq!(strip_ansi(&malformed), "isible");
582    }
583
584    #[test]
585    fn strips_wikipedia_sgr_8bit_color_pattern() {
586        let input = "x\x1b[38;5;196mred\x1b[0my";
587        assert_eq!(strip_ansi(input), "xredy");
588    }
589
590    #[test]
591    fn strips_wikipedia_sgr_truecolor_pattern() {
592        let input = "x\x1b[48;2;12;34;56mblock\x1b[0my";
593        assert_eq!(strip_ansi(input), "xblocky");
594    }
595
596    #[test]
597    fn strips_wikipedia_osc8_hyperlink_pattern() {
598        let input = "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now";
599        assert_eq!(strip_ansi(input), "go here now");
600    }
601
602    #[test]
603    fn strips_dec_private_mode_csi() {
604        let input = "a\x1b[?25lb\x1b[?25hc";
605        assert_eq!(strip_ansi(input), "abc");
606    }
607
608    #[test]
609    fn strips_mintty_overstrike_mode_sequences() {
610        // mintty/VK100 overstrike switching: SGR `8:7` enables overstrike,
611        // `28` returns to overwriting mode, and `?20h`/`?20l` are the
612        // private-mode forms. All are consumed like any other CSI sequence.
613        let input = "a\x1b[8:7mb\x1b[28mc\x1b[?20hd\x1b[?20le";
614        assert_eq!(strip_ansi(input), "abcde");
615        assert_eq!(strip_ansi_ascii_only(input), "abcde");
616    }
617
618    #[test]
619    fn strips_three_byte_esc_sequences() {
620        // ESC # 8 = DEC screen alignment test
621        let input = "a\x1b#8b";
622        assert_eq!(strip_ansi(input), "ab");
623
624        // ESC ( B = designate US ASCII as G0
625        let input2 = "a\x1b(Bb";
626        assert_eq!(strip_ansi(input2), "ab");
627
628        // ESC SP F = 7-bit controls
629        let input3 = "a\x1b Fb";
630        assert_eq!(strip_ansi(input3), "ab");
631
632        // ESC % G = select UTF-8
633        let input4 = "a\x1b%Gb";
634        assert_eq!(strip_ansi(input4), "ab");
635    }
636
637    #[test]
638    fn incomplete_three_byte_esc_sequence_drops_tail() {
639        // ESC # at end — incomplete, should not consume past end
640        let input = "text\x1b#";
641        assert_eq!(strip_ansi(input), "text");
642    }
643
644    /// Reference stripper built from the in-tree boundary parser, independent
645    /// of `anstream`. Used as the oracle for the delegation refactor.
646    fn legacy_strip(text: &str) -> String {
647        let bytes = text.as_bytes();
648        let mut output = Vec::with_capacity(bytes.len());
649        let mut index = 0;
650        while index < bytes.len() {
651            let next_esc = bytes[index..]
652                .iter()
653                .position(|&b| b == b'\x1b')
654                .map_or(bytes.len(), |o| index + o);
655            for &byte in &bytes[index..next_esc] {
656                push_visible_byte(&mut output, byte);
657            }
658            index = next_esc;
659            if index >= bytes.len() {
660                break;
661            }
662            if let Some(len) = parse_ansi_sequence_bytes(&bytes[index..]) {
663                index += len;
664            } else {
665                break;
666            }
667        }
668        String::from_utf8(output).expect("filtering ASCII controls cannot break UTF-8")
669    }
670
671    #[test]
672    fn anstream_matches_legacy_stripper_on_structured_corpus() {
673        let cases = [
674            "plain text",
675            "a\x1b[31mred\x1b[0mz",
676            "\r\x1b[2KProgress 10%\r\x1b[2KDone\n",
677            "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now",
678            "out\x1b]7501;state=working\x07done",
679            "a\x1b#8b",
680            "a\x1b(Bb",
681            "a\x1b Fb",
682            "a\x1b%Gb",
683            "a\x1b[31\x1b[32mgreen\x1b[0mz",
684            "a\u{009b}31mred",
685            "x\x1b[38;5;196mred\x1b[0my",
686            "a\x1b[?25lb\x1b[?25hc",
687            "text\x1b[31",
688        ];
689        for case in cases {
690            assert_eq!(strip_ansi(case), legacy_strip(case), "case {case:?}");
691        }
692    }
693
694    #[test]
695    fn strip_stream_keeps_parser_state_across_split_sequences() {
696        let mut stream = AnsiStripStream::new();
697        let mut visible = stream.strip_chunk("text\x1b[3");
698        // Neither half is a valid sequence on its own; only together do they
699        // form SGR. A stateless stripper would leak "31m" into the output.
700        visible.push_str(&stream.strip_chunk("1mred\x1b[0mz"));
701        assert_eq!(visible, "textredz");
702
703        let mut stream = AnsiStripStream::new();
704        let mut visible = stream.strip_chunk("pre\x1b]8;;https://exa");
705        visible.push_str(&stream.strip_chunk("mple.com\x1b\\linkpost"));
706        assert_eq!(visible, "prelinkpost");
707    }
708
709    #[test]
710    fn strip_stream_output_is_independent_of_chunk_boundaries() {
711        // A C0 control inside CSI is executed, not an abort: the next 0x40..=0x7e
712        // byte is the sequence's final byte. Both the boundary detector and
713        // anstream must agree, or visible text appears/disappears based on the
714        // arbitrary PTY read boundary.
715        let whole = "PRE\x1b[31mMID\x1b[12\x10visiblePOST";
716        let expected = strip_ansi(whole);
717        for split in 0..=whole.len() {
718            if !whole.is_char_boundary(split) {
719                continue;
720            }
721            let (first, second) = whole.split_at(split);
722            let mut stream = AnsiStripStream::new();
723            let mut visible = stream.strip_chunk(first);
724            visible.push_str(&stream.strip_chunk(second));
725            assert_eq!(visible, expected, "split at byte {split}");
726        }
727    }
728
729    #[test]
730    fn strip_stream_passes_plain_text_through_unchanged() {
731        let mut stream = AnsiStripStream::new();
732        assert_eq!(stream.strip_chunk("plain text\n"), "plain text\n");
733        assert_eq!(stream.strip_chunk("second\rline"), "second\rline");
734    }
735
736    /// The retained suffix is capped, but an overlong OSC string must still
737    /// not leak its continuation into the transcript when a PTY read splits it.
738    #[test]
739    fn strip_stream_handles_overlong_incomplete_sequence_at_chunk_boundary() {
740        for terminator in ["\x1b\\", "\x07"] {
741            let mut payload = String::from("PRE\x1b]8;;");
742            payload.push_str(&"x".repeat(MAX_STRING_SEQUENCE_BYTES + 16));
743            payload.push_str(terminator);
744            payload.push_str("POST");
745            let expected = strip_ansi(&payload);
746            assert_eq!(expected, "PREPOST", "terminator {terminator:?}");
747
748            for split in [
749                "PRE\x1b]8;;".len() + 8,
750                "PRE\x1b]8;;".len() + MAX_STRING_SEQUENCE_BYTES - 1,
751                "PRE\x1b]8;;".len() + MAX_STRING_SEQUENCE_BYTES + 8,
752                payload.len() - terminator.len(),
753            ] {
754                let (first, second) = payload.split_at(split);
755                let mut stream = AnsiStripStream::new();
756                let mut visible = stream.strip_chunk(first);
757                assert!(stream.pending.len() <= MAX_STRING_SEQUENCE_BYTES, "retention cap");
758                visible.push_str(&stream.strip_chunk(second));
759                assert!(stream.pending.is_empty(), "buffer released after terminator");
760                assert_eq!(visible, expected, "split at {split}, terminator {terminator:?}");
761            }
762        }
763    }
764
765    /// A PTY read can end at any byte boundary. Streaming output must match
766    /// one-shot stripping for every possible split, not just hand-picked ones.
767    #[test]
768    fn strip_stream_matches_one_shot_for_every_chunk_boundary() {
769        let cases = [
770            "a\x1b[31mred\x1b[0mz",
771            "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now",
772            "out\x1b]7501;state=working\x07done",
773            "a\x1b#8b",
774            "a\x1b(Bb",
775            "a\x1b[31\x1b[32mgreen\x1b[0mz",
776            "\r\x1b[2KProgress 10%\r\x1b[2KDone\n",
777            "text\x1b[31",
778            "a\u{009b}31mred",
779            "x\x1b[38;5;196mred\x1b[0my",
780        ];
781        for case in cases {
782            let expected = strip_ansi(case);
783            for index in 0..=case.len() {
784                if !case.is_char_boundary(index) {
785                    continue;
786                }
787                let (first, second) = case.split_at(index);
788                let mut stream = AnsiStripStream::new();
789                let mut visible = stream.strip_chunk(first);
790                visible.push_str(&stream.strip_chunk(second));
791                assert_eq!(visible, expected, "split at {index} of {case:?}");
792            }
793        }
794    }
795}