Debian Codegraph @

src/ansi/mod.rs

raw symbols SCIP
1 mod console_tests;
2 mod iterator;
3
4 use std::borrow::Cow;
5
6 use ansi_term::Style;
7 use itertools::Itertools;
8 use unicode_segmentation::UnicodeSegmentation;
9 use unicode_width::UnicodeWidthStr;
10
11 use iterator::{AnsiElementIterator, Element};
12
13 pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K";
14 pub const ANSI_CSI_CLEAR_TO_BOL: &str = "\x1b[1K";
15 pub const ANSI_SGR_BOLD: &str = "\x1b[1m";
16 pub const ANSI_SGR_RESET: &str = "\x1b[0m";
17 pub const ANSI_SGR_REVERSE: &str = "\x1b[7m";
18 pub const ANSI_SGR_UNDERLINE: &str = "\x1b[4m";
19
20 pub fn strip_ansi_codes(s: &str) -> String {
21 strip_ansi_codes_from_strings_iterator(ansi_strings_iterator(s))
22 }
23
24 pub fn measure_text_width(s: &str) -> usize {
25 ansi_strings_iterator(s).fold(0, |acc, (element, is_ansi)| {
26 acc + if is_ansi { 0 } else { element.width() }
27 })
28 }
29
30 fn truncate_str_impl<'a>(
31 s: &'a str,
32 display_width: usize,
33 tail: &str,
34 fill2w: Option<char>,
35 ) -> Cow<'a, str> {
36 let items = ansi_strings_iterator(s).collect::<Vec<(&str, bool)>>();
37 let width = strip_ansi_codes_from_strings_iterator(items.iter().copied()).width();
38 if width <= display_width {
39 return Cow::from(s);
40 }
41 let result_tail = if !tail.is_empty() {
42 truncate_str_impl(tail, display_width, "", fill2w).to_string()
43 } else {
44 String::new()
45 };
46 let mut used = measure_text_width(&result_tail);
47 let mut result = String::new();
48 for (t, is_ansi) in items {
49 if !is_ansi {
50 for g in t.graphemes(true) {
51 let width_of_grapheme = g.width();
52 if used + width_of_grapheme > display_width {
53 // Handle case "2." mentioned in `truncate_str` docs and fill the
54 // hole left by double-width (2w) truncation.
55 if let Some(fillchar) = fill2w {
56 if width_of_grapheme == 2 && used < display_width {
57 result.push(fillchar);
58 } else if width_of_grapheme > 2 {
59 // Should not happen, this means either unicode_segmentation
60 // graphemes are too wide, or the unicode_width is calculated wrong.
61 // Fallback:
62 debug_assert!(width_of_grapheme <= 2, "strange grapheme width");
63 for _ in 0..display_width.saturating_sub(used) {
64 result.push(fillchar);
65 }
66 }
67 }
68 break;
69 }
70 result.push_str(g);
71 used += width_of_grapheme;
72 }
73 } else {
74 result.push_str(t);
75 }
76 }
77
78 result.push_str(&result_tail);
79 Cow::from(result)
80 }
81
82 /// Truncate string such that `tail` is present as a suffix, preceded by as much of `s` as can be
83 /// displayed in the requested width. Even with `tail` empty the result may not be a prefix of `s`.
84 // Return string constructed as follows:
85 // 1. `display_width` characters are available. If the string fits, return it.
86 //
87 // 2. If a double-width (fullwidth) grapheme has to be cut in the following steps, replace the first
88 // half with a space (' '). If this happens the result is no longer a prefix of the input.
89 //
90 // 3. Contribute graphemes and ANSI escape sequences from `tail` until either (1) `tail` is
91 // exhausted, or (2) the display width of the result would exceed `display_width`.
92 //
93 // 4. If tail was exhausted, then contribute graphemes and ANSI escape sequences from `s` until the
94 // display_width of the result would exceed `display_width`.
95 pub fn truncate_str<'a>(s: &'a str, display_width: usize, tail: &str) -> Cow<'a, str> {
96 truncate_str_impl(s, display_width, tail, Some(' '))
97 }
98
99 /// Truncate string `s` so it fits into `display_width`, ignoring any ANSI escape sequences when
100 /// calculating the width. If a double-width ("fullwidth") grapheme has to be cut, it is omitted and
101 /// the resulting string is *shorter* than `display_width`. But this way the result is always a
102 /// prefix of the input `s`.
103 pub fn truncate_str_short(s: &str, display_width: usize) -> Cow<'_, str> {
104 truncate_str_impl(s, display_width, "", None)
105 }
106
107 pub fn parse_style_sections(s: &str) -> Vec<(ansi_term::Style, &str)> {
108 let mut sections = Vec::new();
109 let mut curr_style = Style::default();
110 for element in AnsiElementIterator::new(s) {
111 match element {
112 Element::Text(start, end) => sections.push((curr_style, &s[start..end])),
113 Element::Sgr(style, _, _) => curr_style = style,
114 _ => {}
115 }
116 }
117 sections
118 }
119
120 // Return the first CSI element, if any, as an `ansi_term::Style`.
121 pub fn parse_first_style(s: &str) -> Option<ansi_term::Style> {
122 AnsiElementIterator::new(s).find_map(|el| match el {
123 Element::Sgr(style, _, _) => Some(style),
124 _ => None,
125 })
126 }
127
128 pub fn string_starts_with_ansi_style_sequence(s: &str) -> bool {
129 AnsiElementIterator::new(s)
130 .next()
131 .map(|el| matches!(el, Element::Sgr(_, _, _)))
132 .unwrap_or(false)
133 }
134
135 /// Return string formed from a byte slice starting at byte position `start`, where the index
136 /// counts bytes in non-ANSI-escape-sequence content only. All ANSI escape sequences in the
137 /// original string are preserved.
138 pub fn ansi_preserving_slice(s: &str, start: usize) -> String {
139 AnsiElementIterator::new(s)
140 .scan(0, |index, element| {
141 // `index` is the index in non-ANSI-escape-sequence content.
142 Some(match element {
143 Element::Sgr(_, a, b) => &s[a..b],
144 Element::Csi(a, b) => &s[a..b],
145 Element::Esc(a, b) => &s[a..b],
146 Element::Osc(a, b) => &s[a..b],
147 Element::Text(a, b) => {
148 let i = *index;
149 *index += b - a;
150 if *index <= start {
151 // This text segment ends before start, so contributes no bytes.
152 ""
153 } else if i > start {
154 // This section starts after `start`, so contributes all its bytes.
155 &s[a..b]
156 } else {
157 // This section contributes those bytes that are >= start
158 &s[(a + start - i)..b]
159 }
160 }
161 })
162 })
163 .join("")
164 }
165
166 /// Return the byte index in `s` of the i-th text byte in `s`. I.e. `i` counts
167 /// bytes in non-ANSI-escape-sequence content only.
168 pub fn ansi_preserving_index(s: &str, i: usize) -> Option<usize> {
169 let mut index = 0;
170 for element in AnsiElementIterator::new(s) {
171 if let Element::Text(a, b) = element {
172 index += b - a;
173 if index > i {
174 return Some(b - (index - i));
175 }
176 }
177 }
178 None
179 }
180
181 fn ansi_strings_iterator(s: &str) -> impl Iterator<Item = (&str, bool)> {
182 AnsiElementIterator::new(s).map(move |el| match el {
183 Element::Sgr(_, i, j) => (&s[i..j], true),
184 Element::Csi(i, j) => (&s[i..j], true),
185 Element::Esc(i, j) => (&s[i..j], true),
186 Element::Osc(i, j) => (&s[i..j], true),
187 Element::Text(i, j) => (&s[i..j], false),
188 })
189 }
190
191 fn strip_ansi_codes_from_strings_iterator<'a>(
192 strings: impl Iterator<Item = (&'a str, bool)>,
193 ) -> String {
194 strings
195 .filter_map(|(el, is_ansi)| if !is_ansi { Some(el) } else { None })
196 .join("")
197 }
198
199 pub fn explain_ansi(line: &str, colorful: bool) -> String {
200 use crate::style::Style;
201
202 parse_style_sections(line)
203 .into_iter()
204 .map(|(ansi_term_style, s)| {
205 let style = Style {
206 ansi_term_style,
207 ..Style::default()
208 };
209 if colorful {
210 format!("({}){}", style.to_painted_string(), style.paint(s))
211 } else {
212 format!("({style}){s}")
213 }
214 })
215 .collect()
216 }
217
218 #[cfg(test)]
219 mod tests {
220 use unicode_width::UnicodeWidthStr;
221
222 // Note that src/ansi/console_tests.rs contains additional test coverage for this module.
223 use super::{
224 ansi_preserving_index, ansi_preserving_slice, measure_text_width, parse_first_style,
225 string_starts_with_ansi_style_sequence, strip_ansi_codes, truncate_str, truncate_str_short,
226 };
227
228 #[test]
229 fn test_strip_ansi_codes() {
230 for s in &["src/ansi/mod.rs", "バー", "src/ansi/modバー.rs"] {
231 assert_eq!(strip_ansi_codes(s), *s);
232 }
233 assert_eq!(strip_ansi_codes("\x1b[31mバー\x1b[0m"), "バー");
234 }
235
236 #[test]
237 fn test_measure_text_width() {
238 assert_eq!(measure_text_width("src/ansi/mod.rs"), 15);
239 assert_eq!(measure_text_width("バー"), 4);
240 assert_eq!(measure_text_width("src/ansi/modバー.rs"), 19);
241 assert_eq!(measure_text_width("\x1b[31mバー\x1b[0m"), 4);
242 assert_eq!(measure_text_width("a\nb\n"), 2);
243 }
244
245 #[test]
246 fn test_strip_ansi_codes_osc_hyperlink() {
247 assert_eq!(strip_ansi_codes("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/mod.rs\x1b]8;;\x1b\\\x1b[0m\n"),
248 "src/ansi/mod.rs\n");
249 }
250
251 #[test]
252 fn test_measure_text_width_osc_hyperlink() {
253 assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/mod.rs\x1b]8;;\x1b\\\x1b[0m"),
254 measure_text_width("src/ansi/mod.rs"));
255 }
256
257 #[test]
258 fn test_measure_text_width_osc_hyperlink_non_ascii() {
259 assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"),
260 measure_text_width("src/ansi/modバー.rs"));
261 }
262
263 #[test]
264 fn test_parse_first_style() {
265 let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n";
266 let style = parse_first_style(minus_line_from_unconfigured_git);
267 let expected_style = ansi_term::Style {
268 foreground: Some(ansi_term::Color::Red),
269 ..ansi_term::Style::default()
270 };
271 assert_eq!(Some(expected_style), style);
272 }
273
274 #[test]
275 fn test_string_starts_with_ansi_escape_sequence() {
276 assert!(!string_starts_with_ansi_style_sequence(""));
277 assert!(!string_starts_with_ansi_style_sequence("-"));
278 assert!(string_starts_with_ansi_style_sequence(
279 "\x1b[31m-XXX\x1b[m\n"
280 ));
281 assert!(string_starts_with_ansi_style_sequence("\x1b[32m+XXX"));
282 }
283
284 #[test]
285 fn test_ansi_preserving_slice_and_index() {
286 assert_eq!(ansi_preserving_slice("", 0), "");
287 assert_eq!(ansi_preserving_index("", 0), None);
288
289 assert_eq!(ansi_preserving_slice("0", 0), "0");
290 assert_eq!(ansi_preserving_index("0", 0), Some(0));
291
292 assert_eq!(ansi_preserving_slice("0", 1), "");
293 assert_eq!(ansi_preserving_index("0", 1), None);
294
295 let raw_string = "\x1b[1;35m0123456789\x1b[0m";
296 assert_eq!(
297 ansi_preserving_slice(raw_string, 1),
298 "\x1b[1;35m123456789\x1b[0m"
299 );
300 assert_eq!(ansi_preserving_slice(raw_string, 7), "\x1b[1;35m789\x1b[0m");
301 assert_eq!(ansi_preserving_index(raw_string, 0), Some(7));
302 assert_eq!(ansi_preserving_index(raw_string, 1), Some(8));
303 assert_eq!(ansi_preserving_index(raw_string, 7), Some(14));
304
305 let raw_string = "\x1b[1;36m0\x1b[m\x1b[1;36m123456789\x1b[m\n";
306 assert_eq!(
307 ansi_preserving_slice(raw_string, 1),
308 "\x1b[1;36m\x1b[m\x1b[1;36m123456789\x1b[m\n"
309 );
310 assert_eq!(ansi_preserving_index(raw_string, 0), Some(7));
311 assert_eq!(ansi_preserving_index(raw_string, 1), Some(18));
312 assert_eq!(ansi_preserving_index(raw_string, 7), Some(24));
313
314 let raw_string = "\x1b[1;36m012345\x1b[m\x1b[1;36m6789\x1b[m\n";
315 assert_eq!(
316 ansi_preserving_slice(raw_string, 3),
317 "\x1b[1;36m345\x1b[m\x1b[1;36m6789\x1b[m\n"
318 );
319 assert_eq!(ansi_preserving_index(raw_string, 0), Some(7));
320 assert_eq!(ansi_preserving_index(raw_string, 1), Some(8));
321 assert_eq!(ansi_preserving_index(raw_string, 7), Some(24));
322 }
323
324 #[test]
325 fn test_truncate_str() {
326 assert_eq!(truncate_str("1", 1, ""), "1");
327 assert_eq!(truncate_str("12", 1, ""), "1");
328 assert_eq!(truncate_str("123", 2, "s"), "1s");
329 assert_eq!(truncate_str("123", 2, "→"), "1→");
330 assert_eq!(truncate_str("12ݶ", 1, "ݶ"), "ݶ");
331 }
332
333 #[test]
334 fn test_truncate_str_at_double_width_grapheme() {
335 let one_double_four = "1#4";
336 let double = "/";
337 assert_eq!(one_double_four.width(), 4);
338 assert_eq!(double.width(), 2);
339
340 assert_eq!(truncate_str(one_double_four, 1, ""), "1");
341 assert_eq!(truncate_str(one_double_four, 2, ""), "1 ");
342 assert_eq!(truncate_str(one_double_four, 3, ""), "1#");
343 assert_eq!(truncate_str(one_double_four, 4, ""), "1#4");
344
345 assert_eq!(truncate_str_short(one_double_four, 1), "1");
346 assert_eq!(truncate_str_short(one_double_four, 2), "1"); // !!
347 assert_eq!(truncate_str_short(one_double_four, 3), "1#");
348 assert_eq!(truncate_str_short(one_double_four, 4), "1#4");
349
350 assert_eq!(truncate_str(one_double_four, 1, double), " ");
351 assert_eq!(truncate_str(one_double_four, 2, double), "/");
352 assert_eq!(truncate_str(one_double_four, 3, double), "1/");
353 assert_eq!(truncate_str(one_double_four, 4, double), "1#4");
354
355 assert_eq!(truncate_str(one_double_four, 0, ""), "");
356 assert_eq!(truncate_str(one_double_four, 0, double), "");
357 assert_eq!(truncate_str_short(one_double_four, 0), "");
358
359 assert_eq!(truncate_str(double, 0, double), "");
360 assert_eq!(truncate_str(double, 1, double), " ");
361 assert_eq!(truncate_str(double, 2, double), double);
362
363 assert_eq!(truncate_str_short(double, 0), "");
364 assert_eq!(truncate_str_short(double, 1), "");
365 assert_eq!(truncate_str_short(double, 2), double);
366 }
367 }