1use super::{
2 inlay_map::{InlayBufferRows, InlayChunks, InlayEdit, InlayOffset, InlayPoint, InlaySnapshot},
3 TextHighlights,
4};
5use crate::{Anchor, AnchorRangeExt, MultiBufferSnapshot, ToOffset};
6use gpui::{color::Color, fonts::HighlightStyle};
7use language::{Chunk, Edit, Point, TextSummary};
8use std::{
9 any::TypeId,
10 cmp::{self, Ordering},
11 iter,
12 ops::{Add, AddAssign, Range, Sub},
13};
14use sum_tree::{Bias, Cursor, FilterCursor, SumTree};
15
16#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
17pub struct FoldPoint(pub Point);
18
19impl FoldPoint {
20 pub fn new(row: u32, column: u32) -> Self {
21 Self(Point::new(row, column))
22 }
23
24 pub fn row(self) -> u32 {
25 self.0.row
26 }
27
28 pub fn column(self) -> u32 {
29 self.0.column
30 }
31
32 pub fn row_mut(&mut self) -> &mut u32 {
33 &mut self.0.row
34 }
35
36 #[cfg(test)]
37 pub fn column_mut(&mut self) -> &mut u32 {
38 &mut self.0.column
39 }
40
41 pub fn to_inlay_point(self, snapshot: &FoldSnapshot) -> InlayPoint {
42 let mut cursor = snapshot.transforms.cursor::<(FoldPoint, InlayPoint)>();
43 cursor.seek(&self, Bias::Right, &());
44 let overshoot = self.0 - cursor.start().0 .0;
45 InlayPoint(cursor.start().1 .0 + overshoot)
46 }
47
48 pub fn to_offset(self, snapshot: &FoldSnapshot) -> FoldOffset {
49 let mut cursor = snapshot
50 .transforms
51 .cursor::<(FoldPoint, TransformSummary)>();
52 cursor.seek(&self, Bias::Right, &());
53 let overshoot = self.0 - cursor.start().1.output.lines;
54 let mut offset = cursor.start().1.output.len;
55 if !overshoot.is_zero() {
56 let transform = cursor.item().expect("display point out of range");
57 assert!(transform.output_text.is_none());
58 let end_inlay_offset = snapshot
59 .inlay_snapshot
60 .to_offset(InlayPoint(cursor.start().1.input.lines + overshoot));
61 offset += end_inlay_offset.0 - cursor.start().1.input.len;
62 }
63 FoldOffset(offset)
64 }
65}
66
67impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldPoint {
68 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
69 self.0 += &summary.output.lines;
70 }
71}
72
73pub struct FoldMapWriter<'a>(&'a mut FoldMap);
74
75impl<'a> FoldMapWriter<'a> {
76 pub fn fold<T: ToOffset>(
77 &mut self,
78 ranges: impl IntoIterator<Item = Range<T>>,
79 ) -> (FoldSnapshot, Vec<FoldEdit>) {
80 let mut edits = Vec::new();
81 let mut folds = Vec::new();
82 let snapshot = self.0.snapshot.inlay_snapshot.clone();
83 for range in ranges.into_iter() {
84 let buffer = &snapshot.buffer;
85 let range = range.start.to_offset(&buffer)..range.end.to_offset(&buffer);
86
87 // Ignore any empty ranges.
88 if range.start == range.end {
89 continue;
90 }
91
92 // For now, ignore any ranges that span an excerpt boundary.
93 let fold = Fold(buffer.anchor_after(range.start)..buffer.anchor_before(range.end));
94 if fold.0.start.excerpt_id() != fold.0.end.excerpt_id() {
95 continue;
96 }
97
98 folds.push(fold);
99
100 let inlay_range =
101 snapshot.to_inlay_offset(range.start)..snapshot.to_inlay_offset(range.end);
102 edits.push(InlayEdit {
103 old: inlay_range.clone(),
104 new: inlay_range,
105 });
106 }
107
108 let buffer = &snapshot.buffer;
109 folds.sort_unstable_by(|a, b| sum_tree::SeekTarget::cmp(a, b, buffer));
110
111 self.0.snapshot.folds = {
112 let mut new_tree = SumTree::new();
113 let mut cursor = self.0.snapshot.folds.cursor::<Fold>();
114 for fold in folds {
115 new_tree.append(cursor.slice(&fold, Bias::Right, buffer), buffer);
116 new_tree.push(fold, buffer);
117 }
118 new_tree.append(cursor.suffix(buffer), buffer);
119 new_tree
120 };
121
122 consolidate_inlay_edits(&mut edits);
123 let edits = self.0.sync(snapshot.clone(), edits);
124 (self.0.snapshot.clone(), edits)
125 }
126
127 pub fn unfold<T: ToOffset>(
128 &mut self,
129 ranges: impl IntoIterator<Item = Range<T>>,
130 inclusive: bool,
131 ) -> (FoldSnapshot, Vec<FoldEdit>) {
132 let mut edits = Vec::new();
133 let mut fold_ixs_to_delete = Vec::new();
134 let snapshot = self.0.snapshot.inlay_snapshot.clone();
135 let buffer = &snapshot.buffer;
136 for range in ranges.into_iter() {
137 // Remove intersecting folds and add their ranges to edits that are passed to sync.
138 let mut folds_cursor =
139 intersecting_folds(&snapshot, &self.0.snapshot.folds, range, inclusive);
140 while let Some(fold) = folds_cursor.item() {
141 let offset_range = fold.0.start.to_offset(buffer)..fold.0.end.to_offset(buffer);
142 if offset_range.end > offset_range.start {
143 let inlay_range = snapshot.to_inlay_offset(offset_range.start)
144 ..snapshot.to_inlay_offset(offset_range.end);
145 edits.push(InlayEdit {
146 old: inlay_range.clone(),
147 new: inlay_range,
148 });
149 }
150 fold_ixs_to_delete.push(*folds_cursor.start());
151 folds_cursor.next(buffer);
152 }
153 }
154
155 fold_ixs_to_delete.sort_unstable();
156 fold_ixs_to_delete.dedup();
157
158 self.0.snapshot.folds = {
159 let mut cursor = self.0.snapshot.folds.cursor::<usize>();
160 let mut folds = SumTree::new();
161 for fold_ix in fold_ixs_to_delete {
162 folds.append(cursor.slice(&fold_ix, Bias::Right, buffer), buffer);
163 cursor.next(buffer);
164 }
165 folds.append(cursor.suffix(buffer), buffer);
166 folds
167 };
168
169 consolidate_inlay_edits(&mut edits);
170 let edits = self.0.sync(snapshot.clone(), edits);
171 (self.0.snapshot.clone(), edits)
172 }
173}
174
175pub struct FoldMap {
176 snapshot: FoldSnapshot,
177 ellipses_color: Option<Color>,
178}
179
180impl FoldMap {
181 pub fn new(inlay_snapshot: InlaySnapshot) -> (Self, FoldSnapshot) {
182 let this = Self {
183 snapshot: FoldSnapshot {
184 folds: Default::default(),
185 transforms: SumTree::from_item(
186 Transform {
187 summary: TransformSummary {
188 input: inlay_snapshot.text_summary(),
189 output: inlay_snapshot.text_summary(),
190 },
191 output_text: None,
192 },
193 &(),
194 ),
195 inlay_snapshot: inlay_snapshot.clone(),
196 version: 0,
197 ellipses_color: None,
198 },
199 ellipses_color: None,
200 };
201 let snapshot = this.snapshot.clone();
202 (this, snapshot)
203 }
204
205 pub fn read(
206 &mut self,
207 inlay_snapshot: InlaySnapshot,
208 edits: Vec<InlayEdit>,
209 ) -> (FoldSnapshot, Vec<FoldEdit>) {
210 let edits = self.sync(inlay_snapshot, edits);
211 self.check_invariants();
212 (self.snapshot.clone(), edits)
213 }
214
215 pub fn write(
216 &mut self,
217 inlay_snapshot: InlaySnapshot,
218 edits: Vec<InlayEdit>,
219 ) -> (FoldMapWriter, FoldSnapshot, Vec<FoldEdit>) {
220 let (snapshot, edits) = self.read(inlay_snapshot, edits);
221 (FoldMapWriter(self), snapshot, edits)
222 }
223
224 pub fn set_ellipses_color(&mut self, color: Color) -> bool {
225 if self.ellipses_color != Some(color) {
226 self.ellipses_color = Some(color);
227 true
228 } else {
229 false
230 }
231 }
232
233 fn check_invariants(&self) {
234 if cfg!(test) {
235 assert_eq!(
236 self.snapshot.transforms.summary().input.len,
237 self.snapshot.inlay_snapshot.len().0,
238 "transform tree does not match inlay snapshot's length"
239 );
240
241 let mut folds = self.snapshot.folds.iter().peekable();
242 while let Some(fold) = folds.next() {
243 if let Some(next_fold) = folds.peek() {
244 let comparison = fold
245 .0
246 .cmp(&next_fold.0, &self.snapshot.inlay_snapshot.buffer);
247 assert!(comparison.is_le());
248 }
249 }
250 }
251 }
252
253 fn sync(
254 &mut self,
255 inlay_snapshot: InlaySnapshot,
256 inlay_edits: Vec<InlayEdit>,
257 ) -> Vec<FoldEdit> {
258 if inlay_edits.is_empty() {
259 if self.snapshot.inlay_snapshot.version != inlay_snapshot.version {
260 self.snapshot.version += 1;
261 }
262 self.snapshot.inlay_snapshot = inlay_snapshot;
263 Vec::new()
264 } else {
265 let mut inlay_edits_iter = inlay_edits.iter().cloned().peekable();
266
267 let mut new_transforms = SumTree::new();
268 let mut cursor = self.snapshot.transforms.cursor::<InlayOffset>();
269 cursor.seek(&InlayOffset(0), Bias::Right, &());
270
271 while let Some(mut edit) = inlay_edits_iter.next() {
272 new_transforms.append(cursor.slice(&edit.old.start, Bias::Left, &()), &());
273 edit.new.start -= edit.old.start - *cursor.start();
274 edit.old.start = *cursor.start();
275
276 cursor.seek(&edit.old.end, Bias::Right, &());
277 cursor.next(&());
278
279 let mut delta = edit.new_len().0 as isize - edit.old_len().0 as isize;
280 loop {
281 edit.old.end = *cursor.start();
282
283 if let Some(next_edit) = inlay_edits_iter.peek() {
284 if next_edit.old.start > edit.old.end {
285 break;
286 }
287
288 let next_edit = inlay_edits_iter.next().unwrap();
289 delta += next_edit.new_len().0 as isize - next_edit.old_len().0 as isize;
290
291 if next_edit.old.end >= edit.old.end {
292 edit.old.end = next_edit.old.end;
293 cursor.seek(&edit.old.end, Bias::Right, &());
294 cursor.next(&());
295 }
296 } else {
297 break;
298 }
299 }
300
301 edit.new.end =
302 InlayOffset(((edit.new.start + edit.old_len()).0 as isize + delta) as usize);
303
304 let anchor = inlay_snapshot
305 .buffer
306 .anchor_before(inlay_snapshot.to_buffer_offset(edit.new.start));
307 let mut folds_cursor = self.snapshot.folds.cursor::<Fold>();
308 folds_cursor.seek(
309 &Fold(anchor..Anchor::max()),
310 Bias::Left,
311 &inlay_snapshot.buffer,
312 );
313
314 let mut folds = iter::from_fn({
315 let inlay_snapshot = &inlay_snapshot;
316 move || {
317 let item = folds_cursor.item().map(|f| {
318 let buffer_start = f.0.start.to_offset(&inlay_snapshot.buffer);
319 let buffer_end = f.0.end.to_offset(&inlay_snapshot.buffer);
320 inlay_snapshot.to_inlay_offset(buffer_start)
321 ..inlay_snapshot.to_inlay_offset(buffer_end)
322 });
323 folds_cursor.next(&inlay_snapshot.buffer);
324 item
325 }
326 })
327 .peekable();
328
329 while folds.peek().map_or(false, |fold| fold.start < edit.new.end) {
330 let mut fold = folds.next().unwrap();
331 let sum = new_transforms.summary();
332
333 assert!(fold.start.0 >= sum.input.len);
334
335 while folds
336 .peek()
337 .map_or(false, |next_fold| next_fold.start <= fold.end)
338 {
339 let next_fold = folds.next().unwrap();
340 if next_fold.end > fold.end {
341 fold.end = next_fold.end;
342 }
343 }
344
345 if fold.start.0 > sum.input.len {
346 let text_summary = inlay_snapshot
347 .text_summary_for_range(InlayOffset(sum.input.len)..fold.start);
348 new_transforms.push(
349 Transform {
350 summary: TransformSummary {
351 output: text_summary.clone(),
352 input: text_summary,
353 },
354 output_text: None,
355 },
356 &(),
357 );
358 }
359
360 if fold.end > fold.start {
361 let output_text = "⋯";
362 new_transforms.push(
363 Transform {
364 summary: TransformSummary {
365 output: TextSummary::from(output_text),
366 input: inlay_snapshot
367 .text_summary_for_range(fold.start..fold.end),
368 },
369 output_text: Some(output_text),
370 },
371 &(),
372 );
373 }
374 }
375
376 let sum = new_transforms.summary();
377 if sum.input.len < edit.new.end.0 {
378 let text_summary = inlay_snapshot
379 .text_summary_for_range(InlayOffset(sum.input.len)..edit.new.end);
380 new_transforms.push(
381 Transform {
382 summary: TransformSummary {
383 output: text_summary.clone(),
384 input: text_summary,
385 },
386 output_text: None,
387 },
388 &(),
389 );
390 }
391 }
392
393 new_transforms.append(cursor.suffix(&()), &());
394 if new_transforms.is_empty() {
395 let text_summary = inlay_snapshot.text_summary();
396 new_transforms.push(
397 Transform {
398 summary: TransformSummary {
399 output: text_summary.clone(),
400 input: text_summary,
401 },
402 output_text: None,
403 },
404 &(),
405 );
406 }
407
408 drop(cursor);
409
410 let mut fold_edits = Vec::with_capacity(inlay_edits.len());
411 {
412 let mut old_transforms = self
413 .snapshot
414 .transforms
415 .cursor::<(InlayOffset, FoldOffset)>();
416 let mut new_transforms = new_transforms.cursor::<(InlayOffset, FoldOffset)>();
417
418 for mut edit in inlay_edits {
419 old_transforms.seek(&edit.old.start, Bias::Left, &());
420 if old_transforms.item().map_or(false, |t| t.is_fold()) {
421 edit.old.start = old_transforms.start().0;
422 }
423 let old_start =
424 old_transforms.start().1 .0 + (edit.old.start - old_transforms.start().0).0;
425
426 old_transforms.seek_forward(&edit.old.end, Bias::Right, &());
427 if old_transforms.item().map_or(false, |t| t.is_fold()) {
428 old_transforms.next(&());
429 edit.old.end = old_transforms.start().0;
430 }
431 let old_end =
432 old_transforms.start().1 .0 + (edit.old.end - old_transforms.start().0).0;
433
434 new_transforms.seek(&edit.new.start, Bias::Left, &());
435 if new_transforms.item().map_or(false, |t| t.is_fold()) {
436 edit.new.start = new_transforms.start().0;
437 }
438 let new_start =
439 new_transforms.start().1 .0 + (edit.new.start - new_transforms.start().0).0;
440
441 new_transforms.seek_forward(&edit.new.end, Bias::Right, &());
442 if new_transforms.item().map_or(false, |t| t.is_fold()) {
443 new_transforms.next(&());
444 edit.new.end = new_transforms.start().0;
445 }
446 let new_end =
447 new_transforms.start().1 .0 + (edit.new.end - new_transforms.start().0).0;
448
449 fold_edits.push(FoldEdit {
450 old: FoldOffset(old_start)..FoldOffset(old_end),
451 new: FoldOffset(new_start)..FoldOffset(new_end),
452 });
453 }
454
455 consolidate_fold_edits(&mut fold_edits);
456 }
457
458 self.snapshot.transforms = new_transforms;
459 self.snapshot.inlay_snapshot = inlay_snapshot;
460 self.snapshot.version += 1;
461 fold_edits
462 }
463 }
464}
465
466#[derive(Clone)]
467pub struct FoldSnapshot {
468 transforms: SumTree<Transform>,
469 folds: SumTree<Fold>,
470 pub inlay_snapshot: InlaySnapshot,
471 pub version: usize,
472 pub ellipses_color: Option<Color>,
473}
474
475impl FoldSnapshot {
476 #[cfg(test)]
477 pub fn text(&self) -> String {
478 self.chunks(FoldOffset(0)..self.len(), false, None, None, None)
479 .map(|c| c.text)
480 .collect()
481 }
482
483 #[cfg(test)]
484 pub fn fold_count(&self) -> usize {
485 self.folds.items(&self.inlay_snapshot.buffer).len()
486 }
487
488 pub fn text_summary_for_range(&self, range: Range<FoldPoint>) -> TextSummary {
489 let mut summary = TextSummary::default();
490
491 let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
492 cursor.seek(&range.start, Bias::Right, &());
493 if let Some(transform) = cursor.item() {
494 let start_in_transform = range.start.0 - cursor.start().0 .0;
495 let end_in_transform = cmp::min(range.end, cursor.end(&()).0).0 - cursor.start().0 .0;
496 if let Some(output_text) = transform.output_text {
497 summary = TextSummary::from(
498 &output_text
499 [start_in_transform.column as usize..end_in_transform.column as usize],
500 );
501 } else {
502 let inlay_start = self
503 .inlay_snapshot
504 .to_offset(InlayPoint(cursor.start().1 .0 + start_in_transform));
505 let inlay_end = self
506 .inlay_snapshot
507 .to_offset(InlayPoint(cursor.start().1 .0 + end_in_transform));
508 summary = self
509 .inlay_snapshot
510 .text_summary_for_range(inlay_start..inlay_end);
511 }
512 }
513
514 if range.end > cursor.end(&()).0 {
515 cursor.next(&());
516 summary += &cursor
517 .summary::<_, TransformSummary>(&range.end, Bias::Right, &())
518 .output;
519 if let Some(transform) = cursor.item() {
520 let end_in_transform = range.end.0 - cursor.start().0 .0;
521 if let Some(output_text) = transform.output_text {
522 summary += TextSummary::from(&output_text[..end_in_transform.column as usize]);
523 } else {
524 let inlay_start = self.inlay_snapshot.to_offset(cursor.start().1);
525 let inlay_end = self
526 .inlay_snapshot
527 .to_offset(InlayPoint(cursor.start().1 .0 + end_in_transform));
528 summary += self
529 .inlay_snapshot
530 .text_summary_for_range(inlay_start..inlay_end);
531 }
532 }
533 }
534
535 summary
536 }
537
538 pub fn to_fold_point(&self, point: InlayPoint, bias: Bias) -> FoldPoint {
539 let mut cursor = self.transforms.cursor::<(InlayPoint, FoldPoint)>();
540 cursor.seek(&point, Bias::Right, &());
541 if cursor.item().map_or(false, |t| t.is_fold()) {
542 if bias == Bias::Left || point == cursor.start().0 {
543 cursor.start().1
544 } else {
545 cursor.end(&()).1
546 }
547 } else {
548 let overshoot = point.0 - cursor.start().0 .0;
549 FoldPoint(cmp::min(
550 cursor.start().1 .0 + overshoot,
551 cursor.end(&()).1 .0,
552 ))
553 }
554 }
555
556 pub fn len(&self) -> FoldOffset {
557 FoldOffset(self.transforms.summary().output.len)
558 }
559
560 pub fn line_len(&self, row: u32) -> u32 {
561 let line_start = FoldPoint::new(row, 0).to_offset(self).0;
562 let line_end = if row >= self.max_point().row() {
563 self.len().0
564 } else {
565 FoldPoint::new(row + 1, 0).to_offset(self).0 - 1
566 };
567 (line_end - line_start) as u32
568 }
569
570 pub fn buffer_rows(&self, start_row: u32) -> FoldBufferRows {
571 if start_row > self.transforms.summary().output.lines.row {
572 panic!("invalid display row {}", start_row);
573 }
574
575 let fold_point = FoldPoint::new(start_row, 0);
576 let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
577 cursor.seek(&fold_point, Bias::Left, &());
578
579 let overshoot = fold_point.0 - cursor.start().0 .0;
580 let inlay_point = InlayPoint(cursor.start().1 .0 + overshoot);
581 let input_buffer_rows = self.inlay_snapshot.buffer_rows(inlay_point.row());
582
583 FoldBufferRows {
584 fold_point,
585 input_buffer_rows,
586 cursor,
587 }
588 }
589
590 pub fn max_point(&self) -> FoldPoint {
591 FoldPoint(self.transforms.summary().output.lines)
592 }
593
594 #[cfg(test)]
595 pub fn longest_row(&self) -> u32 {
596 self.transforms.summary().output.longest_row
597 }
598
599 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Range<Anchor>>
600 where
601 T: ToOffset,
602 {
603 let mut folds = intersecting_folds(&self.inlay_snapshot, &self.folds, range, false);
604 iter::from_fn(move || {
605 let item = folds.item().map(|f| &f.0);
606 folds.next(&self.inlay_snapshot.buffer);
607 item
608 })
609 }
610
611 pub fn intersects_fold<T>(&self, offset: T) -> bool
612 where
613 T: ToOffset,
614 {
615 let buffer_offset = offset.to_offset(&self.inlay_snapshot.buffer);
616 let inlay_offset = self.inlay_snapshot.to_inlay_offset(buffer_offset);
617 let mut cursor = self.transforms.cursor::<InlayOffset>();
618 cursor.seek(&inlay_offset, Bias::Right, &());
619 cursor.item().map_or(false, |t| t.output_text.is_some())
620 }
621
622 pub fn is_line_folded(&self, buffer_row: u32) -> bool {
623 let mut inlay_point = self
624 .inlay_snapshot
625 .to_inlay_point(Point::new(buffer_row, 0));
626 let mut cursor = self.transforms.cursor::<InlayPoint>();
627 cursor.seek(&inlay_point, Bias::Right, &());
628 loop {
629 match cursor.item() {
630 Some(transform) => {
631 let buffer_point = self.inlay_snapshot.to_buffer_point(inlay_point);
632 if buffer_point.row != buffer_row {
633 return false;
634 } else if transform.output_text.is_some() {
635 return true;
636 }
637 }
638 None => return false,
639 }
640
641 if cursor.end(&()).row() == inlay_point.row() {
642 cursor.next(&());
643 } else {
644 inlay_point.0 += Point::new(1, 0);
645 cursor.seek(&inlay_point, Bias::Right, &());
646 }
647 }
648 }
649
650 pub fn chunks<'a>(
651 &'a self,
652 range: Range<FoldOffset>,
653 language_aware: bool,
654 text_highlights: Option<&'a TextHighlights>,
655 hint_highlights: Option<HighlightStyle>,
656 suggestion_highlights: Option<HighlightStyle>,
657 ) -> FoldChunks<'a> {
658 let mut transform_cursor = self.transforms.cursor::<(FoldOffset, InlayOffset)>();
659
660 let inlay_end = {
661 transform_cursor.seek(&range.end, Bias::Right, &());
662 let overshoot = range.end.0 - transform_cursor.start().0 .0;
663 transform_cursor.start().1 + InlayOffset(overshoot)
664 };
665
666 let inlay_start = {
667 transform_cursor.seek(&range.start, Bias::Right, &());
668 let overshoot = range.start.0 - transform_cursor.start().0 .0;
669 transform_cursor.start().1 + InlayOffset(overshoot)
670 };
671
672 FoldChunks {
673 transform_cursor,
674 inlay_chunks: self.inlay_snapshot.chunks(
675 inlay_start..inlay_end,
676 language_aware,
677 text_highlights,
678 hint_highlights,
679 suggestion_highlights,
680 ),
681 inlay_chunk: None,
682 inlay_offset: inlay_start,
683 output_offset: range.start.0,
684 max_output_offset: range.end.0,
685 ellipses_color: self.ellipses_color,
686 }
687 }
688
689 pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
690 self.chunks(start.to_offset(self)..self.len(), false, None, None, None)
691 .flat_map(|chunk| chunk.text.chars())
692 }
693
694 #[cfg(test)]
695 pub fn clip_offset(&self, offset: FoldOffset, bias: Bias) -> FoldOffset {
696 if offset > self.len() {
697 self.len()
698 } else {
699 self.clip_point(offset.to_point(self), bias).to_offset(self)
700 }
701 }
702
703 pub fn clip_point(&self, point: FoldPoint, bias: Bias) -> FoldPoint {
704 let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
705 cursor.seek(&point, Bias::Right, &());
706 if let Some(transform) = cursor.item() {
707 let transform_start = cursor.start().0 .0;
708 if transform.output_text.is_some() {
709 if point.0 == transform_start || matches!(bias, Bias::Left) {
710 FoldPoint(transform_start)
711 } else {
712 FoldPoint(cursor.end(&()).0 .0)
713 }
714 } else {
715 let overshoot = InlayPoint(point.0 - transform_start);
716 let inlay_point = cursor.start().1 + overshoot;
717 let clipped_inlay_point = self.inlay_snapshot.clip_point(inlay_point, bias);
718 FoldPoint(cursor.start().0 .0 + (clipped_inlay_point - cursor.start().1).0)
719 }
720 } else {
721 FoldPoint(self.transforms.summary().output.lines)
722 }
723 }
724}
725
726fn intersecting_folds<'a, T>(
727 inlay_snapshot: &'a InlaySnapshot,
728 folds: &'a SumTree<Fold>,
729 range: Range<T>,
730 inclusive: bool,
731) -> FilterCursor<'a, impl 'a + FnMut(&FoldSummary) -> bool, Fold, usize>
732where
733 T: ToOffset,
734{
735 let buffer = &inlay_snapshot.buffer;
736 let start = buffer.anchor_before(range.start.to_offset(buffer));
737 let end = buffer.anchor_after(range.end.to_offset(buffer));
738 let mut cursor = folds.filter::<_, usize>(move |summary| {
739 let start_cmp = start.cmp(&summary.max_end, buffer);
740 let end_cmp = end.cmp(&summary.min_start, buffer);
741
742 if inclusive {
743 start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
744 } else {
745 start_cmp == Ordering::Less && end_cmp == Ordering::Greater
746 }
747 });
748 cursor.next(buffer);
749 cursor
750}
751
752fn consolidate_inlay_edits(edits: &mut Vec<InlayEdit>) {
753 edits.sort_unstable_by(|a, b| {
754 a.old
755 .start
756 .cmp(&b.old.start)
757 .then_with(|| b.old.end.cmp(&a.old.end))
758 });
759
760 let mut i = 1;
761 while i < edits.len() {
762 let edit = edits[i].clone();
763 let prev_edit = &mut edits[i - 1];
764 if prev_edit.old.end >= edit.old.start {
765 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
766 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
767 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
768 edits.remove(i);
769 continue;
770 }
771 i += 1;
772 }
773}
774
775fn consolidate_fold_edits(edits: &mut Vec<FoldEdit>) {
776 edits.sort_unstable_by(|a, b| {
777 a.old
778 .start
779 .cmp(&b.old.start)
780 .then_with(|| b.old.end.cmp(&a.old.end))
781 });
782
783 let mut i = 1;
784 while i < edits.len() {
785 let edit = edits[i].clone();
786 let prev_edit = &mut edits[i - 1];
787 if prev_edit.old.end >= edit.old.start {
788 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
789 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
790 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
791 edits.remove(i);
792 continue;
793 }
794 i += 1;
795 }
796}
797
798#[derive(Clone, Debug, Default, Eq, PartialEq)]
799struct Transform {
800 summary: TransformSummary,
801 output_text: Option<&'static str>,
802}
803
804impl Transform {
805 fn is_fold(&self) -> bool {
806 self.output_text.is_some()
807 }
808}
809
810#[derive(Clone, Debug, Default, Eq, PartialEq)]
811struct TransformSummary {
812 output: TextSummary,
813 input: TextSummary,
814}
815
816impl sum_tree::Item for Transform {
817 type Summary = TransformSummary;
818
819 fn summary(&self) -> Self::Summary {
820 self.summary.clone()
821 }
822}
823
824impl sum_tree::Summary for TransformSummary {
825 type Context = ();
826
827 fn add_summary(&mut self, other: &Self, _: &()) {
828 self.input += &other.input;
829 self.output += &other.output;
830 }
831}
832
833#[derive(Clone, Debug)]
834struct Fold(Range<Anchor>);
835
836impl Default for Fold {
837 fn default() -> Self {
838 Self(Anchor::min()..Anchor::max())
839 }
840}
841
842impl sum_tree::Item for Fold {
843 type Summary = FoldSummary;
844
845 fn summary(&self) -> Self::Summary {
846 FoldSummary {
847 start: self.0.start.clone(),
848 end: self.0.end.clone(),
849 min_start: self.0.start.clone(),
850 max_end: self.0.end.clone(),
851 count: 1,
852 }
853 }
854}
855
856#[derive(Clone, Debug)]
857struct FoldSummary {
858 start: Anchor,
859 end: Anchor,
860 min_start: Anchor,
861 max_end: Anchor,
862 count: usize,
863}
864
865impl Default for FoldSummary {
866 fn default() -> Self {
867 Self {
868 start: Anchor::min(),
869 end: Anchor::max(),
870 min_start: Anchor::max(),
871 max_end: Anchor::min(),
872 count: 0,
873 }
874 }
875}
876
877impl sum_tree::Summary for FoldSummary {
878 type Context = MultiBufferSnapshot;
879
880 fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
881 if other.min_start.cmp(&self.min_start, buffer) == Ordering::Less {
882 self.min_start = other.min_start.clone();
883 }
884 if other.max_end.cmp(&self.max_end, buffer) == Ordering::Greater {
885 self.max_end = other.max_end.clone();
886 }
887
888 #[cfg(debug_assertions)]
889 {
890 let start_comparison = self.start.cmp(&other.start, buffer);
891 assert!(start_comparison <= Ordering::Equal);
892 if start_comparison == Ordering::Equal {
893 assert!(self.end.cmp(&other.end, buffer) >= Ordering::Equal);
894 }
895 }
896
897 self.start = other.start.clone();
898 self.end = other.end.clone();
899 self.count += other.count;
900 }
901}
902
903impl<'a> sum_tree::Dimension<'a, FoldSummary> for Fold {
904 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
905 self.0.start = summary.start.clone();
906 self.0.end = summary.end.clone();
907 }
908}
909
910impl<'a> sum_tree::SeekTarget<'a, FoldSummary, Fold> for Fold {
911 fn cmp(&self, other: &Self, buffer: &MultiBufferSnapshot) -> Ordering {
912 self.0.cmp(&other.0, buffer)
913 }
914}
915
916impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
917 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
918 *self += summary.count;
919 }
920}
921
922#[derive(Clone)]
923pub struct FoldBufferRows<'a> {
924 cursor: Cursor<'a, Transform, (FoldPoint, InlayPoint)>,
925 input_buffer_rows: InlayBufferRows<'a>,
926 fold_point: FoldPoint,
927}
928
929impl<'a> Iterator for FoldBufferRows<'a> {
930 type Item = Option<u32>;
931
932 fn next(&mut self) -> Option<Self::Item> {
933 let mut traversed_fold = false;
934 while self.fold_point > self.cursor.end(&()).0 {
935 self.cursor.next(&());
936 traversed_fold = true;
937 if self.cursor.item().is_none() {
938 break;
939 }
940 }
941
942 if self.cursor.item().is_some() {
943 if traversed_fold {
944 self.input_buffer_rows.seek(self.cursor.start().1.row());
945 self.input_buffer_rows.next();
946 }
947 *self.fold_point.row_mut() += 1;
948 self.input_buffer_rows.next()
949 } else {
950 None
951 }
952 }
953}
954
955pub struct FoldChunks<'a> {
956 transform_cursor: Cursor<'a, Transform, (FoldOffset, InlayOffset)>,
957 inlay_chunks: InlayChunks<'a>,
958 inlay_chunk: Option<(InlayOffset, Chunk<'a>)>,
959 inlay_offset: InlayOffset,
960 output_offset: usize,
961 max_output_offset: usize,
962 ellipses_color: Option<Color>,
963}
964
965impl<'a> Iterator for FoldChunks<'a> {
966 type Item = Chunk<'a>;
967
968 fn next(&mut self) -> Option<Self::Item> {
969 if self.output_offset >= self.max_output_offset {
970 return None;
971 }
972
973 let transform = self.transform_cursor.item()?;
974
975 // If we're in a fold, then return the fold's display text and
976 // advance the transform and buffer cursors to the end of the fold.
977 if let Some(output_text) = transform.output_text {
978 self.inlay_chunk.take();
979 self.inlay_offset += InlayOffset(transform.summary.input.len);
980 self.inlay_chunks.seek(self.inlay_offset);
981
982 while self.inlay_offset >= self.transform_cursor.end(&()).1
983 && self.transform_cursor.item().is_some()
984 {
985 self.transform_cursor.next(&());
986 }
987
988 self.output_offset += output_text.len();
989 return Some(Chunk {
990 text: output_text,
991 highlight_style: self.ellipses_color.map(|color| HighlightStyle {
992 color: Some(color),
993 ..Default::default()
994 }),
995 ..Default::default()
996 });
997 }
998
999 // Retrieve a chunk from the current location in the buffer.
1000 if self.inlay_chunk.is_none() {
1001 let chunk_offset = self.inlay_chunks.offset();
1002 self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1003 }
1004
1005 // Otherwise, take a chunk from the buffer's text.
1006 if let Some((buffer_chunk_start, mut chunk)) = self.inlay_chunk {
1007 let buffer_chunk_end = buffer_chunk_start + InlayOffset(chunk.text.len());
1008 let transform_end = self.transform_cursor.end(&()).1;
1009 let chunk_end = buffer_chunk_end.min(transform_end);
1010
1011 chunk.text = &chunk.text
1012 [(self.inlay_offset - buffer_chunk_start).0..(chunk_end - buffer_chunk_start).0];
1013
1014 if chunk_end == transform_end {
1015 self.transform_cursor.next(&());
1016 } else if chunk_end == buffer_chunk_end {
1017 self.inlay_chunk.take();
1018 }
1019
1020 self.inlay_offset = chunk_end;
1021 self.output_offset += chunk.text.len();
1022 return Some(chunk);
1023 }
1024
1025 None
1026 }
1027}
1028
1029#[derive(Copy, Clone, Eq, PartialEq)]
1030struct HighlightEndpoint {
1031 offset: InlayOffset,
1032 is_start: bool,
1033 tag: Option<TypeId>,
1034 style: HighlightStyle,
1035}
1036
1037impl PartialOrd for HighlightEndpoint {
1038 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1039 Some(self.cmp(other))
1040 }
1041}
1042
1043impl Ord for HighlightEndpoint {
1044 fn cmp(&self, other: &Self) -> Ordering {
1045 self.offset
1046 .cmp(&other.offset)
1047 .then_with(|| other.is_start.cmp(&self.is_start))
1048 }
1049}
1050
1051#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1052pub struct FoldOffset(pub usize);
1053
1054impl FoldOffset {
1055 pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1056 let mut cursor = snapshot
1057 .transforms
1058 .cursor::<(FoldOffset, TransformSummary)>();
1059 cursor.seek(&self, Bias::Right, &());
1060 let overshoot = if cursor.item().map_or(true, |t| t.is_fold()) {
1061 Point::new(0, (self.0 - cursor.start().0 .0) as u32)
1062 } else {
1063 let inlay_offset = cursor.start().1.input.len + self.0 - cursor.start().0 .0;
1064 let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1065 inlay_point.0 - cursor.start().1.input.lines
1066 };
1067 FoldPoint(cursor.start().1.output.lines + overshoot)
1068 }
1069
1070 #[cfg(test)]
1071 pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1072 let mut cursor = snapshot.transforms.cursor::<(FoldOffset, InlayOffset)>();
1073 cursor.seek(&self, Bias::Right, &());
1074 let overshoot = self.0 - cursor.start().0 .0;
1075 InlayOffset(cursor.start().1 .0 + overshoot)
1076 }
1077}
1078
1079impl Add for FoldOffset {
1080 type Output = Self;
1081
1082 fn add(self, rhs: Self) -> Self::Output {
1083 Self(self.0 + rhs.0)
1084 }
1085}
1086
1087impl AddAssign for FoldOffset {
1088 fn add_assign(&mut self, rhs: Self) {
1089 self.0 += rhs.0;
1090 }
1091}
1092
1093impl Sub for FoldOffset {
1094 type Output = Self;
1095
1096 fn sub(self, rhs: Self) -> Self::Output {
1097 Self(self.0 - rhs.0)
1098 }
1099}
1100
1101impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1102 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1103 self.0 += &summary.output.len;
1104 }
1105}
1106
1107impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1108 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1109 self.0 += &summary.input.lines;
1110 }
1111}
1112
1113impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1114 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1115 self.0 += &summary.input.len;
1116 }
1117}
1118
1119pub type FoldEdit = Edit<FoldOffset>;
1120
1121#[cfg(test)]
1122mod tests {
1123 use super::*;
1124 use crate::{display_map::inlay_map::InlayMap, MultiBuffer, ToPoint};
1125 use collections::HashSet;
1126 use rand::prelude::*;
1127 use settings::SettingsStore;
1128 use std::{cmp::Reverse, env, mem, sync::Arc};
1129 use sum_tree::TreeMap;
1130 use text::Patch;
1131 use util::test::sample_text;
1132 use util::RandomCharIter;
1133 use Bias::{Left, Right};
1134
1135 #[gpui::test]
1136 fn test_basic_folds(cx: &mut gpui::AppContext) {
1137 init_test(cx);
1138 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1139 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1140 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1141 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1142 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1143
1144 let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1145 let (snapshot2, edits) = writer.fold(vec![
1146 Point::new(0, 2)..Point::new(2, 2),
1147 Point::new(2, 4)..Point::new(4, 1),
1148 ]);
1149 assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1150 assert_eq!(
1151 edits,
1152 &[
1153 FoldEdit {
1154 old: FoldOffset(2)..FoldOffset(16),
1155 new: FoldOffset(2)..FoldOffset(5),
1156 },
1157 FoldEdit {
1158 old: FoldOffset(18)..FoldOffset(29),
1159 new: FoldOffset(7)..FoldOffset(10)
1160 },
1161 ]
1162 );
1163
1164 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1165 buffer.edit(
1166 vec![
1167 (Point::new(0, 0)..Point::new(0, 1), "123"),
1168 (Point::new(2, 3)..Point::new(2, 3), "123"),
1169 ],
1170 None,
1171 cx,
1172 );
1173 buffer.snapshot(cx)
1174 });
1175
1176 let (inlay_snapshot, inlay_edits) =
1177 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1178 let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1179 assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1180 assert_eq!(
1181 edits,
1182 &[
1183 FoldEdit {
1184 old: FoldOffset(0)..FoldOffset(1),
1185 new: FoldOffset(0)..FoldOffset(3),
1186 },
1187 FoldEdit {
1188 old: FoldOffset(6)..FoldOffset(6),
1189 new: FoldOffset(8)..FoldOffset(11),
1190 },
1191 ]
1192 );
1193
1194 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1195 buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1196 buffer.snapshot(cx)
1197 });
1198 let (inlay_snapshot, inlay_edits) =
1199 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1200 let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1201 assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1202
1203 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1204 writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1205 let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1206 assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1207
1208 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1209 writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1210 let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1211 assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1212 }
1213
1214 #[gpui::test]
1215 fn test_adjacent_folds(cx: &mut gpui::AppContext) {
1216 init_test(cx);
1217 let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1218 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1219 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1220 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1221
1222 {
1223 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1224
1225 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1226 writer.fold(vec![5..8]);
1227 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1228 assert_eq!(snapshot.text(), "abcde⋯ijkl");
1229
1230 // Create an fold adjacent to the start of the first fold.
1231 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1232 writer.fold(vec![0..1, 2..5]);
1233 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1234 assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1235
1236 // Create an fold adjacent to the end of the first fold.
1237 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1238 writer.fold(vec![11..11, 8..10]);
1239 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1240 assert_eq!(snapshot.text(), "⋯b⋯kl");
1241 }
1242
1243 {
1244 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1245
1246 // Create two adjacent folds.
1247 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1248 writer.fold(vec![0..2, 2..5]);
1249 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1250 assert_eq!(snapshot.text(), "⋯fghijkl");
1251
1252 // Edit within one of the folds.
1253 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1254 buffer.edit([(0..1, "12345")], None, cx);
1255 buffer.snapshot(cx)
1256 });
1257 let (inlay_snapshot, inlay_edits) =
1258 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1259 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1260 assert_eq!(snapshot.text(), "12345⋯fghijkl");
1261 }
1262 }
1263
1264 #[gpui::test]
1265 fn test_overlapping_folds(cx: &mut gpui::AppContext) {
1266 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1267 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1268 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1269 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1270 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1271 writer.fold(vec![
1272 Point::new(0, 2)..Point::new(2, 2),
1273 Point::new(0, 4)..Point::new(1, 0),
1274 Point::new(1, 2)..Point::new(3, 2),
1275 Point::new(3, 1)..Point::new(4, 1),
1276 ]);
1277 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1278 assert_eq!(snapshot.text(), "aa⋯eeeee");
1279 }
1280
1281 #[gpui::test]
1282 fn test_merging_folds_via_edit(cx: &mut gpui::AppContext) {
1283 init_test(cx);
1284 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1285 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1286 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1287 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1288 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1289
1290 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1291 writer.fold(vec![
1292 Point::new(0, 2)..Point::new(2, 2),
1293 Point::new(3, 1)..Point::new(4, 1),
1294 ]);
1295 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1296 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1297
1298 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1299 buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1300 buffer.snapshot(cx)
1301 });
1302 let (inlay_snapshot, inlay_edits) =
1303 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1304 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1305 assert_eq!(snapshot.text(), "aa⋯eeeee");
1306 }
1307
1308 #[gpui::test]
1309 fn test_folds_in_range(cx: &mut gpui::AppContext) {
1310 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1311 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1312 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1313 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1314
1315 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1316 writer.fold(vec![
1317 Point::new(0, 2)..Point::new(2, 2),
1318 Point::new(0, 4)..Point::new(1, 0),
1319 Point::new(1, 2)..Point::new(3, 2),
1320 Point::new(3, 1)..Point::new(4, 1),
1321 ]);
1322 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1323 let fold_ranges = snapshot
1324 .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1325 .map(|fold| fold.start.to_point(&buffer_snapshot)..fold.end.to_point(&buffer_snapshot))
1326 .collect::<Vec<_>>();
1327 assert_eq!(
1328 fold_ranges,
1329 vec![
1330 Point::new(0, 2)..Point::new(2, 2),
1331 Point::new(1, 2)..Point::new(3, 2)
1332 ]
1333 );
1334 }
1335
1336 #[gpui::test(iterations = 100)]
1337 fn test_random_folds(cx: &mut gpui::AppContext, mut rng: StdRng) {
1338 init_test(cx);
1339 let operations = env::var("OPERATIONS")
1340 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1341 .unwrap_or(10);
1342
1343 let len = rng.gen_range(0..10);
1344 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1345 let buffer = if rng.gen() {
1346 MultiBuffer::build_simple(&text, cx)
1347 } else {
1348 MultiBuffer::build_random(&mut rng, cx)
1349 };
1350 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1351 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1352 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1353
1354 let (mut initial_snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1355 let mut snapshot_edits = Vec::new();
1356
1357 let mut highlights = TreeMap::default();
1358 let highlight_count = rng.gen_range(0_usize..10);
1359 let mut highlight_ranges = (0..highlight_count)
1360 .map(|_| buffer_snapshot.random_byte_range(0, &mut rng))
1361 .collect::<Vec<_>>();
1362 highlight_ranges.sort_by_key(|range| (range.start, Reverse(range.end)));
1363 log::info!("highlighting ranges {:?}", highlight_ranges);
1364 let highlight_ranges = highlight_ranges
1365 .into_iter()
1366 .map(|range| {
1367 buffer_snapshot.anchor_before(range.start)..buffer_snapshot.anchor_after(range.end)
1368 })
1369 .collect::<Vec<_>>();
1370
1371 highlights.insert(
1372 Some(TypeId::of::<()>()),
1373 Arc::new((HighlightStyle::default(), highlight_ranges)),
1374 );
1375
1376 let mut next_inlay_id = 0;
1377 for _ in 0..operations {
1378 log::info!("text: {:?}", buffer_snapshot.text());
1379 let mut buffer_edits = Vec::new();
1380 let mut inlay_edits = Vec::new();
1381 match rng.gen_range(0..=100) {
1382 0..=39 => {
1383 snapshot_edits.extend(map.randomly_mutate(&mut rng));
1384 }
1385 40..=59 => {
1386 let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1387 inlay_edits = edits;
1388 }
1389 _ => buffer.update(cx, |buffer, cx| {
1390 let subscription = buffer.subscribe();
1391 let edit_count = rng.gen_range(1..=5);
1392 buffer.randomly_mutate(&mut rng, edit_count, cx);
1393 buffer_snapshot = buffer.snapshot(cx);
1394 let edits = subscription.consume().into_inner();
1395 log::info!("editing {:?}", edits);
1396 buffer_edits.extend(edits);
1397 }),
1398 };
1399
1400 let (inlay_snapshot, new_inlay_edits) =
1401 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1402 log::info!("inlay text {:?}", inlay_snapshot.text());
1403
1404 let inlay_edits = Patch::new(inlay_edits)
1405 .compose(new_inlay_edits)
1406 .into_inner();
1407 let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
1408 snapshot_edits.push((snapshot.clone(), edits));
1409
1410 let mut expected_text: String = inlay_snapshot.text().to_string();
1411 for fold_range in map.merged_fold_ranges().into_iter().rev() {
1412 let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
1413 let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
1414 expected_text.replace_range(fold_inlay_start.0..fold_inlay_end.0, "⋯");
1415 }
1416
1417 assert_eq!(snapshot.text(), expected_text);
1418 log::info!(
1419 "fold text {:?} ({} lines)",
1420 expected_text,
1421 expected_text.matches('\n').count() + 1
1422 );
1423
1424 let mut prev_row = 0;
1425 let mut expected_buffer_rows = Vec::new();
1426 for fold_range in map.merged_fold_ranges().into_iter() {
1427 let fold_start = inlay_snapshot
1428 .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
1429 .row();
1430 let fold_end = inlay_snapshot
1431 .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
1432 .row();
1433 expected_buffer_rows.extend(
1434 inlay_snapshot
1435 .buffer_rows(prev_row)
1436 .take((1 + fold_start - prev_row) as usize),
1437 );
1438 prev_row = 1 + fold_end;
1439 }
1440 expected_buffer_rows.extend(inlay_snapshot.buffer_rows(prev_row));
1441
1442 assert_eq!(
1443 expected_buffer_rows.len(),
1444 expected_text.matches('\n').count() + 1,
1445 "wrong expected buffer rows {:?}. text: {:?}",
1446 expected_buffer_rows,
1447 expected_text
1448 );
1449
1450 for (output_row, line) in expected_text.lines().enumerate() {
1451 let line_len = snapshot.line_len(output_row as u32);
1452 assert_eq!(line_len, line.len() as u32);
1453 }
1454
1455 let longest_row = snapshot.longest_row();
1456 let longest_char_column = expected_text
1457 .split('\n')
1458 .nth(longest_row as usize)
1459 .unwrap()
1460 .chars()
1461 .count();
1462 let mut fold_point = FoldPoint::new(0, 0);
1463 let mut fold_offset = FoldOffset(0);
1464 let mut char_column = 0;
1465 for c in expected_text.chars() {
1466 let inlay_point = fold_point.to_inlay_point(&snapshot);
1467 let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
1468 assert_eq!(
1469 snapshot.to_fold_point(inlay_point, Right),
1470 fold_point,
1471 "{:?} -> fold point",
1472 inlay_point,
1473 );
1474 assert_eq!(
1475 inlay_snapshot.to_offset(inlay_point),
1476 inlay_offset,
1477 "inlay_snapshot.to_offset({:?})",
1478 inlay_point,
1479 );
1480 assert_eq!(
1481 fold_point.to_offset(&snapshot),
1482 fold_offset,
1483 "fold_point.to_offset({:?})",
1484 fold_point,
1485 );
1486
1487 if c == '\n' {
1488 *fold_point.row_mut() += 1;
1489 *fold_point.column_mut() = 0;
1490 char_column = 0;
1491 } else {
1492 *fold_point.column_mut() += c.len_utf8() as u32;
1493 char_column += 1;
1494 }
1495 fold_offset.0 += c.len_utf8();
1496 if char_column > longest_char_column {
1497 panic!(
1498 "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
1499 longest_row,
1500 longest_char_column,
1501 fold_point.row(),
1502 char_column
1503 );
1504 }
1505 }
1506
1507 for _ in 0..5 {
1508 let mut start = snapshot
1509 .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Left);
1510 let mut end = snapshot
1511 .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Right);
1512 if start > end {
1513 mem::swap(&mut start, &mut end);
1514 }
1515
1516 let text = &expected_text[start.0..end.0];
1517 assert_eq!(
1518 snapshot
1519 .chunks(start..end, false, Some(&highlights), None, None)
1520 .map(|c| c.text)
1521 .collect::<String>(),
1522 text,
1523 );
1524 }
1525
1526 let mut fold_row = 0;
1527 while fold_row < expected_buffer_rows.len() as u32 {
1528 assert_eq!(
1529 snapshot.buffer_rows(fold_row).collect::<Vec<_>>(),
1530 expected_buffer_rows[(fold_row as usize)..],
1531 "wrong buffer rows starting at fold row {}",
1532 fold_row,
1533 );
1534 fold_row += 1;
1535 }
1536
1537 let folded_buffer_rows = map
1538 .merged_fold_ranges()
1539 .iter()
1540 .flat_map(|range| {
1541 let start_row = range.start.to_point(&buffer_snapshot).row;
1542 let end = range.end.to_point(&buffer_snapshot);
1543 if end.column == 0 {
1544 start_row..end.row
1545 } else {
1546 start_row..end.row + 1
1547 }
1548 })
1549 .collect::<HashSet<_>>();
1550 for row in 0..=buffer_snapshot.max_point().row {
1551 assert_eq!(
1552 snapshot.is_line_folded(row),
1553 folded_buffer_rows.contains(&row),
1554 "expected buffer row {}{} to be folded",
1555 row,
1556 if folded_buffer_rows.contains(&row) {
1557 ""
1558 } else {
1559 " not"
1560 }
1561 );
1562 }
1563
1564 for _ in 0..5 {
1565 let end =
1566 buffer_snapshot.clip_offset(rng.gen_range(0..=buffer_snapshot.len()), Right);
1567 let start = buffer_snapshot.clip_offset(rng.gen_range(0..=end), Left);
1568 let expected_folds = map
1569 .snapshot
1570 .folds
1571 .items(&buffer_snapshot)
1572 .into_iter()
1573 .filter(|fold| {
1574 let start = buffer_snapshot.anchor_before(start);
1575 let end = buffer_snapshot.anchor_after(end);
1576 start.cmp(&fold.0.end, &buffer_snapshot) == Ordering::Less
1577 && end.cmp(&fold.0.start, &buffer_snapshot) == Ordering::Greater
1578 })
1579 .map(|fold| fold.0)
1580 .collect::<Vec<_>>();
1581
1582 assert_eq!(
1583 snapshot
1584 .folds_in_range(start..end)
1585 .cloned()
1586 .collect::<Vec<_>>(),
1587 expected_folds
1588 );
1589 }
1590
1591 let text = snapshot.text();
1592 for _ in 0..5 {
1593 let start_row = rng.gen_range(0..=snapshot.max_point().row());
1594 let start_column = rng.gen_range(0..=snapshot.line_len(start_row));
1595 let end_row = rng.gen_range(0..=snapshot.max_point().row());
1596 let end_column = rng.gen_range(0..=snapshot.line_len(end_row));
1597 let mut start =
1598 snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
1599 let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
1600 if start > end {
1601 mem::swap(&mut start, &mut end);
1602 }
1603
1604 let lines = start..end;
1605 let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
1606 assert_eq!(
1607 snapshot.text_summary_for_range(lines),
1608 TextSummary::from(&text[bytes.start.0..bytes.end.0])
1609 )
1610 }
1611
1612 let mut text = initial_snapshot.text();
1613 for (snapshot, edits) in snapshot_edits.drain(..) {
1614 let new_text = snapshot.text();
1615 for edit in edits {
1616 let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
1617 let new_bytes = edit.new.start.0..edit.new.end.0;
1618 text.replace_range(old_bytes, &new_text[new_bytes]);
1619 }
1620
1621 assert_eq!(text, new_text);
1622 initial_snapshot = snapshot;
1623 }
1624 }
1625 }
1626
1627 #[gpui::test]
1628 fn test_buffer_rows(cx: &mut gpui::AppContext) {
1629 let text = sample_text(6, 6, 'a') + "\n";
1630 let buffer = MultiBuffer::build_simple(&text, cx);
1631
1632 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1633 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1634 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1635
1636 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1637 writer.fold(vec![
1638 Point::new(0, 2)..Point::new(2, 2),
1639 Point::new(3, 1)..Point::new(4, 1),
1640 ]);
1641
1642 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1643 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
1644 assert_eq!(
1645 snapshot.buffer_rows(0).collect::<Vec<_>>(),
1646 [Some(0), Some(3), Some(5), Some(6)]
1647 );
1648 assert_eq!(snapshot.buffer_rows(3).collect::<Vec<_>>(), [Some(6)]);
1649 }
1650
1651 fn init_test(cx: &mut gpui::AppContext) {
1652 cx.set_global(SettingsStore::test(cx));
1653 }
1654
1655 impl FoldMap {
1656 fn merged_fold_ranges(&self) -> Vec<Range<usize>> {
1657 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1658 let buffer = &inlay_snapshot.buffer;
1659 let mut folds = self.snapshot.folds.items(buffer);
1660 // Ensure sorting doesn't change how folds get merged and displayed.
1661 folds.sort_by(|a, b| a.0.cmp(&b.0, buffer));
1662 let mut fold_ranges = folds
1663 .iter()
1664 .map(|fold| fold.0.start.to_offset(buffer)..fold.0.end.to_offset(buffer))
1665 .peekable();
1666
1667 let mut merged_ranges = Vec::new();
1668 while let Some(mut fold_range) = fold_ranges.next() {
1669 while let Some(next_range) = fold_ranges.peek() {
1670 if fold_range.end >= next_range.start {
1671 if next_range.end > fold_range.end {
1672 fold_range.end = next_range.end;
1673 }
1674 fold_ranges.next();
1675 } else {
1676 break;
1677 }
1678 }
1679 if fold_range.end > fold_range.start {
1680 merged_ranges.push(fold_range);
1681 }
1682 }
1683 merged_ranges
1684 }
1685
1686 pub fn randomly_mutate(
1687 &mut self,
1688 rng: &mut impl Rng,
1689 ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
1690 let mut snapshot_edits = Vec::new();
1691 match rng.gen_range(0..=100) {
1692 0..=39 if !self.snapshot.folds.is_empty() => {
1693 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1694 let buffer = &inlay_snapshot.buffer;
1695 let mut to_unfold = Vec::new();
1696 for _ in 0..rng.gen_range(1..=3) {
1697 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1698 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1699 to_unfold.push(start..end);
1700 }
1701 log::info!("unfolding {:?}", to_unfold);
1702 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
1703 snapshot_edits.push((snapshot, edits));
1704 let (snapshot, edits) = writer.fold(to_unfold);
1705 snapshot_edits.push((snapshot, edits));
1706 }
1707 _ => {
1708 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1709 let buffer = &inlay_snapshot.buffer;
1710 let mut to_fold = Vec::new();
1711 for _ in 0..rng.gen_range(1..=2) {
1712 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1713 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1714 to_fold.push(start..end);
1715 }
1716 log::info!("folding {:?}", to_fold);
1717 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
1718 snapshot_edits.push((snapshot, edits));
1719 let (snapshot, edits) = writer.fold(to_fold);
1720 snapshot_edits.push((snapshot, edits));
1721 }
1722 }
1723 snapshot_edits
1724 }
1725 }
1726}