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
6use 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 let mut index = start;
64 let mut phase = 0u8; let mut consumed = 0usize;
66
67 while index < bytes.len() {
68 let byte = bytes[index];
69 if byte == ESC {
70 return Some(index);
72 }
73 if byte == CAN || byte == SUB {
74 return Some(index + 1);
76 }
77
78 consumed += 1;
79 if consumed > MAX_CSI_SEQUENCE_BYTES {
80 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 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 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 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 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
189pub 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#[inline]
206fn is_transcript_control(byte: u8) -> bool {
207 (byte < b' ' && !matches!(byte, b'\n' | b'\r' | b'\t')) || byte == DEL
208}
209
210fn strip_plain(text: &str) -> String {
212 let mut output = strip_str(text).to_string().into_bytes();
213 output.retain(|byte| !is_transcript_control(*byte));
216 String::from_utf8(output).expect("removing ASCII control bytes preserves UTF-8")
217}
218
219pub fn strip_ansi(text: &str) -> String {
225 strip_plain(text)
226}
227
228#[derive(Default)]
237pub struct AnsiStripStream {
238 pending: String,
241 discarding: Option<State>,
249}
250
251impl AnsiStripStream {
252 #[must_use]
254 pub fn new() -> Self {
255 Self::default()
256 }
257
258 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 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 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 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
322struct SequenceTail {
324 start: usize,
327 state: State,
329 overlong: bool,
331}
332
333fn 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 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 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
369fn 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 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 break;
390 }
391
392 push_visible_byte(&mut output, rest[0]);
393 i += 1;
394 }
395 output
396}
397
398pub fn parse_ansi_sequence(text: &str) -> Option<usize> {
408 let bytes = text.as_bytes();
409 parse_ansi_sequence_bytes(bytes)
410}
411
412pub fn strip_ansi_ascii_only(text: &str) -> String {
420 strip_ansi(text)
421}
422
423#[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 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 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 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 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 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 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 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 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 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 let input = "a\x1b#8b";
618 assert_eq!(strip_ansi(input), "ab");
619
620 let input2 = "a\x1b(Bb";
622 assert_eq!(strip_ansi(input2), "ab");
623
624 let input3 = "a\x1b Fb";
626 assert_eq!(strip_ansi(input3), "ab");
627
628 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 let input = "text\x1b#";
637 assert_eq!(strip_ansi(input), "text");
638 }
639
640 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 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 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 #[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 #[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}