Debian Codegraph @

src/utils/formatting/content_split/custom_styling.rs

raw symbols SCIP
1 use ansi_str::AnsiStr;
2 use unicode_segmentation::UnicodeSegmentation;
3 use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
4
5 const ANSI_RESET: &str = "\u{1b}[0m";
6
7 /// Returns printed length of string, takes into account escape codes
8 #[inline(always)]
9 pub fn measure_text_width(s: &str) -> usize {
10 s.ansi_strip().width()
11 }
12
13 /// Split the line by the given deliminator without breaking ansi codes that contain the delimiter
14 pub fn split_line_by_delimiter(line: &str, delimiter: char) -> Vec<String> {
15 let mut lines: Vec<String> = Vec::new();
16 let mut current_line = String::default();
17
18 // Iterate over line, splitting text with delimiter
19 let iter = console::AnsiCodeIterator::new(line);
20 for (str_slice, is_esc) in iter {
21 if is_esc {
22 current_line.push_str(str_slice);
23 } else {
24 let mut split = str_slice.split(delimiter);
25
26 // Text before first delimiter (if any) belongs to previous line
27 let first = split
28 .next()
29 .expect("split always produces at least one value");
30 current_line.push_str(first);
31
32 // Text after each delimiter goes to new line.
33 for text in split {
34 lines.push(current_line);
35 current_line = text.to_string();
36 }
37 }
38 }
39 lines.push(current_line);
40 fix_style_in_split_str(lines.as_mut());
41 lines
42 }
43
44 /// Splits a long word at a given character width. Inserting the needed ansi codes to preserve
45 /// style.
46 pub fn split_long_word(allowed_width: usize, word: &str) -> (String, String) {
47 // A buffer for the first half of the split str, which will take up at most `allowed_len`
48 // characters when printed to the terminal.
49 let mut head = String::with_capacity(word.len());
50 // A buffer for the second half of the split str
51 let mut tail = String::with_capacity(word.len());
52 // Tracks the len() of head
53 let mut head_len = 0;
54 // Tracks the len() of head, sans trailing ansi escape codes
55 let mut head_len_last = 0;
56 // Count of *non-trailing* escape codes in the buffer.
57 let mut escape_count_last = 0;
58 // A buffer for the escape codes that exist in the str before the split.
59 let mut escapes = Vec::new();
60
61 // Iterate over segments of the input string, each segment is either a singe escape code or
62 // block of text containing no escape codes. Add text and escape codes to the head buffer,
63 // keeping track of printable length and what ansi codes are active, until there is no more room
64 // in allowed_width. If the str was split at a point with active escape-codes, add the ansi
65 // reset code to the end of head, and the list of active escape codes to the beginning of tail.
66 let mut iter = console::AnsiCodeIterator::new(word);
67 for (str_slice, is_esc) in iter.by_ref() {
68 if is_esc {
69 escapes.push(str_slice);
70 // If the code is reset, that means all current codes in the buffer can be ignored.
71 if str_slice == ANSI_RESET {
72 escapes.clear();
73 }
74 }
75
76 let slice_len = match is_esc {
77 true => 0,
78 false => str_slice.width(),
79 };
80
81 if head_len + slice_len <= allowed_width {
82 head.push_str(str_slice);
83 head_len += slice_len;
84
85 if !is_esc {
86 // allows popping unneeded escape codes later
87 head_len_last = head.len();
88 escape_count_last = escapes.len();
89 }
90 } else {
91 assert!(!is_esc);
92 let mut graphmes = str_slice.graphemes(true).peekable();
93 while let Some(c) = graphmes.peek() {
94 let character_width = c.width();
95 if allowed_width < head_len + character_width {
96 break;
97 }
98
99 head_len += character_width;
100 let c = graphmes.next().unwrap();
101 head.push_str(c);
102
103 // c is not escape code
104 head_len_last = head.len();
105 escape_count_last = escapes.len();
106 }
107
108 // cut off dangling escape codes since they should have no effect
109 head.truncate(head_len_last);
110 if escape_count_last != 0 {
111 head.push_str(ANSI_RESET);
112 }
113
114 for esc in escapes {
115 tail.push_str(esc);
116 }
117 let remaining: String = graphmes.collect();
118 tail.push_str(&remaining);
119 break;
120 }
121 }
122
123 iter.for_each(|s| tail.push_str(s.0));
124 (head, tail)
125 }
126
127 /// Fixes ansi escape codes in a split string
128 /// 1. Adds reset code to the end of each substring if needed.
129 /// 2. Keeps track of previous substring's escape codes and inserts them in later substrings to
130 /// continue style
131 pub fn fix_style_in_split_str(words: &mut [String]) {
132 let mut escapes: Vec<String> = Vec::new();
133
134 for word in words {
135 // before we modify the escape list, make a copy
136 let prepend = if !escapes.is_empty() {
137 Some(escapes.join(""))
138 } else {
139 None
140 };
141
142 // add escapes in word to escape list
143 let iter = console::AnsiCodeIterator::new(word)
144 .filter(|(_, is_esc)| *is_esc)
145 .map(|v| v.0);
146 for esc in iter {
147 if esc == ANSI_RESET {
148 escapes.clear()
149 } else {
150 escapes.push(esc.to_string())
151 }
152 }
153
154 // insert previous esc sequences at the beginning of the segment
155 if let Some(prepend) = prepend {
156 word.insert_str(0, &prepend);
157 }
158
159 // if there are active escape sequences, we need to append reset
160 if !escapes.is_empty() {
161 word.push_str(ANSI_RESET);
162 }
163 }
164 }
165
166 #[cfg(test)]
167 mod test {
168 #[test]
169 fn ansi_aware_split_test() {
170 use super::split_line_by_delimiter;
171
172 let text = "\u{1b}[1m head [ middle [ tail \u{1b}[0m[ after";
173 let split = split_line_by_delimiter(text, '[');
174
175 assert_eq!(
176 split,
177 [
178 "\u{1b}[1m head \u{1b}[0m",
179 "\u{1b}[1m middle \u{1b}[0m",
180 "\u{1b}[1m tail \u{1b}[0m",
181 " after"
182 ]
183 )
184 }
185
186 // TODO: Figure out why this fails with the custom_styling feature enabled.
187 #[test]
188 #[cfg(not(feature = "custom_styling"))]
189 fn measure_text_width_osc8_test() {
190 use unicode_width::UnicodeWidthStr;
191
192 use super::measure_text_width;
193
194 let text = "\x1b]8;;https://github.com\x1b\\This is a link\x1b]8;;\x1b";
195 let width = measure_text_width(text);
196
197 assert_eq!(text.width(), 41);
198 assert_eq!(width, 14);
199 }
200 }