Debian Codegraph @

helix-tui/src/widgets/reflow.rs

raw symbols SCIP
1 use crate::text::StyledGrapheme;
2 use helix_core::line_ending::str_is_line_ending;
3 use helix_core::unicode::width::UnicodeWidthStr;
4 use unicode_segmentation::UnicodeSegmentation;
5
6 const NBSP: &str = "\u{00a0}";
7 const NNBSP: &str = "\u{202f}";
8
9 /// A state machine to pack styled symbols into lines.
10 /// Cannot implement it as Iterator since it yields slices of the internal buffer (need streaming
11 /// iterators for that).
12 pub trait LineComposer<'a> {
13 fn next_line(&mut self) -> Option<(&[StyledGrapheme<'a>], u16)>;
14 }
15
16 /// A state machine that wraps lines on word boundaries.
17 pub struct WordWrapper<'a, 'b> {
18 symbols: &'b mut dyn Iterator<Item = StyledGrapheme<'a>>,
19 max_line_width: u16,
20 current_line: Vec<StyledGrapheme<'a>>,
21 next_line: Vec<StyledGrapheme<'a>>,
22 /// Removes the leading whitespace from lines
23 trim: bool,
24 }
25
26 impl<'a, 'b> WordWrapper<'a, 'b> {
27 pub fn new(
28 symbols: &'b mut dyn Iterator<Item = StyledGrapheme<'a>>,
29 max_line_width: u16,
30 trim: bool,
31 ) -> WordWrapper<'a, 'b> {
32 WordWrapper {
33 symbols,
34 max_line_width,
35 current_line: vec![],
36 next_line: vec![],
37 trim,
38 }
39 }
40 }
41
42 impl<'a> LineComposer<'a> for WordWrapper<'a, '_> {
43 fn next_line(&mut self) -> Option<(&[StyledGrapheme<'a>], u16)> {
44 if self.max_line_width == 0 {
45 return None;
46 }
47 std::mem::swap(&mut self.current_line, &mut self.next_line);
48 self.next_line.truncate(0);
49
50 let mut current_line_width = self
51 .current_line
52 .iter()
53 .map(|StyledGrapheme { symbol, .. }| symbol.width() as u16)
54 .sum();
55
56 let mut symbols_to_last_word_end: usize = 0;
57 let mut width_to_last_word_end: u16 = 0;
58 let mut prev_whitespace = false;
59 let mut symbols_exhausted = true;
60 for StyledGrapheme { symbol, style } in &mut self.symbols {
61 symbols_exhausted = false;
62 let symbol_whitespace =
63 symbol.chars().all(&char::is_whitespace) && symbol != NBSP && symbol != NNBSP;
64
65 // Ignore characters wider that the total max width.
66 if symbol.width() as u16 > self.max_line_width
67 // Skip leading whitespace when trim is enabled.
68 || self.trim && symbol_whitespace && !str_is_line_ending(symbol) && current_line_width == 0
69 {
70 continue;
71 }
72
73 // Break on newline and discard it.
74 if str_is_line_ending(symbol) {
75 if prev_whitespace {
76 current_line_width = width_to_last_word_end;
77 self.current_line.truncate(symbols_to_last_word_end);
78 }
79 break;
80 }
81
82 // Mark the previous symbol as word end.
83 if symbol_whitespace && !prev_whitespace {
84 symbols_to_last_word_end = self.current_line.len();
85 width_to_last_word_end = current_line_width;
86 }
87
88 self.current_line.push(StyledGrapheme { symbol, style });
89 current_line_width += symbol.width() as u16;
90
91 if current_line_width > self.max_line_width {
92 // If there was no word break in the text, wrap at the end of the line.
93 let (truncate_at, truncated_width) = if symbols_to_last_word_end != 0 {
94 (symbols_to_last_word_end, width_to_last_word_end)
95 } else {
96 (self.current_line.len() - 1, self.max_line_width)
97 };
98
99 // Push the remainder to the next line but strip leading whitespace:
100 {
101 let remainder = &self.current_line[truncate_at..];
102 if let Some(remainder_nonwhite) =
103 remainder.iter().position(|StyledGrapheme { symbol, .. }| {
104 !symbol.chars().all(&char::is_whitespace)
105 })
106 {
107 self.next_line
108 .extend_from_slice(&remainder[remainder_nonwhite..]);
109 }
110 }
111 self.current_line.truncate(truncate_at);
112 current_line_width = truncated_width;
113 break;
114 }
115
116 prev_whitespace = symbol_whitespace;
117 }
118
119 // Even if the iterator is exhausted, pass the previous remainder.
120 if symbols_exhausted && self.current_line.is_empty() {
121 None
122 } else {
123 Some((&self.current_line[..], current_line_width))
124 }
125 }
126 }
127
128 /// A state machine that truncates overhanging lines.
129 pub struct LineTruncator<'a, 'b> {
130 symbols: &'b mut dyn Iterator<Item = StyledGrapheme<'a>>,
131 max_line_width: u16,
132 current_line: Vec<StyledGrapheme<'a>>,
133 /// Record the offset to skip render
134 horizontal_offset: u16,
135 }
136
137 impl<'a, 'b> LineTruncator<'a, 'b> {
138 pub fn new(
139 symbols: &'b mut dyn Iterator<Item = StyledGrapheme<'a>>,
140 max_line_width: u16,
141 ) -> LineTruncator<'a, 'b> {
142 LineTruncator {
143 symbols,
144 max_line_width,
145 horizontal_offset: 0,
146 current_line: vec![],
147 }
148 }
149
150 pub fn set_horizontal_offset(&mut self, horizontal_offset: u16) {
151 self.horizontal_offset = horizontal_offset;
152 }
153 }
154
155 impl<'a> LineComposer<'a> for LineTruncator<'a, '_> {
156 fn next_line(&mut self) -> Option<(&[StyledGrapheme<'a>], u16)> {
157 if self.max_line_width == 0 {
158 return None;
159 }
160
161 self.current_line.truncate(0);
162 let mut current_line_width = 0;
163
164 let mut skip_rest = false;
165 let mut symbols_exhausted = true;
166 let mut horizontal_offset = self.horizontal_offset as usize;
167 for StyledGrapheme { symbol, style } in &mut self.symbols {
168 symbols_exhausted = false;
169
170 // Ignore characters wider that the total max width.
171 if symbol.width() as u16 > self.max_line_width {
172 continue;
173 }
174
175 // Break on newline and discard it.
176 if str_is_line_ending(symbol) {
177 break;
178 }
179
180 if current_line_width + symbol.width() as u16 > self.max_line_width {
181 // Exhaust the remainder of the line.
182 skip_rest = true;
183 break;
184 }
185
186 let symbol = if horizontal_offset == 0 {
187 symbol
188 } else {
189 let w = symbol.width();
190 if w > horizontal_offset {
191 let t = trim_offset(symbol, horizontal_offset);
192 horizontal_offset = 0;
193 t
194 } else {
195 horizontal_offset -= w;
196 ""
197 }
198 };
199 current_line_width += symbol.width() as u16;
200 self.current_line.push(StyledGrapheme { symbol, style });
201 }
202
203 if skip_rest {
204 for StyledGrapheme { symbol, .. } in &mut self.symbols {
205 if str_is_line_ending(symbol) {
206 break;
207 }
208 }
209 }
210
211 if symbols_exhausted && self.current_line.is_empty() {
212 None
213 } else {
214 Some((&self.current_line[..], current_line_width))
215 }
216 }
217 }
218
219 /// This function will return a str slice which start at specified offset.
220 /// As src is a unicode str, start offset has to be calculated with each character.
221 fn trim_offset(src: &str, mut offset: usize) -> &str {
222 let mut start = 0;
223 for c in UnicodeSegmentation::graphemes(src, true) {
224 let w = c.width();
225 if w <= offset {
226 offset -= w;
227 start += c.len();
228 } else {
229 break;
230 }
231 }
232 &src[start..]
233 }
234
235 #[cfg(test)]
236 mod test {
237 use super::*;
238 use unicode_segmentation::UnicodeSegmentation;
239
240 enum Composer {
241 WordWrapper { trim: bool },
242 LineTruncator,
243 }
244
245 fn run_composer(which: Composer, text: &str, text_area_width: u16) -> (Vec<String>, Vec<u16>) {
246 let style = Default::default();
247 let mut styled =
248 UnicodeSegmentation::graphemes(text, true).map(|g| StyledGrapheme { symbol: g, style });
249 let mut composer: Box<dyn LineComposer> = match which {
250 Composer::WordWrapper { trim } => {
251 Box::new(WordWrapper::new(&mut styled, text_area_width, trim))
252 }
253 Composer::LineTruncator => Box::new(LineTruncator::new(&mut styled, text_area_width)),
254 };
255 let mut lines = vec![];
256 let mut widths = vec![];
257 while let Some((styled, width)) = composer.next_line() {
258 let line = styled
259 .iter()
260 .map(|StyledGrapheme { symbol, .. }| *symbol)
261 .collect::<String>();
262 assert!(width <= text_area_width);
263 lines.push(line);
264 widths.push(width);
265 }
266 (lines, widths)
267 }
268
269 #[test]
270 fn line_composer_one_line() {
271 let width = 40;
272 for i in 1..width {
273 let text = "a".repeat(i);
274 let (word_wrapper, _) =
275 run_composer(Composer::WordWrapper { trim: true }, &text, width as u16);
276 let (line_truncator, _) = run_composer(Composer::LineTruncator, &text, width as u16);
277 let expected = vec![text];
278 assert_eq!(word_wrapper, expected);
279 assert_eq!(line_truncator, expected);
280 }
281 }
282
283 #[test]
284 fn line_composer_short_lines() {
285 let width = 20;
286 let text =
287 "abcdefg\nhijklmno\npabcdefg\nhijklmn\nopabcdefghijk\nlmnopabcd\n\n\nefghijklmno";
288 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
289 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
290
291 let wrapped: Vec<&str> = text.split('\n').collect();
292 assert_eq!(word_wrapper, wrapped);
293 assert_eq!(line_truncator, wrapped);
294 }
295
296 #[test]
297 fn line_composer_long_word() {
298 let width = 20;
299 let text = "abcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmno";
300 let (word_wrapper, _) =
301 run_composer(Composer::WordWrapper { trim: true }, text, width as u16);
302 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width as u16);
303
304 let wrapped = vec![
305 &text[..width],
306 &text[width..width * 2],
307 &text[width * 2..width * 3],
308 &text[width * 3..],
309 ];
310 assert_eq!(
311 word_wrapper, wrapped,
312 "WordWrapper should detect the line cannot be broken on word boundary and \
313 break it at line width limit."
314 );
315 assert_eq!(line_truncator, vec![&text[..width]]);
316 }
317
318 #[test]
319 fn line_composer_long_sentence() {
320 let width = 20;
321 let text =
322 "abcd efghij klmnopabcd efgh ijklmnopabcdefg hijkl mnopab c d e f g h i j k l m n o";
323 let text_multi_space =
324 "abcd efghij klmnopabcd efgh ijklmnopabcdefg hijkl mnopab c d e f g h i j k l \
325 m n o";
326 let (word_wrapper_single_space, _) =
327 run_composer(Composer::WordWrapper { trim: true }, text, width as u16);
328 let (word_wrapper_multi_space, _) = run_composer(
329 Composer::WordWrapper { trim: true },
330 text_multi_space,
331 width as u16,
332 );
333 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width as u16);
334
335 let word_wrapped = vec![
336 "abcd efghij",
337 "klmnopabcd efgh",
338 "ijklmnopabcdefg",
339 "hijkl mnopab c d e f",
340 "g h i j k l m n o",
341 ];
342 assert_eq!(word_wrapper_single_space, word_wrapped);
343 assert_eq!(word_wrapper_multi_space, word_wrapped);
344
345 assert_eq!(line_truncator, vec![&text[..width]]);
346 }
347
348 #[test]
349 fn line_composer_zero_width() {
350 let width = 0;
351 let text = "abcd efghij klmnopabcd efgh ijklmnopabcdefg hijkl mnopab ";
352 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
353 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
354
355 let expected: Vec<&str> = Vec::new();
356 assert_eq!(word_wrapper, expected);
357 assert_eq!(line_truncator, expected);
358 }
359
360 #[test]
361 fn line_composer_max_line_width_of_1() {
362 let width = 1;
363 let text = "abcd efghij klmnopabcd efgh ijklmnopabcdefg hijkl mnopab ";
364 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
365 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
366
367 let expected: Vec<&str> = UnicodeSegmentation::graphemes(text, true)
368 .filter(|g| g.chars().any(|c| !c.is_whitespace()))
369 .collect();
370 assert_eq!(word_wrapper, expected);
371 assert_eq!(line_truncator, vec!["a"]);
372 }
373
374 #[test]
375 fn line_composer_max_line_width_of_1_double_width_characters() {
376 let width = 1;
377 let text = "コンピュータ上で文字を扱う場合、典型的には文字\naaaによる通信を行う場合にその\
378 両端点では、";
379 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
380 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
381 assert_eq!(word_wrapper, vec!["", "a", "a", "a"]);
382 assert_eq!(line_truncator, vec!["", "a"]);
383 }
384
385 /// Tests WordWrapper with words some of which exceed line length and some not.
386 #[test]
387 fn line_composer_word_wrapper_mixed_length() {
388 let width = 20;
389 let text = "abcd efghij klmnopabcdefghijklmnopabcdefghijkl mnopab cdefghi j klmno";
390 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
391 assert_eq!(
392 word_wrapper,
393 vec![
394 "abcd efghij",
395 "klmnopabcdefghijklmn",
396 "opabcdefghijkl",
397 "mnopab cdefghi j",
398 "klmno",
399 ]
400 )
401 }
402
403 #[test]
404 fn line_composer_double_width_chars() {
405 let width = 20;
406 let text = "コンピュータ上で文字を扱う場合、典型的には文字による通信を行う場合にその両端点\
407 では、";
408 let (word_wrapper, word_wrapper_width) =
409 run_composer(Composer::WordWrapper { trim: true }, text, width);
410 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
411 assert_eq!(line_truncator, vec!["コンピュータ上で文字"]);
412 let wrapped = vec![
413 "コンピュータ上で文字",
414 "を扱う場合、典型的に",
415 "は文字による通信を行",
416 "う場合にその両端点で",
417 "は、",
418 ];
419 assert_eq!(word_wrapper, wrapped);
420 assert_eq!(word_wrapper_width, vec![width, width, width, width, 4]);
421 }
422
423 #[test]
424 fn line_composer_leading_whitespace_removal() {
425 let width = 20;
426 let text = "AAAAAAAAAAAAAAAAAAAA AAA";
427 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
428 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
429 assert_eq!(word_wrapper, vec!["AAAAAAAAAAAAAAAAAAAA", "AAA",]);
430 assert_eq!(line_truncator, vec!["AAAAAAAAAAAAAAAAAAAA"]);
431 }
432
433 /// Tests truncation of leading whitespace.
434 #[test]
435 fn line_composer_lots_of_spaces() {
436 let width = 20;
437 let text = " ";
438 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
439 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
440 assert_eq!(word_wrapper, vec![""]);
441 assert_eq!(line_truncator, vec![" "]);
442 }
443
444 /// Tests an input starting with a letter, followed by spaces - some of the behaviour is
445 /// incidental.
446 #[test]
447 fn line_composer_char_plus_lots_of_spaces() {
448 let width = 20;
449 let text = "a ";
450 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
451 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
452 // What's happening below is: the first line gets consumed, trailing spaces discarded,
453 // after 20 of which a word break occurs (probably shouldn't). The second line break
454 // discards all whitespace. The result should probably be vec!["a"] but it doesn't matter
455 // that much.
456 assert_eq!(word_wrapper, vec!["a", ""]);
457 assert_eq!(line_truncator, vec!["a "]);
458 }
459
460 #[test]
461 fn line_composer_word_wrapper_double_width_chars_mixed_with_spaces() {
462 let width = 20;
463 // Japanese seems not to use spaces but we should break on spaces anyway... We're using it
464 // to test double-width chars.
465 // You are more than welcome to add word boundary detection based of alterations of
466 // hiragana and katakana...
467 // This happens to also be a test case for mixed width because regular spaces are single width.
468 let text = "コンピュ ータ上で文字を扱う場合、 典型的には文 字による 通信を行 う場合にその両端点では、";
469 let (word_wrapper, word_wrapper_width) =
470 run_composer(Composer::WordWrapper { trim: true }, text, width);
471 assert_eq!(
472 word_wrapper,
473 vec![
474 "コンピュ",
475 "ータ上で文字を扱う場",
476 "合、 典型的には文",
477 "字による 通信を行",
478 "う場合にその両端点で",
479 "は、",
480 ]
481 );
482 // Odd-sized lines have a space in them.
483 assert_eq!(word_wrapper_width, vec![8, 20, 17, 17, 20, 4]);
484 }
485
486 /// Ensure words separated by nbsp are wrapped as if they were a single one.
487 #[test]
488 fn line_composer_word_wrapper_nbsp() {
489 let width = 20;
490 let text = "AAAAAAAAAAAAAAA AAAA\u{00a0}AAA";
491 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
492 assert_eq!(word_wrapper, vec!["AAAAAAAAAAAAAAA", "AAAA\u{00a0}AAA",]);
493
494 // Ensure that if the character was a regular space, it would be wrapped differently.
495 let text_space = text.replace('\u{00a0}', " ");
496 let (word_wrapper_space, _) =
497 run_composer(Composer::WordWrapper { trim: true }, &text_space, width);
498 assert_eq!(word_wrapper_space, vec!["AAAAAAAAAAAAAAA AAAA", "AAA",]);
499 }
500
501 #[test]
502 fn line_composer_word_wrapper_nnbsp() {
503 let width = 20;
504 let text = "AAAAAAAAAAAAAAA AAAA\u{202f}AAA";
505 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
506 assert_eq!(word_wrapper, vec!["AAAAAAAAAAAAAAA", "AAAA\u{202f}AAA",]);
507
508 // Ensure that if the character was a regular space, it would be wrapped differently.
509 let text_space = text.replace('\u{202f}', " ");
510 let (word_wrapper_space, _) =
511 run_composer(Composer::WordWrapper { trim: true }, &text_space, width);
512 assert_eq!(word_wrapper_space, vec!["AAAAAAAAAAAAAAA AAAA", "AAA",]);
513 }
514
515 #[test]
516 fn line_composer_word_wrapper_preserve_indentation() {
517 let width = 20;
518 let text = "AAAAAAAAAAAAAAAAAAAA AAA";
519 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: false }, text, width);
520 assert_eq!(word_wrapper, vec!["AAAAAAAAAAAAAAAAAAAA", " AAA",]);
521 }
522
523 #[test]
524 fn line_composer_word_wrapper_preserve_indentation_with_wrap() {
525 let width = 10;
526 let text = "AAA AAA AAAAA AA AAAAAA\n B\n C\n D";
527 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: false }, text, width);
528 assert_eq!(
529 word_wrapper,
530 vec!["AAA AAA", "AAAAA AA", "AAAAAA", " B", " C", " D"]
531 );
532 }
533
534 #[test]
535 fn line_composer_word_wrapper_preserve_indentation_lots_of_whitespace() {
536 let width = 10;
537 let text = " 4 Indent\n must wrap!";
538 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: false }, text, width);
539 assert_eq!(
540 word_wrapper,
541 vec![
542 " ",
543 " 4",
544 "Indent",
545 " ",
546 " must",
547 "wrap!"
548 ]
549 );
550 }
551 }