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)
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 inlay_highlights: Option<HighlightStyle>,
656 ) -> FoldChunks<'a> {
657 let mut transform_cursor = self.transforms.cursor::<(FoldOffset, InlayOffset)>();
658
659 let inlay_end = {
660 transform_cursor.seek(&range.end, Bias::Right, &());
661 let overshoot = range.end.0 - transform_cursor.start().0 .0;
662 transform_cursor.start().1 + InlayOffset(overshoot)
663 };
664
665 let inlay_start = {
666 transform_cursor.seek(&range.start, Bias::Right, &());
667 let overshoot = range.start.0 - transform_cursor.start().0 .0;
668 transform_cursor.start().1 + InlayOffset(overshoot)
669 };
670
671 FoldChunks {
672 transform_cursor,
673 inlay_chunks: self.inlay_snapshot.chunks(
674 inlay_start..inlay_end,
675 language_aware,
676 text_highlights,
677 inlay_highlights,
678 ),
679 inlay_chunk: None,
680 inlay_offset: inlay_start,
681 output_offset: range.start.0,
682 max_output_offset: range.end.0,
683 ellipses_color: self.ellipses_color,
684 }
685 }
686
687 pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
688 self.chunks(start.to_offset(self)..self.len(), false, None, None)
689 .flat_map(|chunk| chunk.text.chars())
690 }
691
692 #[cfg(test)]
693 pub fn clip_offset(&self, offset: FoldOffset, bias: Bias) -> FoldOffset {
694 if offset > self.len() {
695 self.len()
696 } else {
697 self.clip_point(offset.to_point(self), bias).to_offset(self)
698 }
699 }
700
701 pub fn clip_point(&self, point: FoldPoint, bias: Bias) -> FoldPoint {
702 let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
703 cursor.seek(&point, Bias::Right, &());
704 if let Some(transform) = cursor.item() {
705 let transform_start = cursor.start().0 .0;
706 if transform.output_text.is_some() {
707 if point.0 == transform_start || matches!(bias, Bias::Left) {
708 FoldPoint(transform_start)
709 } else {
710 FoldPoint(cursor.end(&()).0 .0)
711 }
712 } else {
713 let overshoot = InlayPoint(point.0 - transform_start);
714 let inlay_point = cursor.start().1 + overshoot;
715 let clipped_inlay_point = self.inlay_snapshot.clip_point(inlay_point, bias);
716 FoldPoint(cursor.start().0 .0 + (clipped_inlay_point - cursor.start().1).0)
717 }
718 } else {
719 FoldPoint(self.transforms.summary().output.lines)
720 }
721 }
722}
723
724fn intersecting_folds<'a, T>(
725 inlay_snapshot: &'a InlaySnapshot,
726 folds: &'a SumTree<Fold>,
727 range: Range<T>,
728 inclusive: bool,
729) -> FilterCursor<'a, impl 'a + FnMut(&FoldSummary) -> bool, Fold, usize>
730where
731 T: ToOffset,
732{
733 let buffer = &inlay_snapshot.buffer;
734 let start = buffer.anchor_before(range.start.to_offset(buffer));
735 let end = buffer.anchor_after(range.end.to_offset(buffer));
736 let mut cursor = folds.filter::<_, usize>(move |summary| {
737 let start_cmp = start.cmp(&summary.max_end, buffer);
738 let end_cmp = end.cmp(&summary.min_start, buffer);
739
740 if inclusive {
741 start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
742 } else {
743 start_cmp == Ordering::Less && end_cmp == Ordering::Greater
744 }
745 });
746 cursor.next(buffer);
747 cursor
748}
749
750fn consolidate_inlay_edits(edits: &mut Vec<InlayEdit>) {
751 edits.sort_unstable_by(|a, b| {
752 a.old
753 .start
754 .cmp(&b.old.start)
755 .then_with(|| b.old.end.cmp(&a.old.end))
756 });
757
758 let mut i = 1;
759 while i < edits.len() {
760 let edit = edits[i].clone();
761 let prev_edit = &mut edits[i - 1];
762 if prev_edit.old.end >= edit.old.start {
763 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
764 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
765 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
766 edits.remove(i);
767 continue;
768 }
769 i += 1;
770 }
771}
772
773fn consolidate_fold_edits(edits: &mut Vec<FoldEdit>) {
774 edits.sort_unstable_by(|a, b| {
775 a.old
776 .start
777 .cmp(&b.old.start)
778 .then_with(|| b.old.end.cmp(&a.old.end))
779 });
780
781 let mut i = 1;
782 while i < edits.len() {
783 let edit = edits[i].clone();
784 let prev_edit = &mut edits[i - 1];
785 if prev_edit.old.end >= edit.old.start {
786 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
787 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
788 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
789 edits.remove(i);
790 continue;
791 }
792 i += 1;
793 }
794}
795
796#[derive(Clone, Debug, Default, Eq, PartialEq)]
797struct Transform {
798 summary: TransformSummary,
799 output_text: Option<&'static str>,
800}
801
802impl Transform {
803 fn is_fold(&self) -> bool {
804 self.output_text.is_some()
805 }
806}
807
808#[derive(Clone, Debug, Default, Eq, PartialEq)]
809struct TransformSummary {
810 output: TextSummary,
811 input: TextSummary,
812}
813
814impl sum_tree::Item for Transform {
815 type Summary = TransformSummary;
816
817 fn summary(&self) -> Self::Summary {
818 self.summary.clone()
819 }
820}
821
822impl sum_tree::Summary for TransformSummary {
823 type Context = ();
824
825 fn add_summary(&mut self, other: &Self, _: &()) {
826 self.input += &other.input;
827 self.output += &other.output;
828 }
829}
830
831#[derive(Clone, Debug)]
832struct Fold(Range<Anchor>);
833
834impl Default for Fold {
835 fn default() -> Self {
836 Self(Anchor::min()..Anchor::max())
837 }
838}
839
840impl sum_tree::Item for Fold {
841 type Summary = FoldSummary;
842
843 fn summary(&self) -> Self::Summary {
844 FoldSummary {
845 start: self.0.start.clone(),
846 end: self.0.end.clone(),
847 min_start: self.0.start.clone(),
848 max_end: self.0.end.clone(),
849 count: 1,
850 }
851 }
852}
853
854#[derive(Clone, Debug)]
855struct FoldSummary {
856 start: Anchor,
857 end: Anchor,
858 min_start: Anchor,
859 max_end: Anchor,
860 count: usize,
861}
862
863impl Default for FoldSummary {
864 fn default() -> Self {
865 Self {
866 start: Anchor::min(),
867 end: Anchor::max(),
868 min_start: Anchor::max(),
869 max_end: Anchor::min(),
870 count: 0,
871 }
872 }
873}
874
875impl sum_tree::Summary for FoldSummary {
876 type Context = MultiBufferSnapshot;
877
878 fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
879 if other.min_start.cmp(&self.min_start, buffer) == Ordering::Less {
880 self.min_start = other.min_start.clone();
881 }
882 if other.max_end.cmp(&self.max_end, buffer) == Ordering::Greater {
883 self.max_end = other.max_end.clone();
884 }
885
886 #[cfg(debug_assertions)]
887 {
888 let start_comparison = self.start.cmp(&other.start, buffer);
889 assert!(start_comparison <= Ordering::Equal);
890 if start_comparison == Ordering::Equal {
891 assert!(self.end.cmp(&other.end, buffer) >= Ordering::Equal);
892 }
893 }
894
895 self.start = other.start.clone();
896 self.end = other.end.clone();
897 self.count += other.count;
898 }
899}
900
901impl<'a> sum_tree::Dimension<'a, FoldSummary> for Fold {
902 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
903 self.0.start = summary.start.clone();
904 self.0.end = summary.end.clone();
905 }
906}
907
908impl<'a> sum_tree::SeekTarget<'a, FoldSummary, Fold> for Fold {
909 fn cmp(&self, other: &Self, buffer: &MultiBufferSnapshot) -> Ordering {
910 self.0.cmp(&other.0, buffer)
911 }
912}
913
914impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
915 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
916 *self += summary.count;
917 }
918}
919
920#[derive(Clone)]
921pub struct FoldBufferRows<'a> {
922 cursor: Cursor<'a, Transform, (FoldPoint, InlayPoint)>,
923 input_buffer_rows: InlayBufferRows<'a>,
924 fold_point: FoldPoint,
925}
926
927impl<'a> Iterator for FoldBufferRows<'a> {
928 type Item = Option<u32>;
929
930 fn next(&mut self) -> Option<Self::Item> {
931 let mut traversed_fold = false;
932 while self.fold_point > self.cursor.end(&()).0 {
933 self.cursor.next(&());
934 traversed_fold = true;
935 if self.cursor.item().is_none() {
936 break;
937 }
938 }
939
940 if self.cursor.item().is_some() {
941 if traversed_fold {
942 self.input_buffer_rows.seek(self.cursor.start().1.row());
943 self.input_buffer_rows.next();
944 }
945 *self.fold_point.row_mut() += 1;
946 self.input_buffer_rows.next()
947 } else {
948 None
949 }
950 }
951}
952
953pub struct FoldChunks<'a> {
954 transform_cursor: Cursor<'a, Transform, (FoldOffset, InlayOffset)>,
955 inlay_chunks: InlayChunks<'a>,
956 inlay_chunk: Option<(InlayOffset, Chunk<'a>)>,
957 inlay_offset: InlayOffset,
958 output_offset: usize,
959 max_output_offset: usize,
960 ellipses_color: Option<Color>,
961}
962
963impl<'a> Iterator for FoldChunks<'a> {
964 type Item = Chunk<'a>;
965
966 fn next(&mut self) -> Option<Self::Item> {
967 if self.output_offset >= self.max_output_offset {
968 return None;
969 }
970
971 let transform = self.transform_cursor.item()?;
972
973 // If we're in a fold, then return the fold's display text and
974 // advance the transform and buffer cursors to the end of the fold.
975 if let Some(output_text) = transform.output_text {
976 self.inlay_chunk.take();
977 self.inlay_offset += InlayOffset(transform.summary.input.len);
978 self.inlay_chunks.seek(self.inlay_offset);
979
980 while self.inlay_offset >= self.transform_cursor.end(&()).1
981 && self.transform_cursor.item().is_some()
982 {
983 self.transform_cursor.next(&());
984 }
985
986 self.output_offset += output_text.len();
987 return Some(Chunk {
988 text: output_text,
989 highlight_style: self.ellipses_color.map(|color| HighlightStyle {
990 color: Some(color),
991 ..Default::default()
992 }),
993 ..Default::default()
994 });
995 }
996
997 // Retrieve a chunk from the current location in the buffer.
998 if self.inlay_chunk.is_none() {
999 let chunk_offset = self.inlay_chunks.offset();
1000 self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1001 }
1002
1003 // Otherwise, take a chunk from the buffer's text.
1004 if let Some((buffer_chunk_start, mut chunk)) = self.inlay_chunk {
1005 let buffer_chunk_end = buffer_chunk_start + InlayOffset(chunk.text.len());
1006 let transform_end = self.transform_cursor.end(&()).1;
1007 let chunk_end = buffer_chunk_end.min(transform_end);
1008
1009 chunk.text = &chunk.text
1010 [(self.inlay_offset - buffer_chunk_start).0..(chunk_end - buffer_chunk_start).0];
1011
1012 if chunk_end == transform_end {
1013 self.transform_cursor.next(&());
1014 } else if chunk_end == buffer_chunk_end {
1015 self.inlay_chunk.take();
1016 }
1017
1018 self.inlay_offset = chunk_end;
1019 self.output_offset += chunk.text.len();
1020 return Some(chunk);
1021 }
1022
1023 None
1024 }
1025}
1026
1027#[derive(Copy, Clone, Eq, PartialEq)]
1028struct HighlightEndpoint {
1029 offset: InlayOffset,
1030 is_start: bool,
1031 tag: Option<TypeId>,
1032 style: HighlightStyle,
1033}
1034
1035impl PartialOrd for HighlightEndpoint {
1036 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1037 Some(self.cmp(other))
1038 }
1039}
1040
1041impl Ord for HighlightEndpoint {
1042 fn cmp(&self, other: &Self) -> Ordering {
1043 self.offset
1044 .cmp(&other.offset)
1045 .then_with(|| other.is_start.cmp(&self.is_start))
1046 }
1047}
1048
1049#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1050pub struct FoldOffset(pub usize);
1051
1052impl FoldOffset {
1053 pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1054 let mut cursor = snapshot
1055 .transforms
1056 .cursor::<(FoldOffset, TransformSummary)>();
1057 cursor.seek(&self, Bias::Right, &());
1058 let overshoot = if cursor.item().map_or(true, |t| t.is_fold()) {
1059 Point::new(0, (self.0 - cursor.start().0 .0) as u32)
1060 } else {
1061 let inlay_offset = cursor.start().1.input.len + self.0 - cursor.start().0 .0;
1062 let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1063 inlay_point.0 - cursor.start().1.input.lines
1064 };
1065 FoldPoint(cursor.start().1.output.lines + overshoot)
1066 }
1067
1068 #[cfg(test)]
1069 pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1070 let mut cursor = snapshot.transforms.cursor::<(FoldOffset, InlayOffset)>();
1071 cursor.seek(&self, Bias::Right, &());
1072 let overshoot = self.0 - cursor.start().0 .0;
1073 InlayOffset(cursor.start().1 .0 + overshoot)
1074 }
1075}
1076
1077impl Add for FoldOffset {
1078 type Output = Self;
1079
1080 fn add(self, rhs: Self) -> Self::Output {
1081 Self(self.0 + rhs.0)
1082 }
1083}
1084
1085impl AddAssign for FoldOffset {
1086 fn add_assign(&mut self, rhs: Self) {
1087 self.0 += rhs.0;
1088 }
1089}
1090
1091impl Sub for FoldOffset {
1092 type Output = Self;
1093
1094 fn sub(self, rhs: Self) -> Self::Output {
1095 Self(self.0 - rhs.0)
1096 }
1097}
1098
1099impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1100 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1101 self.0 += &summary.output.len;
1102 }
1103}
1104
1105impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1106 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1107 self.0 += &summary.input.lines;
1108 }
1109}
1110
1111impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1112 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1113 self.0 += &summary.input.len;
1114 }
1115}
1116
1117pub type FoldEdit = Edit<FoldOffset>;
1118
1119#[cfg(test)]
1120mod tests {
1121 use super::*;
1122 use crate::{display_map::inlay_map::InlayMap, MultiBuffer, ToPoint};
1123 use collections::HashSet;
1124 use rand::prelude::*;
1125 use settings::SettingsStore;
1126 use std::{cmp::Reverse, env, mem, sync::Arc};
1127 use sum_tree::TreeMap;
1128 use text::Patch;
1129 use util::test::sample_text;
1130 use util::RandomCharIter;
1131 use Bias::{Left, Right};
1132
1133 #[gpui::test]
1134 fn test_basic_folds(cx: &mut gpui::AppContext) {
1135 init_test(cx);
1136 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1137 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1138 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1139 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1140 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1141
1142 let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1143 let (snapshot2, edits) = writer.fold(vec![
1144 Point::new(0, 2)..Point::new(2, 2),
1145 Point::new(2, 4)..Point::new(4, 1),
1146 ]);
1147 assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1148 assert_eq!(
1149 edits,
1150 &[
1151 FoldEdit {
1152 old: FoldOffset(2)..FoldOffset(16),
1153 new: FoldOffset(2)..FoldOffset(5),
1154 },
1155 FoldEdit {
1156 old: FoldOffset(18)..FoldOffset(29),
1157 new: FoldOffset(7)..FoldOffset(10)
1158 },
1159 ]
1160 );
1161
1162 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1163 buffer.edit(
1164 vec![
1165 (Point::new(0, 0)..Point::new(0, 1), "123"),
1166 (Point::new(2, 3)..Point::new(2, 3), "123"),
1167 ],
1168 None,
1169 cx,
1170 );
1171 buffer.snapshot(cx)
1172 });
1173
1174 let (inlay_snapshot, inlay_edits) =
1175 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1176 let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1177 assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1178 assert_eq!(
1179 edits,
1180 &[
1181 FoldEdit {
1182 old: FoldOffset(0)..FoldOffset(1),
1183 new: FoldOffset(0)..FoldOffset(3),
1184 },
1185 FoldEdit {
1186 old: FoldOffset(6)..FoldOffset(6),
1187 new: FoldOffset(8)..FoldOffset(11),
1188 },
1189 ]
1190 );
1191
1192 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1193 buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1194 buffer.snapshot(cx)
1195 });
1196 let (inlay_snapshot, inlay_edits) =
1197 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1198 let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1199 assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1200
1201 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1202 writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1203 let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1204 assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1205
1206 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1207 writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1208 let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1209 assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1210 }
1211
1212 #[gpui::test]
1213 fn test_adjacent_folds(cx: &mut gpui::AppContext) {
1214 init_test(cx);
1215 let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1216 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1217 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1218 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1219
1220 {
1221 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1222
1223 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1224 writer.fold(vec![5..8]);
1225 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1226 assert_eq!(snapshot.text(), "abcde⋯ijkl");
1227
1228 // Create an fold adjacent to the start of the first fold.
1229 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1230 writer.fold(vec![0..1, 2..5]);
1231 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1232 assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1233
1234 // Create an fold adjacent to the end of the first fold.
1235 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1236 writer.fold(vec![11..11, 8..10]);
1237 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1238 assert_eq!(snapshot.text(), "⋯b⋯kl");
1239 }
1240
1241 {
1242 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1243
1244 // Create two adjacent folds.
1245 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1246 writer.fold(vec![0..2, 2..5]);
1247 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1248 assert_eq!(snapshot.text(), "⋯fghijkl");
1249
1250 // Edit within one of the folds.
1251 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1252 buffer.edit([(0..1, "12345")], None, cx);
1253 buffer.snapshot(cx)
1254 });
1255 let (inlay_snapshot, inlay_edits) =
1256 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1257 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1258 assert_eq!(snapshot.text(), "12345⋯fghijkl");
1259 }
1260 }
1261
1262 #[gpui::test]
1263 fn test_overlapping_folds(cx: &mut gpui::AppContext) {
1264 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1265 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1266 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1267 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1268 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1269 writer.fold(vec![
1270 Point::new(0, 2)..Point::new(2, 2),
1271 Point::new(0, 4)..Point::new(1, 0),
1272 Point::new(1, 2)..Point::new(3, 2),
1273 Point::new(3, 1)..Point::new(4, 1),
1274 ]);
1275 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1276 assert_eq!(snapshot.text(), "aa⋯eeeee");
1277 }
1278
1279 #[gpui::test]
1280 fn test_merging_folds_via_edit(cx: &mut gpui::AppContext) {
1281 init_test(cx);
1282 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1283 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1284 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1285 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1286 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1287
1288 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1289 writer.fold(vec![
1290 Point::new(0, 2)..Point::new(2, 2),
1291 Point::new(3, 1)..Point::new(4, 1),
1292 ]);
1293 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1294 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1295
1296 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1297 buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1298 buffer.snapshot(cx)
1299 });
1300 let (inlay_snapshot, inlay_edits) =
1301 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1302 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1303 assert_eq!(snapshot.text(), "aa⋯eeeee");
1304 }
1305
1306 #[gpui::test]
1307 fn test_folds_in_range(cx: &mut gpui::AppContext) {
1308 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1309 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1310 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1311 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1312
1313 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1314 writer.fold(vec![
1315 Point::new(0, 2)..Point::new(2, 2),
1316 Point::new(0, 4)..Point::new(1, 0),
1317 Point::new(1, 2)..Point::new(3, 2),
1318 Point::new(3, 1)..Point::new(4, 1),
1319 ]);
1320 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1321 let fold_ranges = snapshot
1322 .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1323 .map(|fold| fold.start.to_point(&buffer_snapshot)..fold.end.to_point(&buffer_snapshot))
1324 .collect::<Vec<_>>();
1325 assert_eq!(
1326 fold_ranges,
1327 vec![
1328 Point::new(0, 2)..Point::new(2, 2),
1329 Point::new(1, 2)..Point::new(3, 2)
1330 ]
1331 );
1332 }
1333
1334 #[gpui::test(iterations = 100)]
1335 fn test_random_folds(cx: &mut gpui::AppContext, mut rng: StdRng) {
1336 init_test(cx);
1337 let operations = env::var("OPERATIONS")
1338 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1339 .unwrap_or(10);
1340
1341 let len = rng.gen_range(0..10);
1342 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1343 let buffer = if rng.gen() {
1344 MultiBuffer::build_simple(&text, cx)
1345 } else {
1346 MultiBuffer::build_random(&mut rng, cx)
1347 };
1348 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1349 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1350 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1351
1352 let (mut initial_snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1353 let mut snapshot_edits = Vec::new();
1354
1355 let mut highlights = TreeMap::default();
1356 let highlight_count = rng.gen_range(0_usize..10);
1357 let mut highlight_ranges = (0..highlight_count)
1358 .map(|_| buffer_snapshot.random_byte_range(0, &mut rng))
1359 .collect::<Vec<_>>();
1360 highlight_ranges.sort_by_key(|range| (range.start, Reverse(range.end)));
1361 log::info!("highlighting ranges {:?}", highlight_ranges);
1362 let highlight_ranges = highlight_ranges
1363 .into_iter()
1364 .map(|range| {
1365 buffer_snapshot.anchor_before(range.start)..buffer_snapshot.anchor_after(range.end)
1366 })
1367 .collect::<Vec<_>>();
1368
1369 highlights.insert(
1370 Some(TypeId::of::<()>()),
1371 Arc::new((HighlightStyle::default(), highlight_ranges)),
1372 );
1373
1374 let mut next_inlay_id = 0;
1375 for _ in 0..operations {
1376 log::info!("text: {:?}", buffer_snapshot.text());
1377 let mut buffer_edits = Vec::new();
1378 let mut inlay_edits = Vec::new();
1379 match rng.gen_range(0..=100) {
1380 0..=39 => {
1381 snapshot_edits.extend(map.randomly_mutate(&mut rng));
1382 }
1383 40..=59 => {
1384 let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1385 inlay_edits = edits;
1386 }
1387 _ => buffer.update(cx, |buffer, cx| {
1388 let subscription = buffer.subscribe();
1389 let edit_count = rng.gen_range(1..=5);
1390 buffer.randomly_mutate(&mut rng, edit_count, cx);
1391 buffer_snapshot = buffer.snapshot(cx);
1392 let edits = subscription.consume().into_inner();
1393 log::info!("editing {:?}", edits);
1394 buffer_edits.extend(edits);
1395 }),
1396 };
1397
1398 let (inlay_snapshot, new_inlay_edits) =
1399 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1400 log::info!("inlay text {:?}", inlay_snapshot.text());
1401
1402 let inlay_edits = Patch::new(inlay_edits)
1403 .compose(new_inlay_edits)
1404 .into_inner();
1405 let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
1406 snapshot_edits.push((snapshot.clone(), edits));
1407
1408 let mut expected_text: String = inlay_snapshot.text().to_string();
1409 for fold_range in map.merged_fold_ranges().into_iter().rev() {
1410 let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
1411 let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
1412 expected_text.replace_range(fold_inlay_start.0..fold_inlay_end.0, "⋯");
1413 }
1414
1415 assert_eq!(snapshot.text(), expected_text);
1416 log::info!(
1417 "fold text {:?} ({} lines)",
1418 expected_text,
1419 expected_text.matches('\n').count() + 1
1420 );
1421
1422 let mut prev_row = 0;
1423 let mut expected_buffer_rows = Vec::new();
1424 for fold_range in map.merged_fold_ranges().into_iter() {
1425 let fold_start = inlay_snapshot
1426 .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
1427 .row();
1428 let fold_end = inlay_snapshot
1429 .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
1430 .row();
1431 expected_buffer_rows.extend(
1432 inlay_snapshot
1433 .buffer_rows(prev_row)
1434 .take((1 + fold_start - prev_row) as usize),
1435 );
1436 prev_row = 1 + fold_end;
1437 }
1438 expected_buffer_rows.extend(inlay_snapshot.buffer_rows(prev_row));
1439
1440 assert_eq!(
1441 expected_buffer_rows.len(),
1442 expected_text.matches('\n').count() + 1,
1443 "wrong expected buffer rows {:?}. text: {:?}",
1444 expected_buffer_rows,
1445 expected_text
1446 );
1447
1448 for (output_row, line) in expected_text.lines().enumerate() {
1449 let line_len = snapshot.line_len(output_row as u32);
1450 assert_eq!(line_len, line.len() as u32);
1451 }
1452
1453 let longest_row = snapshot.longest_row();
1454 let longest_char_column = expected_text
1455 .split('\n')
1456 .nth(longest_row as usize)
1457 .unwrap()
1458 .chars()
1459 .count();
1460 let mut fold_point = FoldPoint::new(0, 0);
1461 let mut fold_offset = FoldOffset(0);
1462 let mut char_column = 0;
1463 for c in expected_text.chars() {
1464 let inlay_point = fold_point.to_inlay_point(&snapshot);
1465 let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
1466 assert_eq!(
1467 snapshot.to_fold_point(inlay_point, Right),
1468 fold_point,
1469 "{:?} -> fold point",
1470 inlay_point,
1471 );
1472 assert_eq!(
1473 inlay_snapshot.to_offset(inlay_point),
1474 inlay_offset,
1475 "inlay_snapshot.to_offset({:?})",
1476 inlay_point,
1477 );
1478 assert_eq!(
1479 fold_point.to_offset(&snapshot),
1480 fold_offset,
1481 "fold_point.to_offset({:?})",
1482 fold_point,
1483 );
1484
1485 if c == '\n' {
1486 *fold_point.row_mut() += 1;
1487 *fold_point.column_mut() = 0;
1488 char_column = 0;
1489 } else {
1490 *fold_point.column_mut() += c.len_utf8() as u32;
1491 char_column += 1;
1492 }
1493 fold_offset.0 += c.len_utf8();
1494 if char_column > longest_char_column {
1495 panic!(
1496 "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
1497 longest_row,
1498 longest_char_column,
1499 fold_point.row(),
1500 char_column
1501 );
1502 }
1503 }
1504
1505 for _ in 0..5 {
1506 let mut start = snapshot
1507 .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Left);
1508 let mut end = snapshot
1509 .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Right);
1510 if start > end {
1511 mem::swap(&mut start, &mut end);
1512 }
1513
1514 let text = &expected_text[start.0..end.0];
1515 assert_eq!(
1516 snapshot
1517 .chunks(start..end, false, Some(&highlights), None)
1518 .map(|c| c.text)
1519 .collect::<String>(),
1520 text,
1521 );
1522 }
1523
1524 let mut fold_row = 0;
1525 while fold_row < expected_buffer_rows.len() as u32 {
1526 assert_eq!(
1527 snapshot.buffer_rows(fold_row).collect::<Vec<_>>(),
1528 expected_buffer_rows[(fold_row as usize)..],
1529 "wrong buffer rows starting at fold row {}",
1530 fold_row,
1531 );
1532 fold_row += 1;
1533 }
1534
1535 let folded_buffer_rows = map
1536 .merged_fold_ranges()
1537 .iter()
1538 .flat_map(|range| {
1539 let start_row = range.start.to_point(&buffer_snapshot).row;
1540 let end = range.end.to_point(&buffer_snapshot);
1541 if end.column == 0 {
1542 start_row..end.row
1543 } else {
1544 start_row..end.row + 1
1545 }
1546 })
1547 .collect::<HashSet<_>>();
1548 for row in 0..=buffer_snapshot.max_point().row {
1549 assert_eq!(
1550 snapshot.is_line_folded(row),
1551 folded_buffer_rows.contains(&row),
1552 "expected buffer row {}{} to be folded",
1553 row,
1554 if folded_buffer_rows.contains(&row) {
1555 ""
1556 } else {
1557 " not"
1558 }
1559 );
1560 }
1561
1562 for _ in 0..5 {
1563 let end =
1564 buffer_snapshot.clip_offset(rng.gen_range(0..=buffer_snapshot.len()), Right);
1565 let start = buffer_snapshot.clip_offset(rng.gen_range(0..=end), Left);
1566 let expected_folds = map
1567 .snapshot
1568 .folds
1569 .items(&buffer_snapshot)
1570 .into_iter()
1571 .filter(|fold| {
1572 let start = buffer_snapshot.anchor_before(start);
1573 let end = buffer_snapshot.anchor_after(end);
1574 start.cmp(&fold.0.end, &buffer_snapshot) == Ordering::Less
1575 && end.cmp(&fold.0.start, &buffer_snapshot) == Ordering::Greater
1576 })
1577 .map(|fold| fold.0)
1578 .collect::<Vec<_>>();
1579
1580 assert_eq!(
1581 snapshot
1582 .folds_in_range(start..end)
1583 .cloned()
1584 .collect::<Vec<_>>(),
1585 expected_folds
1586 );
1587 }
1588
1589 let text = snapshot.text();
1590 for _ in 0..5 {
1591 let start_row = rng.gen_range(0..=snapshot.max_point().row());
1592 let start_column = rng.gen_range(0..=snapshot.line_len(start_row));
1593 let end_row = rng.gen_range(0..=snapshot.max_point().row());
1594 let end_column = rng.gen_range(0..=snapshot.line_len(end_row));
1595 let mut start =
1596 snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
1597 let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
1598 if start > end {
1599 mem::swap(&mut start, &mut end);
1600 }
1601
1602 let lines = start..end;
1603 let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
1604 assert_eq!(
1605 snapshot.text_summary_for_range(lines),
1606 TextSummary::from(&text[bytes.start.0..bytes.end.0])
1607 )
1608 }
1609
1610 let mut text = initial_snapshot.text();
1611 for (snapshot, edits) in snapshot_edits.drain(..) {
1612 let new_text = snapshot.text();
1613 for edit in edits {
1614 let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
1615 let new_bytes = edit.new.start.0..edit.new.end.0;
1616 text.replace_range(old_bytes, &new_text[new_bytes]);
1617 }
1618
1619 assert_eq!(text, new_text);
1620 initial_snapshot = snapshot;
1621 }
1622 }
1623 }
1624
1625 #[gpui::test]
1626 fn test_buffer_rows(cx: &mut gpui::AppContext) {
1627 let text = sample_text(6, 6, 'a') + "\n";
1628 let buffer = MultiBuffer::build_simple(&text, cx);
1629
1630 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1631 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1632 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1633
1634 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1635 writer.fold(vec![
1636 Point::new(0, 2)..Point::new(2, 2),
1637 Point::new(3, 1)..Point::new(4, 1),
1638 ]);
1639
1640 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1641 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
1642 assert_eq!(
1643 snapshot.buffer_rows(0).collect::<Vec<_>>(),
1644 [Some(0), Some(3), Some(5), Some(6)]
1645 );
1646 assert_eq!(snapshot.buffer_rows(3).collect::<Vec<_>>(), [Some(6)]);
1647 }
1648
1649 fn init_test(cx: &mut gpui::AppContext) {
1650 cx.set_global(SettingsStore::test(cx));
1651 }
1652
1653 impl FoldMap {
1654 fn merged_fold_ranges(&self) -> Vec<Range<usize>> {
1655 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1656 let buffer = &inlay_snapshot.buffer;
1657 let mut folds = self.snapshot.folds.items(buffer);
1658 // Ensure sorting doesn't change how folds get merged and displayed.
1659 folds.sort_by(|a, b| a.0.cmp(&b.0, buffer));
1660 let mut fold_ranges = folds
1661 .iter()
1662 .map(|fold| fold.0.start.to_offset(buffer)..fold.0.end.to_offset(buffer))
1663 .peekable();
1664
1665 let mut merged_ranges = Vec::new();
1666 while let Some(mut fold_range) = fold_ranges.next() {
1667 while let Some(next_range) = fold_ranges.peek() {
1668 if fold_range.end >= next_range.start {
1669 if next_range.end > fold_range.end {
1670 fold_range.end = next_range.end;
1671 }
1672 fold_ranges.next();
1673 } else {
1674 break;
1675 }
1676 }
1677 if fold_range.end > fold_range.start {
1678 merged_ranges.push(fold_range);
1679 }
1680 }
1681 merged_ranges
1682 }
1683
1684 pub fn randomly_mutate(
1685 &mut self,
1686 rng: &mut impl Rng,
1687 ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
1688 let mut snapshot_edits = Vec::new();
1689 match rng.gen_range(0..=100) {
1690 0..=39 if !self.snapshot.folds.is_empty() => {
1691 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1692 let buffer = &inlay_snapshot.buffer;
1693 let mut to_unfold = Vec::new();
1694 for _ in 0..rng.gen_range(1..=3) {
1695 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1696 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1697 to_unfold.push(start..end);
1698 }
1699 log::info!("unfolding {:?}", to_unfold);
1700 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
1701 snapshot_edits.push((snapshot, edits));
1702 let (snapshot, edits) = writer.fold(to_unfold);
1703 snapshot_edits.push((snapshot, edits));
1704 }
1705 _ => {
1706 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1707 let buffer = &inlay_snapshot.buffer;
1708 let mut to_fold = Vec::new();
1709 for _ in 0..rng.gen_range(1..=2) {
1710 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1711 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1712 to_fold.push(start..end);
1713 }
1714 log::info!("folding {:?}", to_fold);
1715 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
1716 snapshot_edits.push((snapshot, edits));
1717 let (snapshot, edits) = writer.fold(to_fold);
1718 snapshot_edits.push((snapshot, edits));
1719 }
1720 }
1721 snapshot_edits
1722 }
1723 }
1724}