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).unwrap_or_else(|error| String::from_utf8_lossy(error.as_bytes()).into_owned())
221}
222
223pub fn strip_ansi(text: &str) -> String {
229 strip_plain(text)
230}
231
232#[derive(Default)]
241pub struct AnsiStripStream {
242 pending: String,
245 discarding: Option<State>,
253}
254
255impl AnsiStripStream {
256 #[must_use]
258 pub fn new() -> Self {
259 Self::default()
260 }
261
262 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 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 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 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
326struct SequenceTail {
328 start: usize,
331 state: State,
333 overlong: bool,
335}
336
337fn 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 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 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
373fn 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 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 break;
394 }
395
396 push_visible_byte(&mut output, rest[0]);
397 i += 1;
398 }
399 output
400}
401
402pub fn parse_ansi_sequence(text: &str) -> Option<usize> {
412 let bytes = text.as_bytes();
413 parse_ansi_sequence_bytes(bytes)
414}
415
416pub fn strip_ansi_ascii_only(text: &str) -> String {
424 strip_ansi(text)
425}
426
427#[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 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 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 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 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 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 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 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 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 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 let input = "a\x1b#8b";
622 assert_eq!(strip_ansi(input), "ab");
623
624 let input2 = "a\x1b(Bb";
626 assert_eq!(strip_ansi(input2), "ab");
627
628 let input3 = "a\x1b Fb";
630 assert_eq!(strip_ansi(input3), "ab");
631
632 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 let input = "text\x1b#";
641 assert_eq!(strip_ansi(input), "text");
642 }
643
644 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 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 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 #[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 #[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}