Skip to main content

gpui_base/input/editor/display_map/
text_wrapper.rs

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