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 .background_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 .background_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 self.input_chunk.tabs = self.input_chunk.tabs.unbounded_shr(input_len as u32);
1083 self.input_chunk.chars = self.input_chunk.chars.unbounded_shr(input_len as u32);
1084
1085 self.input_chunk.text = suffix;
1086 Some(Chunk {
1087 text: prefix,
1088 chars,
1089 tabs,
1090 ..self.input_chunk.clone()
1091 })
1092 }
1093}
1094
1095impl Iterator for WrapRows<'_> {
1096 type Item = RowInfo;
1097
1098 #[ztracing::instrument(skip_all)]
1099 fn next(&mut self) -> Option<Self::Item> {
1100 if self.output_row > self.max_output_row {
1101 return None;
1102 }
1103
1104 let buffer_row = self.input_buffer_row;
1105 let soft_wrapped = self.soft_wrapped;
1106 let diff_status = self.input_buffer_row.diff_status;
1107
1108 self.output_row += WrapRow(1);
1109 self.transforms
1110 .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left);
1111 if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
1112 self.input_buffer_row = self.input_buffer_rows.next().unwrap();
1113 self.soft_wrapped = false;
1114 } else {
1115 self.soft_wrapped = true;
1116 }
1117
1118 Some(if soft_wrapped {
1119 RowInfo {
1120 buffer_id: None,
1121 buffer_row: None,
1122 multibuffer_row: None,
1123 diff_status,
1124 expand_info: None,
1125 wrapped_buffer_row: buffer_row.buffer_row,
1126 }
1127 } else {
1128 buffer_row
1129 })
1130 }
1131}
1132
1133impl Transform {
1134 #[ztracing::instrument(skip_all)]
1135 fn isomorphic(summary: TextSummary) -> Self {
1136 #[cfg(test)]
1137 assert!(!summary.lines.is_zero());
1138
1139 Self {
1140 summary: TransformSummary {
1141 input: summary.clone(),
1142 output: summary,
1143 },
1144 display_text: None,
1145 }
1146 }
1147
1148 #[ztracing::instrument(skip_all)]
1149 fn wrap(indent: u32) -> Self {
1150 static WRAP_TEXT: LazyLock<String> = LazyLock::new(|| {
1151 let mut wrap_text = String::new();
1152 wrap_text.push('\n');
1153 wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
1154 wrap_text
1155 });
1156
1157 Self {
1158 summary: TransformSummary {
1159 input: TextSummary::default(),
1160 output: TextSummary {
1161 lines: Point::new(1, indent),
1162 first_line_chars: 0,
1163 last_line_chars: indent,
1164 longest_row: 1,
1165 longest_row_chars: indent,
1166 },
1167 },
1168 display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
1169 }
1170 }
1171
1172 fn is_isomorphic(&self) -> bool {
1173 self.display_text.is_none()
1174 }
1175}
1176
1177impl sum_tree::Item for Transform {
1178 type Summary = TransformSummary;
1179
1180 fn summary(&self, _cx: ()) -> Self::Summary {
1181 self.summary.clone()
1182 }
1183}
1184
1185fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
1186 if let Some(last_transform) = transforms.last_mut()
1187 && last_transform.is_isomorphic()
1188 {
1189 last_transform.summary.input += &summary;
1190 last_transform.summary.output += &summary;
1191 return;
1192 }
1193 transforms.push(Transform::isomorphic(summary));
1194}
1195
1196trait SumTreeExt {
1197 fn push_or_extend(&mut self, transform: Transform);
1198}
1199
1200impl SumTreeExt for SumTree<Transform> {
1201 #[ztracing::instrument(skip_all)]
1202 fn push_or_extend(&mut self, transform: Transform) {
1203 let mut transform = Some(transform);
1204 self.update_last(
1205 |last_transform| {
1206 if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
1207 let transform = transform.take().unwrap();
1208 last_transform.summary.input += &transform.summary.input;
1209 last_transform.summary.output += &transform.summary.output;
1210 }
1211 },
1212 (),
1213 );
1214
1215 if let Some(transform) = transform {
1216 self.push(transform, ());
1217 }
1218 }
1219}
1220
1221impl WrapPoint {
1222 pub fn new(row: WrapRow, column: u32) -> Self {
1223 Self(Point::new(row.0, column))
1224 }
1225
1226 pub fn row(self) -> WrapRow {
1227 WrapRow(self.0.row)
1228 }
1229
1230 pub fn row_mut(&mut self) -> &mut u32 {
1231 &mut self.0.row
1232 }
1233
1234 pub fn column(self) -> u32 {
1235 self.0.column
1236 }
1237
1238 pub fn column_mut(&mut self) -> &mut u32 {
1239 &mut self.0.column
1240 }
1241}
1242
1243impl sum_tree::ContextLessSummary for TransformSummary {
1244 fn zero() -> Self {
1245 Default::default()
1246 }
1247
1248 fn add_summary(&mut self, other: &Self) {
1249 self.input += &other.input;
1250 self.output += &other.output;
1251 }
1252}
1253
1254impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
1255 fn zero(_cx: ()) -> Self {
1256 Default::default()
1257 }
1258
1259 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1260 self.0 += summary.input.lines;
1261 }
1262}
1263
1264impl sum_tree::SeekTarget<'_, TransformSummary, TransformSummary> for TabPoint {
1265 #[ztracing::instrument(skip_all)]
1266 fn cmp(&self, cursor_location: &TransformSummary, _: ()) -> std::cmp::Ordering {
1267 Ord::cmp(&self.0, &cursor_location.input.lines)
1268 }
1269}
1270
1271impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
1272 fn zero(_cx: ()) -> Self {
1273 Default::default()
1274 }
1275
1276 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1277 self.0 += summary.output.lines;
1278 }
1279}
1280
1281fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
1282 let _old_alloc_ptr = edits.as_ptr();
1283 let mut wrap_edits = edits.into_iter();
1284
1285 if let Some(mut first_edit) = wrap_edits.next() {
1286 // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1287 #[allow(clippy::filter_map_identity)]
1288 let mut v: Vec<_> = wrap_edits
1289 .scan(&mut first_edit, |prev_edit, edit| {
1290 if prev_edit.old.end >= edit.old.start {
1291 prev_edit.old.end = edit.old.end;
1292 prev_edit.new.end = edit.new.end;
1293 Some(None) // Skip this edit, it's merged
1294 } else {
1295 let prev = std::mem::replace(*prev_edit, edit);
1296 Some(Some(prev)) // Yield the previous edit
1297 }
1298 })
1299 .filter_map(|x| x)
1300 .collect();
1301 v.push(first_edit.clone());
1302 debug_assert_eq!(v.as_ptr(), _old_alloc_ptr, "Wrap edits were reallocated");
1303 v
1304 } else {
1305 vec![]
1306 }
1307}
1308
1309#[cfg(test)]
1310mod tests {
1311 use super::*;
1312 use crate::{
1313 MultiBuffer,
1314 display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
1315 test::test_font,
1316 };
1317 use gpui::{LineFragment, px, test::observe};
1318 use rand::prelude::*;
1319 use settings::SettingsStore;
1320 use smol::stream::StreamExt;
1321 use std::{cmp, env, num::NonZeroU32};
1322 use text::Rope;
1323 use theme::LoadThemes;
1324
1325 #[gpui::test]
1326 async fn test_prev_row_boundary(cx: &mut gpui::TestAppContext) {
1327 init_test(cx);
1328
1329 fn test_wrap_snapshot(
1330 text: &str,
1331 soft_wrap_every: usize, // font size multiple
1332 cx: &mut gpui::TestAppContext,
1333 ) -> WrapSnapshot {
1334 let text_system = cx.read(|cx| cx.text_system().clone());
1335 let tab_size = 4.try_into().unwrap();
1336 let font = test_font();
1337 let _font_id = text_system.resolve_font(&font);
1338 let font_size = px(14.0);
1339 // this is very much an estimate to try and get the wrapping to
1340 // occur at `soft_wrap_every` we check that it pans out for every test case
1341 let soft_wrapping = Some(font_size * soft_wrap_every * 0.6);
1342
1343 let buffer = cx.new(|cx| language::Buffer::local(text, cx));
1344 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1345 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1346 let (_inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1347 let (_fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
1348 let (mut tab_map, _) = TabMap::new(fold_snapshot, tab_size);
1349 let tabs_snapshot = tab_map.set_max_expansion_column(32);
1350 let (_wrap_map, wrap_snapshot) =
1351 cx.update(|cx| WrapMap::new(tabs_snapshot, font, font_size, soft_wrapping, cx));
1352
1353 wrap_snapshot
1354 }
1355
1356 // These two should pass but dont, see the comparison note in
1357 // prev_row_boundary about why.
1358 //
1359 // // 0123 4567 wrap_rows
1360 // let wrap_snapshot = test_wrap_snapshot("1234\n5678", 1, cx);
1361 // assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8");
1362 // let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1363 // assert_eq!(row.0, 3);
1364
1365 // // 012 345 678 wrap_rows
1366 // let wrap_snapshot = test_wrap_snapshot("123\n456\n789", 1, cx);
1367 // assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8\n9");
1368 // let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1369 // assert_eq!(row.0, 5);
1370
1371 // 012345678 wrap_rows
1372 let wrap_snapshot = test_wrap_snapshot("123456789", 1, cx);
1373 assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8\n9");
1374 let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1375 assert_eq!(row.0, 0);
1376
1377 // 111 2222 44 wrap_rows
1378 let wrap_snapshot = test_wrap_snapshot("123\n4567\n\n89", 4, cx);
1379 assert_eq!(wrap_snapshot.text(), "123\n4567\n\n89");
1380 let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1381 assert_eq!(row.0, 2);
1382
1383 // 11 2223 wrap_rows
1384 let wrap_snapshot = test_wrap_snapshot("12\n3456\n\n", 3, cx);
1385 assert_eq!(wrap_snapshot.text(), "12\n345\n6\n\n");
1386 let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1387 assert_eq!(row.0, 3);
1388 }
1389
1390 #[gpui::test(iterations = 100)]
1391 async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1392 // todo this test is flaky
1393 init_test(cx);
1394
1395 cx.background_executor.set_block_on_ticks(0..=50);
1396 let operations = env::var("OPERATIONS")
1397 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1398 .unwrap_or(10);
1399
1400 let text_system = cx.read(|cx| cx.text_system().clone());
1401 let mut wrap_width = if rng.random_bool(0.1) {
1402 None
1403 } else {
1404 Some(px(rng.random_range(0.0..=1000.0)))
1405 };
1406 let tab_size = NonZeroU32::new(rng.random_range(1..=4)).unwrap();
1407
1408 let font = test_font();
1409 let _font_id = text_system.resolve_font(&font);
1410 let font_size = px(14.0);
1411
1412 log::info!("Tab size: {}", tab_size);
1413 log::info!("Wrap width: {:?}", wrap_width);
1414
1415 let buffer = cx.update(|cx| {
1416 if rng.random() {
1417 MultiBuffer::build_random(&mut rng, cx)
1418 } else {
1419 let len = rng.random_range(0..10);
1420 let text = util::RandomCharIter::new(&mut rng)
1421 .take(len)
1422 .collect::<String>();
1423 MultiBuffer::build_simple(&text, cx)
1424 }
1425 });
1426 let mut buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1427 log::info!("Buffer text: {:?}", buffer_snapshot.text());
1428 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1429 log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1430 let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot.clone());
1431 log::info!("FoldMap text: {:?}", fold_snapshot.text());
1432 let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
1433 let tabs_snapshot = tab_map.set_max_expansion_column(32);
1434 log::info!("TabMap text: {:?}", tabs_snapshot.text());
1435
1436 let mut line_wrapper = text_system.line_wrapper(font.clone(), font_size);
1437 let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1438
1439 let (wrap_map, _) =
1440 cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font, font_size, wrap_width, cx));
1441 let mut notifications = observe(&wrap_map, cx);
1442
1443 if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1444 notifications.next().await.unwrap();
1445 }
1446
1447 let (initial_snapshot, _) = wrap_map.update(cx, |map, cx| {
1448 assert!(!map.is_rewrapping());
1449 map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1450 });
1451
1452 let actual_text = initial_snapshot.text();
1453 assert_eq!(
1454 actual_text,
1455 expected_text,
1456 "unwrapped text is: {:?}",
1457 tabs_snapshot.text()
1458 );
1459 log::info!("Wrapped text: {:?}", actual_text);
1460
1461 let mut next_inlay_id = 0;
1462 let mut edits = Vec::new();
1463 for _i in 0..operations {
1464 log::info!("{} ==============================================", _i);
1465
1466 let mut buffer_edits = Vec::new();
1467 match rng.random_range(0..=100) {
1468 0..=19 => {
1469 wrap_width = if rng.random_bool(0.2) {
1470 None
1471 } else {
1472 Some(px(rng.random_range(0.0..=1000.0)))
1473 };
1474 log::info!("Setting wrap width to {:?}", wrap_width);
1475 wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1476 }
1477 20..=39 => {
1478 for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1479 let (tabs_snapshot, tab_edits) =
1480 tab_map.sync(fold_snapshot, fold_edits, tab_size);
1481 let (mut snapshot, wrap_edits) =
1482 wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1483 snapshot.check_invariants();
1484 snapshot.verify_chunks(&mut rng);
1485 edits.push((snapshot, wrap_edits));
1486 }
1487 }
1488 40..=59 => {
1489 let (inlay_snapshot, inlay_edits) =
1490 inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1491 let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1492 let (tabs_snapshot, tab_edits) =
1493 tab_map.sync(fold_snapshot, fold_edits, tab_size);
1494 let (mut snapshot, wrap_edits) =
1495 wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1496 snapshot.check_invariants();
1497 snapshot.verify_chunks(&mut rng);
1498 edits.push((snapshot, wrap_edits));
1499 }
1500 _ => {
1501 buffer.update(cx, |buffer, cx| {
1502 let subscription = buffer.subscribe();
1503 let edit_count = rng.random_range(1..=5);
1504 buffer.randomly_mutate(&mut rng, edit_count, cx);
1505 buffer_snapshot = buffer.snapshot(cx);
1506 buffer_edits.extend(subscription.consume());
1507 });
1508 }
1509 }
1510
1511 log::info!("Buffer text: {:?}", buffer_snapshot.text());
1512 let (inlay_snapshot, inlay_edits) =
1513 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1514 log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1515 let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1516 log::info!("FoldMap text: {:?}", fold_snapshot.text());
1517 let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
1518 log::info!("TabMap text: {:?}", tabs_snapshot.text());
1519
1520 let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1521 let (mut snapshot, wrap_edits) =
1522 wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot.clone(), tab_edits, cx));
1523 snapshot.check_invariants();
1524 snapshot.verify_chunks(&mut rng);
1525 edits.push((snapshot, wrap_edits));
1526
1527 if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) && rng.random_bool(0.4) {
1528 log::info!("Waiting for wrapping to finish");
1529 while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1530 notifications.next().await.unwrap();
1531 }
1532 wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1533 }
1534
1535 if !wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1536 let (mut wrapped_snapshot, wrap_edits) = wrap_map.update(cx, |map, cx| {
1537 map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1538 });
1539 let actual_text = wrapped_snapshot.text();
1540 let actual_longest_row = wrapped_snapshot.longest_row();
1541 log::info!("Wrapping finished: {:?}", actual_text);
1542 wrapped_snapshot.check_invariants();
1543 wrapped_snapshot.verify_chunks(&mut rng);
1544 edits.push((wrapped_snapshot.clone(), wrap_edits));
1545 assert_eq!(
1546 actual_text,
1547 expected_text,
1548 "unwrapped text is: {:?}",
1549 tabs_snapshot.text()
1550 );
1551
1552 let mut summary = TextSummary::default();
1553 for (ix, item) in wrapped_snapshot
1554 .transforms
1555 .items(())
1556 .into_iter()
1557 .enumerate()
1558 {
1559 summary += &item.summary.output;
1560 log::info!("{} summary: {:?}", ix, item.summary.output,);
1561 }
1562
1563 if tab_size.get() == 1
1564 || !wrapped_snapshot
1565 .tab_snapshot
1566 .fold_snapshot
1567 .text()
1568 .contains('\t')
1569 {
1570 let mut expected_longest_rows = Vec::new();
1571 let mut longest_line_len = -1;
1572 for (row, line) in expected_text.split('\n').enumerate() {
1573 let line_char_count = line.chars().count() as isize;
1574 if line_char_count > longest_line_len {
1575 expected_longest_rows.clear();
1576 longest_line_len = line_char_count;
1577 }
1578 if line_char_count >= longest_line_len {
1579 expected_longest_rows.push(row as u32);
1580 }
1581 }
1582
1583 assert!(
1584 expected_longest_rows.contains(&actual_longest_row),
1585 "incorrect longest row {}. expected {:?} with length {}",
1586 actual_longest_row,
1587 expected_longest_rows,
1588 longest_line_len,
1589 )
1590 }
1591 }
1592 }
1593
1594 let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1595 for (snapshot, patch) in edits {
1596 let snapshot_text = Rope::from(snapshot.text().as_str());
1597 for edit in &patch {
1598 let old_start = initial_text.point_to_offset(Point::new(edit.new.start.0, 0));
1599 let old_end = initial_text.point_to_offset(cmp::min(
1600 Point::new(edit.new.start.0 + (edit.old.end - edit.old.start).0, 0),
1601 initial_text.max_point(),
1602 ));
1603 let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start.0, 0));
1604 let new_end = snapshot_text.point_to_offset(cmp::min(
1605 Point::new(edit.new.end.0, 0),
1606 snapshot_text.max_point(),
1607 ));
1608 let new_text = snapshot_text
1609 .chunks_in_range(new_start..new_end)
1610 .collect::<String>();
1611
1612 initial_text.replace(old_start..old_end, &new_text);
1613 }
1614 assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1615 }
1616
1617 if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1618 log::info!("Waiting for wrapping to finish");
1619 while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1620 notifications.next().await.unwrap();
1621 }
1622 }
1623 wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1624 }
1625
1626 fn init_test(cx: &mut gpui::TestAppContext) {
1627 cx.update(|cx| {
1628 let settings = SettingsStore::test(cx);
1629 cx.set_global(settings);
1630 theme::init(LoadThemes::JustBase, cx);
1631 });
1632 }
1633
1634 fn wrap_text(
1635 tab_snapshot: &TabSnapshot,
1636 wrap_width: Option<Pixels>,
1637 line_wrapper: &mut LineWrapper,
1638 ) -> String {
1639 if let Some(wrap_width) = wrap_width {
1640 let mut wrapped_text = String::new();
1641 for (row, line) in tab_snapshot.text().split('\n').enumerate() {
1642 if row > 0 {
1643 wrapped_text.push('\n');
1644 }
1645
1646 let mut prev_ix = 0;
1647 for boundary in line_wrapper.wrap_line(&[LineFragment::text(line)], wrap_width) {
1648 wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1649 wrapped_text.push('\n');
1650 wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1651 prev_ix = boundary.ix;
1652 }
1653 wrapped_text.push_str(&line[prev_ix..]);
1654 }
1655
1656 wrapped_text
1657 } else {
1658 tab_snapshot.text()
1659 }
1660 }
1661
1662 impl WrapSnapshot {
1663 fn verify_chunks(&mut self, rng: &mut impl Rng) {
1664 for _ in 0..5 {
1665 let mut end_row = rng.random_range(0..=self.max_point().row().0);
1666 let start_row = rng.random_range(0..=end_row);
1667 end_row += 1;
1668
1669 let mut expected_text = self.text_chunks(WrapRow(start_row)).collect::<String>();
1670 if expected_text.ends_with('\n') {
1671 expected_text.push('\n');
1672 }
1673 let mut expected_text = expected_text
1674 .lines()
1675 .take((end_row - start_row) as usize)
1676 .collect::<Vec<_>>()
1677 .join("\n");
1678 if end_row <= self.max_point().row().0 {
1679 expected_text.push('\n');
1680 }
1681
1682 let actual_text = self
1683 .chunks(
1684 WrapRow(start_row)..WrapRow(end_row),
1685 true,
1686 Highlights::default(),
1687 )
1688 .map(|c| c.text)
1689 .collect::<String>();
1690 assert_eq!(
1691 expected_text,
1692 actual_text,
1693 "chunks != highlighted_chunks for rows {:?}",
1694 start_row..end_row
1695 );
1696 }
1697 }
1698 }
1699}