Skip to main content

gpui_base/input/editor/display_map/
text_wrapper.rs

1use super::inline_line::InputLine;
2mod measurements;
3mod wrap_width;
4use gpui::Half;
5use measurements::WidthMeasurements;
6use std::borrow::Cow;
7use std::ops::Range;
8use std::rc::Rc;
9use wrap_width::{MeasuredWrap, WidthRange};
10
11use gpui::{
12    App, Bounds, ContentMask, Font, LineFragment, Pixels, Point, ShapedLine, Size, TextAlign,
13    Window, point, px, size,
14};
15use ropey::Rope;
16use smallvec::SmallVec;
17use sum_tree::{Bias, Dimensions, SumTree};
18use unicode_segmentation::UnicodeSegmentation as _;
19
20use crate::input::{
21    Point as TreeSitterPoint, RopeExt, TabSize,
22    layout::{LastLayout, WhitespaceIndicators},
23    tab_stops::{expanded_width, tab_stop_width},
24};
25
26/// Controls how soft-wrapped continuation lines are indented.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub enum WrappingIndent {
29    /// Continuation lines start flush-left at the full editor width.
30    None,
31    /// Continuation lines keep the same indentation as the first line.
32    #[default]
33    Same,
34}
35
36/// Unmodified upstream character-first algorithm is the independent differential-test oracle.
37#[cfg(test)]
38fn measured_wrap_boundaries(
39    text: &str,
40    width: Pixels,
41    wrapping_indent: WrappingIndent,
42    mut measure: impl FnMut(&str) -> Pixels,
43) -> Vec<gpui::Boundary> {
44    let indent = if wrapping_indent == WrappingIndent::Same {
45        text.chars()
46            .take_while(|&c| c == ' ')
47            .count()
48            .min(gpui::LineWrapper::MAX_INDENT as usize)
49    } else {
50        0
51    };
52    let indent_width = measure(&text[..indent]);
53    let ends: Vec<usize> = text
54        .grapheme_indices(true)
55        .map(|(ix, grapheme)| ix + grapheme.len())
56        .collect();
57    let opportunities: Vec<usize> = unicode_linebreak::linebreaks(text)
58        .map(|(ix, _)| ix)
59        .filter(|ix| ends.binary_search(ix).is_ok())
60        .collect();
61    let mut result = Vec::new();
62    let mut first = 0;
63    let mut start = 0;
64    while first < ends.len() {
65        let available = if start == 0 {
66            width
67        } else {
68            width - indent_width
69        };
70        // Find the fitting prefix locally. Exponential probing avoids shaping
71        // the entire remaining logical line for every visual row of a long paste.
72        let remaining = ends.len() - first;
73        let mut low = 0;
74        let mut high = 1;
75        while measure(&text[start..ends[first + high - 1]]) <= available {
76            low = high;
77            if high == remaining {
78                break;
79            }
80            high = (high * 2).min(remaining);
81        }
82        while low + 1 < high {
83            let mid = (low + high) / 2;
84            if measure(&text[start..ends[first + mid - 1]]) <= available {
85                low = mid;
86            } else {
87                high = mid;
88            }
89        }
90        // An indivisible grapheme wider than the viewport still consumes a row.
91        let fitting_end = ends[first + low.max(1) - 1];
92        if fitting_end == text.len() {
93            break;
94        }
95        let candidate = opportunities.partition_point(|&ix| ix <= fitting_end);
96        let end = candidate
97            .checked_sub(1)
98            .map(|ix| opportunities[ix])
99            .filter(|&ix| ix > start && (start != 0 || ix > indent))
100            .unwrap_or(fitting_end);
101        result.push(gpui::Boundary {
102            ix: end,
103            next_indent: indent as u32,
104        });
105        first = ends.partition_point(|&ix| ix <= end);
106        start = end;
107    }
108    result
109}
110
111/// Preserve the measured comparisons that make these breaks valid at nearby widths.
112fn measured_wrap(
113    text: &str,
114    width: Pixels,
115    wrapping_indent: WrappingIndent,
116    mut measure: impl FnMut(&str) -> Pixels,
117) -> MeasuredWrap {
118    #[cfg(test)]
119    wrap_width::MEASURED_LINES.with(|count| count.set(count.get() + 1));
120    let mut valid_widths = WidthRange::all();
121    let indent = if wrapping_indent == WrappingIndent::Same {
122        text.chars()
123            .take_while(|&c| c == ' ')
124            .count()
125            .min(gpui::LineWrapper::MAX_INDENT as usize)
126    } else {
127        0
128    };
129    let indent_width = measure(&text[..indent]);
130    let ends: Vec<usize> = text
131        .grapheme_indices(true)
132        .map(|(ix, grapheme)| ix + grapheme.len())
133        .collect();
134    let opportunities: Vec<usize> = unicode_linebreak::linebreaks(text)
135        .map(|(ix, _)| ix)
136        .filter(|ix| ends.binary_search(ix).is_ok())
137        .collect();
138    let mut result = Vec::new();
139    let mut first = 0;
140    let mut start = 0;
141    while first < ends.len() {
142        let available = if start == 0 {
143            width
144        } else {
145            width - indent_width
146        };
147        // Probe legal word breaks first. Character-fit changes inside the same word do not
148        // change the result, so they must not invalidate a cached line during a divider drag.
149        // Bound word probes before shaping: a single word can span the entire remaining line.
150        // Beyond this local window, use the original exponential grapheme search instead.
151        const MAX_WORD_PROBE_GRAPHEMES: usize = 256;
152        let word_probe_end = ends[first..]
153            .get(MAX_WORD_PROBE_GRAPHEMES - 1)
154            .copied()
155            .unwrap_or(text.len());
156        let mut fitting = |candidates: &[usize], limit: Option<usize>| {
157            let mut fits = |end| {
158                if limit.is_some_and(|limit| end > limit) {
159                    return None;
160                }
161                Some(valid_widths.fits(
162                    measure(&text[start..end]),
163                    available,
164                    if start == 0 { px(0.) } else { indent_width },
165                ))
166            };
167            let mut low = 0;
168            let mut high = 1;
169            while high <= candidates.len() && fits(candidates[high - 1])? {
170                low = high;
171                if high == candidates.len() {
172                    break;
173                }
174                high = (high * 2).min(candidates.len());
175            }
176            while low + 1 < high {
177                let mid = (low + high) / 2;
178                if fits(candidates[mid - 1])? {
179                    low = mid;
180                } else {
181                    high = mid;
182                }
183            }
184            Some(low)
185        };
186        let first_word =
187            opportunities.partition_point(|&ix| ix <= start || (start == 0 && ix <= indent));
188        let words = &opportunities[first_word..];
189        let end = if let Some(word_count) = fitting(words, Some(word_probe_end))
190            && word_count > 0
191        {
192            words[word_count - 1]
193        } else {
194            // An oversized word retains the original complete-grapheme fallback. At least one
195            // grapheme is consumed even when it is wider than the available viewport.
196            let count = fitting(&ends[first..], None).unwrap();
197            let fitting_end = ends[first + count.max(1) - 1];
198            if fitting_end == text.len() {
199                break;
200            }
201            let word_count = words.partition_point(|&ix| ix <= fitting_end);
202            word_count
203                .checked_sub(1)
204                .map(|ix| words[ix])
205                .unwrap_or(fitting_end)
206        };
207        if end == text.len() {
208            break;
209        }
210        result.push(gpui::Boundary {
211            ix: end,
212            next_indent: indent as u32,
213        });
214        first = ends.partition_point(|&ix| ix <= end);
215        start = end;
216    }
217    MeasuredWrap {
218        boundaries: result,
219        valid_widths,
220    }
221}
222
223/// A line with soft wrapped lines info.
224#[derive(Debug, Clone)]
225pub(crate) struct LineItem {
226    /// The byte length of the line, without the end `\n`.
227    len: usize,
228    /// Number of leading characters of the line reserved as indentation for continuation wrapped
229    /// lines, when [`WrappingIndent::Same`] is used.
230    ///
231    /// Zero when [`WrappingIndent::None`] is used or the line is not wrapped.
232    pub(crate) indent: u32,
233    /// The soft wrapped lines relative byte range (0..len) of this line (Include first line).
234    ///
235    /// Not contains the line end `\n`.
236    pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,
237    /// Width-only reuse is valid only while every measured fit decision stays unchanged.
238    valid_widths: WidthRange,
239}
240
241impl LineItem {
242    /// Get the bytes length of this line.
243    #[inline]
244    pub(crate) fn len(&self) -> usize {
245        self.len
246    }
247
248    /// Get number of soft wrapped lines of this line (include the first line).
249    #[inline]
250    pub(crate) fn lines_len(&self) -> usize {
251        self.wrapped_lines.len()
252    }
253}
254
255/// Summary of a subtree of [`LineItem`]s, maintained incrementally by the [`SumTree`].
256#[derive(Debug, Clone)]
257pub(crate) struct LineSummary {
258    /// Number of buffer lines.
259    buffer_rows: usize,
260    /// Number of wrap rows (sum of each line's `lines_len()`).
261    wrap_rows: usize,
262    /// Sum of byte lengths of the buffer lines (without the trailing `\n`).
263    bytes: usize,
264    /// Byte length of the longest line in this subtree.
265    max_line_len: usize,
266    /// Buffer row (relative to this subtree) of the first line achieving `max_line_len`.
267    longest_row: usize,
268    /// Intersection permits a constant-time no-op when every line retains its current breaks.
269    valid_widths: WidthRange,
270}
271
272impl sum_tree::Summary for LineSummary {
273    type Context<'a> = &'a ();
274
275    fn zero(_: &()) -> Self {
276        LineSummary {
277            buffer_rows: 0,
278            wrap_rows: 0,
279            bytes: 0,
280            max_line_len: 0,
281            longest_row: 0,
282            valid_widths: WidthRange::all(),
283        }
284    }
285
286    fn add_summary(&mut self, other: &Self, _: &()) {
287        // Keep the leftmost row that achieves a strictly greater length
288        if other.max_line_len > self.max_line_len {
289            self.longest_row = self.buffer_rows + other.longest_row;
290            self.max_line_len = other.max_line_len;
291        }
292        self.buffer_rows += other.buffer_rows;
293        self.wrap_rows += other.wrap_rows;
294        self.bytes += other.bytes;
295        self.valid_widths.intersect(other.valid_widths);
296    }
297}
298
299impl sum_tree::Item for LineItem {
300    type Summary = LineSummary;
301
302    fn summary(&self, _: &()) -> LineSummary {
303        LineSummary {
304            buffer_rows: 1,
305            wrap_rows: self.lines_len(),
306            bytes: self.len(),
307            max_line_len: self.len(),
308            longest_row: 0,
309            valid_widths: self.valid_widths,
310        }
311    }
312}
313
314/// Cursor dimension counting buffer rows.
315#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
316pub(crate) struct BufferRows(pub usize);
317
318impl<'a> sum_tree::Dimension<'a, LineSummary> for BufferRows {
319    fn zero(_: &()) -> Self {
320        BufferRows(0)
321    }
322
323    fn add_summary(&mut self, summary: &'a LineSummary, _: &()) {
324        self.0 += summary.buffer_rows;
325    }
326}
327
328/// Cursor dimension counting wrap rows.
329#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
330pub(crate) struct WrapRows(pub usize);
331
332impl<'a> sum_tree::Dimension<'a, LineSummary> for WrapRows {
333    fn zero(_: &()) -> Self {
334        WrapRows(0)
335    }
336
337    fn add_summary(&mut self, summary: &'a LineSummary, _: &()) {
338        self.0 += summary.wrap_rows;
339    }
340}
341
342/// Used to prepare the text with soft wrap to be get lines to displayed in the Editor.
343///
344/// After use lines to calculate the scroll size of the Editor.
345pub(crate) struct TextWrapper {
346    text: Rope,
347    font: Font,
348    font_size: Pixels,
349    /// If is none, it means the text is not wrapped
350    wrap_width: Option<Pixels>,
351    wrapping_indent: WrappingIndent,
352    /// Spaces per tab stop, so tabs are measured as they are drawn.
353    tab_size: usize,
354    /// The lines by split \n
355    pub(crate) lines: SumTree<LineItem>,
356
357    inline_metrics: Rc<[(Range<usize>, Pixels)]>,
358    /// Exact native widths avoid reshaping the same prefix when a drag crosses wrap thresholds.
359    width_measurements: Rc<std::cell::RefCell<WidthMeasurements>>,
360    _initialized: bool,
361}
362
363#[allow(unused)]
364impl TextWrapper {
365    pub(crate) fn new(font: Font, font_size: Pixels, wrap_width: Option<Pixels>) -> Self {
366        Self {
367            text: Rope::new(),
368            font,
369            font_size,
370            wrap_width,
371            wrapping_indent: WrappingIndent::default(),
372            tab_size: TabSize::default().tab_size,
373            lines: SumTree::new(&()),
374            inline_metrics: Rc::from([]),
375            width_measurements: Rc::default(),
376            _initialized: false,
377        }
378    }
379
380    /// Whether the text has been shaped once, which happens at the first layout.
381    #[inline]
382    pub(crate) fn is_prepared(&self) -> bool {
383        self._initialized
384    }
385
386    #[inline]
387    pub(crate) fn set_default_text(&mut self, text: &Rope) {
388        self.text = text.clone();
389    }
390
391    /// Get reference to the rope text.
392    #[inline]
393    pub(crate) fn text(&self) -> &Rope {
394        &self.text
395    }
396
397    /// Get the total number of lines including wrapped lines.
398    #[inline]
399    pub(crate) fn len(&self) -> usize {
400        self.lines.summary().wrap_rows
401    }
402
403    /// Get the total number of buffer lines.
404    #[inline]
405    pub(crate) fn lines_count(&self) -> usize {
406        self.lines.summary().buffer_rows
407    }
408
409    /// Get the 0-based row index of the longest line (by byte length).
410    #[inline]
411    pub(crate) fn longest_row(&self) -> usize {
412        self.lines.summary().longest_row
413    }
414
415    /// Get the line item by buffer row index.
416    #[inline]
417    pub(crate) fn line(&self, row: usize) -> Option<&LineItem> {
418        let mut cursor = self.lines.cursor::<BufferRows>(&());
419        cursor.seek(&BufferRows(row), Bias::Right);
420        cursor.item()
421    }
422
423    /// Iterate buffer lines in order.
424    #[inline]
425    pub(crate) fn iter_lines(&self) -> impl Iterator<Item = &LineItem> {
426        self.lines.iter()
427    }
428
429    /// First wrap row of buffer line `row`. Returns the total wrap row count if `row` is
430    /// out of range.
431    pub(crate) fn buffer_line_to_first_wrap_row(&self, row: usize) -> usize {
432        let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
433        cursor.seek(&BufferRows(row), Bias::Right);
434        cursor.start().1.0
435    }
436
437    /// Wrap row range of buffer line `row`.
438    pub(crate) fn buffer_line_to_wrap_row_range(&self, row: usize) -> Range<usize> {
439        let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
440        cursor.seek(&BufferRows(row), Bias::Right);
441        let start = cursor.start().1.0;
442        let len = cursor.item().map(|l| l.lines_len()).unwrap_or(0);
443        start..start + len
444    }
445
446    /// Buffer line containing wrap row `wrap_row`, clamped to the last line.
447    pub(crate) fn wrap_row_to_buffer_line(&self, wrap_row: usize) -> usize {
448        let mut cursor = self.lines.cursor::<Dimensions<WrapRows, BufferRows>>(&());
449        cursor.seek(&WrapRows(wrap_row), Bias::Right);
450        match cursor.item() {
451            Some(_) => cursor.start().1.0,
452            None => self.lines_count().saturating_sub(1),
453        }
454    }
455
456    pub(crate) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
457        if wrap_width == self.wrap_width {
458            return;
459        }
460
461        let width_only = self.wrap_width.is_some() && wrap_width.is_some();
462        self.wrap_width = wrap_width;
463        if width_only
464            && self
465                .lines
466                .summary()
467                .valid_widths
468                .contains(wrap_width.unwrap())
469        {
470            return;
471        }
472        let text = self.text.clone();
473        self.update_wrapped(&text, &(0..text.len()), &text, width_only, cx);
474    }
475
476    pub(crate) fn set_wrapping_indent(&mut self, wrapping_indent: WrappingIndent, cx: &mut App) {
477        if wrapping_indent == self.wrapping_indent {
478            return;
479        }
480
481        self.wrapping_indent = wrapping_indent;
482        self.update_all(&self.text.clone(), cx);
483    }
484
485    /// Returns whether the tab size changed, and so the wrapping.
486    pub(crate) fn set_tab_size(&mut self, tab_size: usize, cx: &mut App) -> bool {
487        if tab_size == self.tab_size {
488            return false;
489        }
490
491        self.tab_size = tab_size;
492        self.update_all(&self.text.clone(), cx);
493        true
494    }
495
496    pub(crate) fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
497        if self.font.eq(&font) && self.font_size == font_size {
498            return;
499        }
500
501        self.font = font;
502        self.font_size = font_size;
503        self.update_all(&self.text.clone(), cx);
504    }
505
506    pub(crate) fn prepare_if_need(&mut self, text: &Rope, cx: &mut App) -> bool {
507        if self._initialized {
508            return false;
509        }
510        self._initialized = true;
511        self.update_all(text, cx);
512        true
513    }
514
515    /// Update the text wrapper and recalculate the wrapped lines.
516    ///
517    /// If the `text` is the same as the current text, do nothing.
518    ///
519    /// - `changed_text`: The text [`Rope`] that has changed.
520    /// - `range`: The `selected_range` before change.
521    /// - `new_text`: The inserted text.
522    /// - `force`: Whether to force the update, if false, the update will be skipped if the text is the same.
523    /// - `cx`: The application context.
524    pub(crate) fn update(
525        &mut self,
526        changed_text: &Rope,
527        range: &Range<usize>,
528        new_text: &Rope,
529        cx: &mut App,
530    ) {
531        self.update_wrapped(changed_text, range, new_text, false, cx);
532    }
533
534    /// Only width changes reuse rows and measurements; edits, fonts, tab stops and inline metrics remeasure.
535    fn update_wrapped(
536        &mut self,
537        changed_text: &Rope,
538        range: &Range<usize>,
539        new_text: &Rope,
540        reuse_widths: bool,
541        cx: &mut App,
542    ) {
543        let mut line_wrapper = cx
544            .text_system()
545            .line_wrapper(self.font.clone(), self.font_size);
546        let metrics = self.inline_metrics.clone();
547        let measurements = self.width_measurements.clone();
548        if !reuse_widths {
549            measurements.borrow_mut().clear();
550        }
551        let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
552        let font = self.font.clone();
553        let font_size = self.font_size;
554        let wrapping_indent = self.wrapping_indent;
555        let tab_stop = tab_stop_width(&text_system, &font, font_size, self.tab_size);
556        self.update_lines(
557            changed_text,
558            range,
559            new_text,
560            reuse_widths,
561            &mut |line_str, wrap_width, line_start| {
562                let mut fragments = Vec::new();
563                let mut offset = 0;
564                let first = metrics.partition_point(|(r, _)| r.end <= line_start);
565                for (range, width) in &metrics[first..] {
566                    if range.start >= line_start + line_str.len() {
567                        break;
568                    }
569                    if range.start < line_start || range.end > line_start + line_str.len() {
570                        continue;
571                    }
572                    let range = range.start - line_start..range.end - line_start;
573                    if !line_str.is_char_boundary(range.start)
574                        || !line_str.is_char_boundary(range.end)
575                    {
576                        continue;
577                    }
578                    if offset < range.start {
579                        fragments.push(LineFragment::text(&line_str[offset..range.start]));
580                    }
581                    fragments.push(LineFragment::element(*width, range.len()));
582                    offset = range.end;
583                }
584                if fragments.is_empty() {
585                    return measured_wrap(line_str, wrap_width, wrapping_indent, |text| {
586                        measurements.borrow_mut().measure(text, || {
587                            let layout = text_system.layout_line(
588                                text,
589                                font_size,
590                                &[gpui::TextRun {
591                                    len: text.len(),
592                                    font: font.clone(),
593                                    color: gpui::black(),
594                                    background_color: None,
595                                    underline: None,
596                                    strikethrough: None,
597                                }],
598                                None,
599                            );
600                            expanded_width(&layout, text, tab_stop)
601                        })
602                    });
603                }
604                if offset < line_str.len() {
605                    fragments.push(LineFragment::text(&line_str[offset..]));
606                }
607                // Inline element widths retain the original wrapper; no safe interval is inferred.
608                MeasuredWrap::uncached(
609                    line_wrapper
610                        .wrap_line(&fragments, wrap_width, gpui::IndentAdjustment::SameIndent)
611                        .collect(),
612                )
613            },
614        );
615    }
616
617    pub(crate) fn adjust_inline_metrics(&mut self, range: &Range<usize>, new_len: usize) {
618        if self.inline_metrics.is_empty() {
619            return;
620        }
621        let shift = new_len as isize - range.len() as isize;
622        self.inline_metrics = self
623            .inline_metrics
624            .iter()
625            .filter_map(|(token, width)| {
626                if token.start < range.end && range.start < token.end {
627                    return None;
628                }
629                let token = if token.start >= range.end {
630                    token.start.checked_add_signed(shift)?..token.end.checked_add_signed(shift)?
631                } else {
632                    token.clone()
633                };
634                Some((token, *width))
635            })
636            .collect();
637    }
638
639    pub(crate) fn set_inline_metrics(
640        &mut self,
641        metrics: Rc<[(Range<usize>, Pixels)]>,
642        cx: &mut App,
643    ) {
644        if self.inline_metrics == metrics {
645            return;
646        }
647        // Only rows whose element geometry changed need another wrap pass.
648        let mut affected = Vec::new();
649        let (mut old, mut new) = (
650            self.inline_metrics.iter().peekable(),
651            metrics.iter().peekable(),
652        );
653        while old.peek().is_some() || new.peek().is_some() {
654            match (old.peek(), new.peek()) {
655                (Some(a), Some(b)) if a == b => {
656                    old.next();
657                    new.next();
658                }
659                (Some(a), Some(b)) if a.0.start <= b.0.start => {
660                    affected.push(a.0.clone());
661                    old.next();
662                }
663                (Some(_), Some(b)) | (None, Some(b)) => {
664                    affected.push(b.0.clone());
665                    new.next();
666                }
667                (Some(a), None) => {
668                    affected.push(a.0.clone());
669                    old.next();
670                }
671                (None, None) => break,
672            }
673        }
674        self.inline_metrics = metrics;
675        let text = self.text.clone();
676        let mut rows: Vec<usize> = affected
677            .iter()
678            .map(|r| text.offset_to_point(r.start.min(text.len())).row)
679            .collect();
680        rows.sort_unstable();
681        rows.dedup();
682        for row in rows {
683            let start = text.line_start_offset(row);
684            let end = text.line_end_offset(row);
685            self.update(
686                &text,
687                &(start..end),
688                &Rope::from(text.slice(start..end).to_string()),
689                cx,
690            );
691        }
692    }
693
694    /// Keep the existing synthetic edit tests independent of native glyph measurement.
695    #[cfg(test)]
696    fn _update<F>(
697        &mut self,
698        changed_text: &Rope,
699        range: &Range<usize>,
700        new_text: &Rope,
701        wrap_line: &mut F,
702    ) where
703        F: FnMut(&str, Pixels, usize) -> Vec<gpui::Boundary>,
704    {
705        self.update_lines(
706            changed_text,
707            range,
708            new_text,
709            false,
710            &mut |text, width, start| MeasuredWrap::uncached(wrap_line(text, width, start)),
711        );
712    }
713
714    /// Splice changed rows into the sole display map, retaining valid rows on full width passes.
715    fn update_lines<F>(
716        &mut self,
717        changed_text: &Rope,
718        range: &Range<usize>,
719        new_text: &Rope,
720        reuse_widths: bool,
721        wrap_line: &mut F,
722    ) where
723        F: FnMut(&str, Pixels, usize) -> MeasuredWrap,
724    {
725        // Remove the old changed lines.
726        let buffer_line_count = self.lines_count();
727        let start_row = self.text.offset_to_point(range.start).row;
728        let start_row = start_row.min(buffer_line_count.saturating_sub(1));
729        let end_row = self.text.offset_to_point(range.end).row;
730        let end_row = end_row.min(buffer_line_count.saturating_sub(1));
731
732        // To add the new lines.
733        let new_start_row = changed_text.offset_to_point(range.start).row;
734        let new_end_row = changed_text
735            .offset_to_point(range.start + new_text.len())
736            .row;
737
738        let mut new_lines = Vec::with_capacity(new_end_row.saturating_sub(new_start_row) + 1);
739        let wrap_width = self.wrap_width;
740        let mut previous = self.lines.iter();
741        debug_assert!(!reuse_widths || (new_start_row == 0 && range == &(0..self.text.len())));
742
743        // line not contains `\n`.
744        for row in new_start_row..=new_end_row {
745            if reuse_widths {
746                if let Some(previous) = previous.next()
747                    && wrap_width.is_some_and(|width| previous.valid_widths.contains(width))
748                {
749                    new_lines.push(previous.clone());
750                    continue;
751                }
752            }
753            let line = changed_text.slice_line(row);
754            let mut wrapped_lines = SmallVec::<[Range<usize>; 1]>::new();
755            let mut prev_boundary_ix = 0;
756            let mut indent_chars = 0;
757            let mut valid_widths = WidthRange::all();
758
759            // If wrap_width is Pixels::MAX, skip wrapping to disable word wrap
760            if let Some(wrap_width) = wrap_width {
761                // Borrowed for lines within a single rope chunk.
762                let line_str: Cow<str> = line.into();
763                match self.wrapping_indent {
764                    WrappingIndent::Same => {
765                        // Here only have wrapped line, if there is no wrap meet, the `line_wraps`
766                        // result will empty.
767                        let measured =
768                            wrap_line(&line_str, wrap_width, changed_text.line_start_offset(row));
769                        valid_widths.intersect(measured.valid_widths);
770                        for boundary in measured.boundaries {
771                            wrapped_lines.push(prev_boundary_ix..boundary.ix);
772                            prev_boundary_ix = boundary.ix;
773                            indent_chars = boundary.next_indent;
774                        }
775                    }
776                    WrappingIndent::None => {
777                        // The first visual line keeps the line's leading indentation, so it is
778                        // wrapped as is.
779                        let boundaries =
780                            wrap_line(&line_str, wrap_width, changed_text.line_start_offset(row));
781                        valid_widths.intersect(boundaries.valid_widths);
782                        if let Some(first_ix) = boundaries.boundaries.first().map(|b| b.ix) {
783                            wrapped_lines.push(prev_boundary_ix..first_ix);
784                            prev_boundary_ix = first_ix;
785
786                            let continuation = wrap_line(
787                                &line_str[first_ix..],
788                                wrap_width,
789                                changed_text.line_start_offset(row) + first_ix,
790                            );
791                            valid_widths.intersect(continuation.valid_widths);
792                            for boundary in continuation.boundaries {
793                                let ix = first_ix + boundary.ix;
794                                wrapped_lines.push(prev_boundary_ix..ix);
795                                prev_boundary_ix = ix;
796                            }
797                        }
798                    }
799                }
800            }
801
802            // Reset of the line
803            if prev_boundary_ix < line.len() || prev_boundary_ix == 0 {
804                wrapped_lines.push(prev_boundary_ix..line.len());
805            }
806
807            new_lines.push(LineItem {
808                len: line.len(),
809                indent: indent_chars,
810                wrapped_lines,
811                valid_widths,
812            });
813        }
814
815        drop(previous);
816        if self.lines.is_empty() {
817            self.lines = SumTree::from_iter(new_lines, &());
818        } else {
819            let mut cursor = self.lines.cursor::<BufferRows>(&());
820            let mut new_tree = cursor.slice(&BufferRows(start_row), Bias::Right);
821            // Skip the replaced rows
822            cursor.seek_forward(&BufferRows(end_row + 1), Bias::Right);
823            new_tree.extend(new_lines, &());
824            // Untouched rows after the edit
825            new_tree.append(cursor.suffix(), &());
826            drop(cursor);
827            self.lines = new_tree;
828        }
829
830        self.text = changed_text.clone();
831    }
832
833    /// Update the text wrapper and recalculate the wrapped lines.
834    ///
835    /// If the `text` is the same as the current text, do nothing.
836    fn update_all(&mut self, text: &Rope, cx: &mut App) {
837        self.update(text, &(0..text.len()), &text, cx);
838    }
839
840    /// Return display point (with soft wrap) from the given byte offset in the text.
841    ///
842    /// Panics if the `offset` is out of bounds.
843    pub(crate) fn offset_to_display_point(&self, offset: usize) -> WrapDisplayPoint {
844        self.offset_to_display_point_with_affinity(offset, false)
845    }
846
847    /// Like [`Self::offset_to_display_point`], but honours the caret's line-end affinity.
848    ///
849    /// A soft wrap boundary is one offset shared by two visual rows. Without affinity it always
850    /// resolves to the start of the second row, which is wrong for a caret that is being drawn at
851    /// the end of the first one -- vertical movement would then step from the row below the one
852    /// the user can see.
853    pub(crate) fn offset_to_display_point_with_affinity(
854        &self,
855        offset: usize,
856        line_end_affinity: bool,
857    ) -> WrapDisplayPoint {
858        let row = self.text.offset_to_point(offset).row;
859        let start = self.text.line_start_offset(row);
860
861        // Seek to buffer row
862        let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
863        cursor.seek(&BufferRows(row), Bias::Right);
864        let wrapped_row = cursor.start().1.0;
865        let Some(line) = cursor.item() else {
866            return WrapDisplayPoint::new(wrapped_row, 0, 0);
867        };
868
869        let local_offset = offset.saturating_sub(start);
870        for (ix, range) in line.wrapped_lines.iter().enumerate() {
871            // With affinity the boundary offset closes the current row instead of opening the
872            // next one, so the range is matched inclusively.
873            let matches =
874                range.contains(&local_offset) || (line_end_affinity && local_offset == range.end);
875            if matches {
876                return WrapDisplayPoint::new(
877                    wrapped_row + ix,
878                    ix,
879                    local_offset.saturating_sub(range.start),
880                );
881            }
882        }
883
884        // Otherwise return the eof of the line.
885        let last_range = line.wrapped_lines.last().unwrap_or(&(0..0));
886        let ix = line.lines_len().saturating_sub(1);
887        return WrapDisplayPoint::new(wrapped_row + ix, ix, last_range.len());
888    }
889
890    /// Return byte offset in the text from the given display point (with soft wrap).
891    ///
892    /// Panics if the `point.row` is out of bounds.
893    pub(crate) fn display_point_to_offset(&self, point: WrapDisplayPoint) -> usize {
894        // Seek to wrap row `point.row`
895        let mut cursor = self.lines.cursor::<Dimensions<WrapRows, BufferRows>>(&());
896        cursor.seek(&WrapRows(point.row), Bias::Right);
897        let Some(line) = cursor.item() else {
898            return self.text.len();
899        };
900        let wrapped_row = cursor.start().0.0;
901        let row = cursor.start().1.0;
902
903        let line_start = self.text.line_start_offset(row);
904        let local_row = point.row.saturating_sub(wrapped_row);
905        if let Some(range) = line.wrapped_lines.get(local_row) {
906            line_start + (range.start + point.column).min(range.end)
907        } else {
908            // If not found, return the end of the line.
909            line_start + line.len()
910        }
911    }
912
913    pub(crate) fn display_point_to_point(&self, point: WrapDisplayPoint) -> TreeSitterPoint {
914        let offset = self.display_point_to_offset(point);
915        self.text.offset_to_point(offset)
916    }
917
918    pub(crate) fn point_to_display_point(&self, point: TreeSitterPoint) -> WrapDisplayPoint {
919        let offset = self.text.point_to_offset(point);
920        self.offset_to_display_point(offset)
921    }
922}
923
924/// A display point within the soft-wrapped text.
925///
926/// This represents a position in the text after soft-wrapping,
927/// with an additional `local_row` field tracking the wrap line
928/// within the original buffer line.
929#[derive(Debug, Clone, Copy, PartialEq, Eq)]
930pub(crate) struct WrapDisplayPoint {
931    /// The 0-based soft wrapped row index in the text.
932    pub row: usize,
933    /// The 0-based row index in local line (include first line).
934    ///
935    /// This value only valid when return from [`TextWrapper::offset_to_display_point`], otherwise it will be ignored.
936    pub local_row: usize,
937    /// The 0-based column byte index in the display line (with soft wrap).
938    pub column: usize,
939}
940
941impl WrapDisplayPoint {
942    pub(crate) fn new(row: usize, local_row: usize, column: usize) -> Self {
943        Self {
944            row,
945            local_row,
946            column,
947        }
948    }
949}
950
951/// The layout info of a line with soft wrapped lines.
952pub(crate) struct LineLayout {
953    /// Total bytes length of this line.
954    len: usize,
955    /// The soft wrapped lines of this line (Include the first line).
956    pub(crate) wrapped_lines: SmallVec<[InputLine; 1]>,
957    /// Extra left offset applied to continuation wrapped lines, used to reserve the first line's
958    /// indentation when [`WrappingIndent::Same`] is used.
959    pub(crate) wrap_indent: Pixels,
960    pub(crate) longest_width: Pixels,
961    pub(crate) whitespace_indicators: Option<WhitespaceIndicators>,
962    /// Whitespace indicators: (line_index, x_position, the tab's width, or `None` for a space)
963    pub(crate) whitespace_chars: Vec<(usize, Pixels, Option<Pixels>)>,
964    /// Whether any run of this line carries a background color, so [`Self::paint_background`]
965    /// can skip the glyph walk for the common case of a line without highlights.
966    has_background: bool,
967}
968
969impl LineLayout {
970    pub(crate) fn new() -> Self {
971        Self {
972            len: 0,
973            longest_width: px(0.),
974            wrapped_lines: SmallVec::new(),
975            wrap_indent: px(0.),
976            whitespace_chars: Vec::new(),
977            whitespace_indicators: None,
978            has_background: false,
979        }
980    }
981
982    /// Record whether any run of this line carries a background color.
983    pub(crate) fn with_background(mut self, has_background: bool) -> Self {
984        self.has_background = has_background;
985        self
986    }
987
988    /// Set the left offset reserved for continuation wrapped lines.
989    pub(crate) fn wrap_indent(mut self, wrap_indent: Pixels) -> Self {
990        self.wrap_indent = wrap_indent;
991        self
992    }
993
994    /// The pixel indent applied to the given visual line, relative to the line's
995    /// leading text. Only continuation lines (index > 0) are indented.
996    #[inline]
997    fn line_indent(&self, line_index: usize) -> Pixels {
998        if line_index == 0 {
999            px(0.)
1000        } else {
1001            self.wrap_indent
1002        }
1003    }
1004
1005    pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {
1006        self.set_wrapped_lines(wrapped_lines);
1007        self
1008    }
1009
1010    pub(crate) fn set_wrapped_lines(&mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) {
1011        self.len = wrapped_lines.iter().map(|l| l.len).sum();
1012        let width = wrapped_lines
1013            .iter()
1014            .map(|l| l.width)
1015            .max()
1016            .unwrap_or_default();
1017        self.longest_width = width;
1018        self.wrapped_lines = wrapped_lines.into_iter().map(InputLine::from).collect();
1019    }
1020
1021    pub(crate) fn inline_lines(mut self, lines: SmallVec<[InputLine; 1]>) -> Self {
1022        self.len = lines.iter().map(|line| line.len).sum();
1023        self.longest_width = lines
1024            .iter()
1025            .map(|line| line.width)
1026            .max()
1027            .unwrap_or_default();
1028        self.wrapped_lines = lines;
1029        self
1030    }
1031
1032    pub(crate) fn with_whitespaces(mut self, indicators: Option<WhitespaceIndicators>) -> Self {
1033        self.whitespace_indicators = indicators;
1034        let Some(indicators) = self.whitespace_indicators.as_ref() else {
1035            return self;
1036        };
1037
1038        let space_indicator_offset = indicators.space.width.half();
1039
1040        for (line_index, wrapped_line) in self.wrapped_lines.iter().enumerate() {
1041            for (relative_offset, c) in wrapped_line.text.char_indices() {
1042                if matches!(c, ' ' | '\t') {
1043                    let is_tab = c == '\t';
1044                    let start_x = wrapped_line.x_for_index(relative_offset);
1045                    let end_x = wrapped_line.x_for_index(relative_offset + c.len_utf8());
1046                    // Center the indicator in the actual character's space
1047                    let x_position = if c == ' ' {
1048                        (start_x + end_x).half() - space_indicator_offset
1049                    } else {
1050                        start_x
1051                    };
1052
1053                    self.whitespace_chars.push((
1054                        line_index,
1055                        x_position,
1056                        is_tab.then_some(end_x - start_x),
1057                    ));
1058                }
1059            }
1060        }
1061        self
1062    }
1063
1064    #[inline]
1065    pub(crate) fn len(&self) -> usize {
1066        self.len
1067    }
1068
1069    /// Get the position (x, y) for the given index in this line layout.
1070    ///
1071    /// - The `offset` is a local byte index in this line layout.
1072    /// - When `line_end_affinity` is true, an offset at a soft wrap boundary is placed at
1073    ///   the end of the current visual line rather than the start of the next one.
1074    /// - The return value is relative to the top-left corner of this line layout, start from (0, 0)
1075    pub(crate) fn position_for_index(
1076        &self,
1077        offset: usize,
1078        last_layout: &LastLayout,
1079        line_end_affinity: bool,
1080    ) -> Option<Point<Pixels>> {
1081        let mut acc_len = 0;
1082        let mut offset_y = px(0.);
1083
1084        let x_offset = last_layout.alignment_offset(self.longest_width);
1085
1086        for (i, line) in self.wrapped_lines.iter().enumerate() {
1087            let is_last = i + 1 == self.wrapped_lines.len();
1088
1089            let matches = if line.len == 0 {
1090                // Empty visual lines still own their boundary offset.
1091                offset == acc_len
1092            } else if is_last || line_end_affinity {
1093                // Inclusive: cursor can sit at end of this visual line.
1094                offset >= acc_len && offset <= acc_len + line.len
1095            } else {
1096                // Exclusive: boundary offset belongs to the next visual line.
1097                offset >= acc_len && offset < acc_len + line.len
1098            };
1099
1100            if matches {
1101                let x = line.x_for_index(offset.saturating_sub(acc_len))
1102                    + x_offset
1103                    + self.line_indent(i);
1104                return Some(point(x, offset_y));
1105            }
1106
1107            // Always advance by actual line length. The last line gets +1 so the
1108            // cursor can be placed after the final character.
1109            acc_len += if is_last { line.len + 1 } else { line.len };
1110            offset_y += last_layout.line_height;
1111        }
1112
1113        None
1114    }
1115
1116    /// Get the closest index for the given x in this line layout.
1117    ///
1118    /// This ignores y, so it only makes sense for a layout that is known to occupy a single
1119    /// visual line. Wrapped layouts must use [`Self::closest_index_for_position`], which also
1120    /// reports the caret affinity that a wrap boundary needs.
1121    pub(crate) fn closest_index_for_x(&self, x: Pixels, last_layout: &LastLayout) -> usize {
1122        let mut acc_len = 0;
1123        let x_offset = last_layout.alignment_offset(self.longest_width);
1124        let x = x - x_offset;
1125
1126        for (i, line) in self.wrapped_lines.iter().enumerate() {
1127            let line_indent = self.line_indent(i);
1128            if x <= line_indent + line.width {
1129                return acc_len + line.closest_index_for_x(x - line_indent);
1130            }
1131            acc_len += line.len;
1132        }
1133
1134        acc_len
1135    }
1136
1137    /// Resolve `pos` to the wrapped sub-line under it.
1138    ///
1139    /// Returns the sub-line index, the byte offset that sub-line starts at within this line
1140    /// layout, and `pos.x` translated into that sub-line's own coordinate space.
1141    fn wrapped_line_at(
1142        &self,
1143        pos: Point<Pixels>,
1144        last_layout: &LastLayout,
1145    ) -> Option<(usize, usize, Pixels)> {
1146        let mut offset = 0;
1147        let mut line_top = px(0.);
1148        let x_offset = last_layout.alignment_offset(self.longest_width);
1149
1150        for (i, line) in self.wrapped_lines.iter().enumerate() {
1151            let line_bottom = line_top + last_layout.line_height;
1152            if pos.y >= line_top && pos.y < line_bottom {
1153                return Some((i, offset, pos.x - x_offset - self.line_indent(i)));
1154            }
1155
1156            offset += line.len;
1157            line_top = line_bottom;
1158        }
1159
1160        None
1161    }
1162
1163    /// Get the index for the given position (x, y) in this line layout.
1164    ///
1165    /// The `pos` is relative to the top-left corner of this line layout, start from (0, 0).
1166    ///
1167    /// Returns a local byte index in this line layout (start from 0) together with the caret
1168    /// affinity to use for it: `true` when the index landed on the wrap boundary of a non-final
1169    /// sub-line. That boundary offset is shared by the end of one visual line and the start of
1170    /// the next, so the affinity is what tells [`Self::position_for_index`] which of the two the
1171    /// caret belongs to. Without it a click past the last glyph of a wrapped line would put a
1172    /// visible caret on the following line.
1173    pub(crate) fn closest_index_for_position(
1174        &self,
1175        pos: Point<Pixels>,
1176        last_layout: &LastLayout,
1177    ) -> Option<(usize, bool)> {
1178        let (i, offset, x) = self.wrapped_line_at(pos, last_layout)?;
1179        let line = &self.wrapped_lines[i];
1180        let ix = line.closest_index_for_x(x);
1181        let line_end_affinity = i + 1 < self.wrapped_lines.len() && ix == line.len;
1182
1183        Some((offset + ix, line_end_affinity))
1184    }
1185
1186    /// How many columns the given position sits past the end of the line under it.
1187    ///
1188    /// Past the end of a line there is no glyph to hit-test against, so a position out
1189    /// there resolves to the line end and loses how far right it really was. The extra
1190    /// distance is reported here in whole spaces, letting a columnar selection keep its
1191    /// width over a short row. Only the final visual line of a wrapped layout has that
1192    /// trailing space; a continuation line ends at a wrap boundary, where the next glyph
1193    /// merely lives on the following row.
1194    ///
1195    /// The `pos` is relative to the top-left corner of this line layout, start from (0, 0).
1196    pub(crate) fn columns_past_line_end(
1197        &self,
1198        pos: Point<Pixels>,
1199        last_layout: &LastLayout,
1200    ) -> usize {
1201        let Some((i, _, x)) = self.wrapped_line_at(pos, last_layout) else {
1202            return 0;
1203        };
1204
1205        if i + 1 < self.wrapped_lines.len() || last_layout.space_width <= px(0.) {
1206            return 0;
1207        }
1208
1209        let past_end = x - self.wrapped_lines[i].width;
1210        if past_end <= px(0.) {
1211            return 0;
1212        }
1213
1214        (past_end / last_layout.space_width).round() as usize
1215    }
1216
1217    pub(crate) fn index_for_position(
1218        &self,
1219        pos: Point<Pixels>,
1220        last_layout: &LastLayout,
1221    ) -> Option<usize> {
1222        let (i, offset, x) = self.wrapped_line_at(pos, last_layout)?;
1223
1224        Some(offset + self.wrapped_lines[i].index_for_x(x)?)
1225    }
1226
1227    pub(crate) fn size(&self, line_height: Pixels) -> Size<Pixels> {
1228        let width = self
1229            .wrapped_lines
1230            .iter()
1231            .enumerate()
1232            .map(|(ix, line)| line.width + self.line_indent(ix))
1233            .max()
1234            .unwrap_or(self.longest_width);
1235        size(width, self.wrapped_lines.len() * line_height)
1236    }
1237
1238    /// Paint only the glyph background quads of this line.
1239    ///
1240    /// gpui's [`ShapedLine::paint`] does not draw backgrounds, so every line painted with
1241    /// [`Self::paint`] needs this called first, with the same origin and align width.
1242    pub(crate) fn paint_background(
1243        &self,
1244        pos: Point<Pixels>,
1245        line_height: Pixels,
1246        text_align: TextAlign,
1247        align_width: Option<Pixels>,
1248        window: &mut Window,
1249        cx: &mut App,
1250    ) {
1251        // Painting a background walks every glyph and pushes a scene layer, so skip the
1252        // whole pass for lines that have no background color to paint.
1253        if !self.has_background {
1254            return;
1255        }
1256
1257        for (ix, line) in self.wrapped_lines.iter().enumerate() {
1258            _ = line.paint_background(
1259                pos + point(self.line_indent(ix), ix * line_height),
1260                line_height,
1261                text_align,
1262                align_width,
1263                window,
1264                cx,
1265            );
1266        }
1267    }
1268
1269    pub(crate) fn paint(
1270        &self,
1271        pos: Point<Pixels>,
1272        line_height: Pixels,
1273        text_align: TextAlign,
1274        align_width: Option<Pixels>,
1275        window: &mut Window,
1276        cx: &mut App,
1277    ) {
1278        for (ix, line) in self.wrapped_lines.iter().enumerate() {
1279            _ = line.paint(
1280                pos + point(self.line_indent(ix), ix * line_height),
1281                line_height,
1282                text_align,
1283                align_width,
1284                window,
1285                cx,
1286            );
1287        }
1288
1289        // Paint whitespace indicators
1290        if let Some(indicators) = self.whitespace_indicators.as_ref() {
1291            for (line_index, x_position, tab_width) in &self.whitespace_chars {
1292                let origin = point(
1293                    pos.x + *x_position + self.line_indent(*line_index),
1294                    pos.y + *line_index as f32 * line_height,
1295                );
1296
1297                match tab_width {
1298                    Some(tab_width) => {
1299                        let tab_cell = ContentMask {
1300                            bounds: Bounds::new(origin, size(*tab_width, line_height)),
1301                        };
1302                        window.with_content_mask(Some(tab_cell), |window| {
1303                            _ = indicators.tab.paint(
1304                                origin,
1305                                line_height,
1306                                text_align,
1307                                align_width,
1308                                window,
1309                                cx,
1310                            );
1311                        });
1312                    }
1313                    None => {
1314                        _ = indicators.space.paint(
1315                            origin,
1316                            line_height,
1317                            text_align,
1318                            align_width,
1319                            window,
1320                            cx,
1321                        );
1322                    }
1323                }
1324            }
1325        }
1326    }
1327}
1328
1329#[cfg(test)]
1330mod tests {
1331    use super::*;
1332    use std::rc::Rc;
1333
1334    #[cfg(target_os = "linux")]
1335    use gpui::TestAppContext;
1336    use gpui::{Boundary, FontFeatures, FontStyle, FontWeight, px};
1337
1338    #[cfg(target_os = "linux")]
1339    fn shaped_width(text: &str, font: &Font, font_size: Pixels, cx: &App) -> Pixels {
1340        gpui::WindowTextSystem::new(cx.text_system().clone())
1341            .layout_line(
1342                text,
1343                font_size,
1344                &[gpui::TextRun {
1345                    len: text.len(),
1346                    font: font.clone(),
1347                    color: gpui::black(),
1348                    background_color: None,
1349                    underline: None,
1350                    strikethrough: None,
1351                }],
1352                None,
1353            )
1354            .width
1355    }
1356
1357    // Linux exposes its native text engine without creating a desktop window.
1358    // macOS platform creation requires the main thread, and Windows headless
1359    // mode uses NoopTextSystem rather than native shaping.
1360    #[cfg(target_os = "linux")]
1361    fn shaping_test_context() -> TestAppContext {
1362        let platform = gpui_platform::current_platform(true);
1363        TestAppContext::build_with_text_system(
1364            gpui::TestDispatcher::new(0),
1365            None,
1366            platform.text_system(),
1367        )
1368    }
1369
1370    #[cfg(target_os = "linux")]
1371    #[test]
1372    fn production_wrap_keeps_shaped_cjk_latin_boundary_during_edits() {
1373        let cx = shaping_test_context();
1374        cx.update(|cx| {
1375            let font = test_font();
1376            let font_size = px(14.);
1377            let prefix = "abcd的";
1378            let width = shaped_width(prefix, &font, font_size, cx);
1379            assert!(shaped_width("abcd的s", &font, font_size, cx) > width);
1380            let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));
1381            let mut previous = Rope::new();
1382
1383            for value in ["abcd的", "abcd的s", "abcd的ss", "abcd的s", "abcd的"] {
1384                let text = Rope::from(value);
1385                let start = previous.len().min(text.len());
1386                let inserted = Rope::from(text.slice(start..).to_string());
1387                wrapper.update(&text, &(start..previous.len()), &inserted, cx);
1388                let expected = if value.ends_with('s') {
1389                    vec![0..prefix.len(), prefix.len()..value.len()]
1390                } else {
1391                    vec![0..prefix.len()]
1392                };
1393                assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), expected);
1394                for range in &wrapper.line(0).unwrap().wrapped_lines {
1395                    assert!(shaped_width(&value[range.clone()], &font, font_size, cx) <= width);
1396                }
1397                assert_eq!(
1398                    wrapper.offset_to_display_point(value.len()).row,
1399                    usize::from(value.ends_with('s'))
1400                );
1401                previous = text;
1402            }
1403        });
1404    }
1405
1406    #[cfg(target_os = "linux")]
1407    #[test]
1408    fn production_wrap_preserves_words_and_complete_graphemes() {
1409        let cx = shaping_test_context();
1410        cx.update(|cx| {
1411            let font = test_font();
1412            let font_size = px(14.);
1413            for (value, prefix) in [("hello world", "hello "), ("a👩‍💻b", "a👩‍💻")] {
1414                // Either complete row must fit even when the native font makes
1415                // the second word wider than the first word and its space.
1416                let width = shaped_width(prefix, &font, font_size, cx).max(shaped_width(
1417                    &value[prefix.len()..],
1418                    &font,
1419                    font_size,
1420                    cx,
1421                ));
1422                assert!(shaped_width(value, &font, font_size, cx) > width);
1423                let text = Rope::from(value);
1424                let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));
1425                wrapper.update(&text, &(0..0), &text, cx);
1426                assert_eq!(
1427                    wrapper.line(0).unwrap().wrapped_lines.as_slice(),
1428                    [0..prefix.len(), prefix.len()..value.len()]
1429                );
1430                for range in &wrapper.line(0).unwrap().wrapped_lines {
1431                    assert!(shaped_width(&value[range.clone()], &font, font_size, cx) <= width);
1432                }
1433            }
1434        });
1435    }
1436
1437    #[test]
1438    fn measured_wrap_keeps_cjk_latin_boundary_stable_during_edits() {
1439        let measure = |text: &str| {
1440            px(text
1441                .chars()
1442                .map(|c| if c.is_ascii() { 1. } else { 2. })
1443                .sum())
1444        };
1445        let mut wrapper = TextWrapper::new(gpui::font("Arial"), px(14.), Some(px(6.)));
1446        let mut previous = Rope::new();
1447        for value in ["abcd的", "abcd的s", "abcd的ss", "abcd的s", "abcd的"] {
1448            let text = Rope::from(value);
1449            let start = previous.len().min(text.len());
1450            let inserted = Rope::from(text.slice(start..).to_string());
1451            wrapper._update(
1452                &text,
1453                &(start..previous.len()),
1454                &inserted,
1455                &mut |line, width, _| {
1456                    measured_wrap_boundaries(line, width, WrappingIndent::None, measure)
1457                },
1458            );
1459            let expected = if value.ends_with('s') {
1460                vec![0..7, 7..value.len()]
1461            } else {
1462                vec![0..7]
1463            };
1464            assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), expected);
1465            let cursor = wrapper.offset_to_display_point(value.len());
1466            assert_eq!(cursor.row, usize::from(value.ends_with('s')));
1467            previous = text;
1468        }
1469    }
1470
1471    #[test]
1472    fn measured_wrap_preserves_words_graphemes_and_indentation() {
1473        let wrap = |text: &str, width, indent| {
1474            measured_wrap_boundaries(text, px(width), indent, |s| {
1475                px(s.graphemes(true).count() as f32)
1476            })
1477            .into_iter()
1478            .map(|b| b.ix)
1479            .collect::<Vec<_>>()
1480        };
1481        assert_eq!(wrap("hello world", 8., WrappingIndent::None), vec![6]);
1482        assert_eq!(wrap("a👩‍💻b", 2., WrappingIndent::None), vec!["a👩‍💻".len()]);
1483        assert_eq!(wrap("  abcdefgh", 5., WrappingIndent::Same), vec![5, 8]);
1484        assert_eq!(wrap("  abcdefgh", 5., WrappingIndent::None), vec![2, 7]);
1485        assert!(wrap("", 0., WrappingIndent::None).is_empty());
1486        assert_eq!(wrap("abc", 0., WrappingIndent::None), vec![1, 2]);
1487        // Closing punctuation stays with the preceding Chinese character.
1488        assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);
1489    }
1490
1491    #[test]
1492    fn test_update() {
1493        let font = gpui::Font {
1494            family: "Arial".into(),
1495            weight: FontWeight::default(),
1496            style: FontStyle::Normal,
1497            features: FontFeatures::default(),
1498            fallbacks: None,
1499        };
1500
1501        let mut wrapper = TextWrapper::new(font, px(14.), None);
1502        let mut text = Rope::from(
1503            "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。",
1504        );
1505
1506        fn fake_wrap_line(_line: &str, _wrap_width: Pixels, _: usize) -> Vec<Boundary> {
1507            vec![]
1508        }
1509
1510        #[track_caller]
1511        fn assert_wrapper_lines(text: &Rope, wrapper: &TextWrapper, expected_lines: &[&[&str]]) {
1512            let mut actual_lines = vec![];
1513            let mut offset = 0;
1514            for line in wrapper.iter_lines() {
1515                actual_lines.push(
1516                    line.wrapped_lines
1517                        .iter()
1518                        .map(|range| text.slice(offset + range.start..offset + range.end))
1519                        .collect::<Vec<_>>(),
1520                );
1521                // +1 \n
1522                offset += line.len() + 1;
1523            }
1524            assert_eq!(actual_lines, expected_lines);
1525        }
1526
1527        wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
1528        assert_eq!(wrapper.lines_count(), 4);
1529        assert_wrapper_lines(
1530            &text,
1531            &wrapper,
1532            &[
1533                &["Hello, 世界!\r"],
1534                &["This is second line."],
1535                &["This is third line."],
1536                &["这里是第 4 行。"],
1537            ],
1538        );
1539
1540        // Add a new text to end
1541        let range = text.len()..text.len();
1542        let new_text = "New text";
1543        text.replace(range.clone(), new_text);
1544        wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
1545        assert_eq!(
1546            text.to_string(),
1547            "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
1548        );
1549        assert_eq!(wrapper.lines_count(), 4);
1550        assert_eq!(wrapper.lines_count(), 4);
1551        assert_wrapper_lines(
1552            &text,
1553            &wrapper,
1554            &[
1555                &["Hello, 世界!\r"],
1556                &["This is second line."],
1557                &["This is third line."],
1558                &["这里是第 4 行。New text"],
1559            ],
1560        );
1561
1562        // Replace first line `Hello` to `AAA`
1563        let range = 0..5;
1564        let new_text = "AAA";
1565        text.replace(range.clone(), new_text);
1566        wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
1567        assert_eq!(
1568            text.to_string(),
1569            "AAA, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
1570        );
1571        assert_eq!(wrapper.lines_count(), 4);
1572        assert_wrapper_lines(
1573            &text,
1574            &wrapper,
1575            &[
1576                &["AAA, 世界!\r"],
1577                &["This is second line."],
1578                &["This is third line."],
1579                &["这里是第 4 行。New text"],
1580            ],
1581        );
1582
1583        // Remove the second line
1584        let start_offset = text.line_start_offset(1);
1585        let end_offset = text.line_end_offset(1);
1586        let range = start_offset..end_offset + 1;
1587        text.replace(range.clone(), "");
1588        wrapper._update(&text, &range, &Rope::from(""), &mut fake_wrap_line);
1589        assert_eq!(
1590            text.to_string(),
1591            "AAA, 世界!\r\nThis is third line.\n这里是第 4 行。New text"
1592        );
1593        assert_eq!(wrapper.lines_count(), 3);
1594        assert_wrapper_lines(
1595            &text,
1596            &wrapper,
1597            &[
1598                &["AAA, 世界!\r"],
1599                &["This is third line."],
1600                &["这里是第 4 行。New text"],
1601            ],
1602        );
1603
1604        // Replace the first 2 lines to "This is a new line."
1605        let range = text.line_start_offset(0)..text.line_end_offset(1) + 1;
1606        let new_text = "This is a new line.\nThis is new line 2.\n";
1607        text.replace(range.clone(), new_text);
1608        wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
1609        assert_eq!(
1610            text.to_string(),
1611            "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text"
1612        );
1613        assert_eq!(wrapper.lines_count(), 3);
1614        assert_wrapper_lines(
1615            &text,
1616            &wrapper,
1617            &[
1618                &["This is a new line."],
1619                &["This is new line 2."],
1620                &["这里是第 4 行。New text"],
1621            ],
1622        );
1623
1624        // Add a new line at the end
1625        let range = text.len()..text.len();
1626        let new_text = "\nThis is a new line at the end.";
1627        text.replace(range.clone(), new_text);
1628        wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
1629        assert_eq!(
1630            text.to_string(),
1631            "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
1632        );
1633        assert_eq!(wrapper.lines_count(), 4);
1634        assert_wrapper_lines(
1635            &text,
1636            &wrapper,
1637            &[
1638                &["This is a new line."],
1639                &["This is new line 2."],
1640                &["这里是第 4 行。New text"],
1641                &["This is a new line at the end."],
1642            ],
1643        );
1644
1645        // Add a new line at the beginning
1646        let range = 0..0;
1647        let new_text = "This is a new line at the beginning.\n";
1648        text.replace(range.clone(), new_text);
1649        wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
1650        assert_eq!(
1651            text.to_string(),
1652            "This is a new line at the beginning.\nThis is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
1653        );
1654        assert_eq!(wrapper.lines_count(), 5);
1655        assert_wrapper_lines(
1656            &text,
1657            &wrapper,
1658            &[
1659                &["This is a new line at the beginning."],
1660                &["This is a new line."],
1661                &["This is new line 2."],
1662                &["这里是第 4 行。New text"],
1663                &["This is a new line at the end."],
1664            ],
1665        );
1666
1667        // Remove all to at least one line in `lines`.
1668        let range = 0..text.len();
1669        let new_text = "";
1670        text.replace(range.clone(), new_text);
1671        wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
1672        assert_eq!(text.to_string(), "");
1673        assert_eq!(wrapper.lines_count(), 1);
1674        assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
1675
1676        // Test update_all
1677        let range = 0..text.len();
1678        let new_text = "This is a full text.\nThis is a second line.";
1679        text.replace(range.clone(), new_text);
1680        wrapper._update(&text, &range, &text, &mut fake_wrap_line);
1681        assert_eq!(
1682            text.to_string(),
1683            "This is a full text.\nThis is a second line."
1684        );
1685        assert_eq!(wrapper.lines_count(), 2);
1686    }
1687
1688    fn test_font() -> gpui::Font {
1689        gpui::Font {
1690            family: "Arial".into(),
1691            weight: FontWeight::default(),
1692            style: FontStyle::Normal,
1693            features: FontFeatures::default(),
1694            fallbacks: None,
1695        }
1696    }
1697
1698    /// The longest-row summary stays exact when the previously-longest line is shrunk.
1699    #[test]
1700    fn test_longest_row_after_shrink() {
1701        let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
1702        let mut text = Rope::from("aa\nthis is the longest line\nbb");
1703        wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
1704        assert_eq!(wrapper.longest_row(), 1);
1705
1706        // Shrink line 1 so line 2-equivalent isn't longest.
1707        // Make line 0 the longest now.
1708        let start = text.line_start_offset(0);
1709        let end = text.line_end_offset(0);
1710        let range = start..end;
1711        let new_text = "a very very long first line now";
1712        text.replace(range.clone(), new_text);
1713        wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
1714        assert_eq!(wrapper.longest_row(), 0);
1715    }
1716
1717    /// Editing the last line and deleting everything must keep the tree consistent.
1718    #[test]
1719    fn test_edit_last_line_and_full_delete() {
1720        let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
1721        let mut text = Rope::from("one\ntwo\nthree");
1722        wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
1723        assert_eq!(wrapper.lines_count(), 3);
1724
1725        // Replace the last line only.
1726        let start = text.line_start_offset(2);
1727        let range = start..text.len();
1728        let new_text = "THREE EDITED";
1729        text.replace(range.clone(), new_text);
1730        wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
1731        assert_eq!(wrapper.lines_count(), 3);
1732        assert_eq!(wrapper.line(2).unwrap().len(), "THREE EDITED".len());
1733
1734        // Delete everything.
1735        let range = 0..text.len();
1736        text.replace(range.clone(), "");
1737        wrapper._update(&text, &range, &Rope::from(""), &mut |_, _, _| vec![]);
1738        assert_eq!(wrapper.lines_count(), 1);
1739        assert_eq!(wrapper.len(), 1);
1740        assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
1741    }
1742
1743    #[test]
1744    fn test_wrap_row_buffer_line_boundaries() {
1745        let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
1746        wrapper.text = Rope::from("aa\nbbbb\nc");
1747        wrapper.lines = SumTree::from_iter(
1748            vec![
1749                LineItem {
1750                    len: 2,
1751                    indent: 0,
1752                    wrapped_lines: smallvec::smallvec![0..2],
1753                    valid_widths: WidthRange::empty(),
1754                },
1755                LineItem {
1756                    len: 4,
1757                    indent: 0,
1758                    wrapped_lines: smallvec::smallvec![0..2, 2..4],
1759                    valid_widths: WidthRange::empty(),
1760                },
1761                LineItem {
1762                    len: 1,
1763                    indent: 0,
1764                    wrapped_lines: smallvec::smallvec![0..1],
1765                    valid_widths: WidthRange::empty(),
1766                },
1767            ],
1768            &(),
1769        );
1770
1771        assert_eq!(wrapper.lines_count(), 3);
1772        assert_eq!(wrapper.len(), 4);
1773
1774        assert_eq!(wrapper.buffer_line_to_first_wrap_row(0), 0);
1775        assert_eq!(wrapper.buffer_line_to_first_wrap_row(1), 1);
1776        assert_eq!(wrapper.buffer_line_to_first_wrap_row(2), 3);
1777        assert_eq!(wrapper.buffer_line_to_first_wrap_row(3), 4);
1778
1779        assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
1780        assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
1781        assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
1782        assert_eq!(wrapper.buffer_line_to_wrap_row_range(3), 4..4);
1783
1784        assert_eq!(wrapper.wrap_row_to_buffer_line(0), 0);
1785        assert_eq!(wrapper.wrap_row_to_buffer_line(1), 1);
1786        assert_eq!(wrapper.wrap_row_to_buffer_line(2), 1);
1787        assert_eq!(wrapper.wrap_row_to_buffer_line(3), 2);
1788        assert_eq!(wrapper.wrap_row_to_buffer_line(4), 2);
1789    }
1790
1791    #[test]
1792    fn test_wrap_row_queries_after_incremental_splice() {
1793        let mut wrapper = TextWrapper::new(test_font(), px(14.), Some(px(10.)));
1794        let mut text = Rope::from("aa\nbbbb\nc");
1795        let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
1796            if line.len() > 2 {
1797                vec![Boundary {
1798                    ix: 2,
1799                    next_indent: 0,
1800                }]
1801            } else {
1802                vec![]
1803            }
1804        };
1805
1806        wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
1807        assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
1808        assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
1809        assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
1810
1811        let range = text.line_start_offset(1)..text.line_end_offset(1);
1812        let new_text = "dd\neeee";
1813        text.replace(range.clone(), new_text);
1814        wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
1815
1816        assert_eq!(wrapper.lines_count(), 4);
1817        assert_eq!(wrapper.len(), 5);
1818        assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
1819        assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..2);
1820        assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 2..4);
1821        assert_eq!(wrapper.buffer_line_to_wrap_row_range(3), 4..5);
1822        assert_eq!(wrapper.wrap_row_to_buffer_line(0), 0);
1823        assert_eq!(wrapper.wrap_row_to_buffer_line(1), 1);
1824        assert_eq!(wrapper.wrap_row_to_buffer_line(2), 2);
1825        assert_eq!(wrapper.wrap_row_to_buffer_line(3), 2);
1826        assert_eq!(wrapper.wrap_row_to_buffer_line(4), 3);
1827    }
1828
1829    #[test]
1830    fn test_line_layout() {
1831        let mut line_layout = LineLayout::new();
1832
1833        let line1 = ShapedLine::default().with_len(100);
1834        let line2 = ShapedLine::default().with_len(50);
1835        let wrapped_lines = smallvec::smallvec![line1, line2];
1836        line_layout.set_wrapped_lines(wrapped_lines);
1837        assert_eq!(line_layout.len(), 150);
1838        assert_eq!(line_layout.wrapped_lines.len(), 2);
1839    }
1840
1841    /// A layout context whose only load-bearing field is the line height.
1842    fn test_last_layout(line_height: Pixels) -> LastLayout {
1843        LastLayout {
1844            visible_range: 0..1,
1845            visible_buffer_lines: vec![0],
1846            visible_line_byte_offsets: vec![0],
1847            visible_top: px(0.),
1848            visible_range_offset: 0..0,
1849            lines: Rc::new(vec![]),
1850            line_height,
1851            wrap_width: None,
1852            wrapping_indent: WrappingIndent::default(),
1853            line_number_width: px(0.),
1854            space_width: px(0.),
1855            cursor_bounds: None,
1856            text_align: TextAlign::Left,
1857            content_width: px(0.),
1858        }
1859    }
1860
1861    #[test]
1862    fn test_position_for_index_prefers_first_leading_empty_visual_line() {
1863        let mut line_layout = LineLayout::new();
1864        line_layout.set_wrapped_lines(smallvec::smallvec![
1865            ShapedLine::default(),
1866            ShapedLine::default(),
1867            ShapedLine::default().with_len(3),
1868        ]);
1869
1870        assert_eq!(
1871            line_layout.position_for_index(0, &test_last_layout(px(20.)), false),
1872            Some(point(px(0.), px(0.)))
1873        );
1874    }
1875
1876    #[test]
1877    fn clicking_past_a_wrapped_row_keeps_the_caret_on_that_row() {
1878        // One buffer line wrapped into two visual rows, splitting at byte 10.
1879        let mut line_layout = LineLayout::new();
1880        line_layout.set_wrapped_lines(smallvec::smallvec![
1881            ShapedLine::default().with_len(10),
1882            ShapedLine::default().with_len(5),
1883        ]);
1884        let last_layout = test_last_layout(px(20.));
1885
1886        // Clicking past the last glyph of the first row resolves to the wrap boundary, which is
1887        // also the first offset of the second row -- hence the affinity.
1888        let (ix, line_end_affinity) = line_layout
1889            .closest_index_for_position(point(px(999.), px(5.)), &last_layout)
1890            .unwrap();
1891        assert_eq!(ix, 10);
1892        assert!(line_end_affinity);
1893
1894        // Carrying that affinity is what keeps the caret on the row that was clicked; dropping it
1895        // is the bug -- the caret shows up one row below the pointer.
1896        assert_eq!(
1897            line_layout
1898                .position_for_index(ix, &last_layout, line_end_affinity)
1899                .map(|pos| pos.y),
1900            Some(px(0.))
1901        );
1902        assert_eq!(
1903            line_layout
1904                .position_for_index(ix, &last_layout, false)
1905                .map(|pos| pos.y),
1906            Some(px(20.))
1907        );
1908
1909        // The final row owns the end of the line outright, so there is nothing to disambiguate.
1910        let (ix, line_end_affinity) = line_layout
1911            .closest_index_for_position(point(px(999.), px(25.)), &last_layout)
1912            .unwrap();
1913        assert_eq!(ix, 15);
1914        assert!(!line_end_affinity);
1915    }
1916
1917    #[test]
1918    fn a_wrap_boundary_offset_resolves_to_the_row_the_caret_is_drawn_on() {
1919        let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
1920        wrapper.text = Rope::from("first line\nthis one wraps");
1921        wrapper.lines = SumTree::from_iter(
1922            vec![
1923                LineItem {
1924                    len: Rope::from("first line").len(),
1925                    indent: 0,
1926                    wrapped_lines: smallvec::smallvec![0..10],
1927                    valid_widths: WidthRange::empty(),
1928                },
1929                LineItem {
1930                    len: Rope::from("this one wraps").len(),
1931                    indent: 0,
1932                    wrapped_lines: smallvec::smallvec![0..9, 9..14],
1933                    valid_widths: WidthRange::empty(),
1934                },
1935            ],
1936            &(),
1937        );
1938
1939        // Offset 20 is the wrap boundary of the second buffer line: 11 (line start) + 9.
1940        // It is the last offset of wrap row 1 and the first of wrap row 2 at the same time, so
1941        // only the affinity can say which row a vertical move should step away from.
1942        assert_eq!(
1943            wrapper.offset_to_display_point_with_affinity(20, true),
1944            WrapDisplayPoint::new(1, 0, 9)
1945        );
1946        assert_eq!(
1947            wrapper.offset_to_display_point_with_affinity(20, false),
1948            WrapDisplayPoint::new(2, 1, 0)
1949        );
1950        assert_eq!(
1951            wrapper.offset_to_display_point(20),
1952            wrapper.offset_to_display_point_with_affinity(20, false)
1953        );
1954
1955        // An offset that is not on a boundary is unaffected either way.
1956        for line_end_affinity in [false, true] {
1957            assert_eq!(
1958                wrapper.offset_to_display_point_with_affinity(23, line_end_affinity),
1959                WrapDisplayPoint::new(2, 1, 3)
1960            );
1961        }
1962    }
1963
1964    #[test]
1965    fn test_offset_to_display_point() {
1966        let font = gpui::Font {
1967            family: "Arial".into(),
1968            weight: FontWeight::default(),
1969            style: FontStyle::Normal,
1970            features: FontFeatures::default(),
1971            fallbacks: None,
1972        };
1973
1974        let mut wrapper = TextWrapper::new(font, px(14.), None);
1975        wrapper.text = Rope::from(
1976            "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。",
1977        );
1978        wrapper.lines = SumTree::from_iter(
1979            vec![
1980                // range: 0..15
1981                LineItem {
1982                    len: Rope::from("Hello, 世界!\r").len(),
1983                    indent: 0,
1984                    wrapped_lines: smallvec::smallvec![0..15],
1985                    valid_widths: WidthRange::empty(),
1986                },
1987                // range: 16..36
1988                LineItem {
1989                    len: Rope::from("This is second line.\n").len(),
1990                    indent: 0,
1991                    wrapped_lines: smallvec::smallvec![0..10, 10..20],
1992                    valid_widths: WidthRange::empty(),
1993                },
1994                // range: 37..56
1995                LineItem {
1996                    len: Rope::from("This is third line.\n").len(),
1997                    indent: 0,
1998                    wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],
1999                    valid_widths: WidthRange::empty(),
2000                },
2001                // range: 57..79
2002                LineItem {
2003                    len: Rope::from("这里是第 4 行。").len(),
2004                    indent: 0,
2005                    wrapped_lines: smallvec::smallvec![0..22],
2006                    valid_widths: WidthRange::empty(),
2007                },
2008            ],
2009            &(),
2010        );
2011
2012        assert_eq!(
2013            wrapper.offset_to_display_point(12),
2014            WrapDisplayPoint::new(0, 0, 12)
2015        );
2016        assert_eq!(
2017            wrapper.offset_to_display_point(15),
2018            WrapDisplayPoint::new(0, 0, 15)
2019        );
2020
2021        assert_eq!(
2022            wrapper.offset_to_display_point(16),
2023            WrapDisplayPoint::new(1, 0, 0)
2024        );
2025        assert_eq!(
2026            wrapper.offset_to_display_point(21),
2027            WrapDisplayPoint::new(1, 0, 5)
2028        );
2029        assert_eq!(
2030            wrapper.offset_to_display_point(27),
2031            WrapDisplayPoint::new(2, 1, 1)
2032        );
2033        assert_eq!(
2034            wrapper.offset_to_display_point(37),
2035            WrapDisplayPoint::new(3, 0, 0)
2036        );
2037        assert_eq!(
2038            wrapper.offset_to_display_point(54),
2039            WrapDisplayPoint::new(5, 2, 2)
2040        );
2041        assert_eq!(
2042            wrapper.offset_to_display_point(59),
2043            WrapDisplayPoint::new(6, 0, 2)
2044        );
2045
2046        assert_eq!(
2047            wrapper.display_point_to_offset(WrapDisplayPoint::new(6, 0, 2)),
2048            59
2049        );
2050        assert_eq!(
2051            wrapper.display_point_to_offset(WrapDisplayPoint::new(5, 2, 2)),
2052            54
2053        );
2054        assert_eq!(
2055            wrapper.display_point_to_offset(WrapDisplayPoint::new(3, 0, 0)),
2056            37
2057        );
2058        assert_eq!(
2059            wrapper.display_point_to_offset(WrapDisplayPoint::new(2, 1, 1)),
2060            27
2061        );
2062        assert_eq!(
2063            wrapper.display_point_to_offset(WrapDisplayPoint::new(1, 0, 5)),
2064            21
2065        );
2066        assert_eq!(
2067            wrapper.display_point_to_offset(WrapDisplayPoint::new(1, 0, 0)),
2068            16
2069        );
2070        assert_eq!(
2071            wrapper.display_point_to_offset(WrapDisplayPoint::new(0, 0, 15)),
2072            15
2073        );
2074    }
2075
2076    #[test]
2077    fn test_wrapping_indent_same_keeps_indent_reserved() {
2078        let mut wrapper = TextWrapper::new(test_font(), px(14.0), Some(px(10.)));
2079        wrapper.wrapping_indent = WrappingIndent::Same;
2080        let text = Rope::from("  abcdefghijklmnopqrstuv");
2081        let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
2082            if line.starts_with(' ') {
2083                vec![Boundary {
2084                    ix: 5,
2085                    next_indent: 2,
2086                }]
2087            } else {
2088                let mut boundaries = vec![];
2089                let mut i = 8;
2090                while i < line.len() {
2091                    boundaries.push(Boundary {
2092                        ix: i,
2093                        next_indent: 0,
2094                    });
2095                    i += 8;
2096                }
2097                boundaries
2098            }
2099        };
2100
2101        wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2102
2103        let line = wrapper.line(0).unwrap();
2104        assert_eq!(line.indent, 2);
2105        assert_eq!(line.wrapped_lines.as_slice(), [0..5, 5..24]);
2106    }
2107
2108    #[test]
2109    fn test_wrapping_indent_none_continuation_lines_wrapped_at_full_width() {
2110        let mut wrapper = TextWrapper::new(test_font(), px(14.0), Some(px(10.)));
2111        wrapper.wrapping_indent = WrappingIndent::None;
2112        let text = Rope::from("  abcdefghijklmnopqrstuv");
2113        let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
2114            if line.starts_with(' ') {
2115                vec![Boundary {
2116                    ix: 5,
2117                    next_indent: 2,
2118                }]
2119            } else {
2120                let mut boundaries = vec![];
2121                let mut i = 8;
2122                while i < line.len() {
2123                    boundaries.push(Boundary {
2124                        ix: i,
2125                        next_indent: 0,
2126                    });
2127                    i += 8;
2128                }
2129                boundaries
2130            }
2131        };
2132
2133        wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2134
2135        let line = wrapper.line(0).unwrap();
2136        assert_eq!(line.indent, 0);
2137        assert_eq!(line.wrapped_lines.as_slice(), [0..5, 5..13, 13..21, 21..24]);
2138    }
2139
2140    #[test]
2141    fn test_wrap_indent_offsets_continuation_lines() {
2142        let mut line_layout = LineLayout::new();
2143        line_layout.set_wrapped_lines(smallvec::smallvec![
2144            ShapedLine::default().with_len(5),
2145            ShapedLine::default().with_len(10),
2146        ]);
2147
2148        line_layout = line_layout.wrap_indent(px(20.0));
2149
2150        let last_layout = LastLayout {
2151            visible_range: 0..1,
2152            visible_buffer_lines: vec![0],
2153            visible_line_byte_offsets: vec![0],
2154            visible_top: px(0.),
2155            visible_range_offset: 0..0,
2156            lines: Rc::new(vec![]),
2157            line_height: px(20.0),
2158            wrap_width: Some(px(10.)),
2159            wrapping_indent: WrappingIndent::Same,
2160            line_number_width: px(0.),
2161            space_width: px(0.),
2162            cursor_bounds: None,
2163            text_align: TextAlign::Left,
2164            content_width: px(0.),
2165        };
2166
2167        assert_eq!(
2168            line_layout.position_for_index(0, &last_layout, false),
2169            Some(point(px(0.), px(0.))),
2170        );
2171
2172        assert_eq!(
2173            line_layout.position_for_index(6, &last_layout, false),
2174            Some(point(px(20.), px(20.))),
2175        )
2176    }
2177}