1use super::{
2 Highlights,
3 fold_map::FoldRows,
4 tab_map::{self, TabEdit, TabPoint, TabSnapshot},
5};
6use gpui::{App, AppContext as _, Context, Entity, Font, LineWrapper, 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 WrapRows<'_> {
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 App,
94 ) -> (Entity<Self>, WrapSnapshot) {
95 let handle = cx.new(|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 Context<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 Context<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(&mut self, wrap_width: Option<Pixels>, cx: &mut Context<Self>) -> bool {
155 if wrap_width == self.wrap_width {
156 return false;
157 }
158
159 self.wrap_width = wrap_width;
160 self.rewrap(cx);
161 true
162 }
163
164 fn rewrap(&mut self, cx: &mut Context<Self>) {
165 self.background_task.take();
166 self.interpolated_edits.clear();
167 self.pending_edits.clear();
168
169 if let Some(wrap_width) = self.wrap_width {
170 let mut new_snapshot = self.snapshot.clone();
171
172 let text_system = cx.text_system().clone();
173 let (font, font_size) = self.font_with_size.clone();
174 let task = cx.background_spawn(async move {
175 let mut line_wrapper = text_system.line_wrapper(font, font_size);
176 let tab_snapshot = new_snapshot.tab_snapshot.clone();
177 let range = TabPoint::zero()..tab_snapshot.max_point();
178 let edits = new_snapshot
179 .update(
180 tab_snapshot,
181 &[TabEdit {
182 old: range.clone(),
183 new: range.clone(),
184 }],
185 wrap_width,
186 &mut line_wrapper,
187 )
188 .await;
189 (new_snapshot, edits)
190 });
191
192 match cx
193 .background_executor()
194 .block_with_timeout(Duration::from_millis(5), task)
195 {
196 Ok((snapshot, edits)) => {
197 self.snapshot = snapshot;
198 self.edits_since_sync = self.edits_since_sync.compose(&edits);
199 }
200 Err(wrap_task) => {
201 self.background_task = Some(cx.spawn(async move |this, cx| {
202 let (snapshot, edits) = wrap_task.await;
203 this.update(cx, |this, cx| {
204 this.snapshot = snapshot;
205 this.edits_since_sync = this
206 .edits_since_sync
207 .compose(mem::take(&mut this.interpolated_edits).invert())
208 .compose(&edits);
209 this.background_task = None;
210 this.flush_edits(cx);
211 cx.notify();
212 })
213 .ok();
214 }));
215 }
216 }
217 } else {
218 let old_rows = self.snapshot.transforms.summary().output.lines.row + 1;
219 self.snapshot.transforms = SumTree::default();
220 let summary = self.snapshot.tab_snapshot.text_summary();
221 if !summary.lines.is_zero() {
222 self.snapshot
223 .transforms
224 .push(Transform::isomorphic(summary), &());
225 }
226 let new_rows = self.snapshot.transforms.summary().output.lines.row + 1;
227 self.snapshot.interpolated = false;
228 self.edits_since_sync = self.edits_since_sync.compose(Patch::new(vec![WrapEdit {
229 old: 0..old_rows,
230 new: 0..new_rows,
231 }]));
232 }
233 }
234
235 fn flush_edits(&mut self, cx: &mut Context<Self>) {
236 if !self.snapshot.interpolated {
237 let mut to_remove_len = 0;
238 for (tab_snapshot, _) in &self.pending_edits {
239 if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
240 to_remove_len += 1;
241 } else {
242 break;
243 }
244 }
245 self.pending_edits.drain(..to_remove_len);
246 }
247
248 if self.pending_edits.is_empty() {
249 return;
250 }
251
252 if let Some(wrap_width) = self.wrap_width {
253 if self.background_task.is_none() {
254 let pending_edits = self.pending_edits.clone();
255 let mut snapshot = self.snapshot.clone();
256 let text_system = cx.text_system().clone();
257 let (font, font_size) = self.font_with_size.clone();
258 let update_task = cx.background_spawn(async move {
259 let mut edits = Patch::default();
260 let mut line_wrapper = text_system.line_wrapper(font, font_size);
261 for (tab_snapshot, tab_edits) in pending_edits {
262 let wrap_edits = snapshot
263 .update(tab_snapshot, &tab_edits, wrap_width, &mut line_wrapper)
264 .await;
265 edits = edits.compose(&wrap_edits);
266 }
267 (snapshot, edits)
268 });
269
270 match cx
271 .background_executor()
272 .block_with_timeout(Duration::from_millis(1), update_task)
273 {
274 Ok((snapshot, output_edits)) => {
275 self.snapshot = snapshot;
276 self.edits_since_sync = self.edits_since_sync.compose(&output_edits);
277 }
278 Err(update_task) => {
279 self.background_task = Some(cx.spawn(async move |this, cx| {
280 let (snapshot, edits) = update_task.await;
281 this.update(cx, |this, cx| {
282 this.snapshot = snapshot;
283 this.edits_since_sync = this
284 .edits_since_sync
285 .compose(mem::take(&mut this.interpolated_edits).invert())
286 .compose(&edits);
287 this.background_task = None;
288 this.flush_edits(cx);
289 cx.notify();
290 })
291 .ok();
292 }));
293 }
294 }
295 }
296 }
297
298 let was_interpolated = self.snapshot.interpolated;
299 let mut to_remove_len = 0;
300 for (tab_snapshot, edits) in &self.pending_edits {
301 if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
302 to_remove_len += 1;
303 } else {
304 let interpolated_edits = self.snapshot.interpolate(tab_snapshot.clone(), edits);
305 self.edits_since_sync = self.edits_since_sync.compose(&interpolated_edits);
306 self.interpolated_edits = self.interpolated_edits.compose(&interpolated_edits);
307 }
308 }
309
310 if !was_interpolated {
311 self.pending_edits.drain(..to_remove_len);
312 }
313 }
314}
315
316impl WrapSnapshot {
317 fn new(tab_snapshot: TabSnapshot) -> Self {
318 let mut transforms = SumTree::default();
319 let extent = tab_snapshot.text_summary();
320 if !extent.lines.is_zero() {
321 transforms.push(Transform::isomorphic(extent), &());
322 }
323 Self {
324 transforms,
325 tab_snapshot,
326 interpolated: true,
327 }
328 }
329
330 pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
331 self.tab_snapshot.buffer_snapshot()
332 }
333
334 fn interpolate(&mut self, new_tab_snapshot: TabSnapshot, tab_edits: &[TabEdit]) -> Patch<u32> {
335 let mut new_transforms;
336 if tab_edits.is_empty() {
337 new_transforms = self.transforms.clone();
338 } else {
339 let mut old_cursor = self.transforms.cursor::<TabPoint>(&());
340
341 let mut tab_edits_iter = tab_edits.iter().peekable();
342 new_transforms =
343 old_cursor.slice(&tab_edits_iter.peek().unwrap().old.start, Bias::Right, &());
344
345 while let Some(edit) = tab_edits_iter.next() {
346 if edit.new.start > TabPoint::from(new_transforms.summary().input.lines) {
347 let summary = new_tab_snapshot.text_summary_for_range(
348 TabPoint::from(new_transforms.summary().input.lines)..edit.new.start,
349 );
350 new_transforms.push_or_extend(Transform::isomorphic(summary));
351 }
352
353 if !edit.new.is_empty() {
354 new_transforms.push_or_extend(Transform::isomorphic(
355 new_tab_snapshot.text_summary_for_range(edit.new.clone()),
356 ));
357 }
358
359 old_cursor.seek_forward(&edit.old.end, Bias::Right, &());
360 if let Some(next_edit) = tab_edits_iter.peek() {
361 if next_edit.old.start > old_cursor.end(&()) {
362 if old_cursor.end(&()) > edit.old.end {
363 let summary = self
364 .tab_snapshot
365 .text_summary_for_range(edit.old.end..old_cursor.end(&()));
366 new_transforms.push_or_extend(Transform::isomorphic(summary));
367 }
368
369 old_cursor.next(&());
370 new_transforms.append(
371 old_cursor.slice(&next_edit.old.start, Bias::Right, &()),
372 &(),
373 );
374 }
375 } else {
376 if old_cursor.end(&()) > edit.old.end {
377 let summary = self
378 .tab_snapshot
379 .text_summary_for_range(edit.old.end..old_cursor.end(&()));
380 new_transforms.push_or_extend(Transform::isomorphic(summary));
381 }
382 old_cursor.next(&());
383 new_transforms.append(old_cursor.suffix(&()), &());
384 }
385 }
386 }
387
388 let old_snapshot = mem::replace(
389 self,
390 WrapSnapshot {
391 tab_snapshot: new_tab_snapshot,
392 transforms: new_transforms,
393 interpolated: true,
394 },
395 );
396 self.check_invariants();
397 old_snapshot.compute_edits(tab_edits, self)
398 }
399
400 async fn update(
401 &mut self,
402 new_tab_snapshot: TabSnapshot,
403 tab_edits: &[TabEdit],
404 wrap_width: Pixels,
405 line_wrapper: &mut LineWrapper,
406 ) -> Patch<u32> {
407 #[derive(Debug)]
408 struct RowEdit {
409 old_rows: Range<u32>,
410 new_rows: Range<u32>,
411 }
412
413 let mut tab_edits_iter = tab_edits.iter().peekable();
414 let mut row_edits = Vec::new();
415 while let Some(edit) = tab_edits_iter.next() {
416 let mut row_edit = RowEdit {
417 old_rows: edit.old.start.row()..edit.old.end.row() + 1,
418 new_rows: edit.new.start.row()..edit.new.end.row() + 1,
419 };
420
421 while let Some(next_edit) = tab_edits_iter.peek() {
422 if next_edit.old.start.row() <= row_edit.old_rows.end {
423 row_edit.old_rows.end = next_edit.old.end.row() + 1;
424 row_edit.new_rows.end = next_edit.new.end.row() + 1;
425 tab_edits_iter.next();
426 } else {
427 break;
428 }
429 }
430
431 row_edits.push(row_edit);
432 }
433
434 let mut new_transforms;
435 if row_edits.is_empty() {
436 new_transforms = self.transforms.clone();
437 } else {
438 let mut row_edits = row_edits.into_iter().peekable();
439 let mut old_cursor = self.transforms.cursor::<TabPoint>(&());
440
441 new_transforms = old_cursor.slice(
442 &TabPoint::new(row_edits.peek().unwrap().old_rows.start, 0),
443 Bias::Right,
444 &(),
445 );
446
447 while let Some(edit) = row_edits.next() {
448 if edit.new_rows.start > new_transforms.summary().input.lines.row {
449 let summary = new_tab_snapshot.text_summary_for_range(
450 TabPoint(new_transforms.summary().input.lines)
451 ..TabPoint::new(edit.new_rows.start, 0),
452 );
453 new_transforms.push_or_extend(Transform::isomorphic(summary));
454 }
455
456 let mut line = String::new();
457 let mut remaining = None;
458 let mut chunks = new_tab_snapshot.chunks(
459 TabPoint::new(edit.new_rows.start, 0)..new_tab_snapshot.max_point(),
460 false,
461 Highlights::default(),
462 );
463 let mut edit_transforms = Vec::<Transform>::new();
464 for _ in edit.new_rows.start..edit.new_rows.end {
465 while let Some(chunk) =
466 remaining.take().or_else(|| chunks.next().map(|c| c.text))
467 {
468 if let Some(ix) = chunk.find('\n') {
469 line.push_str(&chunk[..ix + 1]);
470 remaining = Some(&chunk[ix + 1..]);
471 break;
472 } else {
473 line.push_str(chunk)
474 }
475 }
476
477 if line.is_empty() {
478 break;
479 }
480
481 let mut prev_boundary_ix = 0;
482 for boundary in line_wrapper.wrap_line(&line, wrap_width) {
483 let wrapped = &line[prev_boundary_ix..boundary.ix];
484 push_isomorphic(&mut edit_transforms, TextSummary::from(wrapped));
485 edit_transforms.push(Transform::wrap(boundary.next_indent));
486 prev_boundary_ix = boundary.ix;
487 }
488
489 if prev_boundary_ix < line.len() {
490 push_isomorphic(
491 &mut edit_transforms,
492 TextSummary::from(&line[prev_boundary_ix..]),
493 );
494 }
495
496 line.clear();
497 yield_now().await;
498 }
499
500 let mut edit_transforms = edit_transforms.into_iter();
501 if let Some(transform) = edit_transforms.next() {
502 new_transforms.push_or_extend(transform);
503 }
504 new_transforms.extend(edit_transforms, &());
505
506 old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right, &());
507 if let Some(next_edit) = row_edits.peek() {
508 if next_edit.old_rows.start > old_cursor.end(&()).row() {
509 if old_cursor.end(&()) > TabPoint::new(edit.old_rows.end, 0) {
510 let summary = self.tab_snapshot.text_summary_for_range(
511 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(&()),
512 );
513 new_transforms.push_or_extend(Transform::isomorphic(summary));
514 }
515 old_cursor.next(&());
516 new_transforms.append(
517 old_cursor.slice(
518 &TabPoint::new(next_edit.old_rows.start, 0),
519 Bias::Right,
520 &(),
521 ),
522 &(),
523 );
524 }
525 } else {
526 if old_cursor.end(&()) > TabPoint::new(edit.old_rows.end, 0) {
527 let summary = self.tab_snapshot.text_summary_for_range(
528 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(&()),
529 );
530 new_transforms.push_or_extend(Transform::isomorphic(summary));
531 }
532 old_cursor.next(&());
533 new_transforms.append(old_cursor.suffix(&()), &());
534 }
535 }
536 }
537
538 let old_snapshot = mem::replace(
539 self,
540 WrapSnapshot {
541 tab_snapshot: new_tab_snapshot,
542 transforms: new_transforms,
543 interpolated: false,
544 },
545 );
546 self.check_invariants();
547 old_snapshot.compute_edits(tab_edits, self)
548 }
549
550 fn compute_edits(&self, tab_edits: &[TabEdit], new_snapshot: &WrapSnapshot) -> Patch<u32> {
551 let mut wrap_edits = Vec::new();
552 let mut old_cursor = self.transforms.cursor::<TransformSummary>(&());
553 let mut new_cursor = new_snapshot.transforms.cursor::<TransformSummary>(&());
554 for mut tab_edit in tab_edits.iter().cloned() {
555 tab_edit.old.start.0.column = 0;
556 tab_edit.old.end.0 += Point::new(1, 0);
557 tab_edit.new.start.0.column = 0;
558 tab_edit.new.end.0 += Point::new(1, 0);
559
560 old_cursor.seek(&tab_edit.old.start, Bias::Right, &());
561 let mut old_start = old_cursor.start().output.lines;
562 old_start += tab_edit.old.start.0 - old_cursor.start().input.lines;
563
564 old_cursor.seek(&tab_edit.old.end, Bias::Right, &());
565 let mut old_end = old_cursor.start().output.lines;
566 old_end += tab_edit.old.end.0 - old_cursor.start().input.lines;
567
568 new_cursor.seek(&tab_edit.new.start, Bias::Right, &());
569 let mut new_start = new_cursor.start().output.lines;
570 new_start += tab_edit.new.start.0 - new_cursor.start().input.lines;
571
572 new_cursor.seek(&tab_edit.new.end, Bias::Right, &());
573 let mut new_end = new_cursor.start().output.lines;
574 new_end += tab_edit.new.end.0 - new_cursor.start().input.lines;
575
576 wrap_edits.push(WrapEdit {
577 old: old_start.row..old_end.row,
578 new: new_start.row..new_end.row,
579 });
580 }
581
582 wrap_edits = consolidate_wrap_edits(wrap_edits);
583 Patch::new(wrap_edits)
584 }
585
586 pub(crate) fn chunks<'a>(
587 &'a self,
588 rows: Range<u32>,
589 language_aware: bool,
590 highlights: Highlights<'a>,
591 ) -> WrapChunks<'a> {
592 let output_start = WrapPoint::new(rows.start, 0);
593 let output_end = WrapPoint::new(rows.end, 0);
594 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>(&());
595 transforms.seek(&output_start, Bias::Right, &());
596 let mut input_start = TabPoint(transforms.start().1.0);
597 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
598 input_start.0 += output_start.0 - transforms.start().0.0;
599 }
600 let input_end = self
601 .to_tab_point(output_end)
602 .min(self.tab_snapshot.max_point());
603 WrapChunks {
604 input_chunks: self.tab_snapshot.chunks(
605 input_start..input_end,
606 language_aware,
607 highlights,
608 ),
609 input_chunk: Default::default(),
610 output_position: output_start,
611 max_output_row: rows.end,
612 transforms,
613 snapshot: self,
614 }
615 }
616
617 pub fn max_point(&self) -> WrapPoint {
618 WrapPoint(self.transforms.summary().output.lines)
619 }
620
621 pub fn line_len(&self, row: u32) -> u32 {
622 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>(&());
623 cursor.seek(&WrapPoint::new(row + 1, 0), Bias::Left, &());
624 if cursor
625 .item()
626 .map_or(false, |transform| transform.is_isomorphic())
627 {
628 let overshoot = row - cursor.start().0.row();
629 let tab_row = cursor.start().1.row() + overshoot;
630 let tab_line_len = self.tab_snapshot.line_len(tab_row);
631 if overshoot == 0 {
632 cursor.start().0.column() + (tab_line_len - cursor.start().1.column())
633 } else {
634 tab_line_len
635 }
636 } else {
637 cursor.start().0.column()
638 }
639 }
640
641 pub fn text_summary_for_range(&self, rows: Range<u32>) -> TextSummary {
642 let mut summary = TextSummary::default();
643
644 let start = WrapPoint::new(rows.start, 0);
645 let end = WrapPoint::new(rows.end, 0);
646
647 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>(&());
648 cursor.seek(&start, Bias::Right, &());
649 if let Some(transform) = cursor.item() {
650 let start_in_transform = start.0 - cursor.start().0.0;
651 let end_in_transform = cmp::min(end, cursor.end(&()).0).0 - cursor.start().0.0;
652 if transform.is_isomorphic() {
653 let tab_start = TabPoint(cursor.start().1.0 + start_in_transform);
654 let tab_end = TabPoint(cursor.start().1.0 + end_in_transform);
655 summary += &self.tab_snapshot.text_summary_for_range(tab_start..tab_end);
656 } else {
657 debug_assert_eq!(start_in_transform.row, end_in_transform.row);
658 let indent_len = end_in_transform.column - start_in_transform.column;
659 summary += &TextSummary {
660 lines: Point::new(0, indent_len),
661 first_line_chars: indent_len,
662 last_line_chars: indent_len,
663 longest_row: 0,
664 longest_row_chars: indent_len,
665 };
666 }
667
668 cursor.next(&());
669 }
670
671 if rows.end > cursor.start().0.row() {
672 summary += &cursor
673 .summary::<_, TransformSummary>(&WrapPoint::new(rows.end, 0), Bias::Right, &())
674 .output;
675
676 if let Some(transform) = cursor.item() {
677 let end_in_transform = end.0 - cursor.start().0.0;
678 if transform.is_isomorphic() {
679 let char_start = cursor.start().1;
680 let char_end = TabPoint(char_start.0 + end_in_transform);
681 summary += &self
682 .tab_snapshot
683 .text_summary_for_range(char_start..char_end);
684 } else {
685 debug_assert_eq!(end_in_transform, Point::new(1, 0));
686 summary += &TextSummary {
687 lines: Point::new(1, 0),
688 first_line_chars: 0,
689 last_line_chars: 0,
690 longest_row: 0,
691 longest_row_chars: 0,
692 };
693 }
694 }
695 }
696
697 summary
698 }
699
700 pub fn soft_wrap_indent(&self, row: u32) -> Option<u32> {
701 let mut cursor = self.transforms.cursor::<WrapPoint>(&());
702 cursor.seek(&WrapPoint::new(row + 1, 0), Bias::Right, &());
703 cursor.item().and_then(|transform| {
704 if transform.is_isomorphic() {
705 None
706 } else {
707 Some(transform.summary.output.lines.column)
708 }
709 })
710 }
711
712 pub fn longest_row(&self) -> u32 {
713 self.transforms.summary().output.longest_row
714 }
715
716 pub fn row_infos(&self, start_row: u32) -> WrapRows {
717 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>(&());
718 transforms.seek(&WrapPoint::new(start_row, 0), Bias::Left, &());
719 let mut input_row = transforms.start().1.row();
720 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
721 input_row += start_row - transforms.start().0.row();
722 }
723 let soft_wrapped = transforms.item().map_or(false, |t| !t.is_isomorphic());
724 let mut input_buffer_rows = self.tab_snapshot.rows(input_row);
725 let input_buffer_row = input_buffer_rows.next().unwrap();
726 WrapRows {
727 transforms,
728 input_buffer_row,
729 input_buffer_rows,
730 output_row: start_row,
731 soft_wrapped,
732 max_output_row: self.max_point().row(),
733 }
734 }
735
736 pub fn to_tab_point(&self, point: WrapPoint) -> TabPoint {
737 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>(&());
738 cursor.seek(&point, Bias::Right, &());
739 let mut tab_point = cursor.start().1.0;
740 if cursor.item().map_or(false, |t| t.is_isomorphic()) {
741 tab_point += point.0 - cursor.start().0.0;
742 }
743 TabPoint(tab_point)
744 }
745
746 pub fn to_point(&self, point: WrapPoint, bias: Bias) -> Point {
747 self.tab_snapshot.to_point(self.to_tab_point(point), bias)
748 }
749
750 pub fn make_wrap_point(&self, point: Point, bias: Bias) -> WrapPoint {
751 self.tab_point_to_wrap_point(self.tab_snapshot.make_tab_point(point, bias))
752 }
753
754 pub fn tab_point_to_wrap_point(&self, point: TabPoint) -> WrapPoint {
755 let mut cursor = self.transforms.cursor::<(TabPoint, WrapPoint)>(&());
756 cursor.seek(&point, Bias::Right, &());
757 WrapPoint(cursor.start().1.0 + (point.0 - cursor.start().0.0))
758 }
759
760 pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
761 if bias == Bias::Left {
762 let mut cursor = self.transforms.cursor::<WrapPoint>(&());
763 cursor.seek(&point, Bias::Right, &());
764 if cursor.item().map_or(false, |t| !t.is_isomorphic()) {
765 point = *cursor.start();
766 *point.column_mut() -= 1;
767 }
768 }
769
770 self.tab_point_to_wrap_point(self.tab_snapshot.clip_point(self.to_tab_point(point), bias))
771 }
772
773 pub fn prev_row_boundary(&self, mut point: WrapPoint) -> u32 {
774 if self.transforms.is_empty() {
775 return 0;
776 }
777
778 *point.column_mut() = 0;
779
780 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>(&());
781 cursor.seek(&point, Bias::Right, &());
782 if cursor.item().is_none() {
783 cursor.prev(&());
784 }
785
786 while let Some(transform) = cursor.item() {
787 if transform.is_isomorphic() && cursor.start().1.column() == 0 {
788 return cmp::min(cursor.end(&()).0.row(), point.row());
789 } else {
790 cursor.prev(&());
791 }
792 }
793
794 unreachable!()
795 }
796
797 pub fn next_row_boundary(&self, mut point: WrapPoint) -> Option<u32> {
798 point.0 += Point::new(1, 0);
799
800 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>(&());
801 cursor.seek(&point, Bias::Right, &());
802 while let Some(transform) = cursor.item() {
803 if transform.is_isomorphic() && cursor.start().1.column() == 0 {
804 return Some(cmp::max(cursor.start().0.row(), point.row()));
805 } else {
806 cursor.next(&());
807 }
808 }
809
810 None
811 }
812
813 #[cfg(test)]
814 pub fn text(&self) -> String {
815 self.text_chunks(0).collect()
816 }
817
818 #[cfg(test)]
819 pub fn text_chunks(&self, wrap_row: u32) -> impl Iterator<Item = &str> {
820 self.chunks(
821 wrap_row..self.max_point().row() + 1,
822 false,
823 Highlights::default(),
824 )
825 .map(|h| h.text)
826 }
827
828 fn check_invariants(&self) {
829 #[cfg(test)]
830 {
831 assert_eq!(
832 TabPoint::from(self.transforms.summary().input.lines),
833 self.tab_snapshot.max_point()
834 );
835
836 {
837 let mut transforms = self.transforms.cursor::<()>(&()).peekable();
838 while let Some(transform) = transforms.next() {
839 if let Some(next_transform) = transforms.peek() {
840 assert!(transform.is_isomorphic() != next_transform.is_isomorphic());
841 }
842 }
843 }
844
845 let text = language::Rope::from(self.text().as_str());
846 let mut input_buffer_rows = self.tab_snapshot.rows(0);
847 let mut expected_buffer_rows = Vec::new();
848 let mut prev_tab_row = 0;
849 for display_row in 0..=self.max_point().row() {
850 let tab_point = self.to_tab_point(WrapPoint::new(display_row, 0));
851 if tab_point.row() == prev_tab_row && display_row != 0 {
852 expected_buffer_rows.push(None);
853 } else {
854 expected_buffer_rows.push(input_buffer_rows.next().unwrap().buffer_row);
855 }
856
857 prev_tab_row = tab_point.row();
858 assert_eq!(self.line_len(display_row), text.line_len(display_row));
859 }
860
861 for start_display_row in 0..expected_buffer_rows.len() {
862 assert_eq!(
863 self.row_infos(start_display_row as u32)
864 .map(|row_info| row_info.buffer_row)
865 .collect::<Vec<_>>(),
866 &expected_buffer_rows[start_display_row..],
867 "invalid buffer_rows({}..)",
868 start_display_row
869 );
870 }
871 }
872 }
873}
874
875impl WrapChunks<'_> {
876 pub(crate) fn seek(&mut self, rows: Range<u32>) {
877 let output_start = WrapPoint::new(rows.start, 0);
878 let output_end = WrapPoint::new(rows.end, 0);
879 self.transforms.seek(&output_start, Bias::Right, &());
880 let mut input_start = TabPoint(self.transforms.start().1.0);
881 if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
882 input_start.0 += output_start.0 - self.transforms.start().0.0;
883 }
884 let input_end = self
885 .snapshot
886 .to_tab_point(output_end)
887 .min(self.snapshot.tab_snapshot.max_point());
888 self.input_chunks.seek(input_start..input_end);
889 self.input_chunk = Chunk::default();
890 self.output_position = output_start;
891 self.max_output_row = rows.end;
892 }
893}
894
895impl<'a> Iterator for WrapChunks<'a> {
896 type Item = Chunk<'a>;
897
898 fn next(&mut self) -> Option<Self::Item> {
899 if self.output_position.row() >= self.max_output_row {
900 return None;
901 }
902
903 let transform = self.transforms.item()?;
904 if let Some(display_text) = transform.display_text {
905 let mut start_ix = 0;
906 let mut end_ix = display_text.len();
907 let mut summary = transform.summary.output.lines;
908
909 if self.output_position > self.transforms.start().0 {
910 // Exclude newline starting prior to the desired row.
911 start_ix = 1;
912 summary.row = 0;
913 } else if self.output_position.row() + 1 >= self.max_output_row {
914 // Exclude soft indentation ending after the desired row.
915 end_ix = 1;
916 summary.column = 0;
917 }
918
919 self.output_position.0 += summary;
920 self.transforms.next(&());
921 return Some(Chunk {
922 text: &display_text[start_ix..end_ix],
923 ..self.input_chunk.clone()
924 });
925 }
926
927 if self.input_chunk.text.is_empty() {
928 self.input_chunk = self.input_chunks.next().unwrap();
929 }
930
931 let mut input_len = 0;
932 let transform_end = self.transforms.end(&()).0;
933 for c in self.input_chunk.text.chars() {
934 let char_len = c.len_utf8();
935 input_len += char_len;
936 if c == '\n' {
937 *self.output_position.row_mut() += 1;
938 *self.output_position.column_mut() = 0;
939 } else {
940 *self.output_position.column_mut() += char_len as u32;
941 }
942
943 if self.output_position >= transform_end {
944 self.transforms.next(&());
945 break;
946 }
947 }
948
949 let (prefix, suffix) = self.input_chunk.text.split_at(input_len);
950 self.input_chunk.text = suffix;
951 Some(Chunk {
952 text: prefix,
953 ..self.input_chunk.clone()
954 })
955 }
956}
957
958impl Iterator for WrapRows<'_> {
959 type Item = RowInfo;
960
961 fn next(&mut self) -> Option<Self::Item> {
962 if self.output_row > self.max_output_row {
963 return None;
964 }
965
966 let buffer_row = self.input_buffer_row;
967 let soft_wrapped = self.soft_wrapped;
968 let diff_status = self.input_buffer_row.diff_status;
969
970 self.output_row += 1;
971 self.transforms
972 .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left, &());
973 if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
974 self.input_buffer_row = self.input_buffer_rows.next().unwrap();
975 self.soft_wrapped = false;
976 } else {
977 self.soft_wrapped = true;
978 }
979
980 Some(if soft_wrapped {
981 RowInfo {
982 buffer_id: None,
983 buffer_row: None,
984 multibuffer_row: None,
985 diff_status,
986 expand_info: None,
987 }
988 } else {
989 buffer_row
990 })
991 }
992}
993
994impl Transform {
995 fn isomorphic(summary: TextSummary) -> Self {
996 #[cfg(test)]
997 assert!(!summary.lines.is_zero());
998
999 Self {
1000 summary: TransformSummary {
1001 input: summary.clone(),
1002 output: summary,
1003 },
1004 display_text: None,
1005 }
1006 }
1007
1008 fn wrap(indent: u32) -> Self {
1009 static WRAP_TEXT: LazyLock<String> = LazyLock::new(|| {
1010 let mut wrap_text = String::new();
1011 wrap_text.push('\n');
1012 wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
1013 wrap_text
1014 });
1015
1016 Self {
1017 summary: TransformSummary {
1018 input: TextSummary::default(),
1019 output: TextSummary {
1020 lines: Point::new(1, indent),
1021 first_line_chars: 0,
1022 last_line_chars: indent,
1023 longest_row: 1,
1024 longest_row_chars: indent,
1025 },
1026 },
1027 display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
1028 }
1029 }
1030
1031 fn is_isomorphic(&self) -> bool {
1032 self.display_text.is_none()
1033 }
1034}
1035
1036impl sum_tree::Item for Transform {
1037 type Summary = TransformSummary;
1038
1039 fn summary(&self, _cx: &()) -> Self::Summary {
1040 self.summary.clone()
1041 }
1042}
1043
1044fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
1045 if let Some(last_transform) = transforms.last_mut() {
1046 if last_transform.is_isomorphic() {
1047 last_transform.summary.input += &summary;
1048 last_transform.summary.output += &summary;
1049 return;
1050 }
1051 }
1052 transforms.push(Transform::isomorphic(summary));
1053}
1054
1055trait SumTreeExt {
1056 fn push_or_extend(&mut self, transform: Transform);
1057}
1058
1059impl SumTreeExt for SumTree<Transform> {
1060 fn push_or_extend(&mut self, transform: Transform) {
1061 let mut transform = Some(transform);
1062 self.update_last(
1063 |last_transform| {
1064 if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
1065 let transform = transform.take().unwrap();
1066 last_transform.summary.input += &transform.summary.input;
1067 last_transform.summary.output += &transform.summary.output;
1068 }
1069 },
1070 &(),
1071 );
1072
1073 if let Some(transform) = transform {
1074 self.push(transform, &());
1075 }
1076 }
1077}
1078
1079impl WrapPoint {
1080 pub fn new(row: u32, column: u32) -> Self {
1081 Self(Point::new(row, column))
1082 }
1083
1084 pub fn row(self) -> u32 {
1085 self.0.row
1086 }
1087
1088 pub fn row_mut(&mut self) -> &mut u32 {
1089 &mut self.0.row
1090 }
1091
1092 pub fn column(self) -> u32 {
1093 self.0.column
1094 }
1095
1096 pub fn column_mut(&mut self) -> &mut u32 {
1097 &mut self.0.column
1098 }
1099}
1100
1101impl sum_tree::Summary for TransformSummary {
1102 type Context = ();
1103
1104 fn zero(_cx: &()) -> Self {
1105 Default::default()
1106 }
1107
1108 fn add_summary(&mut self, other: &Self, _: &()) {
1109 self.input += &other.input;
1110 self.output += &other.output;
1111 }
1112}
1113
1114impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
1115 fn zero(_cx: &()) -> Self {
1116 Default::default()
1117 }
1118
1119 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1120 self.0 += summary.input.lines;
1121 }
1122}
1123
1124impl sum_tree::SeekTarget<'_, TransformSummary, TransformSummary> for TabPoint {
1125 fn cmp(&self, cursor_location: &TransformSummary, _: &()) -> std::cmp::Ordering {
1126 Ord::cmp(&self.0, &cursor_location.input.lines)
1127 }
1128}
1129
1130impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
1131 fn zero(_cx: &()) -> Self {
1132 Default::default()
1133 }
1134
1135 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1136 self.0 += summary.output.lines;
1137 }
1138}
1139
1140fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
1141 let _old_alloc_ptr = edits.as_ptr();
1142 let mut wrap_edits = edits.into_iter();
1143
1144 if let Some(mut first_edit) = wrap_edits.next() {
1145 // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1146 #[allow(clippy::filter_map_identity)]
1147 let mut v: Vec<_> = wrap_edits
1148 .scan(&mut first_edit, |prev_edit, edit| {
1149 if prev_edit.old.end >= edit.old.start {
1150 prev_edit.old.end = edit.old.end;
1151 prev_edit.new.end = edit.new.end;
1152 Some(None) // Skip this edit, it's merged
1153 } else {
1154 let prev = std::mem::replace(*prev_edit, edit);
1155 Some(Some(prev)) // Yield the previous edit
1156 }
1157 })
1158 .filter_map(|x| x)
1159 .collect();
1160 v.push(first_edit.clone());
1161 debug_assert_eq!(v.as_ptr(), _old_alloc_ptr, "Wrap edits were reallocated");
1162 v
1163 } else {
1164 vec![]
1165 }
1166}
1167
1168#[cfg(test)]
1169mod tests {
1170 use super::*;
1171 use crate::{
1172 MultiBuffer,
1173 display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
1174 test::test_font,
1175 };
1176 use gpui::{px, test::observe};
1177 use rand::prelude::*;
1178 use settings::SettingsStore;
1179 use smol::stream::StreamExt;
1180 use std::{cmp, env, num::NonZeroU32};
1181 use text::Rope;
1182 use theme::LoadThemes;
1183
1184 #[gpui::test(iterations = 100)]
1185 async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1186 // todo this test is flaky
1187 init_test(cx);
1188
1189 cx.background_executor.set_block_on_ticks(0..=50);
1190 let operations = env::var("OPERATIONS")
1191 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1192 .unwrap_or(10);
1193
1194 let text_system = cx.read(|cx| cx.text_system().clone());
1195 let mut wrap_width = if rng.gen_bool(0.1) {
1196 None
1197 } else {
1198 Some(px(rng.gen_range(0.0..=1000.0)))
1199 };
1200 let tab_size = NonZeroU32::new(rng.gen_range(1..=4)).unwrap();
1201
1202 let font = test_font();
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.r#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}