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