1use crate::ansi_codes::{BEL_BYTE, ESC_BYTE};
6use memchr::memchr;
7
8const ESC: u8 = ESC_BYTE;
9const BEL: u8 = BEL_BYTE;
10const DEL: u8 = 0x7f;
11const C1_ST: u8 = 0x9c;
12const C1_DCS: u8 = 0x90;
13const C1_SOS: u8 = 0x98;
14const C1_CSI: u8 = 0x9b;
15const C1_OSC: u8 = 0x9d;
16const C1_PM: u8 = 0x9e;
17const C1_APC: u8 = 0x9f;
18const CAN: u8 = 0x18;
19const SUB: u8 = 0x1a;
20const MAX_STRING_SEQUENCE_BYTES: usize = 4096;
21const MAX_CSI_SEQUENCE_BYTES: usize = 64;
22
23#[derive(Clone, Copy)]
24enum StringSequenceTerminator {
25 StOnly,
26 BelOrSt,
27}
28
29impl StringSequenceTerminator {
30 #[inline]
31 const fn allows_bel(self) -> bool {
32 matches!(self, Self::BelOrSt)
33 }
34}
35
36#[inline]
37fn parse_c1_at(bytes: &[u8], start: usize) -> Option<(u8, usize)> {
38 let first = *bytes.get(start)?;
39 if (0x80..=0x9f).contains(&first) {
40 return Some((first, 1));
41 }
42 None
43}
44
45#[inline]
46fn parse_csi(bytes: &[u8], start: usize) -> Option<usize> {
47 let mut index = start;
53 let mut phase = 0u8; let mut consumed = 0usize;
55
56 while index < bytes.len() {
57 let byte = bytes[index];
58 if byte == ESC {
59 return Some(index);
61 }
62 if byte == CAN || byte == SUB {
63 return Some(index + 1);
65 }
66
67 consumed += 1;
68 if consumed > MAX_CSI_SEQUENCE_BYTES {
69 return Some(index + 1);
71 }
72
73 if phase == 0 && (0x30..=0x3f).contains(&byte) {
74 index += 1;
75 continue;
76 }
77 if (0x20..=0x2f).contains(&byte) {
78 phase = 1;
79 index += 1;
80 continue;
81 }
82 if (0x40..=0x7e).contains(&byte) {
83 return Some(index + 1);
84 }
85
86 return Some(index);
88 }
89
90 None
91}
92
93#[inline]
94fn parse_string_sequence(
95 bytes: &[u8],
96 start: usize,
97 terminator: StringSequenceTerminator,
98) -> Option<usize> {
99 let mut consumed = 0usize;
100 for index in start..bytes.len() {
101 if bytes[index] == ESC && !(index + 1 < bytes.len() && bytes[index + 1] == b'\\') {
102 return Some(index);
104 }
105 if bytes[index] == CAN || bytes[index] == SUB {
106 return Some(index + 1);
107 }
108
109 if let Some((c1, len)) = parse_c1_at(bytes, index)
110 && c1 == C1_ST
111 {
112 return Some(index + len);
113 }
114
115 match bytes[index] {
116 BEL if terminator.allows_bel() => return Some(index + 1),
117 ESC if index + 1 < bytes.len() && bytes[index + 1] == b'\\' => return Some(index + 2),
118 _ => {}
119 }
120
121 consumed += 1;
122 if consumed > MAX_STRING_SEQUENCE_BYTES {
123 return Some(index + 1);
125 }
126 }
127 None
128}
129
130#[inline]
131fn push_visible_byte(output: &mut Vec<u8>, byte: u8) {
132 if matches!(byte, b'\n' | b'\r' | b'\t') || !(byte < 32 || byte == DEL) {
133 output.push(byte);
134 }
135}
136
137#[inline]
138fn parse_ansi_sequence_bytes(bytes: &[u8]) -> Option<usize> {
139 if bytes.is_empty() {
140 return None;
141 }
142
143 if let Some((c1, c1_len)) = parse_c1_at(bytes, 0) {
144 return match c1 {
145 C1_CSI => parse_csi(bytes, c1_len),
146 C1_OSC => parse_string_sequence(bytes, c1_len, StringSequenceTerminator::BelOrSt),
147 C1_DCS | C1_SOS | C1_PM | C1_APC => {
148 parse_string_sequence(bytes, c1_len, StringSequenceTerminator::StOnly)
149 }
150 _ => Some(c1_len),
151 };
152 }
153
154 match bytes[0] {
155 ESC => {
156 if bytes.len() < 2 {
157 return None;
158 }
159
160 match bytes[1] {
161 b'[' => parse_csi(bytes, 2),
162 b']' => parse_string_sequence(bytes, 2, StringSequenceTerminator::BelOrSt),
163 b'P' | b'^' | b'_' | b'X' => {
164 parse_string_sequence(bytes, 2, StringSequenceTerminator::StOnly)
165 }
166 b' ' | b'#' | b'%' | b'(' | b')' | b'*' | b'+' => {
172 if bytes.len() > 2 {
173 Some(3)
174 } else {
175 None
176 }
177 }
178 next if next < 128 => Some(2),
179 _ => Some(1),
180 }
181 }
182 _ => None,
183 }
184}
185
186pub fn strip_ansi(text: &str) -> String {
188 let mut output = Vec::with_capacity(text.len());
189 let bytes = text.as_bytes();
190 let mut i = 0;
191
192 while i < bytes.len() {
193 let next_esc = memchr(ESC, &bytes[i..]).map_or(bytes.len(), |offset| i + offset);
194 while i < next_esc {
195 push_visible_byte(&mut output, bytes[i]);
196 i += 1;
197 }
198
199 if i >= bytes.len() {
200 break;
201 }
202
203 if let Some(len) = parse_ansi_sequence_bytes(&bytes[i..]) {
204 i += len;
205 continue;
206 } else {
207 break;
209 }
210 }
211
212 String::from_utf8_lossy(&output).into_owned()
213}
214
215pub fn strip_ansi_bytes(input: &[u8]) -> Vec<u8> {
219 let mut output = Vec::with_capacity(input.len());
220 let bytes = input;
221 let mut i = 0;
222
223 while i < bytes.len() {
224 if (bytes[i] == ESC || parse_c1_at(bytes, i).is_some())
225 && let Some(len) = parse_ansi_sequence_bytes(&bytes[i..])
226 {
227 i += len;
228 continue;
229 }
230 if bytes[i] == ESC || parse_c1_at(bytes, i).is_some() {
231 break;
233 }
234
235 push_visible_byte(&mut output, bytes[i]);
236 i += 1;
237 }
238 output
239}
240
241pub fn parse_ansi_sequence(text: &str) -> Option<usize> {
243 let bytes = text.as_bytes();
244 parse_ansi_sequence_bytes(bytes)
245}
246
247pub fn strip_ansi_ascii_only(text: &str) -> String {
249 let mut output = String::with_capacity(text.len());
250 let bytes = text.as_bytes();
251 let mut search_start = 0;
252 let mut copy_start = 0;
253
254 while let Some(offset) = memchr(ESC, &bytes[search_start..]) {
255 let esc_index = search_start + offset;
256 if let Some(len) = parse_ansi_sequence_bytes(&bytes[esc_index..]) {
257 if copy_start < esc_index {
258 output.push_str(&text[copy_start..esc_index]);
259 }
260 copy_start = esc_index + len;
261 search_start = copy_start;
262 } else {
263 search_start = esc_index + 1;
264 }
265 }
266
267 if copy_start < text.len() {
268 output.push_str(&text[copy_start..]);
269 }
270
271 output
272}
273
274#[must_use]
276pub fn contains_unicode(text: &str) -> bool {
277 text.bytes().any(|b| b >= 0x80)
278}
279
280#[cfg(test)]
281mod tests {
282 use super::{CAN, SUB, strip_ansi, strip_ansi_ascii_only};
283
284 #[test]
285 fn strips_esc_csi_sequences() {
286 let input = "a\x1b[31mred\x1b[0mz";
287 assert_eq!(strip_ansi(input), "aredz");
288 assert_eq!(strip_ansi_ascii_only(input), "aredz");
289 }
290
291 #[test]
292 fn utf8_encoded_c1_is_not_reprocessed_as_control() {
293 let input = "a\u{009b}31mred";
295 assert_eq!(strip_ansi(input), input);
296 }
297
298 #[test]
299 fn strip_removes_ascii_del_control() {
300 let input = format!("a{}b", char::from(0x7f));
301 assert_eq!(strip_ansi(&input), "ab");
302 }
303
304 #[test]
305 fn csi_aborts_on_esc_then_new_sequence_parses() {
306 let input = "a\x1b[31\x1b[32mgreen\x1b[0mz";
307 assert_eq!(strip_ansi(input), "agreenz");
308 }
309
310 #[test]
311 fn csi_aborts_on_can_and_sub() {
312 let can = format!("a\x1b[31{}b", char::from(CAN));
313 let sub = format!("a\x1b[31{}b", char::from(SUB));
314 assert_eq!(strip_ansi(&can), "ab");
315 assert_eq!(strip_ansi(&sub), "ab");
316 }
317
318 #[test]
319 fn osc_aborts_on_esc_non_st() {
320 let input = "a\x1b]title\x1b[31mred\x1b[0mz";
321 assert_eq!(strip_ansi(input), "aredz");
322 }
323
324 #[test]
325 fn incomplete_sequence_drops_tail() {
326 let input = "text\x1b[31";
327 assert_eq!(strip_ansi(input), "text");
328 }
329
330 #[test]
331 fn ascii_only_incomplete_sequence_keeps_tail() {
332 let input = "text\x1b[31";
333 assert_eq!(strip_ansi_ascii_only(input), input);
334 }
335
336 #[test]
337 fn strips_common_progress_redraw_sequences() {
338 let input = "\r\x1b[2KProgress 10%\r\x1b[2KDone\n";
341 assert_eq!(strip_ansi(input), "\rProgress 10%\rDone\n");
342 }
343
344 #[test]
345 fn strips_cursor_navigation_sequences() {
346 let input = "left\x1b[1D!\nup\x1b[1Arow";
347 assert_eq!(strip_ansi(input), "left!\nuprow");
348 }
349
350 #[test]
351 fn strip_ansi_bytes_supports_raw_c1_csi() {
352 let input = [
353 b'a', 0x9b, b'3', b'1', b'm', b'r', b'e', b'd', 0x9b, b'0', b'm', b'z',
354 ];
355 let out = super::strip_ansi_bytes(&input);
356 assert_eq!(out, b"aredz");
357 }
358
359 #[test]
360 fn strip_ansi_bytes_supports_raw_c1_osc_and_st() {
361 let mut input = b"pre".to_vec();
362 input.extend_from_slice(&[0x9d]);
363 input.extend_from_slice(b"8;;https://example.com");
364 input.extend_from_slice(&[0x9c]);
365 input.extend_from_slice(b"link");
366 input.extend_from_slice(&[0x9d]);
367 input.extend_from_slice(b"8;;");
368 input.extend_from_slice(&[0x9c]);
369 input.extend_from_slice(b"post");
370 let out = super::strip_ansi_bytes(&input);
371 assert_eq!(out, b"prelinkpost");
372 }
373
374 #[test]
375 fn csi_respects_parameter_intermediate_final_grammar() {
376 let input = "a\x1b[1;2 mred\x1b[0mz";
378 assert_eq!(strip_ansi(input), "aredz");
379 }
380
381 #[test]
382 fn malformed_csi_does_not_consume_following_text() {
383 let malformed = format!("a\x1b[12{}visible", char::from(0x10));
385 assert_eq!(strip_ansi(&malformed), "avisible");
386 }
387
388 #[test]
389 fn strips_wikipedia_sgr_8bit_color_pattern() {
390 let input = "x\x1b[38;5;196mred\x1b[0my";
391 assert_eq!(strip_ansi(input), "xredy");
392 }
393
394 #[test]
395 fn strips_wikipedia_sgr_truecolor_pattern() {
396 let input = "x\x1b[48;2;12;34;56mblock\x1b[0my";
397 assert_eq!(strip_ansi(input), "xblocky");
398 }
399
400 #[test]
401 fn strips_wikipedia_osc8_hyperlink_pattern() {
402 let input = "go \x1b]8;;https://example.com\x1b\\here\x1b]8;;\x1b\\ now";
403 assert_eq!(strip_ansi(input), "go here now");
404 }
405
406 #[test]
407 fn strips_dec_private_mode_csi() {
408 let input = "a\x1b[?25lb\x1b[?25hc";
409 assert_eq!(strip_ansi(input), "abc");
410 }
411
412 #[test]
413 fn strips_three_byte_esc_sequences() {
414 let input = "a\x1b#8b";
416 assert_eq!(strip_ansi(input), "ab");
417
418 let input2 = "a\x1b(Bb";
420 assert_eq!(strip_ansi(input2), "ab");
421
422 let input3 = "a\x1b Fb";
424 assert_eq!(strip_ansi(input3), "ab");
425
426 let input4 = "a\x1b%Gb";
428 assert_eq!(strip_ansi(input4), "ab");
429 }
430
431 #[test]
432 fn incomplete_three_byte_esc_sequence_drops_tail() {
433 let input = "text\x1b#";
435 assert_eq!(strip_ansi(input), "text");
436 }
437}