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, FontStyle, FontWeight, LineFragment, Pixels, Point, ShapedLine,
17 Size, TextAlign, 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#[derive(Clone, Debug, PartialEq, Eq)]
33pub(crate) struct FontSpan {
34 pub(crate) range: Range<usize>,
35 pub(crate) weight: Option<FontWeight>,
36 pub(crate) style: Option<FontStyle>,
37}
38
39impl FontSpan {
40 fn font(&self, base: &Font) -> Font {
41 Font {
42 weight: self.weight.unwrap_or(base.weight),
43 style: self.style.unwrap_or(base.style),
44 ..base.clone()
45 }
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub enum WrappingIndent {
52 None,
54 #[default]
56 Same,
57}
58
59#[cfg(test)]
61fn measured_wrap_boundaries(
62 text: &str,
63 width: Pixels,
64 wrapping_indent: WrappingIndent,
65 mut measure: impl FnMut(&str) -> Pixels,
66) -> Vec<gpui::Boundary> {
67 let indent = if wrapping_indent == WrappingIndent::Same {
68 text.chars()
69 .take_while(|&c| c == ' ')
70 .count()
71 .min(gpui::LineWrapper::MAX_INDENT as usize)
72 } else {
73 0
74 };
75 let indent_width = measure(&text[..indent]);
76 let ends: Vec<usize> = text
77 .grapheme_indices(true)
78 .map(|(ix, grapheme)| ix + grapheme.len())
79 .collect();
80 let opportunities: Vec<usize> = unicode_linebreak::linebreaks(text)
81 .map(|(ix, _)| ix)
82 .filter(|ix| ends.binary_search(ix).is_ok())
83 .collect();
84 let mut result = Vec::new();
85 let mut first = 0;
86 let mut start = 0;
87 while first < ends.len() {
88 let available = if start == 0 {
89 width
90 } else {
91 width - indent_width
92 };
93 let remaining = ends.len() - first;
96 let mut low = 0;
97 let mut high = 1;
98 while measure(&text[start..ends[first + high - 1]]) <= available {
99 low = high;
100 if high == remaining {
101 break;
102 }
103 high = (high * 2).min(remaining);
104 }
105 while low + 1 < high {
106 let mid = (low + high) / 2;
107 if measure(&text[start..ends[first + mid - 1]]) <= available {
108 low = mid;
109 } else {
110 high = mid;
111 }
112 }
113 let fitting_end = ends[first + low.max(1) - 1];
115 if fitting_end == text.len() {
116 break;
117 }
118 let candidate = opportunities.partition_point(|&ix| ix <= fitting_end);
119 let end = candidate
120 .checked_sub(1)
121 .map(|ix| opportunities[ix])
122 .filter(|&ix| ix > start && (start != 0 || ix > indent))
123 .unwrap_or(fitting_end);
124 result.push(gpui::Boundary {
125 ix: end,
126 next_indent: indent as u32,
127 });
128 first = ends.partition_point(|&ix| ix <= end);
129 start = end;
130 }
131 result
132}
133
134fn monospace_wrap(
140 text: &str,
141 width: Pixels,
142 wrapping_indent: WrappingIndent,
143 scratch: &mut WrapScratch,
144 widths: &MonospaceWidths,
145 mut shaped: impl FnMut(&str) -> Pixels,
146) -> MeasuredWrap {
147 if text.is_empty() {
148 return MeasuredWrap::unbroken(WidthRange::all());
149 }
150 if let Some(line_width) = widths.width(text.len())
151 && line_width <= width
152 {
153 let mut valid_widths = WidthRange::all();
154 valid_widths.fits(line_width, width, px(0.));
155 return MeasuredWrap::unbroken(valid_widths);
156 }
157 measured_wrap(text, width, wrapping_indent, scratch, |text| {
158 widths.width(text.len()).unwrap_or_else(|| shaped(text))
159 })
160}
161
162fn fast_wrap(
166 text: &str,
167 width: Pixels,
168 wrapping_indent: WrappingIndent,
169 scratch: &mut WrapScratch,
170 widths: &LineWidths<'_>,
171) -> MeasuredWrap {
172 let line_width = widths.width(0..text.len());
173 if line_width <= width {
174 let mut valid_widths = WidthRange::all();
175 valid_widths.fits(line_width, width, px(0.));
176 return MeasuredWrap::unbroken(valid_widths);
177 }
178 measured_wrap_ranges(text, width, wrapping_indent, scratch, |range| {
179 widths.width(range)
180 })
181}
182
183fn measured_wrap(
185 text: &str,
186 width: Pixels,
187 wrapping_indent: WrappingIndent,
188 scratch: &mut WrapScratch,
189 mut measure: impl FnMut(&str) -> Pixels,
190) -> MeasuredWrap {
191 measured_wrap_ranges(text, width, wrapping_indent, scratch, |range| {
192 measure(&text[range])
193 })
194}
195
196fn measured_wrap_ranges(
198 text: &str,
199 width: Pixels,
200 wrapping_indent: WrappingIndent,
201 scratch: &mut WrapScratch,
202 mut measure: impl FnMut(Range<usize>) -> Pixels,
203) -> MeasuredWrap {
204 #[cfg(test)]
205 wrap_width::MEASURED_LINES.with(|count| count.set(count.get() + 1));
206 let mut valid_widths = WidthRange::all();
207 let indent = if wrapping_indent == WrappingIndent::Same {
208 text.chars()
209 .take_while(|&c| c == ' ')
210 .count()
211 .min(gpui::LineWrapper::MAX_INDENT as usize)
212 } else {
213 0
214 };
215 let indent_width = measure(0..indent);
216 let WrapScratch {
217 ends,
218 opportunities,
219 } = scratch;
220 let ends = GraphemeEnds::new(text, ends);
221 opportunities.clear();
222 opportunities.extend(
223 unicode_linebreak::linebreaks(text)
224 .map(|(ix, _)| ix)
225 .filter(|&ix| ends.contains(ix)),
226 );
227 let opportunities = opportunities.as_slice();
228 let mut result = Vec::new();
229 let mut first = 0;
230 let mut start = 0;
231 while first < ends.len() {
232 let available = if start == 0 {
233 width
234 } else {
235 width - indent_width
236 };
237 const MAX_WORD_PROBE_GRAPHEMES: usize = 256;
242 let word_probe_end = if first + MAX_WORD_PROBE_GRAPHEMES <= ends.len() {
243 ends.get(first + MAX_WORD_PROBE_GRAPHEMES - 1)
244 } else {
245 text.len()
246 };
247 let mut fits = |end: usize, limit: Option<usize>| {
248 if limit.is_some_and(|limit| end > limit) {
249 return None;
250 }
251 Some(valid_widths.fits(
252 measure(start..end),
253 available,
254 if start == 0 { px(0.) } else { indent_width },
255 ))
256 };
257 let first_word =
258 opportunities.partition_point(|&ix| ix <= start || (start == 0 && ix <= indent));
259 let words = &opportunities[first_word..];
260 let end = if let Some(word_count) =
261 fitting_count(words.len(), |ix| fits(words[ix], Some(word_probe_end)))
262 && word_count > 0
263 {
264 words[word_count - 1]
265 } else {
266 let count =
269 fitting_count(ends.len() - first, |ix| fits(ends.get(first + ix), None)).unwrap();
270 let fitting_end = ends.get(first + count.max(1) - 1);
271 if fitting_end == text.len() {
272 break;
273 }
274 let word_count = words.partition_point(|&ix| ix <= fitting_end);
275 word_count
276 .checked_sub(1)
277 .map(|ix| words[ix])
278 .unwrap_or(fitting_end)
279 };
280 if end == text.len() {
281 break;
282 }
283 result.push(gpui::Boundary {
284 ix: end,
285 next_indent: indent as u32,
286 });
287 first = ends.count_through(end);
288 start = end;
289 }
290 MeasuredWrap {
291 boundaries: result,
292 valid_widths,
293 }
294}
295
296fn fitting_count(count: usize, mut fits: impl FnMut(usize) -> Option<bool>) -> Option<usize> {
300 let mut low = 0;
301 let mut high = 1;
302 while high <= count && fits(high - 1)? {
303 low = high;
304 if high == count {
305 break;
306 }
307 high = (high * 2).min(count);
308 }
309 while low + 1 < high {
310 let mid = (low + high) / 2;
311 if fits(mid - 1)? {
312 low = mid;
313 } else {
314 high = mid;
315 }
316 }
317 Some(low)
318}
319
320#[derive(Default)]
323struct WrapScratch {
324 ends: Vec<usize>,
325 opportunities: Vec<usize>,
326}
327
328impl WrapScratch {
329 fn release_excess(&mut self) {
331 const MAX_RETAINED: usize = 64 * 1024;
332 if self.ends.capacity() > MAX_RETAINED || self.opportunities.capacity() > MAX_RETAINED {
333 *self = Self::default();
334 }
335 }
336}
337
338#[derive(Clone, Copy)]
340enum GraphemeEnds<'a> {
341 Bytes(usize),
343 Segmented(&'a [usize]),
344}
345
346impl<'a> GraphemeEnds<'a> {
347 fn new(text: &str, buffer: &'a mut Vec<usize>) -> Self {
348 if is_printable_ascii(text) {
349 return Self::Bytes(text.len());
350 }
351 buffer.clear();
352 buffer.extend(
353 text.grapheme_indices(true)
354 .map(|(ix, grapheme)| ix + grapheme.len()),
355 );
356 Self::Segmented(buffer.as_slice())
357 }
358
359 fn len(self) -> usize {
360 match self {
361 Self::Bytes(len) => len,
362 Self::Segmented(ends) => ends.len(),
363 }
364 }
365
366 fn get(self, index: usize) -> usize {
367 match self {
368 Self::Bytes(_) => index + 1,
369 Self::Segmented(ends) => ends[index],
370 }
371 }
372
373 fn count_through(self, offset: usize) -> usize {
375 match self {
376 Self::Bytes(len) => offset.min(len),
377 Self::Segmented(ends) => ends.partition_point(|&ix| ix <= offset),
378 }
379 }
380
381 fn contains(self, offset: usize) -> bool {
382 match self {
383 Self::Bytes(len) => (1..=len).contains(&offset),
384 Self::Segmented(ends) => ends.binary_search(&offset).is_ok(),
385 }
386 }
387}
388
389#[derive(Clone, Copy, Debug, PartialEq, Eq)]
391enum Reuse {
392 Nothing,
394 Widths,
397 Measurements,
399}
400
401const ROWS_PER_STALE_ROW: usize = 64;
403
404#[derive(Debug, Clone)]
406pub(crate) struct LineItem {
407 len: usize,
409 pub(crate) indent: u32,
414 pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,
418 valid_widths: WidthRange,
420}
421
422impl LineItem {
423 #[inline]
425 pub(crate) fn len(&self) -> usize {
426 self.len
427 }
428
429 #[inline]
431 pub(crate) fn lines_len(&self) -> usize {
432 self.wrapped_lines.len()
433 }
434}
435
436#[derive(Debug, Clone)]
438pub(crate) struct LineSummary {
439 buffer_rows: usize,
441 wrap_rows: usize,
443 bytes: usize,
445 max_line_len: usize,
447 longest_row: usize,
449 valid_widths: WidthRange,
451}
452
453impl sum_tree::Summary for LineSummary {
454 type Context<'a> = &'a ();
455
456 fn zero(_: &()) -> Self {
457 LineSummary {
458 buffer_rows: 0,
459 wrap_rows: 0,
460 bytes: 0,
461 max_line_len: 0,
462 longest_row: 0,
463 valid_widths: WidthRange::all(),
464 }
465 }
466
467 fn add_summary(&mut self, other: &Self, _: &()) {
468 if other.max_line_len > self.max_line_len {
470 self.longest_row = self.buffer_rows + other.longest_row;
471 self.max_line_len = other.max_line_len;
472 }
473 self.buffer_rows += other.buffer_rows;
474 self.wrap_rows += other.wrap_rows;
475 self.bytes += other.bytes;
476 self.valid_widths.intersect(other.valid_widths);
477 }
478}
479
480impl sum_tree::Item for LineItem {
481 type Summary = LineSummary;
482
483 fn summary(&self, _: &()) -> LineSummary {
484 LineSummary {
485 buffer_rows: 1,
486 wrap_rows: self.lines_len(),
487 bytes: self.len(),
488 max_line_len: self.len(),
489 longest_row: 0,
490 valid_widths: self.valid_widths,
491 }
492 }
493}
494
495#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
497pub(crate) struct BufferRows(pub usize);
498
499impl<'a> sum_tree::Dimension<'a, LineSummary> for BufferRows {
500 fn zero(_: &()) -> Self {
501 BufferRows(0)
502 }
503
504 fn add_summary(&mut self, summary: &'a LineSummary, _: &()) {
505 self.0 += summary.buffer_rows;
506 }
507}
508
509#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
511pub(crate) struct WrapRows(pub usize);
512
513impl<'a> sum_tree::Dimension<'a, LineSummary> for WrapRows {
514 fn zero(_: &()) -> Self {
515 WrapRows(0)
516 }
517
518 fn add_summary(&mut self, summary: &'a LineSummary, _: &()) {
519 self.0 += summary.wrap_rows;
520 }
521}
522
523pub(crate) struct TextWrapper {
527 text: Rope,
528 font: Font,
529 font_size: Pixels,
530 wrap_width: Option<Pixels>,
532 wrapping_indent: WrappingIndent,
533 tab_size: usize,
535 pub(crate) lines: SumTree<LineItem>,
537
538 inline_metrics: Rc<[(Range<usize>, Pixels)]>,
539 font_spans: Rc<[FontSpan]>,
541 width_measurements: Rc<std::cell::RefCell<WidthMeasurements>>,
543 version: usize,
545 monospace: Option<Option<Rc<MonospaceWidths>>>,
547 scratch: WrapScratch,
548 char_widths: CharWidths,
549 #[cfg(test)]
551 fast_non_ascii: bool,
552 _initialized: bool,
553}
554
555#[allow(unused)]
556impl TextWrapper {
557 pub(crate) fn new(font: Font, font_size: Pixels, wrap_width: Option<Pixels>) -> Self {
558 Self {
559 text: Rope::new(),
560 font,
561 font_size,
562 wrap_width,
563 wrapping_indent: WrappingIndent::default(),
564 tab_size: TabSize::default().tab_size,
565 lines: SumTree::new(&()),
566 inline_metrics: Rc::from([]),
567 font_spans: Rc::from([]),
568 width_measurements: Rc::default(),
569 version: 0,
570 monospace: None,
571 scratch: WrapScratch::default(),
572 char_widths: CharWidths::default(),
573 #[cfg(test)]
574 fast_non_ascii: true,
575 _initialized: false,
576 }
577 }
578
579 #[inline]
581 pub(crate) fn is_prepared(&self) -> bool {
582 self._initialized
583 }
584
585 #[inline]
586 pub(crate) fn set_default_text(&mut self, text: &Rope) {
587 self.text = text.clone();
588 }
589
590 #[inline]
592 pub(crate) fn text(&self) -> &Rope {
593 &self.text
594 }
595
596 #[inline]
598 pub(crate) fn len(&self) -> usize {
599 self.lines.summary().wrap_rows
600 }
601
602 #[inline]
604 pub(crate) fn version(&self) -> usize {
605 self.version
606 }
607
608 #[inline]
610 pub(crate) fn lines_count(&self) -> usize {
611 self.lines.summary().buffer_rows
612 }
613
614 #[inline]
616 pub(crate) fn longest_row(&self) -> usize {
617 self.lines.summary().longest_row
618 }
619
620 #[inline]
622 pub(crate) fn line(&self, row: usize) -> Option<&LineItem> {
623 let mut cursor = self.lines.cursor::<BufferRows>(&());
624 cursor.seek(&BufferRows(row), Bias::Right);
625 cursor.item()
626 }
627
628 #[inline]
630 pub(crate) fn iter_lines(&self) -> impl Iterator<Item = &LineItem> {
631 self.lines.iter()
632 }
633
634 pub(crate) fn buffer_line_to_first_wrap_row(&self, row: usize) -> usize {
637 let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
638 cursor.seek(&BufferRows(row), Bias::Right);
639 cursor.start().1.0
640 }
641
642 pub(crate) fn buffer_line_to_wrap_row_range(&self, row: usize) -> Range<usize> {
644 let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
645 cursor.seek(&BufferRows(row), Bias::Right);
646 let start = cursor.start().1.0;
647 let len = cursor.item().map(|l| l.lines_len()).unwrap_or(0);
648 start..start + len
649 }
650
651 pub(crate) fn wrap_row_to_buffer_line(&self, wrap_row: usize) -> usize {
653 let mut cursor = self.lines.cursor::<Dimensions<WrapRows, BufferRows>>(&());
654 cursor.seek(&WrapRows(wrap_row), Bias::Right);
655 match cursor.item() {
656 Some(_) => cursor.start().1.0,
657 None => self.lines_count().saturating_sub(1),
658 }
659 }
660
661 pub(crate) fn wrap_width(&self) -> Option<Pixels> {
662 self.wrap_width
663 }
664
665 pub(crate) fn font(&self) -> (&Font, Pixels) {
666 (&self.font, self.font_size)
667 }
668
669 pub(crate) fn prepare_wrap_width(&mut self, wrap_width: Pixels) {
672 if self.wrap_width.is_some() {
673 self.wrap_width = Some(wrap_width);
674 }
675 }
676
677 pub(crate) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
678 if wrap_width == self.wrap_width {
679 return;
680 }
681
682 let width_only = self.wrap_width.is_some() && wrap_width.is_some();
683 self.wrap_width = wrap_width;
684 let text = self.text.clone();
685 let Some(width) = wrap_width.filter(|_| width_only) else {
686 self.update_wrapped(&text, &(0..text.len()), &text, Reuse::Nothing, cx);
687 return;
688 };
689 if self.lines.summary().valid_widths.contains(width) {
690 return;
691 }
692 match self.stale_rows(width) {
693 Some(stale_rows) => {
694 let edits: Vec<(Range<usize>, Rope)> = stale_rows
695 .into_iter()
696 .map(|rows| {
697 let range =
698 text.line_start_offset(rows.start)..text.line_end_offset(rows.end - 1);
699 let new_text = Rope::from(text.slice(range.clone()));
700 (range, new_text)
701 })
702 .collect();
703 self.update_wrapped_ranges(&text, &edits, Reuse::Measurements, cx);
704 }
705 None => self.update_wrapped(&text, &(0..text.len()), &text, Reuse::Widths, cx),
706 }
707 }
708
709 fn stale_rows(&self, wrap_width: Pixels) -> Option<Vec<Range<usize>>> {
712 let limit = self.lines_count() / ROWS_PER_STALE_ROW;
713 let mut runs: Vec<Range<usize>> = Vec::new();
714 let mut stale_count = 0;
715 let mut cursor = self
716 .lines
717 .filter::<_, BufferRows>(&(), |summary: &LineSummary| {
718 !summary.valid_widths.contains(wrap_width)
719 });
720 cursor.next();
721 while cursor.item().is_some() {
722 stale_count += 1;
723 if stale_count > limit {
724 return None;
725 }
726 let row = cursor.start().0;
727 match runs.last_mut() {
728 Some(run) if run.end == row => run.end += 1,
729 _ => runs.push(row..row + 1),
730 }
731 cursor.next();
732 }
733 Some(runs)
734 }
735
736 pub(crate) fn set_wrapping_indent(&mut self, wrapping_indent: WrappingIndent, cx: &mut App) {
737 if wrapping_indent == self.wrapping_indent {
738 return;
739 }
740
741 self.wrapping_indent = wrapping_indent;
742 self.update_all(&self.text.clone(), cx);
743 }
744
745 pub(crate) fn set_tab_size(&mut self, tab_size: usize, cx: &mut App) -> bool {
747 if tab_size == self.tab_size {
748 return false;
749 }
750
751 self.tab_size = tab_size;
752 self.char_widths.clear();
753 self.update_all(&self.text.clone(), cx);
754 true
755 }
756
757 #[cfg(test)]
758 pub(super) fn set_fast_non_ascii(&mut self, enabled: bool) {
759 self.fast_non_ascii = enabled;
760 }
761
762 pub(crate) fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
763 if self.font.eq(&font) && self.font_size == font_size {
764 return;
765 }
766
767 self.font = font;
768 self.font_size = font_size;
769 self.monospace = None;
770 self.char_widths.clear();
771 self.update_all(&self.text.clone(), cx);
772 }
773
774 pub(crate) fn prepare_if_need(&mut self, text: &Rope, cx: &mut App) -> bool {
775 if self._initialized {
776 return false;
777 }
778 self._initialized = true;
779 self.update_all(text, cx);
780 true
781 }
782
783 pub(crate) fn update(
793 &mut self,
794 changed_text: &Rope,
795 range: &Range<usize>,
796 new_text: &Rope,
797 cx: &mut App,
798 ) {
799 self.update_wrapped(changed_text, range, new_text, Reuse::Nothing, cx);
800 }
801
802 fn update_wrapped(
803 &mut self,
804 changed_text: &Rope,
805 range: &Range<usize>,
806 new_text: &Rope,
807 reuse: Reuse,
808 cx: &mut App,
809 ) {
810 self.update_wrapped_ranges(
811 changed_text,
812 &[(range.clone(), new_text.clone())],
813 reuse,
814 cx,
815 );
816 }
817
818 fn update_wrapped_ranges(
820 &mut self,
821 changed_text: &Rope,
822 edits: &[(Range<usize>, Rope)],
823 reuse: Reuse,
824 cx: &mut App,
825 ) {
826 debug_assert!(reuse != Reuse::Widths || edits.len() == 1);
827 let mut line_wrapper = cx
828 .text_system()
829 .line_wrapper(self.font.clone(), self.font_size);
830 let metrics = self.inline_metrics.clone();
831 let spans = self.font_spans.clone();
832 let measurements = self.width_measurements.clone();
833 if reuse == Reuse::Nothing {
834 measurements.borrow_mut().clear();
835 }
836 let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
837 let font = self.font.clone();
838 let font_size = self.font_size;
839 let wrapping_indent = self.wrapping_indent;
840 let tab_stop = tab_stop_width(&text_system, &font, font_size, self.tab_size);
841 let layout = |text: &str| {
842 text_system.layout_line(
843 text,
844 font_size,
845 &[gpui::TextRun {
846 len: text.len(),
847 font: font.clone(),
848 color: gpui::black(),
849 background_color: None,
850 underline: None,
851 strikethrough: None,
852 }],
853 None,
854 )
855 };
856 let shaped = |text: &str| expanded_width(&layout(text), text, tab_stop);
857 let styled = |text: &str, start: usize, spans: &[FontSpan]| {
859 let mut runs = Vec::with_capacity(spans.len() * 2 + 1);
860 let mut offset = 0;
861 let mut run = |len: usize, font: Font| {
862 if len > 0 {
863 runs.push(gpui::TextRun {
864 len,
865 font,
866 color: gpui::black(),
867 background_color: None,
868 underline: None,
869 strikethrough: None,
870 });
871 }
872 };
873 for span in spans {
874 let from = span.range.start.saturating_sub(start).min(text.len());
875 let to = span.range.end.saturating_sub(start).min(text.len());
876 if from >= to || from < offset {
877 continue;
878 }
879 run(from - offset, font.clone());
880 run(to - from, span.font(&font));
881 offset = to;
882 }
883 run(text.len() - offset, font.clone());
884 let layout = text_system.layout_line(text, font_size, &runs, None);
885 expanded_width(&layout, text, tab_stop)
886 };
887 let cached = |text: &str| measurements.borrow_mut().measure(text, || shaped(text));
888 let glyph_starts = |text: &str| {
889 let layout = layout(text);
890 let glyphs = layout.runs.iter().flat_map(|run| &run.glyphs);
891 let mut starts: Vec<Pixels> = glyphs.map(|glyph| glyph.position.x).collect();
892 starts.push(layout.width);
893 starts
894 };
895 let monospace = if self.wrap_width.is_some() {
897 if self.monospace.is_none() {
898 self.monospace = Some(MonospaceWidths::cached(
899 &font,
900 font_size,
901 glyph_starts,
902 shaped,
903 cx,
904 ));
905 }
906 self.monospace.clone().flatten()
907 } else {
908 None
909 };
910 let mut scratch = std::mem::take(&mut self.scratch);
911 let mut char_widths = std::mem::take(&mut self.char_widths);
912 #[cfg(test)]
913 let fast_non_ascii = self.fast_non_ascii;
914 let mut wrap_line = |line_str: &str, wrap_width: Pixels, line_start: usize| {
915 let mut fragments = Vec::new();
916 let mut offset = 0;
917 let first = metrics.partition_point(|(r, _)| r.end <= line_start);
918 for (range, width) in &metrics[first..] {
919 if range.start >= line_start + line_str.len() {
920 break;
921 }
922 if range.start < line_start || range.end > line_start + line_str.len() {
923 continue;
924 }
925 let range = range.start - line_start..range.end - line_start;
926 if !line_str.is_char_boundary(range.start) || !line_str.is_char_boundary(range.end)
927 {
928 continue;
929 }
930 if offset < range.start {
931 fragments.push(LineFragment::text(&line_str[offset..range.start]));
932 }
933 fragments.push(LineFragment::element(*width, range.len()));
934 offset = range.end;
935 }
936 if fragments.is_empty() {
937 let line_end = line_start + line_str.len();
940 let first = spans.partition_point(|span| span.range.end <= line_start);
941 let last = spans.partition_point(|span| span.range.start < line_end);
942 let line_spans = &spans[first..last.max(first)];
943 if !line_spans.is_empty() && !line_str.is_empty() {
944 return measured_wrap_ranges(
945 line_str,
946 wrap_width,
947 wrapping_indent,
948 &mut scratch,
949 |range| {
950 styled(
951 &line_str[range.clone()],
952 line_start + range.start,
953 line_spans,
954 )
955 },
956 );
957 }
958 if let Some(monospace) = &monospace
959 && is_printable_ascii(line_str)
960 {
961 return monospace_wrap(
962 line_str,
963 wrap_width,
964 wrapping_indent,
965 &mut scratch,
966 monospace,
967 cached,
968 );
969 }
970 #[cfg(test)]
971 let fast = fast_non_ascii;
972 #[cfg(not(test))]
973 let fast = true;
974 if fast
975 && let Some(monospace) = &monospace
976 && let Some(widths) = char_widths.line_widths(
977 line_str,
978 monospace,
979 tab_stop,
980 &mut |text: &str| shaped(text),
981 &mut |text: &str| glyph_starts(text),
982 )
983 {
984 return fast_wrap(line_str, wrap_width, wrapping_indent, &mut scratch, &widths);
985 }
986 return measured_wrap(line_str, wrap_width, wrapping_indent, &mut scratch, cached);
987 }
988 if offset < line_str.len() {
989 fragments.push(LineFragment::text(&line_str[offset..]));
990 }
991 MeasuredWrap::uncached(
993 line_wrapper
994 .wrap_line(&fragments, wrap_width, gpui::IndentAdjustment::SameIndent)
995 .collect(),
996 )
997 };
998 for (range, new_text) in edits {
999 self.update_lines(
1000 changed_text,
1001 range,
1002 new_text,
1003 reuse == Reuse::Widths,
1004 &mut wrap_line,
1005 );
1006 }
1007 drop(wrap_line);
1008 scratch.release_excess();
1009 self.scratch = scratch;
1010 char_widths.release_excess();
1011 self.char_widths = char_widths;
1012 }
1013
1014 pub(crate) fn adjust_inline_metrics(&mut self, range: &Range<usize>, new_len: usize) {
1015 if self.inline_metrics.is_empty() {
1016 return;
1017 }
1018 let shift = new_len as isize - range.len() as isize;
1019 self.inline_metrics = self
1020 .inline_metrics
1021 .iter()
1022 .filter_map(|(token, width)| {
1023 if token.start < range.end && range.start < token.end {
1024 return None;
1025 }
1026 let token = if token.start >= range.end {
1027 token.start.checked_add_signed(shift)?..token.end.checked_add_signed(shift)?
1028 } else {
1029 token.clone()
1030 };
1031 Some((token, *width))
1032 })
1033 .collect();
1034 }
1035
1036 pub(crate) fn set_inline_metrics(
1037 &mut self,
1038 metrics: Rc<[(Range<usize>, Pixels)]>,
1039 cx: &mut App,
1040 ) {
1041 if self.inline_metrics == metrics {
1042 return;
1043 }
1044 let mut affected = Vec::new();
1046 let (mut old, mut new) = (
1047 self.inline_metrics.iter().peekable(),
1048 metrics.iter().peekable(),
1049 );
1050 while old.peek().is_some() || new.peek().is_some() {
1051 match (old.peek(), new.peek()) {
1052 (Some(a), Some(b)) if a == b => {
1053 old.next();
1054 new.next();
1055 }
1056 (Some(a), Some(b)) if a.0.start <= b.0.start => {
1057 affected.push(a.0.clone());
1058 old.next();
1059 }
1060 (Some(_), Some(b)) | (None, Some(b)) => {
1061 affected.push(b.0.clone());
1062 new.next();
1063 }
1064 (Some(a), None) => {
1065 affected.push(a.0.clone());
1066 old.next();
1067 }
1068 (None, None) => break,
1069 }
1070 }
1071 self.inline_metrics = metrics;
1072 let text = self.text.clone();
1073 let mut rows: Vec<usize> = affected
1074 .iter()
1075 .map(|r| text.offset_to_point(r.start.min(text.len())).row)
1076 .collect();
1077 rows.sort_unstable();
1078 rows.dedup();
1079 for row in rows {
1080 let start = text.line_start_offset(row);
1081 let end = text.line_end_offset(row);
1082 self.update(
1083 &text,
1084 &(start..end),
1085 &Rope::from(text.slice(start..end).to_string()),
1086 cx,
1087 );
1088 }
1089 }
1090
1091 pub(crate) fn adjust_font_spans(&mut self, range: &Range<usize>, new_len: usize) {
1094 if self.font_spans.is_empty() {
1095 return;
1096 }
1097 self.font_spans = self
1098 .font_spans
1099 .iter()
1100 .filter_map(|span| {
1101 let range =
1102 crate::input::decorations::adjust_range_for_edit(&span.range, range, new_len);
1103 (!range.is_empty()).then(|| FontSpan {
1104 range,
1105 ..span.clone()
1106 })
1107 })
1108 .collect();
1109 }
1110
1111 pub(crate) fn set_font_spans(&mut self, spans: Rc<[FontSpan]>, cx: &mut App) {
1114 if self.font_spans == spans {
1115 return;
1116 }
1117 let old = std::mem::replace(&mut self.font_spans, spans);
1118 if !self._initialized || self.wrap_width.is_none() {
1120 return;
1121 }
1122 let new = self.font_spans.clone();
1124 let (mut old, mut new) = (old.iter().peekable(), new.iter().peekable());
1125 let text = self.text.clone();
1126 let mut rows: Vec<Range<usize>> = Vec::new();
1127 loop {
1128 let changed = match (old.peek(), new.peek()) {
1129 (Some(a), Some(b)) if a == b => {
1130 old.next();
1131 new.next();
1132 continue;
1133 }
1134 (Some(a), Some(b)) if a.range.start <= b.range.start => old.next(),
1135 (_, Some(_)) => new.next(),
1136 (Some(_), None) => old.next(),
1137 (None, None) => break,
1138 };
1139 let Some(span) = changed else { break };
1140 let start = text.offset_to_point(span.range.start.min(text.len())).row;
1141 let end = text.offset_to_point(span.range.end.min(text.len())).row + 1;
1142 rows.push(start..end);
1143 }
1144 rows.sort_unstable_by_key(|rows| rows.start);
1145 let mut merged: Vec<Range<usize>> = Vec::with_capacity(rows.len());
1146 for row in rows {
1147 match merged.last_mut() {
1148 Some(last) if last.end >= row.start => last.end = last.end.max(row.end),
1149 _ => merged.push(row),
1150 }
1151 }
1152 let edits: Vec<(Range<usize>, Rope)> = merged
1153 .into_iter()
1154 .map(|rows| {
1155 let range = text.line_start_offset(rows.start)..text.line_end_offset(rows.end - 1);
1156 let new_text = Rope::from(text.slice(range.clone()));
1157 (range, new_text)
1158 })
1159 .collect();
1160 self.update_wrapped_ranges(&text, &edits, Reuse::Measurements, cx);
1162 }
1163
1164 #[cfg(test)]
1166 fn _update<F>(
1167 &mut self,
1168 changed_text: &Rope,
1169 range: &Range<usize>,
1170 new_text: &Rope,
1171 wrap_line: &mut F,
1172 ) where
1173 F: FnMut(&str, Pixels, usize) -> Vec<gpui::Boundary>,
1174 {
1175 self.update_lines(
1176 changed_text,
1177 range,
1178 new_text,
1179 false,
1180 &mut |text, width, start| MeasuredWrap::uncached(wrap_line(text, width, start)),
1181 );
1182 }
1183
1184 fn update_lines<F>(
1186 &mut self,
1187 changed_text: &Rope,
1188 range: &Range<usize>,
1189 new_text: &Rope,
1190 reuse_rows: bool,
1191 wrap_line: &mut F,
1192 ) where
1193 F: FnMut(&str, Pixels, usize) -> MeasuredWrap,
1194 {
1195 let buffer_line_count = self.lines_count();
1197 let start_row = self.text.offset_to_point(range.start).row;
1198 let start_row = start_row.min(buffer_line_count.saturating_sub(1));
1199 let end_row = self.text.offset_to_point(range.end).row;
1200 let end_row = end_row.min(buffer_line_count.saturating_sub(1));
1201
1202 let new_start_row = changed_text.offset_to_point(range.start).row;
1204 let new_end_row = changed_text
1205 .offset_to_point(range.start + new_text.len())
1206 .row;
1207
1208 let mut new_lines = Vec::with_capacity(new_end_row.saturating_sub(new_start_row) + 1);
1209 let wrap_width = self.wrap_width;
1210 let mut previous = self.lines.iter();
1211 debug_assert!(!reuse_rows || (new_start_row == 0 && range == &(0..self.text.len())));
1212
1213 let mut lines = LinesFrom::new(changed_text, new_start_row);
1214 for _ in new_start_row..=new_end_row {
1216 let (line_start, line_str) = lines
1217 .next()
1218 .unwrap_or((changed_text.len(), Cow::Borrowed("")));
1219 if reuse_rows {
1220 if let Some(previous) = previous.next()
1221 && wrap_width.is_some_and(|width| previous.valid_widths.contains(width))
1222 {
1223 new_lines.push(previous.clone());
1224 continue;
1225 }
1226 }
1227 let mut wrapped_lines = SmallVec::<[Range<usize>; 1]>::new();
1228 let mut prev_boundary_ix = 0;
1229 let mut indent_chars = 0;
1230 let mut valid_widths = WidthRange::all();
1231
1232 if let Some(wrap_width) = wrap_width {
1234 match self.wrapping_indent {
1235 WrappingIndent::Same => {
1236 let measured = wrap_line(&line_str, wrap_width, line_start);
1239 valid_widths.intersect(measured.valid_widths);
1240 for boundary in measured.boundaries {
1241 wrapped_lines.push(prev_boundary_ix..boundary.ix);
1242 prev_boundary_ix = boundary.ix;
1243 indent_chars = boundary.next_indent;
1244 }
1245 }
1246 WrappingIndent::None => {
1247 let boundaries = wrap_line(&line_str, wrap_width, line_start);
1250 valid_widths.intersect(boundaries.valid_widths);
1251 if let Some(first_ix) = boundaries.boundaries.first().map(|b| b.ix) {
1252 wrapped_lines.push(prev_boundary_ix..first_ix);
1253 prev_boundary_ix = first_ix;
1254
1255 let continuation =
1256 wrap_line(&line_str[first_ix..], wrap_width, line_start + first_ix);
1257 valid_widths.intersect(continuation.valid_widths);
1258 for boundary in continuation.boundaries {
1259 let ix = first_ix + boundary.ix;
1260 wrapped_lines.push(prev_boundary_ix..ix);
1261 prev_boundary_ix = ix;
1262 }
1263 }
1264 }
1265 }
1266 }
1267
1268 if prev_boundary_ix < line_str.len() || prev_boundary_ix == 0 {
1270 wrapped_lines.push(prev_boundary_ix..line_str.len());
1271 }
1272
1273 new_lines.push(LineItem {
1274 len: line_str.len(),
1275 indent: indent_chars,
1276 wrapped_lines,
1277 valid_widths,
1278 });
1279 }
1280
1281 drop(previous);
1282 if self.lines.is_empty() {
1283 self.lines = SumTree::from_iter(new_lines, &());
1284 } else {
1285 let mut cursor = self.lines.cursor::<BufferRows>(&());
1286 let mut new_tree = cursor.slice(&BufferRows(start_row), Bias::Right);
1287 cursor.seek_forward(&BufferRows(end_row + 1), Bias::Right);
1289 new_tree.extend(new_lines, &());
1290 new_tree.append(cursor.suffix(), &());
1292 drop(cursor);
1293 self.lines = new_tree;
1294 }
1295
1296 self.text = changed_text.clone();
1297 self.version = self.version.wrapping_add(1);
1298 }
1299
1300 fn update_all(&mut self, text: &Rope, cx: &mut App) {
1304 self.update(text, &(0..text.len()), &text, cx);
1305 }
1306
1307 pub(crate) fn offset_to_display_point(&self, offset: usize) -> WrapDisplayPoint {
1311 self.offset_to_display_point_with_affinity(offset, false)
1312 }
1313
1314 pub(crate) fn offset_to_display_point_with_affinity(
1321 &self,
1322 offset: usize,
1323 line_end_affinity: bool,
1324 ) -> WrapDisplayPoint {
1325 let row = self.text.offset_to_point(offset).row;
1326 let start = self.text.line_start_offset(row);
1327
1328 let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
1330 cursor.seek(&BufferRows(row), Bias::Right);
1331 let wrapped_row = cursor.start().1.0;
1332 let Some(line) = cursor.item() else {
1333 return WrapDisplayPoint::new(wrapped_row, 0, 0);
1334 };
1335
1336 let local_offset = offset.saturating_sub(start);
1337 for (ix, range) in line.wrapped_lines.iter().enumerate() {
1338 let matches =
1341 range.contains(&local_offset) || (line_end_affinity && local_offset == range.end);
1342 if matches {
1343 return WrapDisplayPoint::new(
1344 wrapped_row + ix,
1345 ix,
1346 local_offset.saturating_sub(range.start),
1347 );
1348 }
1349 }
1350
1351 let last_range = line.wrapped_lines.last().unwrap_or(&(0..0));
1353 let ix = line.lines_len().saturating_sub(1);
1354 return WrapDisplayPoint::new(wrapped_row + ix, ix, last_range.len());
1355 }
1356
1357 pub(crate) fn display_point_to_offset(&self, point: WrapDisplayPoint) -> usize {
1361 let mut cursor = self.lines.cursor::<Dimensions<WrapRows, BufferRows>>(&());
1363 cursor.seek(&WrapRows(point.row), Bias::Right);
1364 let Some(line) = cursor.item() else {
1365 return self.text.len();
1366 };
1367 let wrapped_row = cursor.start().0.0;
1368 let row = cursor.start().1.0;
1369
1370 let line_start = self.text.line_start_offset(row);
1371 let local_row = point.row.saturating_sub(wrapped_row);
1372 if let Some(range) = line.wrapped_lines.get(local_row) {
1373 line_start + (range.start + point.column).min(range.end)
1374 } else {
1375 line_start + line.len()
1377 }
1378 }
1379
1380 pub(crate) fn display_point_to_point(&self, point: WrapDisplayPoint) -> TreeSitterPoint {
1381 let offset = self.display_point_to_offset(point);
1382 self.text.offset_to_point(offset)
1383 }
1384
1385 pub(crate) fn point_to_display_point(&self, point: TreeSitterPoint) -> WrapDisplayPoint {
1386 let offset = self.text.point_to_offset(point);
1387 self.offset_to_display_point(offset)
1388 }
1389}
1390
1391struct LinesFrom<'a> {
1396 chunks: ropey::iter::Chunks<'a>,
1397 rest: &'a str,
1399 pending: Option<String>,
1401 offset: usize,
1402 done: bool,
1403}
1404
1405impl<'a> LinesFrom<'a> {
1406 fn new(text: &'a Rope, row: usize) -> Self {
1407 let offset = text.line_start_offset(row);
1408 let (mut chunks, chunk_start) = text.chunks_at(offset);
1409 let rest = chunks
1410 .next()
1411 .map_or("", |chunk| &chunk[offset - chunk_start..]);
1412 Self {
1413 chunks,
1414 rest,
1415 pending: None,
1416 offset,
1417 done: false,
1418 }
1419 }
1420}
1421
1422impl<'a> Iterator for LinesFrom<'a> {
1423 type Item = (usize, Cow<'a, str>);
1424
1425 fn next(&mut self) -> Option<Self::Item> {
1426 loop {
1427 if let Some(newline) = self.rest.find('\n') {
1428 let piece = &self.rest[..newline];
1429 self.rest = &self.rest[newline + 1..];
1430 return Some(self.line(piece));
1431 }
1432 match self.chunks.next() {
1433 Some(chunk) => {
1434 if !self.rest.is_empty() {
1435 self.pending
1436 .get_or_insert_with(String::new)
1437 .push_str(self.rest);
1438 }
1439 self.rest = chunk;
1440 }
1441 None if !self.done => {
1443 self.done = true;
1444 let piece = std::mem::take(&mut self.rest);
1445 return Some(self.line(piece));
1446 }
1447 None => return None,
1448 }
1449 }
1450 }
1451}
1452
1453impl<'a> LinesFrom<'a> {
1454 fn line(&mut self, piece: &'a str) -> (usize, Cow<'a, str>) {
1455 let line = match self.pending.take() {
1456 Some(mut pending) => {
1457 pending.push_str(piece);
1458 Cow::Owned(pending)
1459 }
1460 None => Cow::Borrowed(piece),
1461 };
1462 let start = self.offset;
1463 self.offset += line.len() + 1;
1464 (start, line)
1465 }
1466}
1467
1468#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1474pub(crate) struct WrapDisplayPoint {
1475 pub row: usize,
1477 pub local_row: usize,
1481 pub column: usize,
1483}
1484
1485impl WrapDisplayPoint {
1486 pub(crate) fn new(row: usize, local_row: usize, column: usize) -> Self {
1487 Self {
1488 row,
1489 local_row,
1490 column,
1491 }
1492 }
1493}
1494
1495pub(crate) struct LineLayout {
1497 len: usize,
1499 pub(crate) wrapped_lines: SmallVec<[InputLine; 1]>,
1501 pub(crate) wrap_indent: Pixels,
1504 pub(crate) longest_width: Pixels,
1505 pub(crate) align: TextAlign,
1507 pub(crate) whitespace_indicators: Option<WhitespaceIndicators>,
1508 pub(crate) whitespace_chars: Vec<(usize, Pixels, Option<Pixels>)>,
1510 has_background: bool,
1513}
1514
1515impl LineLayout {
1516 pub(crate) fn new() -> Self {
1517 Self {
1518 len: 0,
1519 longest_width: px(0.),
1520 align: TextAlign::Left,
1521 wrapped_lines: SmallVec::new(),
1522 wrap_indent: px(0.),
1523 whitespace_chars: Vec::new(),
1524 whitespace_indicators: None,
1525 has_background: false,
1526 }
1527 }
1528
1529 pub(crate) fn with_background(mut self, has_background: bool) -> Self {
1531 self.has_background = has_background;
1532 self
1533 }
1534
1535 pub(crate) fn wrap_indent(mut self, wrap_indent: Pixels) -> Self {
1537 self.wrap_indent = wrap_indent;
1538 self
1539 }
1540
1541 #[inline]
1544 fn line_indent(&self, line_index: usize) -> Pixels {
1545 if line_index == 0 {
1546 px(0.)
1547 } else {
1548 self.wrap_indent
1549 }
1550 }
1551
1552 pub(crate) fn start_align(&self) -> TextAlign {
1555 let direction = self
1556 .wrapped_lines
1557 .iter()
1558 .map(|row| unicode_bidi::get_base_direction(row.text.as_ref()))
1559 .find(|direction| *direction != unicode_bidi::Direction::Mixed);
1560 if direction == Some(unicode_bidi::Direction::Rtl) {
1561 TextAlign::Right
1562 } else {
1563 TextAlign::Left
1564 }
1565 }
1566
1567 pub(crate) fn row_x(&self, line_index: usize, content_width: Pixels) -> Pixels {
1573 let indent = self.line_indent(line_index);
1574 let width = self
1575 .wrapped_lines
1576 .get(line_index)
1577 .map_or(px(0.), |line| line.width);
1578 indent
1579 + match self.align {
1580 TextAlign::Left => px(0.),
1581 TextAlign::Center => (content_width - width).half().max(px(0.)),
1582 TextAlign::Right => (content_width - width).max(px(0.)),
1583 }
1584 }
1585
1586 pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {
1587 self.set_wrapped_lines(wrapped_lines);
1588 self
1589 }
1590
1591 pub(crate) fn set_wrapped_lines(&mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) {
1592 self.len = wrapped_lines.iter().map(|l| l.len).sum();
1593 let width = wrapped_lines
1594 .iter()
1595 .map(|l| l.width)
1596 .max()
1597 .unwrap_or_default();
1598 self.longest_width = width;
1599 self.wrapped_lines = wrapped_lines.into_iter().map(InputLine::from).collect();
1600 }
1601
1602 pub(crate) fn inline_lines(mut self, lines: SmallVec<[InputLine; 1]>) -> Self {
1603 self.len = lines.iter().map(|line| line.len).sum();
1604 self.longest_width = lines
1605 .iter()
1606 .map(|line| line.width)
1607 .max()
1608 .unwrap_or_default();
1609 self.wrapped_lines = lines;
1610 self
1611 }
1612
1613 pub(crate) fn with_whitespaces(mut self, indicators: Option<WhitespaceIndicators>) -> Self {
1614 self.whitespace_indicators = indicators;
1615 let Some(indicators) = self.whitespace_indicators.as_ref() else {
1616 return self;
1617 };
1618
1619 let space_indicator_offset = indicators.space.width.half();
1620
1621 for (line_index, wrapped_line) in self.wrapped_lines.iter().enumerate() {
1622 for (relative_offset, c) in wrapped_line.text.char_indices() {
1623 if matches!(c, ' ' | '\t') {
1624 let is_tab = c == '\t';
1625 let start_x = wrapped_line.x_for_index(relative_offset);
1626 let end_x = wrapped_line.x_for_index(relative_offset + c.len_utf8());
1627 let x_position = if c == ' ' {
1629 (start_x + end_x).half() - space_indicator_offset
1630 } else {
1631 start_x
1632 };
1633
1634 self.whitespace_chars.push((
1635 line_index,
1636 x_position,
1637 is_tab.then_some(end_x - start_x),
1638 ));
1639 }
1640 }
1641 }
1642 self
1643 }
1644
1645 #[inline]
1646 pub(crate) fn len(&self) -> usize {
1647 self.len
1648 }
1649
1650 pub(crate) fn position_for_index(
1657 &self,
1658 offset: usize,
1659 last_layout: &LastLayout,
1660 line_end_affinity: bool,
1661 ) -> Option<Point<Pixels>> {
1662 let mut acc_len = 0;
1663 let mut offset_y = px(0.);
1664
1665 for (i, line) in self.wrapped_lines.iter().enumerate() {
1666 let is_last = i + 1 == self.wrapped_lines.len();
1667
1668 let matches = if line.len == 0 {
1669 offset == acc_len
1671 } else if is_last || line_end_affinity {
1672 offset >= acc_len && offset <= acc_len + line.len
1674 } else {
1675 offset >= acc_len && offset < acc_len + line.len
1677 };
1678
1679 if matches {
1680 let x = line.x_for_index(offset.saturating_sub(acc_len))
1681 + self.row_x(i, last_layout.content_width);
1682 return Some(point(x, offset_y));
1683 }
1684
1685 acc_len += if is_last { line.len + 1 } else { line.len };
1688 offset_y += last_layout.line_height;
1689 }
1690
1691 None
1692 }
1693
1694 pub(crate) fn closest_index_for_x(&self, x: Pixels, last_layout: &LastLayout) -> usize {
1700 let mut acc_len = 0;
1701
1702 for (i, line) in self.wrapped_lines.iter().enumerate() {
1703 let x = x - self.row_x(i, last_layout.content_width);
1704 if x <= line.width {
1705 return acc_len + line.closest_index_for_x(x);
1706 }
1707 acc_len += line.len;
1708 }
1709
1710 acc_len
1711 }
1712
1713 fn wrapped_line_at(
1718 &self,
1719 pos: Point<Pixels>,
1720 last_layout: &LastLayout,
1721 ) -> Option<(usize, usize, Pixels)> {
1722 let mut offset = 0;
1723 let mut line_top = px(0.);
1724
1725 for (i, line) in self.wrapped_lines.iter().enumerate() {
1726 let line_bottom = line_top + last_layout.line_height;
1727 if pos.y >= line_top && pos.y < line_bottom {
1728 return Some((i, offset, pos.x - self.row_x(i, last_layout.content_width)));
1729 }
1730
1731 offset += line.len;
1732 line_top = line_bottom;
1733 }
1734
1735 None
1736 }
1737
1738 pub(crate) fn closest_index_for_position(
1749 &self,
1750 pos: Point<Pixels>,
1751 last_layout: &LastLayout,
1752 ) -> Option<(usize, bool)> {
1753 let (i, offset, x) = self.wrapped_line_at(pos, last_layout)?;
1754 let line = &self.wrapped_lines[i];
1755 let ix = line.closest_index_for_x(x);
1756 let line_end_affinity = i + 1 < self.wrapped_lines.len() && ix == line.len;
1757
1758 Some((offset + ix, line_end_affinity))
1759 }
1760
1761 pub(crate) fn columns_past_line_end(
1772 &self,
1773 pos: Point<Pixels>,
1774 last_layout: &LastLayout,
1775 ) -> usize {
1776 let Some((i, _, x)) = self.wrapped_line_at(pos, last_layout) else {
1777 return 0;
1778 };
1779
1780 if i + 1 < self.wrapped_lines.len() || last_layout.space_width <= px(0.) {
1781 return 0;
1782 }
1783
1784 let past_end = x - self.wrapped_lines[i].width;
1785 if past_end <= px(0.) {
1786 return 0;
1787 }
1788
1789 (past_end / last_layout.space_width).round() as usize
1790 }
1791
1792 pub(crate) fn index_for_position(
1793 &self,
1794 pos: Point<Pixels>,
1795 last_layout: &LastLayout,
1796 ) -> Option<usize> {
1797 let (i, offset, x) = self.wrapped_line_at(pos, last_layout)?;
1798
1799 Some(offset + self.wrapped_lines[i].index_for_x(x)?)
1800 }
1801
1802 pub(crate) fn size(&self, line_height: Pixels) -> Size<Pixels> {
1803 let width = self
1804 .wrapped_lines
1805 .iter()
1806 .enumerate()
1807 .map(|(ix, line)| line.width + self.line_indent(ix))
1808 .max()
1809 .unwrap_or(self.longest_width);
1810 size(width, self.wrapped_lines.len() * line_height)
1811 }
1812
1813 pub(crate) fn paint_background(
1818 &self,
1819 pos: Point<Pixels>,
1820 line_height: Pixels,
1821 content_width: Pixels,
1822 window: &mut Window,
1823 cx: &mut App,
1824 ) {
1825 if !self.has_background {
1828 return;
1829 }
1830
1831 for (ix, line) in self.wrapped_lines.iter().enumerate() {
1832 _ = line.paint_background(
1833 pos + point(self.row_x(ix, content_width), ix * line_height),
1834 line_height,
1835 TextAlign::Left,
1836 None,
1837 window,
1838 cx,
1839 );
1840 }
1841 }
1842
1843 pub(crate) fn paint(
1844 &self,
1845 pos: Point<Pixels>,
1846 line_height: Pixels,
1847 content_width: Pixels,
1848 window: &mut Window,
1849 cx: &mut App,
1850 ) {
1851 for (ix, line) in self.wrapped_lines.iter().enumerate() {
1852 _ = line.paint(
1853 pos + point(self.row_x(ix, content_width), ix * line_height),
1854 line_height,
1855 TextAlign::Left,
1856 None,
1857 window,
1858 cx,
1859 );
1860 }
1861
1862 if let Some(indicators) = self.whitespace_indicators.as_ref() {
1864 for (line_index, x_position, tab_width) in &self.whitespace_chars {
1865 let origin = point(
1866 pos.x + *x_position + self.row_x(*line_index, content_width),
1867 pos.y + *line_index as f32 * line_height,
1868 );
1869
1870 match tab_width {
1871 Some(tab_width) => {
1872 let tab_cell = ContentMask {
1873 bounds: Bounds::new(origin, size(*tab_width, line_height)),
1874 };
1875 window.with_content_mask(Some(tab_cell), |window| {
1876 _ = indicators.tab.paint(
1877 origin,
1878 line_height,
1879 TextAlign::Left,
1880 None,
1881 window,
1882 cx,
1883 );
1884 });
1885 }
1886 None => {
1887 _ = indicators.space.paint(
1888 origin,
1889 line_height,
1890 TextAlign::Left,
1891 None,
1892 window,
1893 cx,
1894 );
1895 }
1896 }
1897 }
1898 }
1899 }
1900}
1901
1902#[cfg(test)]
1903mod tests {
1904 use super::*;
1905 use std::rc::Rc;
1906
1907 #[cfg(target_os = "linux")]
1908 use gpui::TestAppContext;
1909 use gpui::{Boundary, FontFeatures, FontStyle, FontWeight, px};
1910
1911 #[cfg(target_os = "linux")]
1912 fn shaped_width(text: &str, font: &Font, font_size: Pixels, cx: &App) -> Pixels {
1913 gpui::WindowTextSystem::new(cx.text_system().clone())
1914 .layout_line(
1915 text,
1916 font_size,
1917 &[gpui::TextRun {
1918 len: text.len(),
1919 font: font.clone(),
1920 color: gpui::black(),
1921 background_color: None,
1922 underline: None,
1923 strikethrough: None,
1924 }],
1925 None,
1926 )
1927 .width
1928 }
1929
1930 #[cfg(target_os = "linux")]
1934 fn shaping_test_context() -> TestAppContext {
1935 let platform = gpui_platform::current_platform(true);
1936 TestAppContext::build_with_text_system(
1937 gpui::TestDispatcher::new(0),
1938 None,
1939 platform.text_system(),
1940 )
1941 }
1942
1943 #[cfg(target_os = "linux")]
1944 #[test]
1945 fn production_wrap_keeps_shaped_cjk_latin_boundary_during_edits() {
1946 let cx = shaping_test_context();
1947 cx.update(|cx| {
1948 let font = test_font();
1949 let font_size = px(14.);
1950 let prefix = "abcd的";
1951 let width = shaped_width(prefix, &font, font_size, cx);
1952 assert!(shaped_width("abcd的s", &font, font_size, cx) > width);
1953 let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));
1954 let mut previous = Rope::new();
1955
1956 for value in ["abcd的", "abcd的s", "abcd的ss", "abcd的s", "abcd的"] {
1957 let text = Rope::from(value);
1958 let start = previous.len().min(text.len());
1959 let inserted = Rope::from(text.slice(start..).to_string());
1960 wrapper.update(&text, &(start..previous.len()), &inserted, cx);
1961 let expected = if value.ends_with('s') {
1962 vec![0..prefix.len(), prefix.len()..value.len()]
1963 } else {
1964 vec![0..prefix.len()]
1965 };
1966 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), expected);
1967 for range in &wrapper.line(0).unwrap().wrapped_lines {
1968 assert!(shaped_width(&value[range.clone()], &font, font_size, cx) <= width);
1969 }
1970 assert_eq!(
1971 wrapper.offset_to_display_point(value.len()).row,
1972 usize::from(value.ends_with('s'))
1973 );
1974 previous = text;
1975 }
1976 });
1977 }
1978
1979 #[cfg(target_os = "linux")]
1980 #[test]
1981 fn production_wrap_preserves_words_and_complete_graphemes() {
1982 let cx = shaping_test_context();
1983 cx.update(|cx| {
1984 let font = test_font();
1985 let font_size = px(14.);
1986 for (value, prefix) in [("hello world", "hello "), ("a👩💻b", "a👩💻")] {
1987 let width = shaped_width(prefix, &font, font_size, cx).max(shaped_width(
1990 &value[prefix.len()..],
1991 &font,
1992 font_size,
1993 cx,
1994 ));
1995 assert!(shaped_width(value, &font, font_size, cx) > width);
1996 let text = Rope::from(value);
1997 let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));
1998 wrapper.update(&text, &(0..0), &text, cx);
1999 assert_eq!(
2000 wrapper.line(0).unwrap().wrapped_lines.as_slice(),
2001 [0..prefix.len(), prefix.len()..value.len()]
2002 );
2003 for range in &wrapper.line(0).unwrap().wrapped_lines {
2004 assert!(shaped_width(&value[range.clone()], &font, font_size, cx) <= width);
2005 }
2006 }
2007 });
2008 }
2009
2010 #[test]
2011 fn measured_wrap_keeps_cjk_latin_boundary_stable_during_edits() {
2012 let measure = |text: &str| {
2013 px(text
2014 .chars()
2015 .map(|c| if c.is_ascii() { 1. } else { 2. })
2016 .sum())
2017 };
2018 let mut wrapper = TextWrapper::new(gpui::font("Arial"), px(14.), Some(px(6.)));
2019 let mut previous = Rope::new();
2020 for value in ["abcd的", "abcd的s", "abcd的ss", "abcd的s", "abcd的"] {
2021 let text = Rope::from(value);
2022 let start = previous.len().min(text.len());
2023 let inserted = Rope::from(text.slice(start..).to_string());
2024 wrapper._update(
2025 &text,
2026 &(start..previous.len()),
2027 &inserted,
2028 &mut |line, width, _| {
2029 measured_wrap_boundaries(line, width, WrappingIndent::None, measure)
2030 },
2031 );
2032 let expected = if value.ends_with('s') {
2033 vec![0..7, 7..value.len()]
2034 } else {
2035 vec![0..7]
2036 };
2037 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), expected);
2038 let cursor = wrapper.offset_to_display_point(value.len());
2039 assert_eq!(cursor.row, usize::from(value.ends_with('s')));
2040 previous = text;
2041 }
2042 }
2043
2044 #[test]
2045 fn measured_wrap_preserves_words_graphemes_and_indentation() {
2046 let wrap = |text: &str, width, indent| {
2047 measured_wrap_boundaries(text, px(width), indent, |s| {
2048 px(s.graphemes(true).count() as f32)
2049 })
2050 .into_iter()
2051 .map(|b| b.ix)
2052 .collect::<Vec<_>>()
2053 };
2054 assert_eq!(wrap("hello world", 8., WrappingIndent::None), vec![6]);
2055 assert_eq!(wrap("a👩💻b", 2., WrappingIndent::None), vec!["a👩💻".len()]);
2056 assert_eq!(wrap(" abcdefgh", 5., WrappingIndent::Same), vec![5, 8]);
2057 assert_eq!(wrap(" abcdefgh", 5., WrappingIndent::None), vec![2, 7]);
2058 assert!(wrap("", 0., WrappingIndent::None).is_empty());
2059 assert_eq!(wrap("abc", 0., WrappingIndent::None), vec![1, 2]);
2060 assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);
2062 }
2063
2064 #[test]
2065 fn rope_lines_walk_matches_line_lookups() {
2066 let long = "x".repeat(5000);
2067 let texts = [
2068 String::new(),
2069 "\n".into(),
2070 "a\n\nb".into(),
2071 "Hello, 世界!\r\nsecond\nthird\n".into(),
2072 format!("{long}\n{long}é{long}\n\n中{long}"),
2073 format!("{long}\n").repeat(40),
2074 ];
2075 for text in texts {
2076 let rope = Rope::from(text.as_str());
2077 for row in 0..rope.lines_len() {
2078 let walked: Vec<(usize, String)> = LinesFrom::new(&rope, row)
2079 .map(|(start, line)| (start, line.into_owned()))
2080 .collect();
2081 let looked_up: Vec<(usize, String)> = (row..rope.lines_len())
2082 .map(|row| {
2083 (
2084 rope.line_start_offset(row),
2085 rope.slice_line(row).to_string(),
2086 )
2087 })
2088 .collect();
2089 assert_eq!(walked, looked_up, "{text:?} from row {row}");
2090 }
2091 }
2092 }
2093
2094 #[test]
2095 fn test_update() {
2096 let font = gpui::Font {
2097 family: "Arial".into(),
2098 weight: FontWeight::default(),
2099 style: FontStyle::Normal,
2100 features: FontFeatures::default(),
2101 fallbacks: None,
2102 };
2103
2104 let mut wrapper = TextWrapper::new(font, px(14.), None);
2105 let mut text = Rope::from(
2106 "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。",
2107 );
2108
2109 fn fake_wrap_line(_line: &str, _wrap_width: Pixels, _: usize) -> Vec<Boundary> {
2110 vec![]
2111 }
2112
2113 #[track_caller]
2114 fn assert_wrapper_lines(text: &Rope, wrapper: &TextWrapper, expected_lines: &[&[&str]]) {
2115 let mut actual_lines = vec![];
2116 let mut offset = 0;
2117 for line in wrapper.iter_lines() {
2118 actual_lines.push(
2119 line.wrapped_lines
2120 .iter()
2121 .map(|range| text.slice(offset + range.start..offset + range.end))
2122 .collect::<Vec<_>>(),
2123 );
2124 offset += line.len() + 1;
2126 }
2127 assert_eq!(actual_lines, expected_lines);
2128 }
2129
2130 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2131 assert_eq!(wrapper.lines_count(), 4);
2132 assert_wrapper_lines(
2133 &text,
2134 &wrapper,
2135 &[
2136 &["Hello, 世界!\r"],
2137 &["This is second line."],
2138 &["This is third line."],
2139 &["这里是第 4 行。"],
2140 ],
2141 );
2142
2143 let range = text.len()..text.len();
2145 let new_text = "New text";
2146 text.replace(range.clone(), new_text);
2147 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2148 assert_eq!(
2149 text.to_string(),
2150 "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
2151 );
2152 assert_eq!(wrapper.lines_count(), 4);
2153 assert_eq!(wrapper.lines_count(), 4);
2154 assert_wrapper_lines(
2155 &text,
2156 &wrapper,
2157 &[
2158 &["Hello, 世界!\r"],
2159 &["This is second line."],
2160 &["This is third line."],
2161 &["这里是第 4 行。New text"],
2162 ],
2163 );
2164
2165 let range = 0..5;
2167 let new_text = "AAA";
2168 text.replace(range.clone(), new_text);
2169 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2170 assert_eq!(
2171 text.to_string(),
2172 "AAA, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
2173 );
2174 assert_eq!(wrapper.lines_count(), 4);
2175 assert_wrapper_lines(
2176 &text,
2177 &wrapper,
2178 &[
2179 &["AAA, 世界!\r"],
2180 &["This is second line."],
2181 &["This is third line."],
2182 &["这里是第 4 行。New text"],
2183 ],
2184 );
2185
2186 let start_offset = text.line_start_offset(1);
2188 let end_offset = text.line_end_offset(1);
2189 let range = start_offset..end_offset + 1;
2190 text.replace(range.clone(), "");
2191 wrapper._update(&text, &range, &Rope::from(""), &mut fake_wrap_line);
2192 assert_eq!(
2193 text.to_string(),
2194 "AAA, 世界!\r\nThis is third line.\n这里是第 4 行。New text"
2195 );
2196 assert_eq!(wrapper.lines_count(), 3);
2197 assert_wrapper_lines(
2198 &text,
2199 &wrapper,
2200 &[
2201 &["AAA, 世界!\r"],
2202 &["This is third line."],
2203 &["这里是第 4 行。New text"],
2204 ],
2205 );
2206
2207 let range = text.line_start_offset(0)..text.line_end_offset(1) + 1;
2209 let new_text = "This is a new line.\nThis is new line 2.\n";
2210 text.replace(range.clone(), new_text);
2211 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2212 assert_eq!(
2213 text.to_string(),
2214 "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text"
2215 );
2216 assert_eq!(wrapper.lines_count(), 3);
2217 assert_wrapper_lines(
2218 &text,
2219 &wrapper,
2220 &[
2221 &["This is a new line."],
2222 &["This is new line 2."],
2223 &["这里是第 4 行。New text"],
2224 ],
2225 );
2226
2227 let range = text.len()..text.len();
2229 let new_text = "\nThis is a new line at the end.";
2230 text.replace(range.clone(), new_text);
2231 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2232 assert_eq!(
2233 text.to_string(),
2234 "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
2235 );
2236 assert_eq!(wrapper.lines_count(), 4);
2237 assert_wrapper_lines(
2238 &text,
2239 &wrapper,
2240 &[
2241 &["This is a new line."],
2242 &["This is new line 2."],
2243 &["这里是第 4 行。New text"],
2244 &["This is a new line at the end."],
2245 ],
2246 );
2247
2248 let range = 0..0;
2250 let new_text = "This is a new line at the beginning.\n";
2251 text.replace(range.clone(), new_text);
2252 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2253 assert_eq!(
2254 text.to_string(),
2255 "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."
2256 );
2257 assert_eq!(wrapper.lines_count(), 5);
2258 assert_wrapper_lines(
2259 &text,
2260 &wrapper,
2261 &[
2262 &["This is a new line at the beginning."],
2263 &["This is a new line."],
2264 &["This is new line 2."],
2265 &["这里是第 4 行。New text"],
2266 &["This is a new line at the end."],
2267 ],
2268 );
2269
2270 let range = 0..text.len();
2272 let new_text = "";
2273 text.replace(range.clone(), new_text);
2274 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2275 assert_eq!(text.to_string(), "");
2276 assert_eq!(wrapper.lines_count(), 1);
2277 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
2278
2279 let range = 0..text.len();
2281 let new_text = "This is a full text.\nThis is a second line.";
2282 text.replace(range.clone(), new_text);
2283 wrapper._update(&text, &range, &text, &mut fake_wrap_line);
2284 assert_eq!(
2285 text.to_string(),
2286 "This is a full text.\nThis is a second line."
2287 );
2288 assert_eq!(wrapper.lines_count(), 2);
2289 }
2290
2291 fn test_font() -> gpui::Font {
2292 gpui::Font {
2293 family: "Arial".into(),
2294 weight: FontWeight::default(),
2295 style: FontStyle::Normal,
2296 features: FontFeatures::default(),
2297 fallbacks: None,
2298 }
2299 }
2300
2301 #[test]
2303 fn font_spans_follow_edits_like_decorations() {
2304 let bold = |range: Range<usize>| FontSpan {
2305 range,
2306 weight: Some(FontWeight::BOLD),
2307 style: None,
2308 };
2309 let mut wrapper = TextWrapper::new(test_font(), px(14.), Some(px(100.)));
2310 wrapper.font_spans = Rc::from([bold(2..6), bold(10..12)]);
2311 wrapper.adjust_font_spans(&(2..2), 3);
2313 wrapper.adjust_font_spans(&(8..8), 1);
2314 assert_eq!(&*wrapper.font_spans, &[bold(5..10), bold(14..16)]);
2315 wrapper.adjust_font_spans(&(4..15), 0);
2317 assert_eq!(&*wrapper.font_spans, &[bold(4..5)]);
2318 }
2319
2320 #[test]
2322 fn test_longest_row_after_shrink() {
2323 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2324 let mut text = Rope::from("aa\nthis is the longest line\nbb");
2325 wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
2326 assert_eq!(wrapper.longest_row(), 1);
2327
2328 let start = text.line_start_offset(0);
2331 let end = text.line_end_offset(0);
2332 let range = start..end;
2333 let new_text = "a very very long first line now";
2334 text.replace(range.clone(), new_text);
2335 wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
2336 assert_eq!(wrapper.longest_row(), 0);
2337 }
2338
2339 #[test]
2341 fn test_edit_last_line_and_full_delete() {
2342 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2343 let mut text = Rope::from("one\ntwo\nthree");
2344 wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
2345 assert_eq!(wrapper.lines_count(), 3);
2346
2347 let start = text.line_start_offset(2);
2349 let range = start..text.len();
2350 let new_text = "THREE EDITED";
2351 text.replace(range.clone(), new_text);
2352 wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
2353 assert_eq!(wrapper.lines_count(), 3);
2354 assert_eq!(wrapper.line(2).unwrap().len(), "THREE EDITED".len());
2355
2356 let range = 0..text.len();
2358 text.replace(range.clone(), "");
2359 wrapper._update(&text, &range, &Rope::from(""), &mut |_, _, _| vec![]);
2360 assert_eq!(wrapper.lines_count(), 1);
2361 assert_eq!(wrapper.len(), 1);
2362 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
2363 }
2364
2365 #[test]
2366 fn test_wrap_row_buffer_line_boundaries() {
2367 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2368 wrapper.text = Rope::from("aa\nbbbb\nc");
2369 wrapper.lines = SumTree::from_iter(
2370 vec![
2371 LineItem {
2372 len: 2,
2373 indent: 0,
2374 wrapped_lines: smallvec::smallvec![0..2],
2375 valid_widths: WidthRange::empty(),
2376 },
2377 LineItem {
2378 len: 4,
2379 indent: 0,
2380 wrapped_lines: smallvec::smallvec![0..2, 2..4],
2381 valid_widths: WidthRange::empty(),
2382 },
2383 LineItem {
2384 len: 1,
2385 indent: 0,
2386 wrapped_lines: smallvec::smallvec![0..1],
2387 valid_widths: WidthRange::empty(),
2388 },
2389 ],
2390 &(),
2391 );
2392
2393 assert_eq!(wrapper.lines_count(), 3);
2394 assert_eq!(wrapper.len(), 4);
2395
2396 assert_eq!(wrapper.buffer_line_to_first_wrap_row(0), 0);
2397 assert_eq!(wrapper.buffer_line_to_first_wrap_row(1), 1);
2398 assert_eq!(wrapper.buffer_line_to_first_wrap_row(2), 3);
2399 assert_eq!(wrapper.buffer_line_to_first_wrap_row(3), 4);
2400
2401 assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
2402 assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
2403 assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
2404 assert_eq!(wrapper.buffer_line_to_wrap_row_range(3), 4..4);
2405
2406 assert_eq!(wrapper.wrap_row_to_buffer_line(0), 0);
2407 assert_eq!(wrapper.wrap_row_to_buffer_line(1), 1);
2408 assert_eq!(wrapper.wrap_row_to_buffer_line(2), 1);
2409 assert_eq!(wrapper.wrap_row_to_buffer_line(3), 2);
2410 assert_eq!(wrapper.wrap_row_to_buffer_line(4), 2);
2411 }
2412
2413 #[test]
2414 fn test_wrap_row_queries_after_incremental_splice() {
2415 let mut wrapper = TextWrapper::new(test_font(), px(14.), Some(px(10.)));
2416 let mut text = Rope::from("aa\nbbbb\nc");
2417 let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
2418 if line.len() > 2 {
2419 vec![Boundary {
2420 ix: 2,
2421 next_indent: 0,
2422 }]
2423 } else {
2424 vec![]
2425 }
2426 };
2427
2428 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2429 assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
2430 assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
2431 assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
2432
2433 let range = text.line_start_offset(1)..text.line_end_offset(1);
2434 let new_text = "dd\neeee";
2435 text.replace(range.clone(), new_text);
2436 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2437
2438 assert_eq!(wrapper.lines_count(), 4);
2439 assert_eq!(wrapper.len(), 5);
2440 assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
2441 assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..2);
2442 assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 2..4);
2443 assert_eq!(wrapper.buffer_line_to_wrap_row_range(3), 4..5);
2444 assert_eq!(wrapper.wrap_row_to_buffer_line(0), 0);
2445 assert_eq!(wrapper.wrap_row_to_buffer_line(1), 1);
2446 assert_eq!(wrapper.wrap_row_to_buffer_line(2), 2);
2447 assert_eq!(wrapper.wrap_row_to_buffer_line(3), 2);
2448 assert_eq!(wrapper.wrap_row_to_buffer_line(4), 3);
2449 }
2450
2451 #[test]
2452 fn test_line_layout() {
2453 let mut line_layout = LineLayout::new();
2454
2455 let line1 = ShapedLine::default().with_len(100);
2456 let line2 = ShapedLine::default().with_len(50);
2457 let wrapped_lines = smallvec::smallvec![line1, line2];
2458 line_layout.set_wrapped_lines(wrapped_lines);
2459 assert_eq!(line_layout.len(), 150);
2460 assert_eq!(line_layout.wrapped_lines.len(), 2);
2461 }
2462
2463 fn test_last_layout(line_height: Pixels) -> LastLayout {
2465 LastLayout {
2466 visible_range: 0..1,
2467 visible_buffer_lines: vec![0],
2468 visible_line_byte_offsets: vec![0],
2469 visible_top: px(0.),
2470 anchor_display_row: 0,
2471 visible_range_offset: 0..0,
2472 lines: Rc::new(vec![]),
2473 line_height,
2474 wrap_width: None,
2475 wrapping_indent: WrappingIndent::default(),
2476 line_number_width: px(0.),
2477 gutter_gap: px(0.),
2478 gutter_icon_width: px(0.),
2479 gutter_decorations_width: px(0.),
2480 ghost_lines: None,
2481 spacer_rows: Vec::new(),
2482 gutter_side: crate::Side::Left,
2483 gutter_order: crate::input::GutterColumn::DEFAULT_ORDER,
2484 text_origin_x: px(0.),
2485 gutter_origin_x: px(0.),
2486 text_width: px(0.),
2487 space_width: px(0.),
2488 cursor_bounds: None,
2489 text_align: TextAlign::Left,
2490 content_width: px(0.),
2491 }
2492 }
2493
2494 #[test]
2495 fn test_position_for_index_prefers_first_leading_empty_visual_line() {
2496 let mut line_layout = LineLayout::new();
2497 line_layout.set_wrapped_lines(smallvec::smallvec![
2498 ShapedLine::default(),
2499 ShapedLine::default(),
2500 ShapedLine::default().with_len(3),
2501 ]);
2502
2503 assert_eq!(
2504 line_layout.position_for_index(0, &test_last_layout(px(20.)), false),
2505 Some(point(px(0.), px(0.)))
2506 );
2507 }
2508
2509 #[test]
2510 fn clicking_past_a_wrapped_row_keeps_the_caret_on_that_row() {
2511 let mut line_layout = LineLayout::new();
2513 line_layout.set_wrapped_lines(smallvec::smallvec![
2514 ShapedLine::default().with_len(10),
2515 ShapedLine::default().with_len(5),
2516 ]);
2517 let last_layout = test_last_layout(px(20.));
2518
2519 let (ix, line_end_affinity) = line_layout
2522 .closest_index_for_position(point(px(999.), px(5.)), &last_layout)
2523 .unwrap();
2524 assert_eq!(ix, 10);
2525 assert!(line_end_affinity);
2526
2527 assert_eq!(
2530 line_layout
2531 .position_for_index(ix, &last_layout, line_end_affinity)
2532 .map(|pos| pos.y),
2533 Some(px(0.))
2534 );
2535 assert_eq!(
2536 line_layout
2537 .position_for_index(ix, &last_layout, false)
2538 .map(|pos| pos.y),
2539 Some(px(20.))
2540 );
2541
2542 let (ix, line_end_affinity) = line_layout
2544 .closest_index_for_position(point(px(999.), px(25.)), &last_layout)
2545 .unwrap();
2546 assert_eq!(ix, 15);
2547 assert!(!line_end_affinity);
2548 }
2549
2550 #[test]
2551 fn a_wrap_boundary_offset_resolves_to_the_row_the_caret_is_drawn_on() {
2552 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2553 wrapper.text = Rope::from("first line\nthis one wraps");
2554 wrapper.lines = SumTree::from_iter(
2555 vec![
2556 LineItem {
2557 len: Rope::from("first line").len(),
2558 indent: 0,
2559 wrapped_lines: smallvec::smallvec![0..10],
2560 valid_widths: WidthRange::empty(),
2561 },
2562 LineItem {
2563 len: Rope::from("this one wraps").len(),
2564 indent: 0,
2565 wrapped_lines: smallvec::smallvec![0..9, 9..14],
2566 valid_widths: WidthRange::empty(),
2567 },
2568 ],
2569 &(),
2570 );
2571
2572 assert_eq!(
2576 wrapper.offset_to_display_point_with_affinity(20, true),
2577 WrapDisplayPoint::new(1, 0, 9)
2578 );
2579 assert_eq!(
2580 wrapper.offset_to_display_point_with_affinity(20, false),
2581 WrapDisplayPoint::new(2, 1, 0)
2582 );
2583 assert_eq!(
2584 wrapper.offset_to_display_point(20),
2585 wrapper.offset_to_display_point_with_affinity(20, false)
2586 );
2587
2588 for line_end_affinity in [false, true] {
2590 assert_eq!(
2591 wrapper.offset_to_display_point_with_affinity(23, line_end_affinity),
2592 WrapDisplayPoint::new(2, 1, 3)
2593 );
2594 }
2595 }
2596
2597 #[test]
2598 fn test_offset_to_display_point() {
2599 let font = gpui::Font {
2600 family: "Arial".into(),
2601 weight: FontWeight::default(),
2602 style: FontStyle::Normal,
2603 features: FontFeatures::default(),
2604 fallbacks: None,
2605 };
2606
2607 let mut wrapper = TextWrapper::new(font, px(14.), None);
2608 wrapper.text = Rope::from(
2609 "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。",
2610 );
2611 wrapper.lines = SumTree::from_iter(
2612 vec![
2613 LineItem {
2615 len: Rope::from("Hello, 世界!\r").len(),
2616 indent: 0,
2617 wrapped_lines: smallvec::smallvec![0..15],
2618 valid_widths: WidthRange::empty(),
2619 },
2620 LineItem {
2622 len: Rope::from("This is second line.\n").len(),
2623 indent: 0,
2624 wrapped_lines: smallvec::smallvec![0..10, 10..20],
2625 valid_widths: WidthRange::empty(),
2626 },
2627 LineItem {
2629 len: Rope::from("This is third line.\n").len(),
2630 indent: 0,
2631 wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],
2632 valid_widths: WidthRange::empty(),
2633 },
2634 LineItem {
2636 len: Rope::from("这里是第 4 行。").len(),
2637 indent: 0,
2638 wrapped_lines: smallvec::smallvec![0..22],
2639 valid_widths: WidthRange::empty(),
2640 },
2641 ],
2642 &(),
2643 );
2644
2645 assert_eq!(
2646 wrapper.offset_to_display_point(12),
2647 WrapDisplayPoint::new(0, 0, 12)
2648 );
2649 assert_eq!(
2650 wrapper.offset_to_display_point(15),
2651 WrapDisplayPoint::new(0, 0, 15)
2652 );
2653
2654 assert_eq!(
2655 wrapper.offset_to_display_point(16),
2656 WrapDisplayPoint::new(1, 0, 0)
2657 );
2658 assert_eq!(
2659 wrapper.offset_to_display_point(21),
2660 WrapDisplayPoint::new(1, 0, 5)
2661 );
2662 assert_eq!(
2663 wrapper.offset_to_display_point(27),
2664 WrapDisplayPoint::new(2, 1, 1)
2665 );
2666 assert_eq!(
2667 wrapper.offset_to_display_point(37),
2668 WrapDisplayPoint::new(3, 0, 0)
2669 );
2670 assert_eq!(
2671 wrapper.offset_to_display_point(54),
2672 WrapDisplayPoint::new(5, 2, 2)
2673 );
2674 assert_eq!(
2675 wrapper.offset_to_display_point(59),
2676 WrapDisplayPoint::new(6, 0, 2)
2677 );
2678
2679 assert_eq!(
2680 wrapper.display_point_to_offset(WrapDisplayPoint::new(6, 0, 2)),
2681 59
2682 );
2683 assert_eq!(
2684 wrapper.display_point_to_offset(WrapDisplayPoint::new(5, 2, 2)),
2685 54
2686 );
2687 assert_eq!(
2688 wrapper.display_point_to_offset(WrapDisplayPoint::new(3, 0, 0)),
2689 37
2690 );
2691 assert_eq!(
2692 wrapper.display_point_to_offset(WrapDisplayPoint::new(2, 1, 1)),
2693 27
2694 );
2695 assert_eq!(
2696 wrapper.display_point_to_offset(WrapDisplayPoint::new(1, 0, 5)),
2697 21
2698 );
2699 assert_eq!(
2700 wrapper.display_point_to_offset(WrapDisplayPoint::new(1, 0, 0)),
2701 16
2702 );
2703 assert_eq!(
2704 wrapper.display_point_to_offset(WrapDisplayPoint::new(0, 0, 15)),
2705 15
2706 );
2707 }
2708
2709 #[test]
2710 fn test_wrapping_indent_same_keeps_indent_reserved() {
2711 let mut wrapper = TextWrapper::new(test_font(), px(14.0), Some(px(10.)));
2712 wrapper.wrapping_indent = WrappingIndent::Same;
2713 let text = Rope::from(" abcdefghijklmnopqrstuv");
2714 let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
2715 if line.starts_with(' ') {
2716 vec![Boundary {
2717 ix: 5,
2718 next_indent: 2,
2719 }]
2720 } else {
2721 let mut boundaries = vec![];
2722 let mut i = 8;
2723 while i < line.len() {
2724 boundaries.push(Boundary {
2725 ix: i,
2726 next_indent: 0,
2727 });
2728 i += 8;
2729 }
2730 boundaries
2731 }
2732 };
2733
2734 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2735
2736 let line = wrapper.line(0).unwrap();
2737 assert_eq!(line.indent, 2);
2738 assert_eq!(line.wrapped_lines.as_slice(), [0..5, 5..24]);
2739 }
2740
2741 #[test]
2742 fn test_wrapping_indent_none_continuation_lines_wrapped_at_full_width() {
2743 let mut wrapper = TextWrapper::new(test_font(), px(14.0), Some(px(10.)));
2744 wrapper.wrapping_indent = WrappingIndent::None;
2745 let text = Rope::from(" abcdefghijklmnopqrstuv");
2746 let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
2747 if line.starts_with(' ') {
2748 vec![Boundary {
2749 ix: 5,
2750 next_indent: 2,
2751 }]
2752 } else {
2753 let mut boundaries = vec![];
2754 let mut i = 8;
2755 while i < line.len() {
2756 boundaries.push(Boundary {
2757 ix: i,
2758 next_indent: 0,
2759 });
2760 i += 8;
2761 }
2762 boundaries
2763 }
2764 };
2765
2766 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2767
2768 let line = wrapper.line(0).unwrap();
2769 assert_eq!(line.indent, 0);
2770 assert_eq!(line.wrapped_lines.as_slice(), [0..5, 5..13, 13..21, 21..24]);
2771 }
2772
2773 #[test]
2774 fn a_paragraph_starts_at_the_edge_it_reads_from() {
2775 let row = |text: &str, width: f32| {
2776 let mut row = InputLine::from(ShapedLine::default());
2777 row.text = text.to_owned().into();
2778 row.width = px(width);
2779 row
2780 };
2781 let mut arabic = LineLayout::new()
2783 .inline_lines(smallvec::smallvec![row("١٢ مرحبا", 60.), row("hello", 40.)]);
2784 assert_eq!(arabic.start_align(), TextAlign::Right);
2785 arabic.align = arabic.start_align();
2786 assert_eq!(
2787 arabic.row_x(0, px(100.)),
2788 px(40.),
2789 "each row by its own width"
2790 );
2791 assert_eq!(arabic.row_x(1, px(100.)), px(60.));
2792
2793 let english = LineLayout::new().inline_lines(smallvec::smallvec![row("hi مرحبا", 60.)]);
2794 assert_eq!(english.start_align(), TextAlign::Left);
2795 let neutral = LineLayout::new().inline_lines(smallvec::smallvec![row("12 !", 30.)]);
2796 assert_eq!(neutral.start_align(), TextAlign::Left);
2797 }
2798
2799 #[test]
2800 fn test_wrap_indent_offsets_continuation_lines() {
2801 let mut line_layout = LineLayout::new();
2802 line_layout.set_wrapped_lines(smallvec::smallvec![
2803 ShapedLine::default().with_len(5),
2804 ShapedLine::default().with_len(10),
2805 ]);
2806
2807 line_layout = line_layout.wrap_indent(px(20.0));
2808
2809 let last_layout = LastLayout {
2810 visible_range: 0..1,
2811 visible_buffer_lines: vec![0],
2812 visible_line_byte_offsets: vec![0],
2813 visible_top: px(0.),
2814 anchor_display_row: 0,
2815 visible_range_offset: 0..0,
2816 lines: Rc::new(vec![]),
2817 line_height: px(20.0),
2818 wrap_width: Some(px(10.)),
2819 wrapping_indent: WrappingIndent::Same,
2820 line_number_width: px(0.),
2821 gutter_gap: px(0.),
2822 gutter_icon_width: px(0.),
2823 gutter_decorations_width: px(0.),
2824 ghost_lines: None,
2825 spacer_rows: Vec::new(),
2826 gutter_side: crate::Side::Left,
2827 gutter_order: crate::input::GutterColumn::DEFAULT_ORDER,
2828 text_origin_x: px(0.),
2829 gutter_origin_x: px(0.),
2830 text_width: px(0.),
2831 space_width: px(0.),
2832 cursor_bounds: None,
2833 text_align: TextAlign::Left,
2834 content_width: px(0.),
2835 };
2836
2837 assert_eq!(
2838 line_layout.position_for_index(0, &last_layout, false),
2839 Some(point(px(0.), px(0.))),
2840 );
2841
2842 assert_eq!(
2843 line_layout.position_for_index(6, &last_layout, false),
2844 Some(point(px(20.), px(20.))),
2845 )
2846 }
2847}