1use super::{
2 Highlights,
3 dimensions::RowDelta,
4 fold_map::{Chunk, FoldRows},
5 tab_map::{self, TabEdit, TabPoint, TabSnapshot},
6};
7use gpui::{App, AppContext as _, Context, Entity, Font, LineWrapper, Pixels, Task};
8use language::Point;
9use multi_buffer::{MultiBufferSnapshot, RowInfo};
10use smol::future::yield_now;
11use std::{cmp, collections::VecDeque, mem, ops::Range, sync::LazyLock, time::Duration};
12use sum_tree::{Bias, Cursor, Dimensions, SumTree};
13use text::Patch;
14
15pub use super::tab_map::TextSummary;
16pub type WrapEdit = text::Edit<WrapRow>;
17pub type WrapPatch = text::Patch<WrapRow>;
18
19#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
20pub struct WrapRow(pub u32);
21
22impl_for_row_types! {
23 WrapRow => RowDelta
24}
25
26/// Handles soft wrapping of text.
27///
28/// See the [`display_map` module documentation](crate::display_map) for more information.
29pub struct WrapMap {
30 snapshot: WrapSnapshot,
31 pending_edits: VecDeque<(TabSnapshot, Vec<TabEdit>)>,
32 interpolated_edits: WrapPatch,
33 edits_since_sync: WrapPatch,
34 wrap_width: Option<Pixels>,
35 background_task: Option<Task<()>>,
36 font_with_size: (Font, Pixels),
37}
38
39#[derive(Clone)]
40pub struct WrapSnapshot {
41 pub(super) tab_snapshot: TabSnapshot,
42 transforms: SumTree<Transform>,
43 interpolated: bool,
44}
45
46impl std::ops::Deref for WrapSnapshot {
47 type Target = TabSnapshot;
48
49 fn deref(&self) -> &Self::Target {
50 &self.tab_snapshot
51 }
52}
53
54#[derive(Clone, Debug, Default, Eq, PartialEq)]
55struct Transform {
56 summary: TransformSummary,
57 display_text: Option<&'static str>,
58}
59
60#[derive(Clone, Debug, Default, Eq, PartialEq)]
61struct TransformSummary {
62 input: TextSummary,
63 output: TextSummary,
64}
65
66#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
67pub struct WrapPoint(pub Point);
68
69pub struct WrapChunks<'a> {
70 input_chunks: tab_map::TabChunks<'a>,
71 input_chunk: Chunk<'a>,
72 output_position: WrapPoint,
73 max_output_row: WrapRow,
74 transforms: Cursor<'a, 'static, Transform, Dimensions<WrapPoint, TabPoint>>,
75 snapshot: &'a WrapSnapshot,
76}
77
78#[derive(Clone)]
79pub struct WrapRows<'a> {
80 input_buffer_rows: FoldRows<'a>,
81 input_buffer_row: RowInfo,
82 output_row: WrapRow,
83 soft_wrapped: bool,
84 max_output_row: WrapRow,
85 transforms: Cursor<'a, 'static, Transform, Dimensions<WrapPoint, TabPoint>>,
86}
87
88impl WrapRows<'_> {
89 #[ztracing::instrument(skip_all)]
90 pub(crate) fn seek(&mut self, start_row: WrapRow) {
91 self.transforms
92 .seek(&WrapPoint::new(start_row, 0), Bias::Left);
93 let mut input_row = self.transforms.start().1.row();
94 if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
95 input_row += (start_row - self.transforms.start().0.row()).0;
96 }
97 self.soft_wrapped = self.transforms.item().is_some_and(|t| !t.is_isomorphic());
98 self.input_buffer_rows.seek(input_row);
99 self.input_buffer_row = self.input_buffer_rows.next().unwrap();
100 self.output_row = start_row;
101 }
102}
103
104impl WrapMap {
105 #[ztracing::instrument(skip_all)]
106 pub fn new(
107 tab_snapshot: TabSnapshot,
108 font: Font,
109 font_size: Pixels,
110 wrap_width: Option<Pixels>,
111 cx: &mut App,
112 ) -> (Entity<Self>, WrapSnapshot) {
113 let handle = cx.new(|cx| {
114 let mut this = Self {
115 font_with_size: (font, font_size),
116 wrap_width: None,
117 pending_edits: Default::default(),
118 interpolated_edits: Default::default(),
119 edits_since_sync: Default::default(),
120 snapshot: WrapSnapshot::new(tab_snapshot),
121 background_task: None,
122 };
123 this.set_wrap_width(wrap_width, cx);
124 mem::take(&mut this.edits_since_sync);
125 this
126 });
127 let snapshot = handle.read(cx).snapshot.clone();
128 (handle, snapshot)
129 }
130
131 #[cfg(test)]
132 pub fn is_rewrapping(&self) -> bool {
133 self.background_task.is_some()
134 }
135
136 #[ztracing::instrument(skip_all)]
137 pub fn sync(
138 &mut self,
139 tab_snapshot: TabSnapshot,
140 edits: Vec<TabEdit>,
141 cx: &mut Context<Self>,
142 ) -> (WrapSnapshot, WrapPatch) {
143 if self.wrap_width.is_some() {
144 self.pending_edits.push_back((tab_snapshot, edits));
145 self.flush_edits(cx);
146 } else {
147 self.edits_since_sync = self
148 .edits_since_sync
149 .compose(self.snapshot.interpolate(tab_snapshot, &edits));
150 self.snapshot.interpolated = false;
151 }
152
153 (self.snapshot.clone(), mem::take(&mut self.edits_since_sync))
154 }
155
156 #[ztracing::instrument(skip_all)]
157 pub fn set_font_with_size(
158 &mut self,
159 font: Font,
160 font_size: Pixels,
161 cx: &mut Context<Self>,
162 ) -> bool {
163 let font_with_size = (font, font_size);
164
165 if font_with_size == self.font_with_size {
166 false
167 } else {
168 self.font_with_size = font_with_size;
169 self.rewrap(cx);
170 true
171 }
172 }
173
174 #[ztracing::instrument(skip_all)]
175 pub fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut Context<Self>) -> bool {
176 if wrap_width == self.wrap_width {
177 return false;
178 }
179
180 self.wrap_width = wrap_width;
181 self.rewrap(cx);
182 true
183 }
184
185 #[ztracing::instrument(skip_all)]
186 fn rewrap(&mut self, cx: &mut Context<Self>) {
187 self.background_task.take();
188 self.interpolated_edits.clear();
189 self.pending_edits.clear();
190
191 if let Some(wrap_width) = self.wrap_width {
192 let mut new_snapshot = self.snapshot.clone();
193
194 let text_system = cx.text_system().clone();
195 let (font, font_size) = self.font_with_size.clone();
196 let task = cx.background_spawn(async move {
197 let mut line_wrapper = text_system.line_wrapper(font, font_size);
198 let tab_snapshot = new_snapshot.tab_snapshot.clone();
199 let range = TabPoint::zero()..tab_snapshot.max_point();
200 let edits = new_snapshot
201 .update(
202 tab_snapshot,
203 &[TabEdit {
204 old: range.clone(),
205 new: range.clone(),
206 }],
207 wrap_width,
208 &mut line_wrapper,
209 )
210 .await;
211 (new_snapshot, edits)
212 });
213
214 match cx
215 .foreground_executor()
216 .block_with_timeout(Duration::from_millis(5), task)
217 {
218 Ok((snapshot, edits)) => {
219 self.snapshot = snapshot;
220 self.edits_since_sync = self.edits_since_sync.compose(&edits);
221 }
222 Err(wrap_task) => {
223 self.background_task = Some(cx.spawn(async move |this, cx| {
224 let (snapshot, edits) = wrap_task.await;
225 this.update(cx, |this, cx| {
226 this.snapshot = snapshot;
227 this.edits_since_sync = this
228 .edits_since_sync
229 .compose(mem::take(&mut this.interpolated_edits).invert())
230 .compose(&edits);
231 this.background_task = None;
232 this.flush_edits(cx);
233 cx.notify();
234 })
235 .ok();
236 }));
237 }
238 }
239 } else {
240 let old_rows = self.snapshot.transforms.summary().output.lines.row + 1;
241 self.snapshot.transforms = SumTree::default();
242 let summary = self.snapshot.tab_snapshot.text_summary();
243 if !summary.lines.is_zero() {
244 self.snapshot
245 .transforms
246 .push(Transform::isomorphic(summary), ());
247 }
248 let new_rows = self.snapshot.transforms.summary().output.lines.row + 1;
249 self.snapshot.interpolated = false;
250 self.edits_since_sync = self.edits_since_sync.compose(Patch::new(vec![WrapEdit {
251 old: WrapRow(0)..WrapRow(old_rows),
252 new: WrapRow(0)..WrapRow(new_rows),
253 }]));
254 }
255 }
256
257 #[ztracing::instrument(skip_all)]
258 fn flush_edits(&mut self, cx: &mut Context<Self>) {
259 if !self.snapshot.interpolated {
260 let mut to_remove_len = 0;
261 for (tab_snapshot, _) in &self.pending_edits {
262 if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
263 to_remove_len += 1;
264 } else {
265 break;
266 }
267 }
268 self.pending_edits.drain(..to_remove_len);
269 }
270
271 if self.pending_edits.is_empty() {
272 return;
273 }
274
275 if let Some(wrap_width) = self.wrap_width
276 && self.background_task.is_none()
277 {
278 let pending_edits = self.pending_edits.clone();
279 let mut snapshot = self.snapshot.clone();
280 let text_system = cx.text_system().clone();
281 let (font, font_size) = self.font_with_size.clone();
282 let update_task = cx.background_spawn(async move {
283 let mut edits = Patch::default();
284 let mut line_wrapper = text_system.line_wrapper(font, font_size);
285 for (tab_snapshot, tab_edits) in pending_edits {
286 let wrap_edits = snapshot
287 .update(tab_snapshot, &tab_edits, wrap_width, &mut line_wrapper)
288 .await;
289 edits = edits.compose(&wrap_edits);
290 }
291 (snapshot, edits)
292 });
293
294 match cx
295 .foreground_executor()
296 .block_with_timeout(Duration::from_millis(1), update_task)
297 {
298 Ok((snapshot, output_edits)) => {
299 self.snapshot = snapshot;
300 self.edits_since_sync = self.edits_since_sync.compose(&output_edits);
301 }
302 Err(update_task) => {
303 self.background_task = Some(cx.spawn(async move |this, cx| {
304 let (snapshot, edits) = update_task.await;
305 this.update(cx, |this, cx| {
306 this.snapshot = snapshot;
307 this.edits_since_sync = this
308 .edits_since_sync
309 .compose(mem::take(&mut this.interpolated_edits).invert())
310 .compose(&edits);
311 this.background_task = None;
312 this.flush_edits(cx);
313 cx.notify();
314 })
315 .ok();
316 }));
317 }
318 }
319 }
320
321 let was_interpolated = self.snapshot.interpolated;
322 let mut to_remove_len = 0;
323 for (tab_snapshot, edits) in &self.pending_edits {
324 if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
325 to_remove_len += 1;
326 } else {
327 let interpolated_edits = self.snapshot.interpolate(tab_snapshot.clone(), edits);
328 self.edits_since_sync = self.edits_since_sync.compose(&interpolated_edits);
329 self.interpolated_edits = self.interpolated_edits.compose(&interpolated_edits);
330 }
331 }
332
333 if !was_interpolated {
334 self.pending_edits.drain(..to_remove_len);
335 }
336 }
337}
338
339impl WrapSnapshot {
340 #[ztracing::instrument(skip_all)]
341 fn new(tab_snapshot: TabSnapshot) -> Self {
342 let mut transforms = SumTree::default();
343 let extent = tab_snapshot.text_summary();
344 if !extent.lines.is_zero() {
345 transforms.push(Transform::isomorphic(extent), ());
346 }
347 Self {
348 transforms,
349 tab_snapshot,
350 interpolated: true,
351 }
352 }
353
354 #[ztracing::instrument(skip_all)]
355 pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
356 self.tab_snapshot.buffer_snapshot()
357 }
358
359 #[ztracing::instrument(skip_all)]
360 fn interpolate(&mut self, new_tab_snapshot: TabSnapshot, tab_edits: &[TabEdit]) -> WrapPatch {
361 let mut new_transforms;
362 if tab_edits.is_empty() {
363 new_transforms = self.transforms.clone();
364 } else {
365 let mut old_cursor = self.transforms.cursor::<TabPoint>(());
366
367 let mut tab_edits_iter = tab_edits.iter().peekable();
368 new_transforms =
369 old_cursor.slice(&tab_edits_iter.peek().unwrap().old.start, Bias::Right);
370
371 while let Some(edit) = tab_edits_iter.next() {
372 if edit.new.start > TabPoint::from(new_transforms.summary().input.lines) {
373 let summary = new_tab_snapshot.text_summary_for_range(
374 TabPoint::from(new_transforms.summary().input.lines)..edit.new.start,
375 );
376 new_transforms.push_or_extend(Transform::isomorphic(summary));
377 }
378
379 if !edit.new.is_empty() {
380 new_transforms.push_or_extend(Transform::isomorphic(
381 new_tab_snapshot.text_summary_for_range(edit.new.clone()),
382 ));
383 }
384
385 old_cursor.seek_forward(&edit.old.end, Bias::Right);
386 if let Some(next_edit) = tab_edits_iter.peek() {
387 if next_edit.old.start > old_cursor.end() {
388 if old_cursor.end() > edit.old.end {
389 let summary = self
390 .tab_snapshot
391 .text_summary_for_range(edit.old.end..old_cursor.end());
392 new_transforms.push_or_extend(Transform::isomorphic(summary));
393 }
394
395 old_cursor.next();
396 new_transforms
397 .append(old_cursor.slice(&next_edit.old.start, Bias::Right), ());
398 }
399 } else {
400 if old_cursor.end() > edit.old.end {
401 let summary = self
402 .tab_snapshot
403 .text_summary_for_range(edit.old.end..old_cursor.end());
404 new_transforms.push_or_extend(Transform::isomorphic(summary));
405 }
406 old_cursor.next();
407 new_transforms.append(old_cursor.suffix(), ());
408 }
409 }
410 }
411
412 let old_snapshot = mem::replace(
413 self,
414 WrapSnapshot {
415 tab_snapshot: new_tab_snapshot,
416 transforms: new_transforms,
417 interpolated: true,
418 },
419 );
420 self.check_invariants();
421 old_snapshot.compute_edits(tab_edits, self)
422 }
423
424 #[ztracing::instrument(skip_all)]
425 async fn update(
426 &mut self,
427 new_tab_snapshot: TabSnapshot,
428 tab_edits: &[TabEdit],
429 wrap_width: Pixels,
430 line_wrapper: &mut LineWrapper,
431 ) -> WrapPatch {
432 #[derive(Debug)]
433 struct RowEdit {
434 old_rows: Range<u32>,
435 new_rows: Range<u32>,
436 }
437
438 let mut tab_edits_iter = tab_edits.iter().peekable();
439 let mut row_edits = Vec::with_capacity(tab_edits.len());
440 while let Some(edit) = tab_edits_iter.next() {
441 let mut row_edit = RowEdit {
442 old_rows: edit.old.start.row()..edit.old.end.row() + 1,
443 new_rows: edit.new.start.row()..edit.new.end.row() + 1,
444 };
445
446 while let Some(next_edit) = tab_edits_iter.peek() {
447 if next_edit.old.start.row() <= row_edit.old_rows.end {
448 row_edit.old_rows.end = next_edit.old.end.row() + 1;
449 row_edit.new_rows.end = next_edit.new.end.row() + 1;
450 tab_edits_iter.next();
451 } else {
452 break;
453 }
454 }
455
456 row_edits.push(row_edit);
457 }
458
459 let mut new_transforms;
460 if row_edits.is_empty() {
461 new_transforms = self.transforms.clone();
462 } else {
463 let mut row_edits = row_edits.into_iter().peekable();
464 let mut old_cursor = self.transforms.cursor::<TabPoint>(());
465
466 new_transforms = old_cursor.slice(
467 &TabPoint::new(row_edits.peek().unwrap().old_rows.start, 0),
468 Bias::Right,
469 );
470
471 while let Some(edit) = row_edits.next() {
472 if edit.new_rows.start > new_transforms.summary().input.lines.row {
473 let summary = new_tab_snapshot.text_summary_for_range(
474 TabPoint(new_transforms.summary().input.lines)
475 ..TabPoint::new(edit.new_rows.start, 0),
476 );
477 new_transforms.push_or_extend(Transform::isomorphic(summary));
478 }
479
480 let mut line = String::new();
481 let mut line_fragments = Vec::new();
482 let mut remaining = None;
483 let mut chunks = new_tab_snapshot.chunks(
484 TabPoint::new(edit.new_rows.start, 0)..new_tab_snapshot.max_point(),
485 false,
486 Highlights::default(),
487 );
488 let mut edit_transforms = Vec::<Transform>::new();
489 for _ in edit.new_rows.start..edit.new_rows.end {
490 while let Some(chunk) = remaining.take().or_else(|| chunks.next()) {
491 if let Some(ix) = chunk.text.find('\n') {
492 let (prefix, suffix) = chunk.text.split_at(ix + 1);
493 line_fragments.push(gpui::LineFragment::text(prefix));
494 line.push_str(prefix);
495 remaining = Some(Chunk {
496 text: suffix,
497 ..chunk
498 });
499 break;
500 } else {
501 if let Some(width) =
502 chunk.renderer.as_ref().and_then(|r| r.measured_width)
503 {
504 line_fragments
505 .push(gpui::LineFragment::element(width, chunk.text.len()));
506 } else {
507 line_fragments.push(gpui::LineFragment::text(chunk.text));
508 }
509 line.push_str(chunk.text);
510 }
511 }
512
513 if line.is_empty() {
514 break;
515 }
516
517 let mut prev_boundary_ix = 0;
518 for boundary in line_wrapper.wrap_line(&line_fragments, wrap_width) {
519 let wrapped = &line[prev_boundary_ix..boundary.ix];
520 push_isomorphic(&mut edit_transforms, TextSummary::from(wrapped));
521 edit_transforms.push(Transform::wrap(boundary.next_indent));
522 prev_boundary_ix = boundary.ix;
523 }
524
525 if prev_boundary_ix < line.len() {
526 push_isomorphic(
527 &mut edit_transforms,
528 TextSummary::from(&line[prev_boundary_ix..]),
529 );
530 }
531
532 line.clear();
533 line_fragments.clear();
534 yield_now().await;
535 }
536
537 let mut edit_transforms = edit_transforms.into_iter();
538 if let Some(transform) = edit_transforms.next() {
539 new_transforms.push_or_extend(transform);
540 }
541 new_transforms.extend(edit_transforms, ());
542
543 old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right);
544 if let Some(next_edit) = row_edits.peek() {
545 if next_edit.old_rows.start > old_cursor.end().row() {
546 if old_cursor.end() > TabPoint::new(edit.old_rows.end, 0) {
547 let summary = self.tab_snapshot.text_summary_for_range(
548 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(),
549 );
550 new_transforms.push_or_extend(Transform::isomorphic(summary));
551 }
552 old_cursor.next();
553 new_transforms.append(
554 old_cursor
555 .slice(&TabPoint::new(next_edit.old_rows.start, 0), Bias::Right),
556 (),
557 );
558 }
559 } else {
560 if old_cursor.end() > TabPoint::new(edit.old_rows.end, 0) {
561 let summary = self.tab_snapshot.text_summary_for_range(
562 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(),
563 );
564 new_transforms.push_or_extend(Transform::isomorphic(summary));
565 }
566 old_cursor.next();
567 new_transforms.append(old_cursor.suffix(), ());
568 }
569 }
570 }
571
572 let old_snapshot = mem::replace(
573 self,
574 WrapSnapshot {
575 tab_snapshot: new_tab_snapshot,
576 transforms: new_transforms,
577 interpolated: false,
578 },
579 );
580 self.check_invariants();
581 old_snapshot.compute_edits(tab_edits, self)
582 }
583
584 #[ztracing::instrument(skip_all)]
585 fn compute_edits(&self, tab_edits: &[TabEdit], new_snapshot: &WrapSnapshot) -> WrapPatch {
586 let mut wrap_edits = Vec::with_capacity(tab_edits.len());
587 let mut old_cursor = self.transforms.cursor::<TransformSummary>(());
588 let mut new_cursor = new_snapshot.transforms.cursor::<TransformSummary>(());
589 for mut tab_edit in tab_edits.iter().cloned() {
590 tab_edit.old.start.0.column = 0;
591 tab_edit.old.end.0 += Point::new(1, 0);
592 tab_edit.new.start.0.column = 0;
593 tab_edit.new.end.0 += Point::new(1, 0);
594
595 old_cursor.seek(&tab_edit.old.start, Bias::Right);
596 let mut old_start = old_cursor.start().output.lines;
597 old_start += tab_edit.old.start.0 - old_cursor.start().input.lines;
598
599 old_cursor.seek_forward(&tab_edit.old.end, Bias::Right);
600 let mut old_end = old_cursor.start().output.lines;
601 old_end += tab_edit.old.end.0 - old_cursor.start().input.lines;
602
603 new_cursor.seek(&tab_edit.new.start, Bias::Right);
604 let mut new_start = new_cursor.start().output.lines;
605 new_start += tab_edit.new.start.0 - new_cursor.start().input.lines;
606
607 new_cursor.seek_forward(&tab_edit.new.end, Bias::Right);
608 let mut new_end = new_cursor.start().output.lines;
609 new_end += tab_edit.new.end.0 - new_cursor.start().input.lines;
610
611 wrap_edits.push(WrapEdit {
612 old: WrapRow(old_start.row)..WrapRow(old_end.row),
613 new: WrapRow(new_start.row)..WrapRow(new_end.row),
614 });
615 }
616
617 wrap_edits = consolidate_wrap_edits(wrap_edits);
618 Patch::new(wrap_edits)
619 }
620
621 #[ztracing::instrument(skip_all)]
622 pub(crate) fn chunks<'a>(
623 &'a self,
624 rows: Range<WrapRow>,
625 language_aware: bool,
626 highlights: Highlights<'a>,
627 ) -> WrapChunks<'a> {
628 let output_start = WrapPoint::new(rows.start, 0);
629 let output_end = WrapPoint::new(rows.end, 0);
630 let mut transforms = self
631 .transforms
632 .cursor::<Dimensions<WrapPoint, TabPoint>>(());
633 transforms.seek(&output_start, Bias::Right);
634 let mut input_start = TabPoint(transforms.start().1.0);
635 if transforms.item().is_some_and(|t| t.is_isomorphic()) {
636 input_start.0 += output_start.0 - transforms.start().0.0;
637 }
638 let input_end = self.to_tab_point(output_end);
639 let max_point = self.tab_snapshot.max_point();
640 let input_start = input_start.min(max_point);
641 let input_end = input_end.min(max_point);
642 WrapChunks {
643 input_chunks: self.tab_snapshot.chunks(
644 input_start..input_end,
645 language_aware,
646 highlights,
647 ),
648 input_chunk: Default::default(),
649 output_position: output_start,
650 max_output_row: rows.end,
651 transforms,
652 snapshot: self,
653 }
654 }
655
656 #[ztracing::instrument(skip_all)]
657 pub fn max_point(&self) -> WrapPoint {
658 WrapPoint(self.transforms.summary().output.lines)
659 }
660
661 #[ztracing::instrument(skip_all)]
662 pub fn line_len(&self, row: WrapRow) -> u32 {
663 let (start, _, item) = self.transforms.find::<Dimensions<WrapPoint, TabPoint>, _>(
664 (),
665 &WrapPoint::new(row + WrapRow(1), 0),
666 Bias::Left,
667 );
668 if item.is_some_and(|transform| transform.is_isomorphic()) {
669 let overshoot = row - start.0.row();
670 let tab_row = start.1.row() + overshoot.0;
671 let tab_line_len = self.tab_snapshot.line_len(tab_row);
672 if overshoot.0 == 0 {
673 start.0.column() + (tab_line_len - start.1.column())
674 } else {
675 tab_line_len
676 }
677 } else {
678 start.0.column()
679 }
680 }
681
682 #[ztracing::instrument(skip_all, fields(rows))]
683 pub fn text_summary_for_range(&self, rows: Range<WrapRow>) -> TextSummary {
684 let mut summary = TextSummary::default();
685
686 let start = WrapPoint::new(rows.start, 0);
687 let end = WrapPoint::new(rows.end, 0);
688
689 let mut cursor = self
690 .transforms
691 .cursor::<Dimensions<WrapPoint, TabPoint>>(());
692 cursor.seek(&start, Bias::Right);
693 if let Some(transform) = cursor.item() {
694 let start_in_transform = start.0 - cursor.start().0.0;
695 let end_in_transform = cmp::min(end, cursor.end().0).0 - cursor.start().0.0;
696 if transform.is_isomorphic() {
697 let tab_start = TabPoint(cursor.start().1.0 + start_in_transform);
698 let tab_end = TabPoint(cursor.start().1.0 + end_in_transform);
699 summary += &self.tab_snapshot.text_summary_for_range(tab_start..tab_end);
700 } else {
701 debug_assert_eq!(start_in_transform.row, end_in_transform.row);
702 let indent_len = end_in_transform.column - start_in_transform.column;
703 summary += &TextSummary {
704 lines: Point::new(0, indent_len),
705 first_line_chars: indent_len,
706 last_line_chars: indent_len,
707 longest_row: 0,
708 longest_row_chars: indent_len,
709 };
710 }
711
712 cursor.next();
713 }
714
715 if rows.end > cursor.start().0.row() {
716 summary += &cursor
717 .summary::<_, TransformSummary>(&WrapPoint::new(rows.end, 0), Bias::Right)
718 .output;
719
720 if let Some(transform) = cursor.item() {
721 let end_in_transform = end.0 - cursor.start().0.0;
722 if transform.is_isomorphic() {
723 let char_start = cursor.start().1;
724 let char_end = TabPoint(char_start.0 + end_in_transform);
725 summary += &self
726 .tab_snapshot
727 .text_summary_for_range(char_start..char_end);
728 } else {
729 debug_assert_eq!(end_in_transform, Point::new(1, 0));
730 summary += &TextSummary {
731 lines: Point::new(1, 0),
732 first_line_chars: 0,
733 last_line_chars: 0,
734 longest_row: 0,
735 longest_row_chars: 0,
736 };
737 }
738 }
739 }
740
741 summary
742 }
743
744 #[ztracing::instrument(skip_all)]
745 pub fn soft_wrap_indent(&self, row: WrapRow) -> Option<u32> {
746 let (.., item) = self.transforms.find::<WrapPoint, _>(
747 (),
748 &WrapPoint::new(row + WrapRow(1), 0),
749 Bias::Right,
750 );
751 item.and_then(|transform| {
752 if transform.is_isomorphic() {
753 None
754 } else {
755 Some(transform.summary.output.lines.column)
756 }
757 })
758 }
759
760 #[ztracing::instrument(skip_all)]
761 pub fn longest_row(&self) -> u32 {
762 self.transforms.summary().output.longest_row
763 }
764
765 #[ztracing::instrument(skip_all)]
766 pub fn row_infos(&self, start_row: WrapRow) -> WrapRows<'_> {
767 let mut transforms = self
768 .transforms
769 .cursor::<Dimensions<WrapPoint, TabPoint>>(());
770 transforms.seek(&WrapPoint::new(start_row, 0), Bias::Left);
771 let mut input_row = transforms.start().1.row();
772 if transforms.item().is_some_and(|t| t.is_isomorphic()) {
773 input_row += (start_row - transforms.start().0.row()).0;
774 }
775 let soft_wrapped = transforms.item().is_some_and(|t| !t.is_isomorphic());
776 let mut input_buffer_rows = self.tab_snapshot.rows(input_row);
777 let input_buffer_row = input_buffer_rows.next().unwrap();
778 WrapRows {
779 transforms,
780 input_buffer_row,
781 input_buffer_rows,
782 output_row: start_row,
783 soft_wrapped,
784 max_output_row: self.max_point().row(),
785 }
786 }
787
788 #[ztracing::instrument(skip_all)]
789 pub fn to_tab_point(&self, point: WrapPoint) -> TabPoint {
790 let (start, _, item) =
791 self.transforms
792 .find::<Dimensions<WrapPoint, TabPoint>, _>((), &point, Bias::Right);
793 let mut tab_point = start.1.0;
794 if item.is_some_and(|t| t.is_isomorphic()) {
795 tab_point += point.0 - start.0.0;
796 }
797 TabPoint(tab_point)
798 }
799
800 #[ztracing::instrument(skip_all)]
801 pub fn to_point(&self, point: WrapPoint, bias: Bias) -> Point {
802 self.tab_snapshot
803 .tab_point_to_point(self.to_tab_point(point), bias)
804 }
805
806 #[ztracing::instrument(skip_all)]
807 pub fn make_wrap_point(&self, point: Point, bias: Bias) -> WrapPoint {
808 self.tab_point_to_wrap_point(self.tab_snapshot.point_to_tab_point(point, bias))
809 }
810
811 #[ztracing::instrument(skip_all)]
812 pub fn tab_point_to_wrap_point(&self, point: TabPoint) -> WrapPoint {
813 let (start, ..) =
814 self.transforms
815 .find::<Dimensions<TabPoint, WrapPoint>, _>((), &point, Bias::Right);
816 WrapPoint(start.1.0 + (point.0 - start.0.0))
817 }
818
819 #[ztracing::instrument(skip_all)]
820 pub fn wrap_point_cursor(&self) -> WrapPointCursor<'_> {
821 WrapPointCursor {
822 cursor: self
823 .transforms
824 .cursor::<Dimensions<TabPoint, WrapPoint>>(()),
825 }
826 }
827
828 #[ztracing::instrument(skip_all)]
829 pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
830 if bias == Bias::Left {
831 let (start, _, item) = self
832 .transforms
833 .find::<WrapPoint, _>((), &point, Bias::Right);
834 if item.is_some_and(|t| !t.is_isomorphic()) {
835 point = start;
836 *point.column_mut() -= 1;
837 }
838 }
839
840 self.tab_point_to_wrap_point(self.tab_snapshot.clip_point(self.to_tab_point(point), bias))
841 }
842
843 /// Try to find a TabRow start that is also a WrapRow start
844 /// Every TabRow start is a WrapRow start
845 #[ztracing::instrument(skip_all, fields(point=?point))]
846 pub fn prev_row_boundary(&self, point: WrapPoint) -> WrapRow {
847 if self.transforms.is_empty() {
848 return WrapRow(0);
849 }
850
851 let point = WrapPoint::new(point.row(), 0);
852
853 let mut cursor = self
854 .transforms
855 .cursor::<Dimensions<WrapPoint, TabPoint>>(());
856
857 cursor.seek(&point, Bias::Right);
858 if cursor.item().is_none() {
859 cursor.prev();
860 }
861
862 // real newline fake fake
863 // text: helloworldasldlfjasd\njdlasfalsk\naskdjfasdkfj\n
864 // dimensions v v v v v
865 // transforms |-------|-----NW----|-----W------|-----W------|
866 // cursor ^ ^^^^^^^^^^^^^ ^
867 // (^) ^^^^^^^^^^^^^^
868 // point: ^
869 // point(col_zero): (^)
870
871 while let Some(transform) = cursor.item() {
872 if transform.is_isomorphic() {
873 // this transform only has real linefeeds
874 let tab_summary = &transform.summary.input;
875 // is the wrap just before the end of the transform a tab row?
876 // thats only if this transform has at least one newline
877 //
878 // "this wrap row is a tab row" <=> self.to_tab_point(WrapPoint::new(wrap_row, 0)).column() == 0
879
880 // Note on comparison:
881 // We have code that relies on this to be row > 1
882 // It should work with row >= 1 but it does not :(
883 //
884 // That means that if every line is wrapped we walk back all the
885 // way to the start. Which invalidates the entire state triggering
886 // a full re-render.
887 if tab_summary.lines.row > 1 {
888 let wrap_point_at_end = cursor.end().0.row();
889 return cmp::min(wrap_point_at_end - RowDelta(1), point.row());
890 } else if cursor.start().1.column() == 0 {
891 return cmp::min(cursor.end().0.row(), point.row());
892 }
893 }
894
895 cursor.prev();
896 }
897
898 WrapRow(0)
899 }
900
901 #[ztracing::instrument(skip_all)]
902 pub fn next_row_boundary(&self, mut point: WrapPoint) -> Option<WrapRow> {
903 point.0 += Point::new(1, 0);
904
905 let mut cursor = self
906 .transforms
907 .cursor::<Dimensions<WrapPoint, TabPoint>>(());
908 cursor.seek(&point, Bias::Right);
909 while let Some(transform) = cursor.item() {
910 if transform.is_isomorphic() && cursor.start().1.column() == 0 {
911 return Some(cmp::max(cursor.start().0.row(), point.row()));
912 } else {
913 cursor.next();
914 }
915 }
916
917 None
918 }
919
920 #[cfg(test)]
921 pub fn text(&self) -> String {
922 self.text_chunks(WrapRow(0)).collect()
923 }
924
925 #[cfg(test)]
926 pub fn text_chunks(&self, wrap_row: WrapRow) -> impl Iterator<Item = &str> {
927 self.chunks(
928 wrap_row..self.max_point().row() + WrapRow(1),
929 false,
930 Highlights::default(),
931 )
932 .map(|h| h.text)
933 }
934
935 #[ztracing::instrument(skip_all)]
936 fn check_invariants(&self) {
937 #[cfg(test)]
938 {
939 assert_eq!(
940 TabPoint::from(self.transforms.summary().input.lines),
941 self.tab_snapshot.max_point()
942 );
943
944 {
945 let mut transforms = self.transforms.cursor::<()>(()).peekable();
946 while let Some(transform) = transforms.next() {
947 if let Some(next_transform) = transforms.peek() {
948 assert!(transform.is_isomorphic() != next_transform.is_isomorphic());
949 }
950 }
951 }
952
953 let text = language::Rope::from(self.text().as_str());
954 let mut input_buffer_rows = self.tab_snapshot.rows(0);
955 let mut expected_buffer_rows = Vec::new();
956 let mut prev_tab_row = 0;
957 for display_row in 0..=self.max_point().row().0 {
958 let display_row = WrapRow(display_row);
959 let tab_point = self.to_tab_point(WrapPoint::new(display_row, 0));
960 if tab_point.row() == prev_tab_row && display_row != WrapRow(0) {
961 expected_buffer_rows.push(None);
962 } else {
963 expected_buffer_rows.push(input_buffer_rows.next().unwrap().buffer_row);
964 }
965
966 prev_tab_row = tab_point.row();
967 assert_eq!(self.line_len(display_row), text.line_len(display_row.0));
968 }
969
970 for start_display_row in 0..expected_buffer_rows.len() {
971 assert_eq!(
972 self.row_infos(WrapRow(start_display_row as u32))
973 .map(|row_info| row_info.buffer_row)
974 .collect::<Vec<_>>(),
975 &expected_buffer_rows[start_display_row..],
976 "invalid buffer_rows({}..)",
977 start_display_row
978 );
979 }
980 }
981 }
982}
983
984pub struct WrapPointCursor<'transforms> {
985 cursor: Cursor<'transforms, 'static, Transform, Dimensions<TabPoint, WrapPoint>>,
986}
987
988impl WrapPointCursor<'_> {
989 #[ztracing::instrument(skip_all)]
990 pub fn map(&mut self, point: TabPoint) -> WrapPoint {
991 let cursor = &mut self.cursor;
992 if cursor.did_seek() {
993 cursor.seek_forward(&point, Bias::Right);
994 } else {
995 cursor.seek(&point, Bias::Right);
996 }
997 WrapPoint(cursor.start().1.0 + (point.0 - cursor.start().0.0))
998 }
999}
1000
1001impl WrapChunks<'_> {
1002 #[ztracing::instrument(skip_all)]
1003 pub(crate) fn seek(&mut self, rows: Range<WrapRow>) {
1004 let output_start = WrapPoint::new(rows.start, 0);
1005 let output_end = WrapPoint::new(rows.end, 0);
1006 self.transforms.seek(&output_start, Bias::Right);
1007 let mut input_start = TabPoint(self.transforms.start().1.0);
1008 if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
1009 input_start.0 += output_start.0 - self.transforms.start().0.0;
1010 }
1011 let input_end = self.snapshot.to_tab_point(output_end);
1012 let max_point = self.snapshot.tab_snapshot.max_point();
1013 let input_start = input_start.min(max_point);
1014 let input_end = input_end.min(max_point);
1015 self.input_chunks.seek(input_start..input_end);
1016 self.input_chunk = Chunk::default();
1017 self.output_position = output_start;
1018 self.max_output_row = rows.end;
1019 }
1020}
1021
1022impl<'a> Iterator for WrapChunks<'a> {
1023 type Item = Chunk<'a>;
1024
1025 #[ztracing::instrument(skip_all)]
1026 fn next(&mut self) -> Option<Self::Item> {
1027 if self.output_position.row() >= self.max_output_row {
1028 return None;
1029 }
1030
1031 let transform = self.transforms.item()?;
1032 if let Some(display_text) = transform.display_text {
1033 let mut start_ix = 0;
1034 let mut end_ix = display_text.len();
1035 let mut summary = transform.summary.output.lines;
1036
1037 if self.output_position > self.transforms.start().0 {
1038 // Exclude newline starting prior to the desired row.
1039 start_ix = 1;
1040 summary.row = 0;
1041 } else if self.output_position.row() + WrapRow(1) >= self.max_output_row {
1042 // Exclude soft indentation ending after the desired row.
1043 end_ix = 1;
1044 summary.column = 0;
1045 }
1046
1047 self.output_position.0 += summary;
1048 self.transforms.next();
1049 return Some(Chunk {
1050 text: &display_text[start_ix..end_ix],
1051 ..Default::default()
1052 });
1053 }
1054
1055 if self.input_chunk.text.is_empty() {
1056 self.input_chunk = self.input_chunks.next()?;
1057 }
1058
1059 let mut input_len = 0;
1060 let transform_end = self.transforms.end().0;
1061 for c in self.input_chunk.text.chars() {
1062 let char_len = c.len_utf8();
1063 input_len += char_len;
1064 if c == '\n' {
1065 *self.output_position.row_mut() += 1;
1066 *self.output_position.column_mut() = 0;
1067 } else {
1068 *self.output_position.column_mut() += char_len as u32;
1069 }
1070
1071 if self.output_position >= transform_end {
1072 self.transforms.next();
1073 break;
1074 }
1075 }
1076
1077 let (prefix, suffix) = self.input_chunk.text.split_at(input_len);
1078
1079 let mask = 1u128.unbounded_shl(input_len as u32).wrapping_sub(1);
1080 let chars = self.input_chunk.chars & mask;
1081 let tabs = self.input_chunk.tabs & mask;
1082 let newlines = self.input_chunk.newlines & mask;
1083 self.input_chunk.tabs = self.input_chunk.tabs.unbounded_shr(input_len as u32);
1084 self.input_chunk.chars = self.input_chunk.chars.unbounded_shr(input_len as u32);
1085 self.input_chunk.newlines = self.input_chunk.newlines.unbounded_shr(input_len as u32);
1086
1087 self.input_chunk.text = suffix;
1088 Some(Chunk {
1089 text: prefix,
1090 chars,
1091 tabs,
1092 newlines,
1093 ..self.input_chunk.clone()
1094 })
1095 }
1096}
1097
1098impl Iterator for WrapRows<'_> {
1099 type Item = RowInfo;
1100
1101 #[ztracing::instrument(skip_all)]
1102 fn next(&mut self) -> Option<Self::Item> {
1103 if self.output_row > self.max_output_row {
1104 return None;
1105 }
1106
1107 let buffer_row = self.input_buffer_row;
1108 let soft_wrapped = self.soft_wrapped;
1109 let diff_status = self.input_buffer_row.diff_status;
1110
1111 self.output_row += WrapRow(1);
1112 self.transforms
1113 .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left);
1114 if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
1115 self.input_buffer_row = self.input_buffer_rows.next().unwrap();
1116 self.soft_wrapped = false;
1117 } else {
1118 self.soft_wrapped = true;
1119 }
1120
1121 Some(if soft_wrapped {
1122 RowInfo {
1123 buffer_id: None,
1124 buffer_row: None,
1125 multibuffer_row: None,
1126 diff_status,
1127 expand_info: None,
1128 wrapped_buffer_row: buffer_row.buffer_row,
1129 }
1130 } else {
1131 buffer_row
1132 })
1133 }
1134}
1135
1136impl Transform {
1137 #[ztracing::instrument(skip_all)]
1138 fn isomorphic(summary: TextSummary) -> Self {
1139 #[cfg(test)]
1140 assert!(!summary.lines.is_zero());
1141
1142 Self {
1143 summary: TransformSummary {
1144 input: summary.clone(),
1145 output: summary,
1146 },
1147 display_text: None,
1148 }
1149 }
1150
1151 #[ztracing::instrument(skip_all)]
1152 fn wrap(indent: u32) -> Self {
1153 static WRAP_TEXT: LazyLock<String> = LazyLock::new(|| {
1154 let mut wrap_text = String::new();
1155 wrap_text.push('\n');
1156 wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
1157 wrap_text
1158 });
1159
1160 Self {
1161 summary: TransformSummary {
1162 input: TextSummary::default(),
1163 output: TextSummary {
1164 lines: Point::new(1, indent),
1165 first_line_chars: 0,
1166 last_line_chars: indent,
1167 longest_row: 1,
1168 longest_row_chars: indent,
1169 },
1170 },
1171 display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
1172 }
1173 }
1174
1175 fn is_isomorphic(&self) -> bool {
1176 self.display_text.is_none()
1177 }
1178}
1179
1180impl sum_tree::Item for Transform {
1181 type Summary = TransformSummary;
1182
1183 fn summary(&self, _cx: ()) -> Self::Summary {
1184 self.summary.clone()
1185 }
1186}
1187
1188fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
1189 if let Some(last_transform) = transforms.last_mut()
1190 && last_transform.is_isomorphic()
1191 {
1192 last_transform.summary.input += &summary;
1193 last_transform.summary.output += &summary;
1194 return;
1195 }
1196 transforms.push(Transform::isomorphic(summary));
1197}
1198
1199trait SumTreeExt {
1200 fn push_or_extend(&mut self, transform: Transform);
1201}
1202
1203impl SumTreeExt for SumTree<Transform> {
1204 #[ztracing::instrument(skip_all)]
1205 fn push_or_extend(&mut self, transform: Transform) {
1206 let mut transform = Some(transform);
1207 self.update_last(
1208 |last_transform| {
1209 if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
1210 let transform = transform.take().unwrap();
1211 last_transform.summary.input += &transform.summary.input;
1212 last_transform.summary.output += &transform.summary.output;
1213 }
1214 },
1215 (),
1216 );
1217
1218 if let Some(transform) = transform {
1219 self.push(transform, ());
1220 }
1221 }
1222}
1223
1224impl WrapPoint {
1225 pub fn new(row: WrapRow, column: u32) -> Self {
1226 Self(Point::new(row.0, column))
1227 }
1228
1229 pub fn row(self) -> WrapRow {
1230 WrapRow(self.0.row)
1231 }
1232
1233 pub fn row_mut(&mut self) -> &mut u32 {
1234 &mut self.0.row
1235 }
1236
1237 pub fn column(self) -> u32 {
1238 self.0.column
1239 }
1240
1241 pub fn column_mut(&mut self) -> &mut u32 {
1242 &mut self.0.column
1243 }
1244}
1245
1246impl sum_tree::ContextLessSummary for TransformSummary {
1247 fn zero() -> Self {
1248 Default::default()
1249 }
1250
1251 fn add_summary(&mut self, other: &Self) {
1252 self.input += &other.input;
1253 self.output += &other.output;
1254 }
1255}
1256
1257impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
1258 fn zero(_cx: ()) -> Self {
1259 Default::default()
1260 }
1261
1262 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1263 self.0 += summary.input.lines;
1264 }
1265}
1266
1267impl sum_tree::SeekTarget<'_, TransformSummary, TransformSummary> for TabPoint {
1268 #[ztracing::instrument(skip_all)]
1269 fn cmp(&self, cursor_location: &TransformSummary, _: ()) -> std::cmp::Ordering {
1270 Ord::cmp(&self.0, &cursor_location.input.lines)
1271 }
1272}
1273
1274impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
1275 fn zero(_cx: ()) -> Self {
1276 Default::default()
1277 }
1278
1279 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1280 self.0 += summary.output.lines;
1281 }
1282}
1283
1284fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
1285 let _old_alloc_ptr = edits.as_ptr();
1286 let mut wrap_edits = edits.into_iter();
1287
1288 if let Some(mut first_edit) = wrap_edits.next() {
1289 // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1290 #[allow(clippy::filter_map_identity)]
1291 let mut v: Vec<_> = wrap_edits
1292 .scan(&mut first_edit, |prev_edit, edit| {
1293 if prev_edit.old.end >= edit.old.start {
1294 prev_edit.old.end = edit.old.end;
1295 prev_edit.new.end = edit.new.end;
1296 Some(None) // Skip this edit, it's merged
1297 } else {
1298 let prev = std::mem::replace(*prev_edit, edit);
1299 Some(Some(prev)) // Yield the previous edit
1300 }
1301 })
1302 .filter_map(|x| x)
1303 .collect();
1304 v.push(first_edit.clone());
1305 debug_assert_eq!(v.as_ptr(), _old_alloc_ptr, "Wrap edits were reallocated");
1306 v
1307 } else {
1308 vec![]
1309 }
1310}
1311
1312#[cfg(test)]
1313mod tests {
1314 use super::*;
1315 use crate::{
1316 MultiBuffer,
1317 display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
1318 test::test_font,
1319 };
1320 use gpui::{LineFragment, px, test::observe};
1321 use rand::prelude::*;
1322 use settings::SettingsStore;
1323 use smol::stream::StreamExt;
1324 use std::{cmp, env, num::NonZeroU32};
1325 use text::Rope;
1326 use theme::LoadThemes;
1327
1328 #[gpui::test]
1329 async fn test_prev_row_boundary(cx: &mut gpui::TestAppContext) {
1330 init_test(cx);
1331
1332 fn test_wrap_snapshot(
1333 text: &str,
1334 soft_wrap_every: usize, // font size multiple
1335 cx: &mut gpui::TestAppContext,
1336 ) -> WrapSnapshot {
1337 let text_system = cx.read(|cx| cx.text_system().clone());
1338 let tab_size = 4.try_into().unwrap();
1339 let font = test_font();
1340 let _font_id = text_system.resolve_font(&font);
1341 let font_size = px(14.0);
1342 // this is very much an estimate to try and get the wrapping to
1343 // occur at `soft_wrap_every` we check that it pans out for every test case
1344 let soft_wrapping = Some(font_size * soft_wrap_every * 0.6);
1345
1346 let buffer = cx.new(|cx| language::Buffer::local(text, cx));
1347 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1348 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1349 let (_inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1350 let (_fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
1351 let (mut tab_map, _) = TabMap::new(fold_snapshot, tab_size);
1352 let tabs_snapshot = tab_map.set_max_expansion_column(32);
1353 let (_wrap_map, wrap_snapshot) =
1354 cx.update(|cx| WrapMap::new(tabs_snapshot, font, font_size, soft_wrapping, cx));
1355
1356 wrap_snapshot
1357 }
1358
1359 // These two should pass but dont, see the comparison note in
1360 // prev_row_boundary about why.
1361 //
1362 // // 0123 4567 wrap_rows
1363 // let wrap_snapshot = test_wrap_snapshot("1234\n5678", 1, cx);
1364 // assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8");
1365 // let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1366 // assert_eq!(row.0, 3);
1367
1368 // // 012 345 678 wrap_rows
1369 // let wrap_snapshot = test_wrap_snapshot("123\n456\n789", 1, cx);
1370 // assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8\n9");
1371 // let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1372 // assert_eq!(row.0, 5);
1373
1374 // 012345678 wrap_rows
1375 let wrap_snapshot = test_wrap_snapshot("123456789", 1, cx);
1376 assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8\n9");
1377 let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1378 assert_eq!(row.0, 0);
1379
1380 // 111 2222 44 wrap_rows
1381 let wrap_snapshot = test_wrap_snapshot("123\n4567\n\n89", 4, cx);
1382 assert_eq!(wrap_snapshot.text(), "123\n4567\n\n89");
1383 let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1384 assert_eq!(row.0, 2);
1385
1386 // 11 2223 wrap_rows
1387 let wrap_snapshot = test_wrap_snapshot("12\n3456\n\n", 3, cx);
1388 assert_eq!(wrap_snapshot.text(), "12\n345\n6\n\n");
1389 let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1390 assert_eq!(row.0, 3);
1391 }
1392
1393 #[gpui::test(iterations = 100)]
1394 async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1395 // todo this test is flaky
1396 init_test(cx);
1397
1398 cx.background_executor.set_block_on_ticks(0..=50);
1399 let operations = env::var("OPERATIONS")
1400 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1401 .unwrap_or(10);
1402
1403 let text_system = cx.read(|cx| cx.text_system().clone());
1404 let mut wrap_width = if rng.random_bool(0.1) {
1405 None
1406 } else {
1407 Some(px(rng.random_range(0.0..=1000.0)))
1408 };
1409 let tab_size = NonZeroU32::new(rng.random_range(1..=4)).unwrap();
1410
1411 let font = test_font();
1412 let _font_id = text_system.resolve_font(&font);
1413 let font_size = px(14.0);
1414
1415 log::info!("Tab size: {}", tab_size);
1416 log::info!("Wrap width: {:?}", wrap_width);
1417
1418 let buffer = cx.update(|cx| {
1419 if rng.random() {
1420 MultiBuffer::build_random(&mut rng, cx)
1421 } else {
1422 let len = rng.random_range(0..10);
1423 let text = util::RandomCharIter::new(&mut rng)
1424 .take(len)
1425 .collect::<String>();
1426 MultiBuffer::build_simple(&text, cx)
1427 }
1428 });
1429 let mut buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1430 log::info!("Buffer text: {:?}", buffer_snapshot.text());
1431 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1432 log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1433 let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot.clone());
1434 log::info!("FoldMap text: {:?}", fold_snapshot.text());
1435 let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
1436 let tabs_snapshot = tab_map.set_max_expansion_column(32);
1437 log::info!("TabMap text: {:?}", tabs_snapshot.text());
1438
1439 let mut line_wrapper = text_system.line_wrapper(font.clone(), font_size);
1440 let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1441
1442 let (wrap_map, _) =
1443 cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font, font_size, wrap_width, cx));
1444 let mut notifications = observe(&wrap_map, cx);
1445
1446 if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1447 notifications.next().await.unwrap();
1448 }
1449
1450 let (initial_snapshot, _) = wrap_map.update(cx, |map, cx| {
1451 assert!(!map.is_rewrapping());
1452 map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1453 });
1454
1455 let actual_text = initial_snapshot.text();
1456 assert_eq!(
1457 actual_text,
1458 expected_text,
1459 "unwrapped text is: {:?}",
1460 tabs_snapshot.text()
1461 );
1462 log::info!("Wrapped text: {:?}", actual_text);
1463
1464 let mut next_inlay_id = 0;
1465 let mut edits = Vec::new();
1466 for _i in 0..operations {
1467 log::info!("{} ==============================================", _i);
1468
1469 let mut buffer_edits = Vec::new();
1470 match rng.random_range(0..=100) {
1471 0..=19 => {
1472 wrap_width = if rng.random_bool(0.2) {
1473 None
1474 } else {
1475 Some(px(rng.random_range(0.0..=1000.0)))
1476 };
1477 log::info!("Setting wrap width to {:?}", wrap_width);
1478 wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1479 }
1480 20..=39 => {
1481 for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1482 let (tabs_snapshot, tab_edits) =
1483 tab_map.sync(fold_snapshot, fold_edits, tab_size);
1484 let (mut snapshot, wrap_edits) =
1485 wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1486 snapshot.check_invariants();
1487 snapshot.verify_chunks(&mut rng);
1488 edits.push((snapshot, wrap_edits));
1489 }
1490 }
1491 40..=59 => {
1492 let (inlay_snapshot, inlay_edits) =
1493 inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1494 let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1495 let (tabs_snapshot, tab_edits) =
1496 tab_map.sync(fold_snapshot, fold_edits, tab_size);
1497 let (mut snapshot, wrap_edits) =
1498 wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1499 snapshot.check_invariants();
1500 snapshot.verify_chunks(&mut rng);
1501 edits.push((snapshot, wrap_edits));
1502 }
1503 _ => {
1504 buffer.update(cx, |buffer, cx| {
1505 let subscription = buffer.subscribe();
1506 let edit_count = rng.random_range(1..=5);
1507 buffer.randomly_mutate(&mut rng, edit_count, cx);
1508 buffer_snapshot = buffer.snapshot(cx);
1509 buffer_edits.extend(subscription.consume());
1510 });
1511 }
1512 }
1513
1514 log::info!("Buffer text: {:?}", buffer_snapshot.text());
1515 let (inlay_snapshot, inlay_edits) =
1516 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1517 log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1518 let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1519 log::info!("FoldMap text: {:?}", fold_snapshot.text());
1520 let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
1521 log::info!("TabMap text: {:?}", tabs_snapshot.text());
1522
1523 let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1524 let (mut snapshot, wrap_edits) =
1525 wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot.clone(), tab_edits, cx));
1526 snapshot.check_invariants();
1527 snapshot.verify_chunks(&mut rng);
1528 edits.push((snapshot, wrap_edits));
1529
1530 if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) && rng.random_bool(0.4) {
1531 log::info!("Waiting for wrapping to finish");
1532 while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1533 notifications.next().await.unwrap();
1534 }
1535 wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1536 }
1537
1538 if !wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1539 let (mut wrapped_snapshot, wrap_edits) = wrap_map.update(cx, |map, cx| {
1540 map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1541 });
1542 let actual_text = wrapped_snapshot.text();
1543 let actual_longest_row = wrapped_snapshot.longest_row();
1544 log::info!("Wrapping finished: {:?}", actual_text);
1545 wrapped_snapshot.check_invariants();
1546 wrapped_snapshot.verify_chunks(&mut rng);
1547 edits.push((wrapped_snapshot.clone(), wrap_edits));
1548 assert_eq!(
1549 actual_text,
1550 expected_text,
1551 "unwrapped text is: {:?}",
1552 tabs_snapshot.text()
1553 );
1554
1555 let mut summary = TextSummary::default();
1556 for (ix, item) in wrapped_snapshot
1557 .transforms
1558 .items(())
1559 .into_iter()
1560 .enumerate()
1561 {
1562 summary += &item.summary.output;
1563 log::info!("{} summary: {:?}", ix, item.summary.output,);
1564 }
1565
1566 if tab_size.get() == 1
1567 || !wrapped_snapshot
1568 .tab_snapshot
1569 .fold_snapshot
1570 .text()
1571 .contains('\t')
1572 {
1573 let mut expected_longest_rows = Vec::new();
1574 let mut longest_line_len = -1;
1575 for (row, line) in expected_text.split('\n').enumerate() {
1576 let line_char_count = line.chars().count() as isize;
1577 if line_char_count > longest_line_len {
1578 expected_longest_rows.clear();
1579 longest_line_len = line_char_count;
1580 }
1581 if line_char_count >= longest_line_len {
1582 expected_longest_rows.push(row as u32);
1583 }
1584 }
1585
1586 assert!(
1587 expected_longest_rows.contains(&actual_longest_row),
1588 "incorrect longest row {}. expected {:?} with length {}",
1589 actual_longest_row,
1590 expected_longest_rows,
1591 longest_line_len,
1592 )
1593 }
1594 }
1595 }
1596
1597 let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1598 for (snapshot, patch) in edits {
1599 let snapshot_text = Rope::from(snapshot.text().as_str());
1600 for edit in &patch {
1601 let old_start = initial_text.point_to_offset(Point::new(edit.new.start.0, 0));
1602 let old_end = initial_text.point_to_offset(cmp::min(
1603 Point::new(edit.new.start.0 + (edit.old.end - edit.old.start).0, 0),
1604 initial_text.max_point(),
1605 ));
1606 let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start.0, 0));
1607 let new_end = snapshot_text.point_to_offset(cmp::min(
1608 Point::new(edit.new.end.0, 0),
1609 snapshot_text.max_point(),
1610 ));
1611 let new_text = snapshot_text
1612 .chunks_in_range(new_start..new_end)
1613 .collect::<String>();
1614
1615 initial_text.replace(old_start..old_end, &new_text);
1616 }
1617 assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1618 }
1619
1620 if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1621 log::info!("Waiting for wrapping to finish");
1622 while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1623 notifications.next().await.unwrap();
1624 }
1625 }
1626 wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1627 }
1628
1629 fn init_test(cx: &mut gpui::TestAppContext) {
1630 cx.update(|cx| {
1631 let settings = SettingsStore::test(cx);
1632 cx.set_global(settings);
1633 theme::init(LoadThemes::JustBase, cx);
1634 });
1635 }
1636
1637 fn wrap_text(
1638 tab_snapshot: &TabSnapshot,
1639 wrap_width: Option<Pixels>,
1640 line_wrapper: &mut LineWrapper,
1641 ) -> String {
1642 if let Some(wrap_width) = wrap_width {
1643 let mut wrapped_text = String::new();
1644 for (row, line) in tab_snapshot.text().split('\n').enumerate() {
1645 if row > 0 {
1646 wrapped_text.push('\n');
1647 }
1648
1649 let mut prev_ix = 0;
1650 for boundary in line_wrapper.wrap_line(&[LineFragment::text(line)], wrap_width) {
1651 wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1652 wrapped_text.push('\n');
1653 wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1654 prev_ix = boundary.ix;
1655 }
1656 wrapped_text.push_str(&line[prev_ix..]);
1657 }
1658
1659 wrapped_text
1660 } else {
1661 tab_snapshot.text()
1662 }
1663 }
1664
1665 impl WrapSnapshot {
1666 fn verify_chunks(&mut self, rng: &mut impl Rng) {
1667 for _ in 0..5 {
1668 let mut end_row = rng.random_range(0..=self.max_point().row().0);
1669 let start_row = rng.random_range(0..=end_row);
1670 end_row += 1;
1671
1672 let mut expected_text = self.text_chunks(WrapRow(start_row)).collect::<String>();
1673 if expected_text.ends_with('\n') {
1674 expected_text.push('\n');
1675 }
1676 let mut expected_text = expected_text
1677 .lines()
1678 .take((end_row - start_row) as usize)
1679 .collect::<Vec<_>>()
1680 .join("\n");
1681 if end_row <= self.max_point().row().0 {
1682 expected_text.push('\n');
1683 }
1684
1685 let actual_text = self
1686 .chunks(
1687 WrapRow(start_row)..WrapRow(end_row),
1688 true,
1689 Highlights::default(),
1690 )
1691 .map(|c| c.text)
1692 .collect::<String>();
1693 assert_eq!(
1694 expected_text,
1695 actual_text,
1696 "chunks != highlighted_chunks for rows {:?}",
1697 start_row..end_row
1698 );
1699 }
1700 }
1701 }
1702}