1use crate::text::StyledGrapheme;
2use helix_core::line_ending::str_is_line_ending;
3use helix_core::unicode::width::UnicodeWidthStr;
4use unicode_segmentation::UnicodeSegmentation;
6const NBSP: &str = "\u{00a0}";
8/// A state machine to pack styled symbols into lines.
9/// Cannot implement it as Iterator since it yields slices of the internal buffer (need streaming
10/// iterators for that).
11pub trait LineComposer<'a> {
12 fn next_line(&mut self) -> Option<(&[StyledGrapheme<'a>], u16)>;
15/// A state machine that wraps lines on word boundaries.
16pub struct WordWrapper<'a, 'b> {
17 symbols: &'b mut dyn Iterator<Item = StyledGrapheme<'a>>,
19 current_line: Vec<StyledGrapheme<'a>>,
20 next_line: Vec<StyledGrapheme<'a>>,
21 /// Removes the leading whitespace from lines
25impl<'a, 'b> WordWrapper<'a, 'b> {
27 symbols: &'b mut dyn Iterator<Item = StyledGrapheme<'a>>,
30 ) -> WordWrapper<'a, 'b> {
41impl<'a, 'b> LineComposer<'a> for WordWrapper<'a, 'b> {
42 fn next_line(&mut self) -> Option<(&[StyledGrapheme<'a>], u16)> {
43 if self.max_line_width == 0 {
46 std::mem::swap(&mut self.current_line, &mut self.next_line);
47 self.next_line.truncate(0);
49 let mut current_line_width = self
52 .map(|StyledGrapheme { symbol, .. }| symbol.width() as u16)
55 let mut symbols_to_last_word_end: usize = 0;
56 let mut width_to_last_word_end: u16 = 0;
57 let mut prev_whitespace = false;
58 let mut symbols_exhausted = true;
59 for StyledGrapheme { symbol, style } in &mut self.symbols {
60 symbols_exhausted = false;
61 let symbol_whitespace = symbol.chars().all(&char::is_whitespace) && symbol != NBSP;
63 // Ignore characters wider that the total max width.
64 if symbol.width() as u16 > self.max_line_width
65 // Skip leading whitespace when trim is enabled.
66 || self.trim && symbol_whitespace && !str_is_line_ending(symbol) && current_line_width == 0
71 // Break on newline and discard it.
72 if str_is_line_ending(symbol) {
74 current_line_width = width_to_last_word_end;
75 self.current_line.truncate(symbols_to_last_word_end);
80 // Mark the previous symbol as word end.
81 if symbol_whitespace && !prev_whitespace {
82 symbols_to_last_word_end = self.current_line.len();
83 width_to_last_word_end = current_line_width;
86 self.current_line.push(StyledGrapheme { symbol, style });
87 current_line_width += symbol.width() as u16;
89 if current_line_width > self.max_line_width {
90 // If there was no word break in the text, wrap at the end of the line.
91 let (truncate_at, truncated_width) = if symbols_to_last_word_end != 0 {
92 (symbols_to_last_word_end, width_to_last_word_end)
94 (self.current_line.len() - 1, self.max_line_width)
97 // Push the remainder to the next line but strip leading whitespace:
99 let remainder = &self.current_line[truncate_at..];
100 if let Some(remainder_nonwhite) =
101 remainder.iter().position(|StyledGrapheme { symbol, .. }| {
102 !symbol.chars().all(&char::is_whitespace)
106 .extend_from_slice(&remainder[remainder_nonwhite..]);
109 self.current_line.truncate(truncate_at);
110 current_line_width = truncated_width;
114 prev_whitespace = symbol_whitespace;
117 // Even if the iterator is exhausted, pass the previous remainder.
118 if symbols_exhausted && self.current_line.is_empty() {
121 Some((&self.current_line[..], current_line_width))
126/// A state machine that truncates overhanging lines.
127pub struct LineTruncator<'a, 'b> {
128 symbols: &'b mut dyn Iterator<Item = StyledGrapheme<'a>>,
130 current_line: Vec<StyledGrapheme<'a>>,
131 /// Record the offet to skip render
132 horizontal_offset: u16,
135impl<'a, 'b> LineTruncator<'a, 'b> {
137 symbols: &'b mut dyn Iterator<Item = StyledGrapheme<'a>>,
139 ) -> LineTruncator<'a, 'b> {
143 horizontal_offset: 0,
144 current_line: vec![],
148 pub fn set_horizontal_offset(&mut self, horizontal_offset: u16) {
149 self.horizontal_offset = horizontal_offset;
153impl<'a, 'b> LineComposer<'a> for LineTruncator<'a, 'b> {
154 fn next_line(&mut self) -> Option<(&[StyledGrapheme<'a>], u16)> {
155 if self.max_line_width == 0 {
159 self.current_line.truncate(0);
160 let mut current_line_width = 0;
162 let mut skip_rest = false;
163 let mut symbols_exhausted = true;
164 let mut horizontal_offset = self.horizontal_offset as usize;
165 for StyledGrapheme { symbol, style } in &mut self.symbols {
166 symbols_exhausted = false;
168 // Ignore characters wider that the total max width.
169 if symbol.width() as u16 > self.max_line_width {
173 // Break on newline and discard it.
174 if str_is_line_ending(symbol) {
178 if current_line_width + symbol.width() as u16 > self.max_line_width {
179 // Exhaust the remainder of the line.
184 let symbol = if horizontal_offset == 0 {
187 let w = symbol.width();
188 if w > horizontal_offset {
189 let t = trim_offset(symbol, horizontal_offset);
190 horizontal_offset = 0;
193 horizontal_offset -= w;
197 current_line_width += symbol.width() as u16;
198 self.current_line.push(StyledGrapheme { symbol, style });
202 for StyledGrapheme { symbol, .. } in &mut self.symbols {
203 if str_is_line_ending(symbol) {
209 if symbols_exhausted && self.current_line.is_empty() {
212 Some((&self.current_line[..], current_line_width))
217/// This function will return a str slice which start at specified offset.
218/// As src is a unicode str, start offset has to be calculated with each character.
219fn trim_offset(src: &str, mut offset: usize) -> &str {
221 for c in UnicodeSegmentation::graphemes(src, true) {
236 use unicode_segmentation::UnicodeSegmentation;
239 WordWrapper { trim: bool },
243 fn run_composer(which: Composer, text: &str, text_area_width: u16) -> (Vec<String>, Vec<u16>) {
244 let style = Default::default();
246 UnicodeSegmentation::graphemes(text, true).map(|g| StyledGrapheme { symbol: g, style });
247 let mut composer: Box<dyn LineComposer> = match which {
248 Composer::WordWrapper { trim } => {
249 Box::new(WordWrapper::new(&mut styled, text_area_width, trim))
251 Composer::LineTruncator => Box::new(LineTruncator::new(&mut styled, text_area_width)),
253 let mut lines = vec![];
254 let mut widths = vec![];
255 while let Some((styled, width)) = composer.next_line() {
258 .map(|StyledGrapheme { symbol, .. }| *symbol)
259 .collect::<String>();
260 assert!(width <= text_area_width);
268 fn line_composer_one_line() {
271 let text = "a".repeat(i);
272 let (word_wrapper, _) =
273 run_composer(Composer::WordWrapper { trim: true }, &text, width as u16);
274 let (line_truncator, _) = run_composer(Composer::LineTruncator, &text, width as u16);
275 let expected = vec![text];
276 assert_eq!(word_wrapper, expected);
277 assert_eq!(line_truncator, expected);
282 fn line_composer_short_lines() {
285 "abcdefg\nhijklmno\npabcdefg\nhijklmn\nopabcdefghijk\nlmnopabcd\n\n\nefghijklmno";
286 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
287 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
289 let wrapped: Vec<&str> = text.split('\n').collect();
290 assert_eq!(word_wrapper, wrapped);
291 assert_eq!(line_truncator, wrapped);
295 fn line_composer_long_word() {
297 let text = "abcdefghijklmnopabcdefghijklmnopabcdefghijklmnopabcdefghijklmno";
298 let (word_wrapper, _) =
299 run_composer(Composer::WordWrapper { trim: true }, text, width as u16);
300 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width as u16);
304 &text[width..width * 2],
305 &text[width * 2..width * 3],
309 word_wrapper, wrapped,
310 "WordWrapper should detect the line cannot be broken on word boundary and \
311 break it at line width limit."
313 assert_eq!(line_truncator, vec![&text[..width]]);
317 fn line_composer_long_sentence() {
320 "abcd efghij klmnopabcd efgh ijklmnopabcdefg hijkl mnopab c d e f g h i j k l m n o";
321 let text_multi_space =
322 "abcd efghij klmnopabcd efgh ijklmnopabcdefg hijkl mnopab c d e f g h i j k l \
324 let (word_wrapper_single_space, _) =
325 run_composer(Composer::WordWrapper { trim: true }, text, width as u16);
326 let (word_wrapper_multi_space, _) = run_composer(
327 Composer::WordWrapper { trim: true },
331 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width as u16);
333 let word_wrapped = vec![
337 "hijkl mnopab c d e f",
340 assert_eq!(word_wrapper_single_space, word_wrapped);
341 assert_eq!(word_wrapper_multi_space, word_wrapped);
343 assert_eq!(line_truncator, vec![&text[..width]]);
347 fn line_composer_zero_width() {
349 let text = "abcd efghij klmnopabcd efgh ijklmnopabcdefg hijkl mnopab ";
350 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
351 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
353 let expected: Vec<&str> = Vec::new();
354 assert_eq!(word_wrapper, expected);
355 assert_eq!(line_truncator, expected);
359 fn line_composer_max_line_width_of_1() {
361 let text = "abcd efghij klmnopabcd efgh ijklmnopabcdefg hijkl mnopab ";
362 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
363 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
365 let expected: Vec<&str> = UnicodeSegmentation::graphemes(text, true)
366 .filter(|g| g.chars().any(|c| !c.is_whitespace()))
368 assert_eq!(word_wrapper, expected);
369 assert_eq!(line_truncator, vec!["a"]);
373 fn line_composer_max_line_width_of_1_double_width_characters() {
375 let text = "コンピュータ上で文字を扱う場合、典型的には文字\naaaによる通信を行う場合にその\
377 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
378 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
379 assert_eq!(word_wrapper, vec!["", "a", "a", "a"]);
380 assert_eq!(line_truncator, vec!["", "a"]);
383 /// Tests WordWrapper with words some of which exceed line length and some not.
385 fn line_composer_word_wrapper_mixed_length() {
387 let text = "abcd efghij klmnopabcdefghijklmnopabcdefghijkl mnopab cdefghi j klmno";
388 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
393 "klmnopabcdefghijklmn",
402 fn line_composer_double_width_chars() {
404 let text = "コンピュータ上で文字を扱う場合、典型的には文字による通信を行う場合にその両端点\
406 let (word_wrapper, word_wrapper_width) =
407 run_composer(Composer::WordWrapper { trim: true }, &text, width);
408 let (line_truncator, _) = run_composer(Composer::LineTruncator, &text, width);
409 assert_eq!(line_truncator, vec!["コンピュータ上で文字"]);
417 assert_eq!(word_wrapper, wrapped);
418 assert_eq!(word_wrapper_width, vec![width, width, width, width, 4]);
422 fn line_composer_leading_whitespace_removal() {
424 let text = "AAAAAAAAAAAAAAAAAAAA AAA";
425 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
426 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
427 assert_eq!(word_wrapper, vec!["AAAAAAAAAAAAAAAAAAAA", "AAA",]);
428 assert_eq!(line_truncator, vec!["AAAAAAAAAAAAAAAAAAAA"]);
431 /// Tests truncation of leading whitespace.
433 fn line_composer_lots_of_spaces() {
436 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
437 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
438 assert_eq!(word_wrapper, vec![""]);
439 assert_eq!(line_truncator, vec![" "]);
442 /// Tests an input starting with a letter, folowed by spaces - some of the behaviour is
445 fn line_composer_char_plus_lots_of_spaces() {
448 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
449 let (line_truncator, _) = run_composer(Composer::LineTruncator, text, width);
450 // What's happening below is: the first line gets consumed, trailing spaces discarded,
451 // after 20 of which a word break occurs (probably shouldn't). The second line break
452 // discards all whitespace. The result should probably be vec!["a"] but it doesn't matter
454 assert_eq!(word_wrapper, vec!["a", ""]);
455 assert_eq!(line_truncator, vec!["a "]);
459 fn line_composer_word_wrapper_double_width_chars_mixed_with_spaces() {
461 // Japanese seems not to use spaces but we should break on spaces anyway... We're using it
462 // to test double-width chars.
463 // You are more than welcome to add word boundary detection based of alterations of
464 // hiragana and katakana...
465 // This happens to also be a test case for mixed width because regular spaces are single width.
466 let text = "コンピュ ータ上で文字を扱う場合、 典型的には文 字による 通信を行 う場合にその両端点では、";
467 let (word_wrapper, word_wrapper_width) =
468 run_composer(Composer::WordWrapper { trim: true }, text, width);
480 // Odd-sized lines have a space in them.
481 assert_eq!(word_wrapper_width, vec![8, 20, 17, 17, 20, 4]);
484 /// Ensure words separated by nbsp are wrapped as if they were a single one.
486 fn line_composer_word_wrapper_nbsp() {
488 let text = "AAAAAAAAAAAAAAA AAAA\u{00a0}AAA";
489 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
490 assert_eq!(word_wrapper, vec!["AAAAAAAAAAAAAAA", "AAAA\u{00a0}AAA",]);
492 // Ensure that if the character was a regular space, it would be wrapped differently.
493 let text_space = text.replace("\u{00a0}", " ");
494 let (word_wrapper_space, _) =
495 run_composer(Composer::WordWrapper { trim: true }, &text_space, width);
496 assert_eq!(word_wrapper_space, vec!["AAAAAAAAAAAAAAA AAAA", "AAA",]);
500 fn line_composer_word_wrapper_preserve_indentation() {
502 let text = "AAAAAAAAAAAAAAAAAAAA AAA";
503 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: false }, text, width);
504 assert_eq!(word_wrapper, vec!["AAAAAAAAAAAAAAAAAAAA", " AAA",]);
508 fn line_composer_word_wrapper_preserve_indentation_with_wrap() {
510 let text = "AAA AAA AAAAA AA AAAAAA\n B\n C\n D";
511 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: false }, text, width);
514 vec!["AAA AAA", "AAAAA AA", "AAAAAA", " B", " C", " D"]
519 fn line_composer_word_wrapper_preserve_indentation_lots_of_whitespace() {
521 let text = " 4 Indent\n must wrap!";
522 let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: false }, text, width);
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list