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