Skip to main content

gpui/text_system/
line_wrapper.rs

1use crate::{FontId, Pixels, SharedString, TextRun, TextSystem, px};
2use collections::HashMap;
3use std::{borrow::Cow, iter, sync::Arc};
4
5/// Determines whether to truncate text from the start or end.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum TruncateFrom {
8    /// Truncate text from the start.
9    Start,
10    /// Truncate text from the end.
11    End,
12    /// Truncate text from the middle, preserving the start and end.
13    Middle,
14}
15
16/// The GPUI line wrapper, used to wrap lines of text to a given width.
17pub struct LineWrapper {
18    text_system: Arc<TextSystem>,
19    pub(crate) font_id: FontId,
20    pub(crate) font_size: Pixels,
21    char_widths: CharWidthCache,
22}
23
24/// Cached character widths for one font and size.
25pub(crate) struct CharWidthCache {
26    ascii: [Option<Pixels>; 128],
27    other: HashMap<char, Pixels>,
28}
29
30impl Default for CharWidthCache {
31    fn default() -> Self {
32        Self {
33            ascii: [None; 128],
34            other: HashMap::default(),
35        }
36    }
37}
38
39impl LineWrapper {
40    /// The maximum indent that can be applied to a line.
41    pub const MAX_INDENT: u32 = 256;
42
43    pub(crate) fn new(
44        font_id: FontId,
45        font_size: Pixels,
46        text_system: Arc<TextSystem>,
47        char_widths: CharWidthCache,
48    ) -> Self {
49        Self {
50            text_system,
51            font_id,
52            font_size,
53            char_widths,
54        }
55    }
56
57    pub(crate) fn into_char_widths(self) -> CharWidthCache {
58        self.char_widths
59    }
60
61    /// Wrap a line of text to the given width with this wrapper's font and font size.
62    pub fn wrap_line<'a>(
63        &'a mut self,
64        fragments: &'a [LineFragment],
65        wrap_width: Pixels,
66    ) -> impl Iterator<Item = Boundary> + 'a {
67        let mut width = px(0.);
68        let mut first_non_whitespace_ix = None;
69        let mut indent = None;
70        let mut last_candidate_ix = 0;
71        let mut last_candidate_width = px(0.);
72        let mut last_wrap_ix = 0;
73        let mut prev_c = '\0';
74        let mut index = 0;
75        let mut candidates = fragments
76            .iter()
77            .flat_map(move |fragment| fragment.wrap_boundary_candidates())
78            .peekable();
79        iter::from_fn(move || {
80            for candidate in candidates.by_ref() {
81                let ix = index;
82                index += candidate.len_utf8();
83                let mut new_prev_c = prev_c;
84                let item_width = match candidate {
85                    WrapBoundaryCandidate::Char { character: c } => {
86                        if c == '\n' {
87                            continue;
88                        }
89
90                        if Self::is_word_char(c) {
91                            if prev_c == ' ' && c != ' ' && first_non_whitespace_ix.is_some() {
92                                last_candidate_ix = ix;
93                                last_candidate_width = width;
94                            }
95                        } else {
96                            // CJK may not be space separated, e.g.: `Hello world你好世界`
97                            if c != ' ' && first_non_whitespace_ix.is_some() {
98                                last_candidate_ix = ix;
99                                last_candidate_width = width;
100                            }
101                        }
102
103                        if c != ' ' && first_non_whitespace_ix.is_none() {
104                            first_non_whitespace_ix = Some(ix);
105                        }
106
107                        new_prev_c = c;
108
109                        self.width_for_char(c)
110                    }
111                    WrapBoundaryCandidate::Element {
112                        width: element_width,
113                        ..
114                    } => {
115                        if prev_c == ' ' && first_non_whitespace_ix.is_some() {
116                            last_candidate_ix = ix;
117                            last_candidate_width = width;
118                        }
119
120                        if first_non_whitespace_ix.is_none() {
121                            first_non_whitespace_ix = Some(ix);
122                        }
123
124                        element_width
125                    }
126                };
127
128                width += item_width;
129                if width > wrap_width && ix > last_wrap_ix {
130                    if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
131                    {
132                        indent = Some(
133                            Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
134                        );
135                    }
136
137                    if last_candidate_ix > 0 {
138                        last_wrap_ix = last_candidate_ix;
139                        width -= last_candidate_width;
140                        last_candidate_ix = 0;
141                    } else {
142                        last_wrap_ix = ix;
143                        width = item_width;
144                    }
145
146                    if let Some(indent) = indent {
147                        width += self.width_for_char(' ') * indent as f32;
148                    }
149
150                    return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
151                }
152
153                prev_c = new_prev_c;
154            }
155
156            None
157        })
158    }
159
160    /// Determines if a line should be truncated based on its width.
161    ///
162    /// Returns the truncation index in `line`.
163    pub fn should_truncate_line(
164        &mut self,
165        line: &str,
166        truncate_width: Pixels,
167        truncation_affix: &str,
168        truncate_from: TruncateFrom,
169    ) -> Option<usize> {
170        let mut width = px(0.);
171        let suffix_width = truncation_affix
172            .chars()
173            .map(|c| self.width_for_char(c))
174            .fold(px(0.0), |a, x| a + x);
175        let mut truncate_ix = 0;
176
177        match truncate_from {
178            TruncateFrom::Start => {
179                for (ix, c) in line.char_indices().rev() {
180                    if width + suffix_width < truncate_width {
181                        truncate_ix = ix;
182                    }
183
184                    let char_width = self.width_for_char(c);
185                    width += char_width;
186
187                    if width.floor() > truncate_width {
188                        return Some(truncate_ix);
189                    }
190                }
191            }
192            TruncateFrom::End => {
193                for (ix, c) in line.char_indices() {
194                    if width + suffix_width < truncate_width {
195                        truncate_ix = ix;
196                    }
197
198                    let char_width = self.width_for_char(c);
199                    width += char_width;
200
201                    if width.floor() > truncate_width {
202                        return Some(truncate_ix);
203                    }
204                }
205            }
206            TruncateFrom::Middle => {}
207        }
208
209        None
210    }
211
212    fn should_truncate_line_middle(
213        &mut self,
214        line: &str,
215        truncate_width: Pixels,
216        truncation_affix: &str,
217    ) -> Option<(usize, usize)> {
218        let suffix_width = truncation_affix
219            .chars()
220            .map(|c| self.width_for_char(c))
221            .fold(px(0.0), |a, x| a + x);
222
223        let total_width: Pixels = line
224            .chars()
225            .map(|c| self.width_for_char(c))
226            .fold(px(0.0), |a, x| a + x);
227
228        if total_width <= truncate_width {
229            return None;
230        }
231
232        let content_budget = truncate_width - suffix_width;
233        if content_budget <= px(0.) {
234            return Some((0, line.len()));
235        }
236
237        let front_budget = content_budget * (2.0 / 3.0);
238        let back_budget = content_budget - front_budget;
239
240        let mut front_width = px(0.);
241        let mut front_end_ix = 0usize;
242        for (ix, c) in line.char_indices() {
243            let char_width = self.width_for_char(c);
244            if front_width + char_width > front_budget {
245                break;
246            }
247            front_width += char_width;
248            front_end_ix = ix + c.len_utf8();
249        }
250
251        let mut back_width = px(0.);
252        let mut back_start_ix = line.len();
253        for (ix, c) in line.char_indices().rev() {
254            let char_width = self.width_for_char(c);
255            if back_width + char_width > back_budget {
256                break;
257            }
258            back_width += char_width;
259            back_start_ix = ix;
260        }
261
262        if front_end_ix >= back_start_ix {
263            return Some((0, line.len()));
264        }
265
266        Some((front_end_ix, back_start_ix))
267    }
268
269    /// Truncate a line of text to the given width with this wrapper's font and font size.
270    pub fn truncate_line<'a>(
271        &mut self,
272        line: SharedString,
273        truncate_width: Pixels,
274        truncation_affix: &str,
275        runs: &'a [TextRun],
276        truncate_from: TruncateFrom,
277    ) -> (SharedString, Cow<'a, [TextRun]>) {
278        if truncate_from == TruncateFrom::Middle {
279            if let Some((front_end_ix, back_start_ix)) =
280                self.should_truncate_line_middle(&line, truncate_width, truncation_affix)
281            {
282                let result = SharedString::from(format!(
283                    "{}{truncation_affix}{}",
284                    &line[..front_end_ix],
285                    &line[back_start_ix..]
286                ));
287                let mut runs = runs.to_vec();
288                update_runs_after_middle_truncation(
289                    truncation_affix,
290                    &mut runs,
291                    front_end_ix,
292                    back_start_ix,
293                );
294                return (result, Cow::Owned(runs));
295            } else {
296                return (line, Cow::Borrowed(runs));
297            }
298        }
299
300        if let Some(truncate_ix) =
301            self.should_truncate_line(&line, truncate_width, truncation_affix, truncate_from)
302        {
303            let result = match truncate_from {
304                TruncateFrom::Start => SharedString::from(format!(
305                    "{truncation_affix}{}",
306                    &line[line.ceil_char_boundary(truncate_ix + 1)..]
307                )),
308                TruncateFrom::End => SharedString::from(format!(
309                    "{}{truncation_affix}",
310                    line[..truncate_ix]
311                        .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation())
312                )),
313                TruncateFrom::Middle => unreachable!("Middle truncation is handled above"),
314            };
315            let mut runs = runs.to_vec();
316            update_runs_after_truncation(&result, truncation_affix, &mut runs, truncate_from);
317            (result, Cow::Owned(runs))
318        } else {
319            (line, Cow::Borrowed(runs))
320        }
321    }
322
323    /// Truncate text to fit within a given number of wrapped lines.
324    ///
325    /// Unlike `truncate_line` which treats the text as a flat width budget
326    /// (`width * max_lines`), this method accounts for word-boundary wrapping:
327    /// it walks through characters once, tracking wrap boundaries and the
328    /// truncation point simultaneously. When text overflows on the last
329    /// allowed line, it truncates there and appends the affix.
330    ///
331    /// For `max_lines == 1`, this delegates to `truncate_line`.
332    pub fn truncate_wrapped_line<'a>(
333        &mut self,
334        text: SharedString,
335        wrap_width: Pixels,
336        max_lines: usize,
337        truncation_affix: &str,
338        runs: &'a [TextRun],
339        truncate_from: TruncateFrom,
340    ) -> (SharedString, Cow<'a, [TextRun]>) {
341        if max_lines <= 1 || truncate_from == TruncateFrom::Start {
342            return self.truncate_line(
343                text,
344                wrap_width * max_lines,
345                truncation_affix,
346                runs,
347                truncate_from,
348            );
349        }
350        if truncate_from == TruncateFrom::Middle {
351            return self.truncate_line(text, wrap_width, truncation_affix, runs, truncate_from);
352        }
353
354        let affix_width: Pixels = truncation_affix
355            .chars()
356            .map(|c| self.width_for_char(c))
357            .sum();
358
359        let mut width = px(0.);
360        let mut line = 0usize;
361        let mut first_non_whitespace_ix = None;
362        let mut last_candidate_ix = 0usize;
363        let mut last_candidate_width = px(0.);
364        let mut last_wrap_ix = 0usize;
365        let mut prev_c = '\0';
366        let mut indent: Option<u32> = None;
367        let mut truncate_ix = 0usize;
368
369        for (ix, c) in text.char_indices() {
370            if c == '\n' {
371                if line >= max_lines - 1 && !text[ix + 1..].trim().is_empty() {
372                    // Newline on the last allowed line with real content
373                    // below. Truncate here.
374                    let truncated = text[..truncate_ix]
375                        .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation());
376                    let result = SharedString::from(format!("{truncated}{truncation_affix}"));
377                    let mut runs = runs.to_vec();
378                    update_runs_after_truncation(
379                        &result,
380                        truncation_affix,
381                        &mut runs,
382                        TruncateFrom::End,
383                    );
384                    return (result, Cow::Owned(runs));
385                }
386
387                // Newline before the last line: it consumes a line.
388                line += 1;
389                width = px(0.);
390                first_non_whitespace_ix = None;
391                last_candidate_ix = 0;
392                last_candidate_width = px(0.);
393                last_wrap_ix = ix + 1;
394                prev_c = '\0';
395                indent = None;
396                truncate_ix = ix + 1;
397                continue;
398            }
399
400            let char_width = self.width_for_char(c);
401
402            if Self::is_word_char(c) {
403                if prev_c == ' ' && first_non_whitespace_ix.is_some() {
404                    last_candidate_ix = ix;
405                    last_candidate_width = width;
406                }
407            } else if c != ' ' && first_non_whitespace_ix.is_some() {
408                last_candidate_ix = ix;
409                last_candidate_width = width;
410            }
411
412            if c != ' ' && first_non_whitespace_ix.is_none() {
413                first_non_whitespace_ix = Some(ix);
414            }
415
416            width += char_width;
417
418            if line < max_lines - 1 {
419                // Before the last line: replicate wrap_line's boundary logic.
420                if width > wrap_width && ix > last_wrap_ix {
421                    if let (None, Some(first_nw)) = (indent, first_non_whitespace_ix) {
422                        indent = Some(Self::MAX_INDENT.min((first_nw - last_wrap_ix) as u32));
423                    }
424
425                    if last_candidate_ix > last_wrap_ix {
426                        last_wrap_ix = last_candidate_ix;
427                        width -= last_candidate_width;
428                        last_candidate_ix = 0;
429                    } else {
430                        last_wrap_ix = ix;
431                        width = char_width;
432                    }
433
434                    if let Some(ind) = indent {
435                        width += self.width_for_char(' ') * ind as f32;
436                    }
437
438                    line += 1;
439                    truncate_ix = last_wrap_ix;
440                }
441            } else {
442                // On the last line: track the furthest point where the affix
443                // still fits, and stop as soon as the line overflows.
444                if width + affix_width <= wrap_width {
445                    truncate_ix = ix + c.len_utf8();
446                }
447
448                if width > wrap_width {
449                    let truncated = text[..truncate_ix]
450                        .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation());
451                    let result = SharedString::from(format!("{truncated}{truncation_affix}"));
452                    let mut runs = runs.to_vec();
453                    update_runs_after_truncation(
454                        &result,
455                        truncation_affix,
456                        &mut runs,
457                        TruncateFrom::End,
458                    );
459                    return (result, Cow::Owned(runs));
460                }
461            }
462
463            prev_c = c;
464        }
465
466        // Text fits within max_lines without truncation.
467        (text, Cow::Borrowed(runs))
468    }
469
470    /// Any character in this list should be treated as a word character,
471    /// meaning it can be part of a word that should not be wrapped.
472    pub(crate) fn is_word_char(c: char) -> bool {
473        // ASCII alphanumeric characters, for English, numbers: `Hello123`, etc.
474        c.is_ascii_alphanumeric() ||
475        // Latin script in Unicode for French, German, Spanish, etc.
476        // Latin-1 Supplement
477        // https://en.wikipedia.org/wiki/Latin-1_Supplement
478        matches!(c, '\u{00C0}'..='\u{00FF}') ||
479        // Latin Extended-A
480        // https://en.wikipedia.org/wiki/Latin_Extended-A
481        matches!(c, '\u{0100}'..='\u{017F}') ||
482        // Latin Extended-B
483        // https://en.wikipedia.org/wiki/Latin_Extended-B
484        matches!(c, '\u{0180}'..='\u{024F}') ||
485        // Cyrillic for Russian, Ukrainian, etc.
486        // https://en.wikipedia.org/wiki/Cyrillic_script_in_Unicode
487        matches!(c, '\u{0400}'..='\u{04FF}') ||
488
489        // Vietnamese (https://vietunicode.sourceforge.net/charset/)
490        matches!(c, '\u{1E00}'..='\u{1EFF}') || // Latin Extended Additional
491        matches!(c, '\u{0300}'..='\u{036F}') || // Combining Diacritical Marks
492
493        // Bengali (https://en.wikipedia.org/wiki/Bengali_(Unicode_block))
494        matches!(c, '\u{0980}'..='\u{09FF}') ||
495
496        // Some other known special characters that should be treated as word characters,
497        // e.g. `a-b`, `var_name`, `I'm`/`won’t`, '@mention`, `#hashtag`, `100%`, `3.1415`,
498        // `2^3`, `a~b`, `a=1`, `Self::new`, etc. Trailing punctuation like `,`, `.`, `:`, `;`
499        // is included so it stays attached to the preceding word when wrapping.
500        matches!(c, '-' | '_' | '.' | '\'' | '’' | '‘' | '$' | '%' | '@' | '#' | '^' | '~' | ',' | '=' | ':' | ';') ||
501        // Closing punctuation never starts a line (UAX #14 LB13: no break
502        // before `!`, `)`, `]`, `}`, closing quotes or an ellipsis) — `plz!`,
503        // `see)`, `quoted”` wrap as one word instead of orphaning the mark on
504        // the next line. `/` and `?` stay break opportunities so long paths
505        // and URLs (`a/b`, `foo?b=2`) can wrap.
506        matches!(c, '!' | ')' | ']' | '}' | '"' | '”' | '»' | '…') ||
507        // `⋯` character is special used in Zed, to keep this at the end of the line.
508        matches!(c, '⋯') ||
509
510        // Non-breaking glue characters
511        matches!(c, '\u{202F}' | '\u{00A0}' | '\u{2011}')
512    }
513
514    #[inline(always)]
515    fn width_for_char(&mut self, c: char) -> Pixels {
516        if (c as u32) < 128 {
517            if let Some(cached_width) = self.char_widths.ascii[c as usize] {
518                cached_width
519            } else {
520                let width = self
521                    .text_system
522                    .layout_width(self.font_id, self.font_size, c);
523                self.char_widths.ascii[c as usize] = Some(width);
524                width
525            }
526        } else if let Some(cached_width) = self.char_widths.other.get(&c) {
527            *cached_width
528        } else {
529            let width = self
530                .text_system
531                .layout_width(self.font_id, self.font_size, c);
532            self.char_widths.other.insert(c, width);
533            width
534        }
535    }
536}
537
538fn update_runs_after_truncation(
539    result: &str,
540    ellipsis: &str,
541    runs: &mut Vec<TextRun>,
542    truncate_from: TruncateFrom,
543) {
544    let mut truncate_at = result.len() - ellipsis.len();
545    match truncate_from {
546        TruncateFrom::Start => {
547            for (run_index, run) in runs.iter_mut().enumerate().rev() {
548                if run.len <= truncate_at {
549                    truncate_at -= run.len;
550                } else {
551                    run.len = truncate_at + ellipsis.len();
552                    runs.splice(..run_index, std::iter::empty());
553                    break;
554                }
555            }
556        }
557        TruncateFrom::End => {
558            for (run_index, run) in runs.iter_mut().enumerate() {
559                if run.len <= truncate_at {
560                    truncate_at -= run.len;
561                } else {
562                    run.len = truncate_at + ellipsis.len();
563                    runs.truncate(run_index + 1);
564                    break;
565                }
566            }
567        }
568        TruncateFrom::Middle => {
569            unreachable!("Middle truncation calls this function with TruncateFrom::End directly")
570        }
571    }
572}
573
574fn update_runs_after_middle_truncation(
575    ellipsis: &str,
576    runs: &mut Vec<TextRun>,
577    front_end_ix: usize,
578    back_start_ix: usize,
579) {
580    let original_runs = std::mem::take(runs);
581    let mut result_runs: Vec<TextRun> = Vec::with_capacity(original_runs.len());
582
583    // Front segment [0, front_end_ix) + ellipsis: walk forward until the run
584    // that straddles or ends at front_end_ix, then extend that run's length
585    // to include the ellipsis.
586    let mut front_remaining = front_end_ix;
587    let mut front_done = false;
588    for run in &original_runs {
589        if front_done {
590            break;
591        }
592        if run.len <= front_remaining {
593            result_runs.push(run.clone());
594            front_remaining -= run.len;
595        } else {
596            let mut partial = run.clone();
597            partial.len = front_remaining + ellipsis.len();
598            result_runs.push(partial);
599            front_done = true;
600        }
601    }
602    if !front_done {
603        // front_end_ix landed exactly on a run boundary; append ellipsis to
604        // the last front run (or, if the front is empty, to the first back run).
605        if let Some(last) = result_runs.last_mut() {
606            last.len += ellipsis.len();
607        } else if let Some(first) = original_runs.first() {
608            let mut affix_run = first.clone();
609            affix_run.len = ellipsis.len();
610            result_runs.push(affix_run);
611        }
612    }
613
614    // Back segment [back_start_ix, original.len()): skip runs entirely in the
615    // removed middle, keep the rest.
616    let mut byte_pos = 0usize;
617    for run in &original_runs {
618        let run_end = byte_pos + run.len;
619        if run_end > back_start_ix {
620            if byte_pos < back_start_ix {
621                // Run straddles back_start_ix; keep only the tail.
622                let mut partial = run.clone();
623                partial.len = run_end - back_start_ix;
624                result_runs.push(partial);
625            } else {
626                result_runs.push(run.clone());
627            }
628        }
629        byte_pos = run_end;
630    }
631
632    *runs = result_runs;
633}
634
635/// A fragment of a line that can be wrapped.
636pub enum LineFragment<'a> {
637    /// A text fragment consisting of characters.
638    Text {
639        /// The text content of the fragment.
640        text: &'a str,
641    },
642    /// A non-text element with a fixed width.
643    Element {
644        /// The width of the element in pixels.
645        width: Pixels,
646        /// The UTF-8 encoded length of the element.
647        len_utf8: usize,
648    },
649}
650
651impl<'a> LineFragment<'a> {
652    /// Creates a new text fragment from the given text.
653    pub fn text(text: &'a str) -> Self {
654        LineFragment::Text { text }
655    }
656
657    /// Creates a new non-text element with the given width and UTF-8 encoded length.
658    pub fn element(width: Pixels, len_utf8: usize) -> Self {
659        LineFragment::Element { width, len_utf8 }
660    }
661
662    fn wrap_boundary_candidates(&self) -> impl Iterator<Item = WrapBoundaryCandidate> {
663        let text = match self {
664            LineFragment::Text { text } => text,
665            LineFragment::Element { .. } => "\0",
666        };
667        text.chars().map(move |character| {
668            if let LineFragment::Element { width, len_utf8 } = self {
669                WrapBoundaryCandidate::Element {
670                    width: *width,
671                    len_utf8: *len_utf8,
672                }
673            } else {
674                WrapBoundaryCandidate::Char { character }
675            }
676        })
677    }
678}
679
680enum WrapBoundaryCandidate {
681    Char { character: char },
682    Element { width: Pixels, len_utf8: usize },
683}
684
685impl WrapBoundaryCandidate {
686    pub fn len_utf8(&self) -> usize {
687        match self {
688            WrapBoundaryCandidate::Char { character } => character.len_utf8(),
689            WrapBoundaryCandidate::Element { len_utf8: len, .. } => *len,
690        }
691    }
692}
693
694/// A boundary between two lines of text.
695#[derive(Copy, Clone, Debug, PartialEq, Eq)]
696pub struct Boundary {
697    /// The index of the last character in a line
698    pub ix: usize,
699    /// The indent of the next line.
700    pub next_indent: u32,
701}
702
703impl Boundary {
704    fn new(ix: usize, next_indent: u32) -> Self {
705        Self { ix, next_indent }
706    }
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712    use crate::{Font, FontFeatures, FontStyle, FontWeight, TestAppContext, TestDispatcher, font};
713    #[cfg(target_os = "macos")]
714    use crate::{TextRun, WindowTextSystem, WrapBoundary};
715
716    fn build_wrapper() -> LineWrapper {
717        let dispatcher = TestDispatcher::new(0);
718        let cx = TestAppContext::build(dispatcher, None);
719        let id = cx.text_system().resolve_font(&font(".ZedMono"));
720        LineWrapper::new(
721            id,
722            px(16.),
723            cx.text_system().clone(),
724            CharWidthCache::default(),
725        )
726    }
727
728    fn generate_test_runs(input_run_len: &[usize]) -> Vec<TextRun> {
729        input_run_len
730            .iter()
731            .map(|run_len| TextRun {
732                len: *run_len,
733                font: Font {
734                    family: "Dummy".into(),
735                    features: FontFeatures::default(),
736                    fallbacks: None,
737                    weight: FontWeight::default(),
738                    style: FontStyle::Normal,
739                },
740                ..Default::default()
741            })
742            .collect()
743    }
744
745    #[test]
746    fn test_wrap_line() {
747        let mut wrapper = build_wrapper();
748
749        assert_eq!(
750            wrapper
751                .wrap_line(&[LineFragment::text("aa bbb cccc ddddd eeee")], px(72.))
752                .collect::<Vec<_>>(),
753            &[
754                Boundary::new(7, 0),
755                Boundary::new(12, 0),
756                Boundary::new(18, 0)
757            ],
758        );
759        assert_eq!(
760            wrapper
761                .wrap_line(&[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")], px(72.0))
762                .collect::<Vec<_>>(),
763            &[
764                Boundary::new(4, 0),
765                Boundary::new(11, 0),
766                Boundary::new(18, 0)
767            ],
768        );
769        assert_eq!(
770            wrapper
771                .wrap_line(&[LineFragment::text("     aaaaaaa")], px(72.))
772                .collect::<Vec<_>>(),
773            &[
774                Boundary::new(7, 5),
775                Boundary::new(9, 5),
776                Boundary::new(11, 5),
777            ]
778        );
779        assert_eq!(
780            wrapper
781                .wrap_line(
782                    &[LineFragment::text("                            ")],
783                    px(72.)
784                )
785                .collect::<Vec<_>>(),
786            &[
787                Boundary::new(7, 0),
788                Boundary::new(14, 0),
789                Boundary::new(21, 0)
790            ]
791        );
792        assert_eq!(
793            wrapper
794                .wrap_line(&[LineFragment::text("          aaaaaaaaaaaaaa")], px(72.))
795                .collect::<Vec<_>>(),
796            &[
797                Boundary::new(7, 0),
798                Boundary::new(14, 3),
799                Boundary::new(18, 3),
800                Boundary::new(22, 3),
801            ]
802        );
803
804        // Test wrapping multiple text fragments
805        assert_eq!(
806            wrapper
807                .wrap_line(
808                    &[
809                        LineFragment::text("aa bbb "),
810                        LineFragment::text("cccc ddddd eeee")
811                    ],
812                    px(72.)
813                )
814                .collect::<Vec<_>>(),
815            &[
816                Boundary::new(7, 0),
817                Boundary::new(12, 0),
818                Boundary::new(18, 0)
819            ],
820        );
821
822        // Test wrapping with a mix of text and element fragments
823        assert_eq!(
824            wrapper
825                .wrap_line(
826                    &[
827                        LineFragment::text("aa "),
828                        LineFragment::element(px(20.), 1),
829                        LineFragment::text(" bbb "),
830                        LineFragment::element(px(30.), 1),
831                        LineFragment::text(" cccc")
832                    ],
833                    px(72.)
834                )
835                .collect::<Vec<_>>(),
836            &[
837                Boundary::new(5, 0),
838                Boundary::new(9, 0),
839                Boundary::new(11, 0)
840            ],
841        );
842
843        // Test with element at the beginning and text afterward
844        assert_eq!(
845            wrapper
846                .wrap_line(
847                    &[
848                        LineFragment::element(px(50.), 1),
849                        LineFragment::text(" aaaa bbbb cccc dddd")
850                    ],
851                    px(72.)
852                )
853                .collect::<Vec<_>>(),
854            &[
855                Boundary::new(2, 0),
856                Boundary::new(7, 0),
857                Boundary::new(12, 0),
858                Boundary::new(17, 0)
859            ],
860        );
861
862        // Test with a large element that forces wrapping by itself
863        assert_eq!(
864            wrapper
865                .wrap_line(
866                    &[
867                        LineFragment::text("short text "),
868                        LineFragment::element(px(100.), 1),
869                        LineFragment::text(" more text")
870                    ],
871                    px(72.)
872                )
873                .collect::<Vec<_>>(),
874            &[
875                Boundary::new(6, 0),
876                Boundary::new(11, 0),
877                Boundary::new(12, 0),
878                Boundary::new(18, 0)
879            ],
880        );
881
882        // Test with non-breaking glue characters
883        assert_eq!(
884            wrapper
885                .wrap_line(
886                    &[LineFragment::text("a\u{202F}b\u{00A0}c\u{2011}d e")],
887                    px(72.0)
888                )
889                .collect::<Vec<_>>(),
890            &[Boundary::new(12, 0),], // special chars above take up 3, 2 and 3 bytes, so boundary ends up at 12
891        );
892    }
893
894    #[test]
895    fn test_truncate_line_end() {
896        let mut wrapper = build_wrapper();
897
898        fn perform_test(
899            wrapper: &mut LineWrapper,
900            text: &'static str,
901            expected: &'static str,
902            ellipsis: &str,
903        ) {
904            let dummy_run_lens = vec![text.len()];
905            let dummy_runs = generate_test_runs(&dummy_run_lens);
906            let (result, dummy_runs) = wrapper.truncate_line(
907                text.into(),
908                px(220.),
909                ellipsis,
910                &dummy_runs,
911                TruncateFrom::End,
912            );
913            assert_eq!(result, expected);
914            assert_eq!(dummy_runs.first().unwrap().len, result.len());
915        }
916
917        perform_test(
918            &mut wrapper,
919            "aa bbb cccc ddddd eeee ffff gggg",
920            "aa bbb cccc ddddd eeee",
921            "",
922        );
923        perform_test(
924            &mut wrapper,
925            "aa bbb cccc ddddd eeee ffff gggg",
926            "aa bbb cccc ddddd eee…",
927            "…",
928        );
929        perform_test(
930            &mut wrapper,
931            "aa bbb cccc ddddd eeee ffff gggg",
932            "aa bbb cccc dddd......",
933            "......",
934        );
935        perform_test(
936            &mut wrapper,
937            "aa bbb cccc 🦀🦀🦀🦀🦀 eeee ffff gggg",
938            "aa bbb cccc 🦀🦀🦀🦀…",
939            "…",
940        );
941    }
942
943    #[test]
944    fn test_truncate_line_start() {
945        let mut wrapper = build_wrapper();
946
947        #[track_caller]
948        fn perform_test(
949            wrapper: &mut LineWrapper,
950            text: &'static str,
951            expected: &'static str,
952            ellipsis: &str,
953        ) {
954            let dummy_run_lens = vec![text.len()];
955            let dummy_runs = generate_test_runs(&dummy_run_lens);
956            let (result, dummy_runs) = wrapper.truncate_line(
957                text.into(),
958                px(220.),
959                ellipsis,
960                &dummy_runs,
961                TruncateFrom::Start,
962            );
963            assert_eq!(result, expected);
964            assert_eq!(dummy_runs.first().unwrap().len, result.len());
965        }
966
967        perform_test(
968            &mut wrapper,
969            "aaaa bbbb cccc ddddd eeee fff gg",
970            "cccc ddddd eeee fff gg",
971            "",
972        );
973        perform_test(
974            &mut wrapper,
975            "aaaa bbbb cccc ddddd eeee fff gg",
976            "…ccc ddddd eeee fff gg",
977            "…",
978        );
979        perform_test(
980            &mut wrapper,
981            "aaaa bbbb cccc ddddd eeee fff gg",
982            "......dddd eeee fff gg",
983            "......",
984        );
985        perform_test(
986            &mut wrapper,
987            "aaaa bbbb cccc 🦀🦀🦀🦀🦀 eeee fff gg",
988            "…🦀🦀🦀🦀 eeee fff gg",
989            "…",
990        );
991    }
992
993    #[test]
994    fn test_truncate_multiple_runs_end() {
995        let mut wrapper = build_wrapper();
996
997        fn perform_test(
998            wrapper: &mut LineWrapper,
999            text: &'static str,
1000            expected: &str,
1001            run_lens: &[usize],
1002            result_run_len: &[usize],
1003            line_width: Pixels,
1004        ) {
1005            let dummy_runs = generate_test_runs(run_lens);
1006            let (result, dummy_runs) =
1007                wrapper.truncate_line(text.into(), line_width, "…", &dummy_runs, TruncateFrom::End);
1008            assert_eq!(result, expected);
1009            for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
1010                assert_eq!(run.len, *result_len);
1011            }
1012        }
1013        // Case 0: Normal
1014        // Text: abcdefghijkl
1015        // Runs: Run0 { len: 12, ... }
1016        //
1017        // Truncate res: abcd… (truncate_at = 4)
1018        // Run res: Run0 { string: abcd…, len: 7, ... }
1019        perform_test(&mut wrapper, "abcdefghijkl", "abcd…", &[12], &[7], px(50.));
1020        // Case 1: Drop some runs
1021        // Text: abcdefghijkl
1022        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1023        //
1024        // Truncate res: abcdef… (truncate_at = 6)
1025        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
1026        // 5, ... }
1027        perform_test(
1028            &mut wrapper,
1029            "abcdefghijkl",
1030            "abcdef…",
1031            &[4, 4, 4],
1032            &[4, 5],
1033            px(70.),
1034        );
1035        // Case 2: Truncate at start of some run
1036        // Text: abcdefghijkl
1037        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1038        //
1039        // Truncate res: abcdefgh… (truncate_at = 8)
1040        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
1041        // 4, ... }, Run2 { string: …, len: 3, ... }
1042        perform_test(
1043            &mut wrapper,
1044            "abcdefghijkl",
1045            "abcdefgh…",
1046            &[4, 4, 4],
1047            &[4, 4, 3],
1048            px(90.),
1049        );
1050    }
1051
1052    #[test]
1053    fn test_truncate_multiple_runs_start() {
1054        let mut wrapper = build_wrapper();
1055
1056        #[track_caller]
1057        fn perform_test(
1058            wrapper: &mut LineWrapper,
1059            text: &'static str,
1060            expected: &str,
1061            run_lens: &[usize],
1062            result_run_len: &[usize],
1063            line_width: Pixels,
1064        ) {
1065            let dummy_runs = generate_test_runs(run_lens);
1066            let (result, dummy_runs) = wrapper.truncate_line(
1067                text.into(),
1068                line_width,
1069                "…",
1070                &dummy_runs,
1071                TruncateFrom::Start,
1072            );
1073            assert_eq!(result, expected);
1074            for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
1075                assert_eq!(run.len, *result_len);
1076            }
1077        }
1078        // Case 0: Normal
1079        // Text: abcdefghijkl
1080        // Runs: Run0 { len: 12, ... }
1081        //
1082        // Truncate res: …ijkl (truncate_at = 9)
1083        // Run res: Run0 { string: …ijkl, len: 7, ... }
1084        perform_test(&mut wrapper, "abcdefghijkl", "…ijkl", &[12], &[7], px(50.));
1085        // Case 1: Drop some runs
1086        // Text: abcdefghijkl
1087        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1088        //
1089        // Truncate res: …ghijkl (truncate_at = 7)
1090        // Runs res: Run0 { string: …gh, len: 5, ... }, Run1 { string: ijkl, len:
1091        // 4, ... }
1092        perform_test(
1093            &mut wrapper,
1094            "abcdefghijkl",
1095            "…ghijkl",
1096            &[4, 4, 4],
1097            &[5, 4],
1098            px(70.),
1099        );
1100        // Case 2: Truncate at start of some run
1101        // Text: abcdefghijkl
1102        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1103        //
1104        // Truncate res: abcdefgh… (truncate_at = 3)
1105        // Runs res: Run0 { string: …, len: 3, ... }, Run1 { string: efgh, len:
1106        // 4, ... }, Run2 { string: ijkl, len: 4, ... }
1107        perform_test(
1108            &mut wrapper,
1109            "abcdefghijkl",
1110            "…efghijkl",
1111            &[4, 4, 4],
1112            &[3, 4, 4],
1113            px(90.),
1114        );
1115    }
1116
1117    #[test]
1118    fn test_update_run_after_truncation_end() {
1119        fn perform_test(result: &str, run_lens: &[usize], result_run_lens: &[usize]) {
1120            let mut dummy_runs = generate_test_runs(run_lens);
1121            update_runs_after_truncation(result, "…", &mut dummy_runs, TruncateFrom::End);
1122            for (run, result_len) in dummy_runs.iter().zip(result_run_lens) {
1123                assert_eq!(run.len, *result_len);
1124            }
1125        }
1126        // Case 0: Normal
1127        // Text: abcdefghijkl
1128        // Runs: Run0 { len: 12, ... }
1129        //
1130        // Truncate res: abcd… (truncate_at = 4)
1131        // Run res: Run0 { string: abcd…, len: 7, ... }
1132        perform_test("abcd…", &[12], &[7]);
1133        // Case 1: Drop some runs
1134        // Text: abcdefghijkl
1135        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1136        //
1137        // Truncate res: abcdef… (truncate_at = 6)
1138        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
1139        // 5, ... }
1140        perform_test("abcdef…", &[4, 4, 4], &[4, 5]);
1141        // Case 2: Truncate at start of some run
1142        // Text: abcdefghijkl
1143        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1144        //
1145        // Truncate res: abcdefgh… (truncate_at = 8)
1146        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
1147        // 4, ... }, Run2 { string: …, len: 3, ... }
1148        perform_test("abcdefgh…", &[4, 4, 4], &[4, 4, 3]);
1149    }
1150
1151    #[test]
1152    fn test_is_word_char() {
1153        #[track_caller]
1154        fn assert_word(word: &str) {
1155            for c in word.chars() {
1156                assert!(
1157                    LineWrapper::is_word_char(c),
1158                    "assertion failed for '{}' (unicode 0x{:x})",
1159                    c,
1160                    c as u32
1161                );
1162            }
1163        }
1164
1165        #[track_caller]
1166        fn assert_not_word(word: &str) {
1167            let found = word.chars().any(|c| !LineWrapper::is_word_char(c));
1168            assert!(found, "assertion failed for '{}'", word);
1169        }
1170
1171        assert_word("Hello123");
1172        assert_word("non-English");
1173        assert_word("var_name");
1174        assert_word("123456");
1175        assert_word("3.1415");
1176        assert_word("10^2");
1177        assert_word("1~2");
1178        assert_word("100%");
1179        assert_word("@mention");
1180        assert_word("#hashtag");
1181        assert_word("$variable");
1182        assert_word("a=1");
1183        assert_word("Self::is_word_char");
1184        assert_word("on;");
1185        assert_word("more⋯");
1186        assert_word("won’t");
1187        assert_word("‘twas");
1188        assert_word("plz!");
1189        assert_word("see)");
1190        assert_word("quoted”");
1191        assert_word("well…");
1192
1193        // Space
1194        assert_not_word("foo bar");
1195
1196        // URL case
1197        assert_word("github.com");
1198        assert_not_word("zed-industries/zed");
1199        assert_not_word("zed-industries\\zed");
1200        assert_not_word("a=1&b=2");
1201        assert_not_word("foo?b=2");
1202
1203        // Latin-1 Supplement
1204        assert_word("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ");
1205        // Latin Extended-A
1206        assert_word("ĀāĂ㥹ĆćĈĉĊċČčĎď");
1207        // Latin Extended-B
1208        assert_word("ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏ");
1209        // Cyrillic
1210        assert_word("АБВГДЕЖЗИЙКЛМНОП");
1211        // Vietnamese (https://github.com/zed-industries/zed/issues/23245)
1212        assert_word("ThậmchíđếnkhithuachạychúngcònnhẫntâmgiếtnốtsốđôngtùchínhtrịởYênBáivàCaoBằng");
1213        // Bengali
1214        assert_word("গিয়েছিলেন");
1215        assert_word("ছেলে");
1216        assert_word("হচ্ছিল");
1217
1218        // non-word characters
1219        assert_not_word("你好");
1220        assert_not_word("안녕하세요");
1221        assert_not_word("こんにちは");
1222        assert_not_word("😀😁😂");
1223        assert_not_word("()[]{}<>");
1224
1225        // Non-breaking ("Glue") characters, see https://www.unicode.org/reports/tr14/
1226        // (https://github.com/zed-industries/zed/issues/59664)
1227        assert_word("\u{202F}"); // NNBSP " "
1228        assert_word("\u{00A0}"); // NBSP " "
1229        assert_word("\u{2011}"); // NBH "‑"
1230    }
1231
1232    // For compatibility with the test macro
1233    #[cfg(target_os = "macos")]
1234    use crate as gpui;
1235
1236    // These seem to vary wildly based on the text system.
1237    #[cfg(target_os = "macos")]
1238    #[crate::test]
1239    fn test_wrap_shaped_line(cx: &mut TestAppContext) {
1240        cx.update(|cx| {
1241            let text_system = WindowTextSystem::new(cx.text_system().clone());
1242
1243            let normal = TextRun {
1244                len: 0,
1245                font: font("Helvetica"),
1246                color: Default::default(),
1247                underline: Default::default(),
1248                ..Default::default()
1249            };
1250            let bold = TextRun {
1251                len: 0,
1252                font: font("Helvetica").bold(),
1253                ..Default::default()
1254            };
1255
1256            let text = "aa bbb cccc ddddd eeee".into();
1257            let lines = text_system
1258                .shape_text(
1259                    text,
1260                    px(16.),
1261                    &[
1262                        normal.with_len(4),
1263                        bold.with_len(5),
1264                        normal.with_len(6),
1265                        bold.with_len(1),
1266                        normal.with_len(7),
1267                    ],
1268                    Some(px(72.)),
1269                    None,
1270                )
1271                .unwrap();
1272
1273            assert_eq!(
1274                lines[0].layout.wrap_boundaries(),
1275                &[
1276                    WrapBoundary {
1277                        run_ix: 0,
1278                        glyph_ix: 7
1279                    },
1280                    WrapBoundary {
1281                        run_ix: 0,
1282                        glyph_ix: 12
1283                    },
1284                    WrapBoundary {
1285                        run_ix: 0,
1286                        glyph_ix: 18
1287                    }
1288                ],
1289            );
1290        });
1291    }
1292
1293    #[test]
1294    fn test_multiline_truncation_fits_within_wrapped_lines() {
1295        let mut wrapper = build_wrapper();
1296
1297        // With .ZedMono at 16px, each char is 9.6px wide.
1298        // wrap_width = 72px fits ~7 chars per line.
1299        //
1300        // "aa bbbbbb cccccc dddddd eeee ffff" with wrap_width=72px wraps as:
1301        //   Line 1: "aa "       (28.8px, wraps because "bbbbbb" won't fit)
1302        //   Line 2: "bbbbbb "   (67.2px)
1303        //   Line 3: "cccccc "   (67.2px)
1304        //   ...
1305        //
1306        // truncate_wrapped_line should wrap first to find line 2 starts at
1307        // "bbbbbb...", then truncate only that line to fit with ellipsis.
1308        let text: &str = "aa bbbbbb cccccc dddddd eeee ffff";
1309        let wrap_width = px(72.);
1310        let max_lines: usize = 2;
1311
1312        let runs = generate_test_runs(&[text.len()]);
1313        let (truncated, _) = wrapper.truncate_wrapped_line(
1314            text.into(),
1315            wrap_width,
1316            max_lines,
1317            "\u{2026}",
1318            &runs,
1319            TruncateFrom::End,
1320        );
1321
1322        // The truncated text, when wrapped, must fit within max_lines lines.
1323        let wrap_count = wrapper
1324            .wrap_line(&[LineFragment::text(&truncated)], wrap_width)
1325            .count();
1326
1327        assert!(
1328            wrap_count < max_lines,
1329            "Truncated text '{}' wraps into {} visual lines, expected at most {}",
1330            truncated,
1331            wrap_count + 1,
1332            max_lines
1333        );
1334
1335        // The truncated text should end with the ellipsis.
1336        assert!(
1337            truncated.ends_with('\u{2026}'),
1338            "Truncated text '{}' should end with ellipsis",
1339            truncated
1340        );
1341    }
1342
1343    #[test]
1344    fn test_multiline_truncation_no_truncation_needed() {
1345        let mut wrapper = build_wrapper();
1346
1347        // Text that fits in 2 lines shouldn't be truncated.
1348        // Line 1: "aa bbb " (67.2px), Line 2: "cccccc" (57.6px)
1349        let text: &str = "aa bbb cccccc";
1350        let wrap_width = px(72.);
1351        let max_lines: usize = 2;
1352
1353        let runs = generate_test_runs(&[text.len()]);
1354        let (result, _) = wrapper.truncate_wrapped_line(
1355            text.into(),
1356            wrap_width,
1357            max_lines,
1358            "\u{2026}",
1359            &runs,
1360            TruncateFrom::End,
1361        );
1362
1363        assert_eq!(
1364            result.as_ref(),
1365            text,
1366            "Text that fits should not be modified"
1367        );
1368    }
1369
1370    #[test]
1371    fn test_multiline_truncation_three_lines() {
1372        let mut wrapper = build_wrapper();
1373
1374        let text: &str = "aa bbb cccc ddddd eeee ffff gggg hhhh iiii jjjj";
1375        let wrap_width = px(72.);
1376        let max_lines: usize = 3;
1377
1378        let runs = generate_test_runs(&[text.len()]);
1379        let (truncated, _) = wrapper.truncate_wrapped_line(
1380            text.into(),
1381            wrap_width,
1382            max_lines,
1383            "\u{2026}",
1384            &runs,
1385            TruncateFrom::End,
1386        );
1387
1388        let wrap_count = wrapper
1389            .wrap_line(&[LineFragment::text(&truncated)], wrap_width)
1390            .count();
1391
1392        assert!(
1393            wrap_count < max_lines,
1394            "Truncated text '{}' wraps into {} visual lines, expected at most {}",
1395            truncated,
1396            wrap_count + 1,
1397            max_lines
1398        );
1399
1400        assert!(
1401            truncated.ends_with('\u{2026}'),
1402            "Truncated text '{}' should end with ellipsis",
1403            truncated
1404        );
1405    }
1406
1407    #[test]
1408    fn test_multiline_truncation_with_newlines() {
1409        let mut wrapper = build_wrapper();
1410
1411        // "hello\nworld foo bar baz" with line_clamp(2):
1412        // shape_text splits on \n, giving physical lines "hello" and
1413        // "world foo bar baz". The newline consumes line 1, so the
1414        // second physical line should be truncated on line 2.
1415        let text: &str = "hello\nworld foo bar baz";
1416        let wrap_width = px(72.);
1417        let max_lines: usize = 2;
1418
1419        let runs = generate_test_runs(&[text.len()]);
1420        let (truncated, _) = wrapper.truncate_wrapped_line(
1421            text.into(),
1422            wrap_width,
1423            max_lines,
1424            "\u{2026}",
1425            &runs,
1426            TruncateFrom::End,
1427        );
1428
1429        // The newline should be preserved.
1430        let parts: Vec<&str> = truncated.splitn(2, '\n').collect();
1431        assert_eq!(
1432            parts.len(),
1433            2,
1434            "Newline should be preserved: '{}'",
1435            truncated
1436        );
1437        assert_eq!(parts[0], "hello");
1438
1439        // The second line should fit within wrap_width and end with ellipsis.
1440        let second_line_width: Pixels = parts[1].chars().map(|c| wrapper.width_for_char(c)).sum();
1441        assert!(
1442            second_line_width <= wrap_width,
1443            "Second line '{}' ({}px) exceeds wrap_width ({}px)",
1444            parts[1],
1445            second_line_width,
1446            wrap_width
1447        );
1448        assert!(
1449            truncated.ends_with('\u{2026}'),
1450            "Should end with ellipsis: '{}'",
1451            truncated
1452        );
1453    }
1454
1455    #[test]
1456    fn test_multiline_truncation_newline_on_last_line() {
1457        let mut wrapper = build_wrapper();
1458
1459        // "hello\nworld\nmore" with line_clamp(2):
1460        // Line 1: "hello", Line 2: "world" — but there's a third line,
1461        // so line 2 should be truncated with ellipsis.
1462        let text: &str = "hello\nworld\nmore";
1463        let wrap_width = px(72.);
1464        let max_lines: usize = 2;
1465
1466        let runs = generate_test_runs(&[text.len()]);
1467        let (truncated, _) = wrapper.truncate_wrapped_line(
1468            text.into(),
1469            wrap_width,
1470            max_lines,
1471            "\u{2026}",
1472            &runs,
1473            TruncateFrom::End,
1474        );
1475
1476        let parts: Vec<&str> = truncated.splitn(2, '\n').collect();
1477        assert_eq!(parts[0], "hello");
1478        assert!(
1479            truncated.ends_with('\u{2026}'),
1480            "Should end with ellipsis since there's more content: '{}'",
1481            truncated
1482        );
1483    }
1484
1485    #[test]
1486    fn test_truncate_line_middle() {
1487        let mut wrapper = build_wrapper();
1488
1489        // No truncation when text fits within a very wide budget.
1490        let short_text = "hello world";
1491        let runs = generate_test_runs(&[short_text.len()]);
1492        let (result, result_runs) = wrapper.truncate_line(
1493            short_text.into(),
1494            px(10000.),
1495            "…",
1496            &runs,
1497            TruncateFrom::Middle,
1498        );
1499        assert_eq!(result.as_ref(), short_text);
1500        assert_eq!(result_runs.len(), 1);
1501        assert_eq!(result_runs[0].len, short_text.len());
1502
1503        // Basic middle truncation: long string with px(100.) budget.
1504        let long_text = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";
1505        let runs = generate_test_runs(&[long_text.len()]);
1506        let (result, _result_runs) =
1507            wrapper.truncate_line(long_text.into(), px(100.), "…", &runs, TruncateFrom::Middle);
1508        assert!(
1509            result.contains('…'),
1510            "Middle-truncated result should contain '…', got: '{}'",
1511            result
1512        );
1513        assert!(
1514            result.chars().count() < long_text.chars().count(),
1515            "Middle-truncated result should be shorter than original"
1516        );
1517        assert_eq!(
1518            result.chars().next(),
1519            long_text.chars().next(),
1520            "Result should start with the same first character as original"
1521        );
1522        assert_eq!(
1523            result.chars().last(),
1524            long_text.chars().last(),
1525            "Result should end with the same last character as original"
1526        );
1527
1528        // Degenerate case: budget so narrow that middle truncation cannot find a valid split.
1529        // Still show the truncation affix instead of returning the original overflowing text.
1530        let text = "abcdef";
1531        let runs = generate_test_runs(&[text.len()]);
1532        let (result, result_runs) =
1533            wrapper.truncate_line(text.into(), px(1.), "…", &runs, TruncateFrom::Middle);
1534        assert_eq!(result.as_ref(), "…");
1535        assert_eq!(result_runs.len(), 1);
1536        assert_eq!(result_runs[0].len, "…".len());
1537
1538        // Run adjustment correctness: multiple runs across the string.
1539        // Verify that the returned runs' lengths sum to result.len().
1540        let multi_run_text = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";
1541        let run_lens = [20, 20, multi_run_text.len() - 40];
1542        let runs = generate_test_runs(&run_lens);
1543        let (result, result_runs) = wrapper.truncate_line(
1544            multi_run_text.into(),
1545            px(100.),
1546            "…",
1547            &runs,
1548            TruncateFrom::Middle,
1549        );
1550        let total_run_len: usize = result_runs.iter().map(|r| r.len).sum();
1551        assert_eq!(
1552            total_run_len,
1553            result.len(),
1554            "Sum of run lengths ({}) should equal result byte length ({})",
1555            total_run_len,
1556            result.len()
1557        );
1558    }
1559
1560    #[test]
1561    fn test_multiline_truncation_trailing_newline() {
1562        let mut wrapper = build_wrapper();
1563
1564        // "hello\nworld\n" with line_clamp(2):
1565        // The trailing newline has no content after it, so no ellipsis.
1566        let text: &str = "hello\nworld\n";
1567        let wrap_width = px(72.);
1568        let max_lines: usize = 2;
1569
1570        let runs = generate_test_runs(&[text.len()]);
1571        let (result, _) = wrapper.truncate_wrapped_line(
1572            text.into(),
1573            wrap_width,
1574            max_lines,
1575            "\u{2026}",
1576            &runs,
1577            TruncateFrom::End,
1578        );
1579
1580        assert!(
1581            !result.ends_with('\u{2026}'),
1582            "Trailing newline with no content should not add ellipsis: '{}'",
1583            result
1584        );
1585    }
1586
1587    #[test]
1588    fn test_multiline_truncation_newline_fits_exactly() {
1589        let mut wrapper = build_wrapper();
1590
1591        // "hello\nworld" with line_clamp(2):
1592        // Exactly 2 lines, no truncation needed.
1593        let text: &str = "hello\nworld";
1594        let wrap_width = px(72.);
1595        let max_lines: usize = 2;
1596
1597        let runs = generate_test_runs(&[text.len()]);
1598        let (result, _) = wrapper.truncate_wrapped_line(
1599            text.into(),
1600            wrap_width,
1601            max_lines,
1602            "\u{2026}",
1603            &runs,
1604            TruncateFrom::End,
1605        );
1606
1607        assert_eq!(
1608            result.as_ref(),
1609            text,
1610            "Text that fits exactly should not be modified: '{}'",
1611            result
1612        );
1613    }
1614}