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    String::from_utf8(output).expect("removing ASCII control bytes preserves UTF-8")
217}
218
219/// Strip ANSI escape codes from text, keeping only plain text.
220///
221/// Delegates to `anstream`'s ANSI state machine. An incomplete sequence at the
222/// end of the input is dropped rather than emitted as raw control bytes; for
223/// chunked input use [`AnsiStripStream`] so a split sequence is not lost.
224pub fn strip_ansi(text: &str) -> String {
225    strip_plain(text)
226}
227
228/// Stateful ANSI stripper for chunked input such as a PTY byte stream.
229///
230/// `anstream`'s incremental adapter resets its parser to the ground state at
231/// each call, so it cannot recover a sequence split across two chunks. This
232/// wrapper holds back only the trailing, unterminated escape sequence and
233/// re-strips it together with the next chunk. Both the boundary detector and
234/// `anstream` use `anstyle_parse`'s state machine, so they cannot disagree on
235/// where a sequence ends. The retained suffix is bounded.
236#[derive(Default)]
237pub struct AnsiStripStream {
238    /// Trailing, unterminated escape sequence held back for the next chunk.
239    /// Bounded by [`MAX_STRING_SEQUENCE_BYTES`].
240    pending: String,
241    /// Parser state while discarding an overlong, unterminated sequence.
242    ///
243    /// The bound on `pending` means a hostile or buggy child could emit an
244    /// arbitrarily long OSC string. Once the cap is hit, the rest of that
245    /// sequence is dropped until the state machine returns to `Ground`, so
246    /// output stays independent of where the PTY read landed without letting
247    /// the retained buffer grow without limit.
248    discarding: Option<State>,
249}
250
251impl AnsiStripStream {
252    /// Create a stripper with no retained bytes.
253    #[must_use]
254    pub fn new() -> Self {
255        Self::default()
256    }
257
258    /// Strip the next chunk, returning its visible text.
259    ///
260    /// A trailing escape sequence that is incomplete in `chunk` is retained
261    /// and prepended to the next call instead of leaking raw control bytes.
262    pub fn strip_chunk(&mut self, chunk: &str) -> String {
263        let chunk = self.discard_overlong(chunk);
264        if chunk.is_empty() {
265            return String::new();
266        }
267        // The common case has no held-back suffix. Avoid copying the whole
268        // chunk into `pending`'s buffer only to split it again; PTY output is
269        // chunked at high frequency and this path is allocation-sensitive.
270        if self.pending.is_empty() {
271            return self.strip_ready(chunk);
272        }
273        let mut combined = std::mem::take(&mut self.pending);
274        combined.push_str(chunk);
275        self.strip_ready(&combined)
276    }
277
278    /// Drop the continuation of an overlong sequence up to its terminator,
279    /// returning the first byte after the sequence (if the chunk contains it).
280    fn discard_overlong<'a>(&mut self, chunk: &'a str) -> &'a str {
281        let Some(mut state) = self.discarding else {
282            return chunk;
283        };
284        for (index, ch) in chunk.char_indices() {
285            if !ch.is_ascii() {
286                continue;
287            }
288            let (next, _) = state_change(state, ch as u8);
289            if next != State::Anywhere {
290                state = next;
291            }
292            if next == State::Ground {
293                self.discarding = None;
294                return chunk.split_at(index + ch.len_utf8()).1;
295            }
296        }
297        self.discarding = Some(state);
298        ""
299    }
300
301    /// Strip `text`, holding back its trailing incomplete sequence for the next call.
302    fn strip_ready(&mut self, text: &str) -> String {
303        let mut overlong = false;
304        let split_at = if text.as_bytes().contains(&ESC) {
305            let tail = sequence_tail(text);
306            overlong = tail.overlong;
307            if overlong {
308                self.discarding = Some(tail.state);
309            }
310            tail.start
311        } else {
312            text.len()
313        };
314        let (ready, pending) = text.split_at(split_at);
315        if !overlong {
316            self.pending.push_str(pending);
317        }
318        strip_plain(ready)
319    }
320}
321
322/// Where an unterminated escape sequence starts, and the parser state at EOF.
323struct SequenceTail {
324    /// Byte offset where the trailing incomplete sequence begins; `text.len()`
325    /// when the input ends in a complete sequence or was too long to retain.
326    start: usize,
327    /// Parser state after the whole input, used to resume in discard mode.
328    state: State,
329    /// Whether the trailing sequence exceeded the retention cap.
330    overlong: bool,
331}
332
333/// Locate the trailing, unterminated escape sequence.
334///
335/// Uses the same `anstyle_parse` state machine as `anstream`. A second,
336/// hand-rolled grammar here would classify sequences differently (notably a
337/// C0 control inside CSI) and make output depend on where a PTY read landed.
338fn sequence_tail(text: &str) -> SequenceTail {
339    let mut state = State::Ground;
340    let mut candidate = None;
341    for (index, ch) in text.char_indices() {
342        if !ch.is_ascii() {
343            // Validated UTF-8 bytes are printable and do not affect ANSI state.
344            continue;
345        }
346        if state == State::Ground && ch == '\x1b' {
347            candidate = Some(index);
348        }
349        let (next, _) = state_change(state, ch as u8);
350        if next != State::Anywhere {
351            state = next;
352        }
353    }
354
355    if state == State::Ground {
356        return SequenceTail { start: text.len(), state, overlong: false };
357    }
358    // A non-Ground state without an ASCII ESC start can only come from 8-bit
359    // C1 bytes, which `anstream` treats as printable UTF-8 rather than controls.
360    let Some(start) = candidate else {
361        return SequenceTail { start: text.len(), state, overlong: false };
362    };
363    if text.len() - start > MAX_STRING_SEQUENCE_BYTES {
364        return SequenceTail { start: text.len(), state, overlong: true };
365    }
366    SequenceTail { start, state, overlong: false }
367}
368
369/// Strip ANSI escape codes from arbitrary bytes, preserving non-control bytes.
370///
371/// This is the preferred API when input may contain raw C1 (8-bit) controls.
372fn strip_ansi_bytes(input: &[u8]) -> Vec<u8> {
373    let mut output = Vec::with_capacity(input.len());
374    let bytes = input;
375    let mut i = 0;
376
377    while i < bytes.len() {
378        // Pre-slice to the remaining portion so all indexing below shares one bounds edge.
379        let rest = &bytes[i..];
380
381        if (rest[0] == ESC || parse_c1_at(bytes, i).is_some())
382            && let Some(len) = parse_ansi_sequence_bytes(rest)
383        {
384            i += len;
385            continue;
386        }
387        if rest[0] == ESC || parse_c1_at(bytes, i).is_some() {
388            // Incomplete/unterminated control sequence at end of available text.
389            break;
390        }
391
392        push_visible_byte(&mut output, rest[0]);
393        i += 1;
394    }
395    output
396}
397
398/// Parse and determine the length of the ANSI escape sequence at the start of text.
399///
400/// This boundary parser is deliberately conservative: an invalid byte inside a
401/// CSI (including a C0 control other than ESC/CAN/SUB) aborts the sequence
402/// without consuming that byte. PTY echo suppression uses it to skip escape
403/// sequences without swallowing following command text on malformed input.
404/// [`strip_ansi`] follows `anstream`'s ECMA-48 state machine instead, where a
405/// C0 control inside CSI is executed and the sequence continues; the two
406/// parsers therefore disagree on that malformed input by design.
407pub fn parse_ansi_sequence(text: &str) -> Option<usize> {
408    let bytes = text.as_bytes();
409    parse_ansi_sequence_bytes(bytes)
410}
411
412/// ANSI stripping for ASCII-only text.
413///
414/// Retained for API compatibility; this now shares [`strip_ansi`]'s parser.
415/// Two deliberate contract changes from the old copy-raw-spans implementation:
416/// C0 controls and DEL are filtered (as in [`strip_ansi`]), and an unterminated
417/// escape sequence at the end of the input is dropped instead of kept — the
418/// latter would leak raw control bytes when a PTY chunk splits a sequence.
419pub fn strip_ansi_ascii_only(text: &str) -> String {
420    strip_ansi(text)
421}
422
423/// Detect if text contains unicode characters that need special handling
424#[must_use]
425pub fn contains_unicode(text: &str) -> bool {
426    text.bytes().any(|b| b >= 0x80)
427}
428
429#[cfg(test)]
430mod tests {
431    use super::{
432        AnsiStripStream, CAN, MAX_STRING_SEQUENCE_BYTES, SUB, parse_ansi_sequence_bytes, push_visible_byte, strip_ansi,
433        strip_ansi_ascii_only,
434    };
435
436    #[test]
437    fn strips_esc_csi_sequences() {
438        let input = "a\x1b[31mred\x1b[0mz";
439        assert_eq!(strip_ansi(input), "aredz");
440        assert_eq!(strip_ansi_ascii_only(input), "aredz");
441    }
442
443    #[test]
444    fn utf8_encoded_c1_is_not_reprocessed_as_control() {
445        // XTerm/ECMA-48: controls are processed once; decoded UTF-8 text is not reprocessed as C1.
446        let input = "a\u{009b}31mred";
447        assert_eq!(strip_ansi(input), input);
448    }
449
450    #[test]
451    fn strip_removes_ascii_del_control() {
452        let input = format!("a{}b", char::from(0x7f));
453        assert_eq!(strip_ansi(&input), "ab");
454    }
455
456    #[test]
457    fn strip_removes_c0_controls_except_line_whitespace() {
458        // anstream treats FF (0x0C) as printable ASCII whitespace; the shared
459        // stripper must still remove it so raw control bytes never reach a
460        // transcript. VT (0x0B) and the other C0 controls are filtered too.
461        // ESC (0x1B) is an escape-sequence introducer, not a plain control
462        // byte; its behavior is covered by the sequence tests above.
463        for code in (0x00..0x20).filter(|&code| !matches!(code, b'\n' | b'\r' | b'\t' | 0x1b)) {
464            let input = format!("a{}b", char::from(code));
465            assert_eq!(strip_ansi(&input), "ab", "control byte 0x{code:02x}");
466
467            let mut stream = AnsiStripStream::new();
468            assert_eq!(stream.strip_chunk(&input), "ab", "control byte 0x{code:02x}");
469        }
470    }
471
472    #[test]
473    fn csi_aborts_on_esc_then_new_sequence_parses() {
474        let input = "a\x1b[31\x1b[32mgreen\x1b[0mz";
475        assert_eq!(strip_ansi(input), "agreenz");
476    }
477
478    #[test]
479    fn csi_aborts_on_can_and_sub() {
480        let can = format!("a\x1b[31{}b", char::from(CAN));
481        let sub = format!("a\x1b[31{}b", char::from(SUB));
482        assert_eq!(strip_ansi(&can), "ab");
483        assert_eq!(strip_ansi(&sub), "ab");
484    }
485
486    #[test]
487    fn osc_aborts_on_esc_non_st() {
488        let input = "a\x1b]title\x1b[31mred\x1b[0mz";
489        assert_eq!(strip_ansi(input), "aredz");
490    }
491
492    #[test]
493    fn osc_program_status_reports_are_stripped() {
494        // Nested OSC 7501 from child output must never reach the terminal:
495        // VT Code re-projects children with generic labels instead. Both
496        // terminator forms apply; surrounding text survives on both sides.
497        let st = "out\x1b]7501;state=working:app=tool:msg=V29ya2luZw==\x1b\\done";
498        assert_eq!(strip_ansi(st), "outdone");
499        let bel = "out\x1b]7501;state=blocked:kind=permission\x07done";
500        assert_eq!(strip_ansi(bel), "outdone");
501    }
502
503    #[test]
504    fn incomplete_sequence_drops_tail() {
505        let input = "text\x1b[31";
506        assert_eq!(strip_ansi(input), "text");
507    }
508
509    #[test]
510    fn ascii_only_incomplete_sequence_drops_tail() {
511        // The old ASCII fast path kept the unterminated tail, which leaked raw
512        // escape bytes into transcripts when a PTY chunk split a sequence.
513        let input = "text\x1b[31";
514        assert_eq!(strip_ansi_ascii_only(input), "text");
515    }
516
517    #[test]
518    fn strips_common_progress_redraw_sequences() {
519        // Common pattern for dynamic CLI updates:
520        // carriage return + erase line + redraw text.
521        let input = "\r\x1b[2KProgress 10%\r\x1b[2KDone\n";
522        assert_eq!(strip_ansi(input), "\rProgress 10%\rDone\n");
523    }
524
525    #[test]
526    fn strips_cursor_navigation_sequences() {
527        let input = "left\x1b[1D!\nup\x1b[1Arow";
528        assert_eq!(strip_ansi(input), "left!\nuprow");
529    }
530
531    #[test]
532    fn strip_ansi_bytes_supports_raw_c1_csi() {
533        let input = [b'a', 0x9b, b'3', b'1', b'm', b'r', b'e', b'd', 0x9b, b'0', b'm', b'z'];
534        let out = super::strip_ansi_bytes(&input);
535        assert_eq!(out, b"aredz");
536    }
537
538    #[test]
539    fn strip_ansi_bytes_supports_raw_c1_osc_and_st() {
540        let mut input = b"pre".to_vec();
541        input.extend_from_slice(&[0x9d]);
542        input.extend_from_slice(b"8;;https://example.com");
543        input.extend_from_slice(&[0x9c]);
544        input.extend_from_slice(b"link");
545        input.extend_from_slice(&[0x9d]);
546        input.extend_from_slice(b"8;;");
547        input.extend_from_slice(&[0x9c]);
548        input.extend_from_slice(b"post");
549        let out = super::strip_ansi_bytes(&input);
550        assert_eq!(out, b"prelinkpost");
551    }
552
553    #[test]
554    fn csi_respects_parameter_intermediate_final_grammar() {
555        // Parameter bytes ("1;2"), intermediate bytes (" "), then final ("m")
556        let input = "a\x1b[1;2 mred\x1b[0mz";
557        assert_eq!(strip_ansi(input), "aredz");
558    }
559
560    #[test]
561    fn malformed_csi_control_byte_lets_next_final_byte_terminate() {
562        // Per the ECMA-48/DEC state machine, a C0 control inside CSI is
563        // executed but does not abort the sequence. The next byte in 0x40..=0x7e
564        // ('v') is therefore the final byte and is consumed with the sequence.
565        let malformed = format!("a\x1b[12{}visible", char::from(0x10));
566        assert_eq!(strip_ansi(&malformed), "aisible");
567    }
568
569    #[test]
570    fn boundary_parser_stays_conservative_on_malformed_csi() {
571        // Echo suppression relies on the boundary parser not swallowing text
572        // that follows a malformed CSI, so it intentionally disagrees with
573        // `strip_ansi` about where the sequence ends.
574        let malformed = format!("\x1b[12{}visible", char::from(0x10));
575        let len = super::parse_ansi_sequence(&malformed).expect("sequence length");
576        assert_eq!(malformed.split_at(len).0, "\x1b[12");
577        assert_eq!(strip_ansi(&malformed), "isible");
578    }
579
580    #[test]
581    fn strips_wikipedia_sgr_8bit_color_pattern() {
582        let input = "x\x1b[38;5;196mred\x1b[0my";
583        assert_eq!(strip_ansi(input), "xredy");
584    }
585
586    #[test]
587    fn strips_wikipedia_sgr_truecolor_pattern() {
588        let input = "x\x1b[48;2;12;34;56mblock\x1b[0my";
589        assert_eq!(strip_ansi(input), "xblocky");
590    }
591
592    #[test]
593    fn strips_wikipedia_osc8_hyperlink_pattern() {
594        let input = "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now";
595        assert_eq!(strip_ansi(input), "go here now");
596    }
597
598    #[test]
599    fn strips_dec_private_mode_csi() {
600        let input = "a\x1b[?25lb\x1b[?25hc";
601        assert_eq!(strip_ansi(input), "abc");
602    }
603
604    #[test]
605    fn strips_mintty_overstrike_mode_sequences() {
606        // mintty/VK100 overstrike switching: SGR `8:7` enables overstrike,
607        // `28` returns to overwriting mode, and `?20h`/`?20l` are the
608        // private-mode forms. All are consumed like any other CSI sequence.
609        let input = "a\x1b[8:7mb\x1b[28mc\x1b[?20hd\x1b[?20le";
610        assert_eq!(strip_ansi(input), "abcde");
611        assert_eq!(strip_ansi_ascii_only(input), "abcde");
612    }
613
614    #[test]
615    fn strips_three_byte_esc_sequences() {
616        // ESC # 8 = DEC screen alignment test
617        let input = "a\x1b#8b";
618        assert_eq!(strip_ansi(input), "ab");
619
620        // ESC ( B = designate US ASCII as G0
621        let input2 = "a\x1b(Bb";
622        assert_eq!(strip_ansi(input2), "ab");
623
624        // ESC SP F = 7-bit controls
625        let input3 = "a\x1b Fb";
626        assert_eq!(strip_ansi(input3), "ab");
627
628        // ESC % G = select UTF-8
629        let input4 = "a\x1b%Gb";
630        assert_eq!(strip_ansi(input4), "ab");
631    }
632
633    #[test]
634    fn incomplete_three_byte_esc_sequence_drops_tail() {
635        // ESC # at end — incomplete, should not consume past end
636        let input = "text\x1b#";
637        assert_eq!(strip_ansi(input), "text");
638    }
639
640    /// Reference stripper built from the in-tree boundary parser, independent
641    /// of `anstream`. Used as the oracle for the delegation refactor.
642    fn legacy_strip(text: &str) -> String {
643        let bytes = text.as_bytes();
644        let mut output = Vec::with_capacity(bytes.len());
645        let mut index = 0;
646        while index < bytes.len() {
647            let next_esc = bytes[index..]
648                .iter()
649                .position(|&b| b == b'\x1b')
650                .map_or(bytes.len(), |o| index + o);
651            for &byte in &bytes[index..next_esc] {
652                push_visible_byte(&mut output, byte);
653            }
654            index = next_esc;
655            if index >= bytes.len() {
656                break;
657            }
658            if let Some(len) = parse_ansi_sequence_bytes(&bytes[index..]) {
659                index += len;
660            } else {
661                break;
662            }
663        }
664        String::from_utf8(output).expect("filtering ASCII controls cannot break UTF-8")
665    }
666
667    #[test]
668    fn anstream_matches_legacy_stripper_on_structured_corpus() {
669        let cases = [
670            "plain text",
671            "a\x1b[31mred\x1b[0mz",
672            "\r\x1b[2KProgress 10%\r\x1b[2KDone\n",
673            "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now",
674            "out\x1b]7501;state=working\x07done",
675            "a\x1b#8b",
676            "a\x1b(Bb",
677            "a\x1b Fb",
678            "a\x1b%Gb",
679            "a\x1b[31\x1b[32mgreen\x1b[0mz",
680            "a\u{009b}31mred",
681            "x\x1b[38;5;196mred\x1b[0my",
682            "a\x1b[?25lb\x1b[?25hc",
683            "text\x1b[31",
684        ];
685        for case in cases {
686            assert_eq!(strip_ansi(case), legacy_strip(case), "case {case:?}");
687        }
688    }
689
690    #[test]
691    fn strip_stream_keeps_parser_state_across_split_sequences() {
692        let mut stream = AnsiStripStream::new();
693        let mut visible = stream.strip_chunk("text\x1b[3");
694        // Neither half is a valid sequence on its own; only together do they
695        // form SGR. A stateless stripper would leak "31m" into the output.
696        visible.push_str(&stream.strip_chunk("1mred\x1b[0mz"));
697        assert_eq!(visible, "textredz");
698
699        let mut stream = AnsiStripStream::new();
700        let mut visible = stream.strip_chunk("pre\x1b]8;;https://exa");
701        visible.push_str(&stream.strip_chunk("mple.com\x1b\\linkpost"));
702        assert_eq!(visible, "prelinkpost");
703    }
704
705    #[test]
706    fn strip_stream_output_is_independent_of_chunk_boundaries() {
707        // A C0 control inside CSI is executed, not an abort: the next 0x40..=0x7e
708        // byte is the sequence's final byte. Both the boundary detector and
709        // anstream must agree, or visible text appears/disappears based on the
710        // arbitrary PTY read boundary.
711        let whole = "PRE\x1b[31mMID\x1b[12\x10visiblePOST";
712        let expected = strip_ansi(whole);
713        for split in 0..=whole.len() {
714            if !whole.is_char_boundary(split) {
715                continue;
716            }
717            let (first, second) = whole.split_at(split);
718            let mut stream = AnsiStripStream::new();
719            let mut visible = stream.strip_chunk(first);
720            visible.push_str(&stream.strip_chunk(second));
721            assert_eq!(visible, expected, "split at byte {split}");
722        }
723    }
724
725    #[test]
726    fn strip_stream_passes_plain_text_through_unchanged() {
727        let mut stream = AnsiStripStream::new();
728        assert_eq!(stream.strip_chunk("plain text\n"), "plain text\n");
729        assert_eq!(stream.strip_chunk("second\rline"), "second\rline");
730    }
731
732    /// The retained suffix is capped, but an overlong OSC string must still
733    /// not leak its continuation into the transcript when a PTY read splits it.
734    #[test]
735    fn strip_stream_handles_overlong_incomplete_sequence_at_chunk_boundary() {
736        for terminator in ["\x1b\\", "\x07"] {
737            let mut payload = String::from("PRE\x1b]8;;");
738            payload.push_str(&"x".repeat(MAX_STRING_SEQUENCE_BYTES + 16));
739            payload.push_str(terminator);
740            payload.push_str("POST");
741            let expected = strip_ansi(&payload);
742            assert_eq!(expected, "PREPOST", "terminator {terminator:?}");
743
744            for split in [
745                "PRE\x1b]8;;".len() + 8,
746                "PRE\x1b]8;;".len() + MAX_STRING_SEQUENCE_BYTES - 1,
747                "PRE\x1b]8;;".len() + MAX_STRING_SEQUENCE_BYTES + 8,
748                payload.len() - terminator.len(),
749            ] {
750                let (first, second) = payload.split_at(split);
751                let mut stream = AnsiStripStream::new();
752                let mut visible = stream.strip_chunk(first);
753                assert!(stream.pending.len() <= MAX_STRING_SEQUENCE_BYTES, "retention cap");
754                visible.push_str(&stream.strip_chunk(second));
755                assert!(stream.pending.is_empty(), "buffer released after terminator");
756                assert_eq!(visible, expected, "split at {split}, terminator {terminator:?}");
757            }
758        }
759    }
760
761    /// A PTY read can end at any byte boundary. Streaming output must match
762    /// one-shot stripping for every possible split, not just hand-picked ones.
763    #[test]
764    fn strip_stream_matches_one_shot_for_every_chunk_boundary() {
765        let cases = [
766            "a\x1b[31mred\x1b[0mz",
767            "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now",
768            "out\x1b]7501;state=working\x07done",
769            "a\x1b#8b",
770            "a\x1b(Bb",
771            "a\x1b[31\x1b[32mgreen\x1b[0mz",
772            "\r\x1b[2KProgress 10%\r\x1b[2KDone\n",
773            "text\x1b[31",
774            "a\u{009b}31mred",
775            "x\x1b[38;5;196mred\x1b[0my",
776        ];
777        for case in cases {
778            let expected = strip_ansi(case);
779            for index in 0..=case.len() {
780                if !case.is_char_boundary(index) {
781                    continue;
782                }
783                let (first, second) = case.split_at(index);
784                let mut stream = AnsiStripStream::new();
785                let mut visible = stream.strip_chunk(first);
786                visible.push_str(&stream.strip_chunk(second));
787                assert_eq!(visible, expected, "split at {index} of {case:?}");
788            }
789        }
790    }
791}