1use super::{
2 inlay_map::{InlayBufferRows, InlayChunks, InlayEdit, InlayOffset, InlayPoint, InlaySnapshot},
3 Highlights,
4};
5use gpui::{ElementId, HighlightStyle, Hsla};
6use language::{Chunk, Edit, Point, TextSummary};
7use multi_buffer::{Anchor, AnchorRangeExt, MultiBufferRow, MultiBufferSnapshot, ToOffset};
8use std::{
9 cmp::{self, Ordering},
10 iter,
11 ops::{Add, AddAssign, Deref, DerefMut, Range, Sub},
12};
13use sum_tree::{Bias, Cursor, FilterCursor, SumTree};
14use util::post_inc;
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(crate) struct FoldMapWriter<'a>(&'a mut FoldMap);
74
75impl<'a> FoldMapWriter<'a> {
76 pub(crate) 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_range =
94 FoldRange(buffer.anchor_after(range.start)..buffer.anchor_before(range.end));
95 if fold_range.0.start.excerpt_id != fold_range.0.end.excerpt_id {
96 continue;
97 }
98
99 folds.push(Fold {
100 id: FoldId(post_inc(&mut self.0.next_fold_id.0)),
101 range: fold_range,
102 });
103
104 let inlay_range =
105 snapshot.to_inlay_offset(range.start)..snapshot.to_inlay_offset(range.end);
106 edits.push(InlayEdit {
107 old: inlay_range.clone(),
108 new: inlay_range,
109 });
110 }
111
112 let buffer = &snapshot.buffer;
113 folds.sort_unstable_by(|a, b| sum_tree::SeekTarget::cmp(&a.range, &b.range, buffer));
114
115 self.0.snapshot.folds = {
116 let mut new_tree = SumTree::new();
117 let mut cursor = self.0.snapshot.folds.cursor::<FoldRange>();
118 for fold in folds {
119 new_tree.append(cursor.slice(&fold.range, Bias::Right, buffer), buffer);
120 new_tree.push(fold, buffer);
121 }
122 new_tree.append(cursor.suffix(buffer), buffer);
123 new_tree
124 };
125
126 consolidate_inlay_edits(&mut edits);
127 let edits = self.0.sync(snapshot.clone(), edits);
128 (self.0.snapshot.clone(), edits)
129 }
130
131 pub(crate) fn unfold<T: ToOffset>(
132 &mut self,
133 ranges: impl IntoIterator<Item = Range<T>>,
134 inclusive: bool,
135 ) -> (FoldSnapshot, Vec<FoldEdit>) {
136 let mut edits = Vec::new();
137 let mut fold_ixs_to_delete = Vec::new();
138 let snapshot = self.0.snapshot.inlay_snapshot.clone();
139 let buffer = &snapshot.buffer;
140 for range in ranges.into_iter() {
141 // Remove intersecting folds and add their ranges to edits that are passed to sync.
142 let mut folds_cursor =
143 intersecting_folds(&snapshot, &self.0.snapshot.folds, range, inclusive);
144 while let Some(fold) = folds_cursor.item() {
145 let offset_range =
146 fold.range.start.to_offset(buffer)..fold.range.end.to_offset(buffer);
147 if offset_range.end > offset_range.start {
148 let inlay_range = snapshot.to_inlay_offset(offset_range.start)
149 ..snapshot.to_inlay_offset(offset_range.end);
150 edits.push(InlayEdit {
151 old: inlay_range.clone(),
152 new: inlay_range,
153 });
154 }
155 fold_ixs_to_delete.push(*folds_cursor.start());
156 folds_cursor.next(buffer);
157 }
158 }
159
160 fold_ixs_to_delete.sort_unstable();
161 fold_ixs_to_delete.dedup();
162
163 self.0.snapshot.folds = {
164 let mut cursor = self.0.snapshot.folds.cursor::<usize>();
165 let mut folds = SumTree::new();
166 for fold_ix in fold_ixs_to_delete {
167 folds.append(cursor.slice(&fold_ix, Bias::Right, buffer), buffer);
168 cursor.next(buffer);
169 }
170 folds.append(cursor.suffix(buffer), buffer);
171 folds
172 };
173
174 consolidate_inlay_edits(&mut edits);
175 let edits = self.0.sync(snapshot.clone(), edits);
176 (self.0.snapshot.clone(), edits)
177 }
178}
179
180/// Decides where the fold indicators should be; also tracks parts of a source file that are currently folded.
181///
182/// See the [`display_map` module documentation](crate::display_map) for more information.
183pub(crate) struct FoldMap {
184 snapshot: FoldSnapshot,
185 ellipses_color: Option<Hsla>,
186 next_fold_id: FoldId,
187}
188
189impl FoldMap {
190 pub(crate) fn new(inlay_snapshot: InlaySnapshot) -> (Self, FoldSnapshot) {
191 let this = Self {
192 snapshot: FoldSnapshot {
193 folds: Default::default(),
194 transforms: SumTree::from_item(
195 Transform {
196 summary: TransformSummary {
197 input: inlay_snapshot.text_summary(),
198 output: inlay_snapshot.text_summary(),
199 },
200 output_text: None,
201 },
202 &(),
203 ),
204 inlay_snapshot: inlay_snapshot.clone(),
205 version: 0,
206 ellipses_color: None,
207 },
208 ellipses_color: None,
209 next_fold_id: FoldId::default(),
210 };
211 let snapshot = this.snapshot.clone();
212 (this, snapshot)
213 }
214
215 pub fn read(
216 &mut self,
217 inlay_snapshot: InlaySnapshot,
218 edits: Vec<InlayEdit>,
219 ) -> (FoldSnapshot, Vec<FoldEdit>) {
220 let edits = self.sync(inlay_snapshot, edits);
221 self.check_invariants();
222 (self.snapshot.clone(), edits)
223 }
224
225 pub fn write(
226 &mut self,
227 inlay_snapshot: InlaySnapshot,
228 edits: Vec<InlayEdit>,
229 ) -> (FoldMapWriter, FoldSnapshot, Vec<FoldEdit>) {
230 let (snapshot, edits) = self.read(inlay_snapshot, edits);
231 (FoldMapWriter(self), snapshot, edits)
232 }
233
234 pub fn set_ellipses_color(&mut self, color: Hsla) -> bool {
235 if self.ellipses_color == Some(color) {
236 false
237 } else {
238 self.ellipses_color = Some(color);
239 true
240 }
241 }
242
243 fn check_invariants(&self) {
244 if cfg!(test) {
245 assert_eq!(
246 self.snapshot.transforms.summary().input.len,
247 self.snapshot.inlay_snapshot.len().0,
248 "transform tree does not match inlay snapshot's length"
249 );
250
251 let mut folds = self.snapshot.folds.iter().peekable();
252 while let Some(fold) = folds.next() {
253 if let Some(next_fold) = folds.peek() {
254 let comparison = fold
255 .range
256 .cmp(&next_fold.range, &self.snapshot.inlay_snapshot.buffer);
257 assert!(comparison.is_le());
258 }
259 }
260 }
261 }
262
263 fn sync(
264 &mut self,
265 inlay_snapshot: InlaySnapshot,
266 inlay_edits: Vec<InlayEdit>,
267 ) -> Vec<FoldEdit> {
268 if inlay_edits.is_empty() {
269 if self.snapshot.inlay_snapshot.version != inlay_snapshot.version {
270 self.snapshot.version += 1;
271 }
272 self.snapshot.inlay_snapshot = inlay_snapshot;
273 Vec::new()
274 } else {
275 let mut inlay_edits_iter = inlay_edits.iter().cloned().peekable();
276
277 let mut new_transforms = SumTree::new();
278 let mut cursor = self.snapshot.transforms.cursor::<InlayOffset>();
279 cursor.seek(&InlayOffset(0), Bias::Right, &());
280
281 while let Some(mut edit) = inlay_edits_iter.next() {
282 new_transforms.append(cursor.slice(&edit.old.start, Bias::Left, &()), &());
283 edit.new.start -= edit.old.start - *cursor.start();
284 edit.old.start = *cursor.start();
285
286 cursor.seek(&edit.old.end, Bias::Right, &());
287 cursor.next(&());
288
289 let mut delta = edit.new_len().0 as isize - edit.old_len().0 as isize;
290 loop {
291 edit.old.end = *cursor.start();
292
293 if let Some(next_edit) = inlay_edits_iter.peek() {
294 if next_edit.old.start > edit.old.end {
295 break;
296 }
297
298 let next_edit = inlay_edits_iter.next().unwrap();
299 delta += next_edit.new_len().0 as isize - next_edit.old_len().0 as isize;
300
301 if next_edit.old.end >= edit.old.end {
302 edit.old.end = next_edit.old.end;
303 cursor.seek(&edit.old.end, Bias::Right, &());
304 cursor.next(&());
305 }
306 } else {
307 break;
308 }
309 }
310
311 edit.new.end =
312 InlayOffset(((edit.new.start + edit.old_len()).0 as isize + delta) as usize);
313
314 let anchor = inlay_snapshot
315 .buffer
316 .anchor_before(inlay_snapshot.to_buffer_offset(edit.new.start));
317 let mut folds_cursor = self.snapshot.folds.cursor::<FoldRange>();
318 folds_cursor.seek(
319 &FoldRange(anchor..Anchor::max()),
320 Bias::Left,
321 &inlay_snapshot.buffer,
322 );
323
324 let mut folds = iter::from_fn({
325 let inlay_snapshot = &inlay_snapshot;
326 move || {
327 let item = folds_cursor.item().map(|f| {
328 let buffer_start = f.range.start.to_offset(&inlay_snapshot.buffer);
329 let buffer_end = f.range.end.to_offset(&inlay_snapshot.buffer);
330 inlay_snapshot.to_inlay_offset(buffer_start)
331 ..inlay_snapshot.to_inlay_offset(buffer_end)
332 });
333 folds_cursor.next(&inlay_snapshot.buffer);
334 item
335 }
336 })
337 .peekable();
338
339 while folds.peek().map_or(false, |fold| fold.start < edit.new.end) {
340 let mut fold = folds.next().unwrap();
341 let sum = new_transforms.summary();
342
343 assert!(fold.start.0 >= sum.input.len);
344
345 while folds
346 .peek()
347 .map_or(false, |next_fold| next_fold.start <= fold.end)
348 {
349 let next_fold = folds.next().unwrap();
350 if next_fold.end > fold.end {
351 fold.end = next_fold.end;
352 }
353 }
354
355 if fold.start.0 > sum.input.len {
356 let text_summary = inlay_snapshot
357 .text_summary_for_range(InlayOffset(sum.input.len)..fold.start);
358 new_transforms.push(
359 Transform {
360 summary: TransformSummary {
361 output: text_summary.clone(),
362 input: text_summary,
363 },
364 output_text: None,
365 },
366 &(),
367 );
368 }
369
370 if fold.end > fold.start {
371 let output_text = "⋯";
372 new_transforms.push(
373 Transform {
374 summary: TransformSummary {
375 output: TextSummary::from(output_text),
376 input: inlay_snapshot
377 .text_summary_for_range(fold.start..fold.end),
378 },
379 output_text: Some(output_text),
380 },
381 &(),
382 );
383 }
384 }
385
386 let sum = new_transforms.summary();
387 if sum.input.len < edit.new.end.0 {
388 let text_summary = inlay_snapshot
389 .text_summary_for_range(InlayOffset(sum.input.len)..edit.new.end);
390 new_transforms.push(
391 Transform {
392 summary: TransformSummary {
393 output: text_summary.clone(),
394 input: text_summary,
395 },
396 output_text: None,
397 },
398 &(),
399 );
400 }
401 }
402
403 new_transforms.append(cursor.suffix(&()), &());
404 if new_transforms.is_empty() {
405 let text_summary = inlay_snapshot.text_summary();
406 new_transforms.push(
407 Transform {
408 summary: TransformSummary {
409 output: text_summary.clone(),
410 input: text_summary,
411 },
412 output_text: None,
413 },
414 &(),
415 );
416 }
417
418 drop(cursor);
419
420 let mut fold_edits = Vec::with_capacity(inlay_edits.len());
421 {
422 let mut old_transforms = self
423 .snapshot
424 .transforms
425 .cursor::<(InlayOffset, FoldOffset)>();
426 let mut new_transforms = new_transforms.cursor::<(InlayOffset, FoldOffset)>();
427
428 for mut edit in inlay_edits {
429 old_transforms.seek(&edit.old.start, Bias::Left, &());
430 if old_transforms.item().map_or(false, |t| t.is_fold()) {
431 edit.old.start = old_transforms.start().0;
432 }
433 let old_start =
434 old_transforms.start().1 .0 + (edit.old.start - old_transforms.start().0).0;
435
436 old_transforms.seek_forward(&edit.old.end, Bias::Right, &());
437 if old_transforms.item().map_or(false, |t| t.is_fold()) {
438 old_transforms.next(&());
439 edit.old.end = old_transforms.start().0;
440 }
441 let old_end =
442 old_transforms.start().1 .0 + (edit.old.end - old_transforms.start().0).0;
443
444 new_transforms.seek(&edit.new.start, Bias::Left, &());
445 if new_transforms.item().map_or(false, |t| t.is_fold()) {
446 edit.new.start = new_transforms.start().0;
447 }
448 let new_start =
449 new_transforms.start().1 .0 + (edit.new.start - new_transforms.start().0).0;
450
451 new_transforms.seek_forward(&edit.new.end, Bias::Right, &());
452 if new_transforms.item().map_or(false, |t| t.is_fold()) {
453 new_transforms.next(&());
454 edit.new.end = new_transforms.start().0;
455 }
456 let new_end =
457 new_transforms.start().1 .0 + (edit.new.end - new_transforms.start().0).0;
458
459 fold_edits.push(FoldEdit {
460 old: FoldOffset(old_start)..FoldOffset(old_end),
461 new: FoldOffset(new_start)..FoldOffset(new_end),
462 });
463 }
464
465 consolidate_fold_edits(&mut fold_edits);
466 }
467
468 self.snapshot.transforms = new_transforms;
469 self.snapshot.inlay_snapshot = inlay_snapshot;
470 self.snapshot.version += 1;
471 fold_edits
472 }
473 }
474}
475
476#[derive(Clone)]
477pub struct FoldSnapshot {
478 transforms: SumTree<Transform>,
479 folds: SumTree<Fold>,
480 pub inlay_snapshot: InlaySnapshot,
481 pub version: usize,
482 pub ellipses_color: Option<Hsla>,
483}
484
485impl FoldSnapshot {
486 #[cfg(test)]
487 pub fn text(&self) -> String {
488 self.chunks(FoldOffset(0)..self.len(), false, Highlights::default())
489 .map(|c| c.text)
490 .collect()
491 }
492
493 #[cfg(test)]
494 pub fn fold_count(&self) -> usize {
495 self.folds.items(&self.inlay_snapshot.buffer).len()
496 }
497
498 pub fn text_summary_for_range(&self, range: Range<FoldPoint>) -> TextSummary {
499 let mut summary = TextSummary::default();
500
501 let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
502 cursor.seek(&range.start, Bias::Right, &());
503 if let Some(transform) = cursor.item() {
504 let start_in_transform = range.start.0 - cursor.start().0 .0;
505 let end_in_transform = cmp::min(range.end, cursor.end(&()).0).0 - cursor.start().0 .0;
506 if let Some(output_text) = transform.output_text {
507 summary = TextSummary::from(
508 &output_text
509 [start_in_transform.column as usize..end_in_transform.column as usize],
510 );
511 } else {
512 let inlay_start = self
513 .inlay_snapshot
514 .to_offset(InlayPoint(cursor.start().1 .0 + start_in_transform));
515 let inlay_end = self
516 .inlay_snapshot
517 .to_offset(InlayPoint(cursor.start().1 .0 + end_in_transform));
518 summary = self
519 .inlay_snapshot
520 .text_summary_for_range(inlay_start..inlay_end);
521 }
522 }
523
524 if range.end > cursor.end(&()).0 {
525 cursor.next(&());
526 summary += &cursor
527 .summary::<_, TransformSummary>(&range.end, Bias::Right, &())
528 .output;
529 if let Some(transform) = cursor.item() {
530 let end_in_transform = range.end.0 - cursor.start().0 .0;
531 if let Some(output_text) = transform.output_text {
532 summary += TextSummary::from(&output_text[..end_in_transform.column as usize]);
533 } else {
534 let inlay_start = self.inlay_snapshot.to_offset(cursor.start().1);
535 let inlay_end = self
536 .inlay_snapshot
537 .to_offset(InlayPoint(cursor.start().1 .0 + end_in_transform));
538 summary += self
539 .inlay_snapshot
540 .text_summary_for_range(inlay_start..inlay_end);
541 }
542 }
543 }
544
545 summary
546 }
547
548 pub fn to_fold_point(&self, point: InlayPoint, bias: Bias) -> FoldPoint {
549 let mut cursor = self.transforms.cursor::<(InlayPoint, FoldPoint)>();
550 cursor.seek(&point, Bias::Right, &());
551 if cursor.item().map_or(false, |t| t.is_fold()) {
552 if bias == Bias::Left || point == cursor.start().0 {
553 cursor.start().1
554 } else {
555 cursor.end(&()).1
556 }
557 } else {
558 let overshoot = point.0 - cursor.start().0 .0;
559 FoldPoint(cmp::min(
560 cursor.start().1 .0 + overshoot,
561 cursor.end(&()).1 .0,
562 ))
563 }
564 }
565
566 pub fn len(&self) -> FoldOffset {
567 FoldOffset(self.transforms.summary().output.len)
568 }
569
570 pub fn line_len(&self, row: u32) -> u32 {
571 let line_start = FoldPoint::new(row, 0).to_offset(self).0;
572 let line_end = if row >= self.max_point().row() {
573 self.len().0
574 } else {
575 FoldPoint::new(row + 1, 0).to_offset(self).0 - 1
576 };
577 (line_end - line_start) as u32
578 }
579
580 pub fn buffer_rows(&self, start_row: u32) -> FoldBufferRows {
581 if start_row > self.transforms.summary().output.lines.row {
582 panic!("invalid display row {}", start_row);
583 }
584
585 let fold_point = FoldPoint::new(start_row, 0);
586 let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
587 cursor.seek(&fold_point, Bias::Left, &());
588
589 let overshoot = fold_point.0 - cursor.start().0 .0;
590 let inlay_point = InlayPoint(cursor.start().1 .0 + overshoot);
591 let input_buffer_rows = self.inlay_snapshot.buffer_rows(inlay_point.row());
592
593 FoldBufferRows {
594 fold_point,
595 input_buffer_rows,
596 cursor,
597 }
598 }
599
600 pub fn max_point(&self) -> FoldPoint {
601 FoldPoint(self.transforms.summary().output.lines)
602 }
603
604 #[cfg(test)]
605 pub fn longest_row(&self) -> u32 {
606 self.transforms.summary().output.longest_row
607 }
608
609 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Fold>
610 where
611 T: ToOffset,
612 {
613 let mut folds = intersecting_folds(&self.inlay_snapshot, &self.folds, range, false);
614 iter::from_fn(move || {
615 let item = folds.item();
616 folds.next(&self.inlay_snapshot.buffer);
617 item
618 })
619 }
620
621 pub fn intersects_fold<T>(&self, offset: T) -> bool
622 where
623 T: ToOffset,
624 {
625 let buffer_offset = offset.to_offset(&self.inlay_snapshot.buffer);
626 let inlay_offset = self.inlay_snapshot.to_inlay_offset(buffer_offset);
627 let mut cursor = self.transforms.cursor::<InlayOffset>();
628 cursor.seek(&inlay_offset, Bias::Right, &());
629 cursor.item().map_or(false, |t| t.output_text.is_some())
630 }
631
632 pub fn is_line_folded(&self, buffer_row: MultiBufferRow) -> bool {
633 let mut inlay_point = self
634 .inlay_snapshot
635 .to_inlay_point(Point::new(buffer_row.0, 0));
636 let mut cursor = self.transforms.cursor::<InlayPoint>();
637 cursor.seek(&inlay_point, Bias::Right, &());
638 loop {
639 match cursor.item() {
640 Some(transform) => {
641 let buffer_point = self.inlay_snapshot.to_buffer_point(inlay_point);
642 if buffer_point.row != buffer_row.0 {
643 return false;
644 } else if transform.output_text.is_some() {
645 return true;
646 }
647 }
648 None => return false,
649 }
650
651 if cursor.end(&()).row() == inlay_point.row() {
652 cursor.next(&());
653 } else {
654 inlay_point.0 += Point::new(1, 0);
655 cursor.seek(&inlay_point, Bias::Right, &());
656 }
657 }
658 }
659
660 pub(crate) fn chunks<'a>(
661 &'a self,
662 range: Range<FoldOffset>,
663 language_aware: bool,
664 highlights: Highlights<'a>,
665 ) -> FoldChunks<'a> {
666 let mut transform_cursor = self.transforms.cursor::<(FoldOffset, InlayOffset)>();
667
668 let inlay_end = {
669 transform_cursor.seek(&range.end, Bias::Right, &());
670 let overshoot = range.end.0 - transform_cursor.start().0 .0;
671 transform_cursor.start().1 + InlayOffset(overshoot)
672 };
673
674 let inlay_start = {
675 transform_cursor.seek(&range.start, Bias::Right, &());
676 let overshoot = range.start.0 - transform_cursor.start().0 .0;
677 transform_cursor.start().1 + InlayOffset(overshoot)
678 };
679
680 FoldChunks {
681 transform_cursor,
682 inlay_chunks: self.inlay_snapshot.chunks(
683 inlay_start..inlay_end,
684 language_aware,
685 highlights,
686 ),
687 inlay_chunk: None,
688 inlay_offset: inlay_start,
689 output_offset: range.start.0,
690 max_output_offset: range.end.0,
691 ellipses_color: self.ellipses_color,
692 }
693 }
694
695 pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
696 self.chunks(
697 start.to_offset(self)..self.len(),
698 false,
699 Highlights::default(),
700 )
701 .flat_map(|chunk| chunk.text.chars())
702 }
703
704 #[cfg(test)]
705 pub fn clip_offset(&self, offset: FoldOffset, bias: Bias) -> FoldOffset {
706 if offset > self.len() {
707 self.len()
708 } else {
709 self.clip_point(offset.to_point(self), bias).to_offset(self)
710 }
711 }
712
713 pub fn clip_point(&self, point: FoldPoint, bias: Bias) -> FoldPoint {
714 let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
715 cursor.seek(&point, Bias::Right, &());
716 if let Some(transform) = cursor.item() {
717 let transform_start = cursor.start().0 .0;
718 if transform.output_text.is_some() {
719 if point.0 == transform_start || matches!(bias, Bias::Left) {
720 FoldPoint(transform_start)
721 } else {
722 FoldPoint(cursor.end(&()).0 .0)
723 }
724 } else {
725 let overshoot = InlayPoint(point.0 - transform_start);
726 let inlay_point = cursor.start().1 + overshoot;
727 let clipped_inlay_point = self.inlay_snapshot.clip_point(inlay_point, bias);
728 FoldPoint(cursor.start().0 .0 + (clipped_inlay_point - cursor.start().1).0)
729 }
730 } else {
731 FoldPoint(self.transforms.summary().output.lines)
732 }
733 }
734}
735
736fn intersecting_folds<'a, T>(
737 inlay_snapshot: &'a InlaySnapshot,
738 folds: &'a SumTree<Fold>,
739 range: Range<T>,
740 inclusive: bool,
741) -> FilterCursor<'a, impl 'a + FnMut(&FoldSummary) -> bool, Fold, usize>
742where
743 T: ToOffset,
744{
745 let buffer = &inlay_snapshot.buffer;
746 let start = buffer.anchor_before(range.start.to_offset(buffer));
747 let end = buffer.anchor_after(range.end.to_offset(buffer));
748 let mut cursor = folds.filter::<_, usize>(move |summary| {
749 let start_cmp = start.cmp(&summary.max_end, buffer);
750 let end_cmp = end.cmp(&summary.min_start, buffer);
751
752 if inclusive {
753 start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
754 } else {
755 start_cmp == Ordering::Less && end_cmp == Ordering::Greater
756 }
757 });
758 cursor.next(buffer);
759 cursor
760}
761
762fn consolidate_inlay_edits(edits: &mut Vec<InlayEdit>) {
763 edits.sort_unstable_by(|a, b| {
764 a.old
765 .start
766 .cmp(&b.old.start)
767 .then_with(|| b.old.end.cmp(&a.old.end))
768 });
769
770 let mut i = 1;
771 while i < edits.len() {
772 let edit = edits[i].clone();
773 let prev_edit = &mut edits[i - 1];
774 if prev_edit.old.end >= edit.old.start {
775 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
776 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
777 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
778 edits.remove(i);
779 continue;
780 }
781 i += 1;
782 }
783}
784
785fn consolidate_fold_edits(edits: &mut Vec<FoldEdit>) {
786 edits.sort_unstable_by(|a, b| {
787 a.old
788 .start
789 .cmp(&b.old.start)
790 .then_with(|| b.old.end.cmp(&a.old.end))
791 });
792
793 let mut i = 1;
794 while i < edits.len() {
795 let edit = edits[i].clone();
796 let prev_edit = &mut edits[i - 1];
797 if prev_edit.old.end >= edit.old.start {
798 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
799 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
800 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
801 edits.remove(i);
802 continue;
803 }
804 i += 1;
805 }
806}
807
808#[derive(Clone, Debug, Default, Eq, PartialEq)]
809struct Transform {
810 summary: TransformSummary,
811 output_text: Option<&'static str>,
812}
813
814impl Transform {
815 fn is_fold(&self) -> bool {
816 self.output_text.is_some()
817 }
818}
819
820#[derive(Clone, Debug, Default, Eq, PartialEq)]
821struct TransformSummary {
822 output: TextSummary,
823 input: TextSummary,
824}
825
826impl sum_tree::Item for Transform {
827 type Summary = TransformSummary;
828
829 fn summary(&self) -> Self::Summary {
830 self.summary.clone()
831 }
832}
833
834impl sum_tree::Summary for TransformSummary {
835 type Context = ();
836
837 fn add_summary(&mut self, other: &Self, _: &()) {
838 self.input += &other.input;
839 self.output += &other.output;
840 }
841}
842
843#[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
844pub struct FoldId(usize);
845
846impl Into<ElementId> for FoldId {
847 fn into(self) -> ElementId {
848 ElementId::Integer(self.0)
849 }
850}
851
852#[derive(Clone, Debug, Eq, PartialEq)]
853pub struct Fold {
854 pub id: FoldId,
855 pub range: FoldRange,
856}
857
858#[derive(Clone, Debug, Eq, PartialEq)]
859pub struct FoldRange(Range<Anchor>);
860
861impl Deref for FoldRange {
862 type Target = Range<Anchor>;
863
864 fn deref(&self) -> &Self::Target {
865 &self.0
866 }
867}
868
869impl DerefMut for FoldRange {
870 fn deref_mut(&mut self) -> &mut Self::Target {
871 &mut self.0
872 }
873}
874
875impl Default for FoldRange {
876 fn default() -> Self {
877 Self(Anchor::min()..Anchor::max())
878 }
879}
880
881impl sum_tree::Item for Fold {
882 type Summary = FoldSummary;
883
884 fn summary(&self) -> Self::Summary {
885 FoldSummary {
886 start: self.range.start,
887 end: self.range.end,
888 min_start: self.range.start,
889 max_end: self.range.end,
890 count: 1,
891 }
892 }
893}
894
895#[derive(Clone, Debug)]
896pub struct FoldSummary {
897 start: Anchor,
898 end: Anchor,
899 min_start: Anchor,
900 max_end: Anchor,
901 count: usize,
902}
903
904impl Default for FoldSummary {
905 fn default() -> Self {
906 Self {
907 start: Anchor::min(),
908 end: Anchor::max(),
909 min_start: Anchor::max(),
910 max_end: Anchor::min(),
911 count: 0,
912 }
913 }
914}
915
916impl sum_tree::Summary for FoldSummary {
917 type Context = MultiBufferSnapshot;
918
919 fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
920 if other.min_start.cmp(&self.min_start, buffer) == Ordering::Less {
921 self.min_start = other.min_start;
922 }
923 if other.max_end.cmp(&self.max_end, buffer) == Ordering::Greater {
924 self.max_end = other.max_end;
925 }
926
927 #[cfg(debug_assertions)]
928 {
929 let start_comparison = self.start.cmp(&other.start, buffer);
930 assert!(start_comparison <= Ordering::Equal);
931 if start_comparison == Ordering::Equal {
932 assert!(self.end.cmp(&other.end, buffer) >= Ordering::Equal);
933 }
934 }
935
936 self.start = other.start;
937 self.end = other.end;
938 self.count += other.count;
939 }
940}
941
942impl<'a> sum_tree::Dimension<'a, FoldSummary> for FoldRange {
943 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
944 self.0.start = summary.start;
945 self.0.end = summary.end;
946 }
947}
948
949impl<'a> sum_tree::SeekTarget<'a, FoldSummary, FoldRange> for FoldRange {
950 fn cmp(&self, other: &Self, buffer: &MultiBufferSnapshot) -> Ordering {
951 self.0.cmp(&other.0, buffer)
952 }
953}
954
955impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
956 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
957 *self += summary.count;
958 }
959}
960
961#[derive(Clone)]
962pub struct FoldBufferRows<'a> {
963 cursor: Cursor<'a, Transform, (FoldPoint, InlayPoint)>,
964 input_buffer_rows: InlayBufferRows<'a>,
965 fold_point: FoldPoint,
966}
967
968impl<'a> Iterator for FoldBufferRows<'a> {
969 type Item = Option<u32>;
970
971 fn next(&mut self) -> Option<Self::Item> {
972 let mut traversed_fold = false;
973 while self.fold_point > self.cursor.end(&()).0 {
974 self.cursor.next(&());
975 traversed_fold = true;
976 if self.cursor.item().is_none() {
977 break;
978 }
979 }
980
981 if self.cursor.item().is_some() {
982 if traversed_fold {
983 self.input_buffer_rows.seek(self.cursor.start().1.row());
984 self.input_buffer_rows.next();
985 }
986 *self.fold_point.row_mut() += 1;
987 self.input_buffer_rows.next()
988 } else {
989 None
990 }
991 }
992}
993
994pub struct FoldChunks<'a> {
995 transform_cursor: Cursor<'a, Transform, (FoldOffset, InlayOffset)>,
996 inlay_chunks: InlayChunks<'a>,
997 inlay_chunk: Option<(InlayOffset, Chunk<'a>)>,
998 inlay_offset: InlayOffset,
999 output_offset: usize,
1000 max_output_offset: usize,
1001 ellipses_color: Option<Hsla>,
1002}
1003
1004impl<'a> Iterator for FoldChunks<'a> {
1005 type Item = Chunk<'a>;
1006
1007 fn next(&mut self) -> Option<Self::Item> {
1008 if self.output_offset >= self.max_output_offset {
1009 return None;
1010 }
1011
1012 let transform = self.transform_cursor.item()?;
1013
1014 // If we're in a fold, then return the fold's display text and
1015 // advance the transform and buffer cursors to the end of the fold.
1016 if let Some(output_text) = transform.output_text {
1017 self.inlay_chunk.take();
1018 self.inlay_offset += InlayOffset(transform.summary.input.len);
1019 self.inlay_chunks.seek(self.inlay_offset);
1020
1021 while self.inlay_offset >= self.transform_cursor.end(&()).1
1022 && self.transform_cursor.item().is_some()
1023 {
1024 self.transform_cursor.next(&());
1025 }
1026
1027 self.output_offset += output_text.len();
1028 return Some(Chunk {
1029 text: output_text,
1030 highlight_style: self.ellipses_color.map(|color| HighlightStyle {
1031 color: Some(color),
1032 ..Default::default()
1033 }),
1034 ..Default::default()
1035 });
1036 }
1037
1038 // Retrieve a chunk from the current location in the buffer.
1039 if self.inlay_chunk.is_none() {
1040 let chunk_offset = self.inlay_chunks.offset();
1041 self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1042 }
1043
1044 // Otherwise, take a chunk from the buffer's text.
1045 if let Some((buffer_chunk_start, mut chunk)) = self.inlay_chunk {
1046 let buffer_chunk_end = buffer_chunk_start + InlayOffset(chunk.text.len());
1047 let transform_end = self.transform_cursor.end(&()).1;
1048 let chunk_end = buffer_chunk_end.min(transform_end);
1049
1050 chunk.text = &chunk.text
1051 [(self.inlay_offset - buffer_chunk_start).0..(chunk_end - buffer_chunk_start).0];
1052
1053 if chunk_end == transform_end {
1054 self.transform_cursor.next(&());
1055 } else if chunk_end == buffer_chunk_end {
1056 self.inlay_chunk.take();
1057 }
1058
1059 self.inlay_offset = chunk_end;
1060 self.output_offset += chunk.text.len();
1061 return Some(chunk);
1062 }
1063
1064 None
1065 }
1066}
1067
1068#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1069pub struct FoldOffset(pub usize);
1070
1071impl FoldOffset {
1072 pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1073 let mut cursor = snapshot
1074 .transforms
1075 .cursor::<(FoldOffset, TransformSummary)>();
1076 cursor.seek(&self, Bias::Right, &());
1077 let overshoot = if cursor.item().map_or(true, |t| t.is_fold()) {
1078 Point::new(0, (self.0 - cursor.start().0 .0) as u32)
1079 } else {
1080 let inlay_offset = cursor.start().1.input.len + self.0 - cursor.start().0 .0;
1081 let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1082 inlay_point.0 - cursor.start().1.input.lines
1083 };
1084 FoldPoint(cursor.start().1.output.lines + overshoot)
1085 }
1086
1087 #[cfg(test)]
1088 pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1089 let mut cursor = snapshot.transforms.cursor::<(FoldOffset, InlayOffset)>();
1090 cursor.seek(&self, Bias::Right, &());
1091 let overshoot = self.0 - cursor.start().0 .0;
1092 InlayOffset(cursor.start().1 .0 + overshoot)
1093 }
1094}
1095
1096impl Add for FoldOffset {
1097 type Output = Self;
1098
1099 fn add(self, rhs: Self) -> Self::Output {
1100 Self(self.0 + rhs.0)
1101 }
1102}
1103
1104impl AddAssign for FoldOffset {
1105 fn add_assign(&mut self, rhs: Self) {
1106 self.0 += rhs.0;
1107 }
1108}
1109
1110impl Sub for FoldOffset {
1111 type Output = Self;
1112
1113 fn sub(self, rhs: Self) -> Self::Output {
1114 Self(self.0 - rhs.0)
1115 }
1116}
1117
1118impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1119 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1120 self.0 += &summary.output.len;
1121 }
1122}
1123
1124impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1125 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1126 self.0 += &summary.input.lines;
1127 }
1128}
1129
1130impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1131 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1132 self.0 += &summary.input.len;
1133 }
1134}
1135
1136pub type FoldEdit = Edit<FoldOffset>;
1137
1138#[cfg(test)]
1139mod tests {
1140 use super::*;
1141 use crate::{display_map::inlay_map::InlayMap, MultiBuffer, ToPoint};
1142 use collections::HashSet;
1143 use rand::prelude::*;
1144 use settings::SettingsStore;
1145 use std::{env, mem};
1146 use text::Patch;
1147 use util::test::sample_text;
1148 use util::RandomCharIter;
1149 use Bias::{Left, Right};
1150
1151 #[gpui::test]
1152 fn test_basic_folds(cx: &mut gpui::AppContext) {
1153 init_test(cx);
1154 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1155 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1156 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1157 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1158 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1159
1160 let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1161 let (snapshot2, edits) = writer.fold(vec![
1162 Point::new(0, 2)..Point::new(2, 2),
1163 Point::new(2, 4)..Point::new(4, 1),
1164 ]);
1165 assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1166 assert_eq!(
1167 edits,
1168 &[
1169 FoldEdit {
1170 old: FoldOffset(2)..FoldOffset(16),
1171 new: FoldOffset(2)..FoldOffset(5),
1172 },
1173 FoldEdit {
1174 old: FoldOffset(18)..FoldOffset(29),
1175 new: FoldOffset(7)..FoldOffset(10)
1176 },
1177 ]
1178 );
1179
1180 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1181 buffer.edit(
1182 vec![
1183 (Point::new(0, 0)..Point::new(0, 1), "123"),
1184 (Point::new(2, 3)..Point::new(2, 3), "123"),
1185 ],
1186 None,
1187 cx,
1188 );
1189 buffer.snapshot(cx)
1190 });
1191
1192 let (inlay_snapshot, inlay_edits) =
1193 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1194 let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1195 assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1196 assert_eq!(
1197 edits,
1198 &[
1199 FoldEdit {
1200 old: FoldOffset(0)..FoldOffset(1),
1201 new: FoldOffset(0)..FoldOffset(3),
1202 },
1203 FoldEdit {
1204 old: FoldOffset(6)..FoldOffset(6),
1205 new: FoldOffset(8)..FoldOffset(11),
1206 },
1207 ]
1208 );
1209
1210 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1211 buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1212 buffer.snapshot(cx)
1213 });
1214 let (inlay_snapshot, inlay_edits) =
1215 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1216 let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1217 assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1218
1219 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1220 writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1221 let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1222 assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1223
1224 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1225 writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1226 let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1227 assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1228 }
1229
1230 #[gpui::test]
1231 fn test_adjacent_folds(cx: &mut gpui::AppContext) {
1232 init_test(cx);
1233 let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1234 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1235 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1236 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1237
1238 {
1239 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1240
1241 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1242 writer.fold(vec![5..8]);
1243 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1244 assert_eq!(snapshot.text(), "abcde⋯ijkl");
1245
1246 // Create an fold adjacent to the start of the first fold.
1247 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1248 writer.fold(vec![0..1, 2..5]);
1249 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1250 assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1251
1252 // Create an fold adjacent to the end of the first fold.
1253 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1254 writer.fold(vec![11..11, 8..10]);
1255 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1256 assert_eq!(snapshot.text(), "⋯b⋯kl");
1257 }
1258
1259 {
1260 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1261
1262 // Create two adjacent folds.
1263 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1264 writer.fold(vec![0..2, 2..5]);
1265 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1266 assert_eq!(snapshot.text(), "⋯fghijkl");
1267
1268 // Edit within one of the folds.
1269 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1270 buffer.edit([(0..1, "12345")], None, cx);
1271 buffer.snapshot(cx)
1272 });
1273 let (inlay_snapshot, inlay_edits) =
1274 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1275 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1276 assert_eq!(snapshot.text(), "12345⋯fghijkl");
1277 }
1278 }
1279
1280 #[gpui::test]
1281 fn test_overlapping_folds(cx: &mut gpui::AppContext) {
1282 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1283 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1284 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1285 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1286 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1287 writer.fold(vec![
1288 Point::new(0, 2)..Point::new(2, 2),
1289 Point::new(0, 4)..Point::new(1, 0),
1290 Point::new(1, 2)..Point::new(3, 2),
1291 Point::new(3, 1)..Point::new(4, 1),
1292 ]);
1293 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1294 assert_eq!(snapshot.text(), "aa⋯eeeee");
1295 }
1296
1297 #[gpui::test]
1298 fn test_merging_folds_via_edit(cx: &mut gpui::AppContext) {
1299 init_test(cx);
1300 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1301 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1302 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1303 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1304 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1305
1306 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1307 writer.fold(vec![
1308 Point::new(0, 2)..Point::new(2, 2),
1309 Point::new(3, 1)..Point::new(4, 1),
1310 ]);
1311 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1312 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1313
1314 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1315 buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1316 buffer.snapshot(cx)
1317 });
1318 let (inlay_snapshot, inlay_edits) =
1319 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1320 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1321 assert_eq!(snapshot.text(), "aa⋯eeeee");
1322 }
1323
1324 #[gpui::test]
1325 fn test_folds_in_range(cx: &mut gpui::AppContext) {
1326 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1327 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1328 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1329 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1330
1331 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1332 writer.fold(vec![
1333 Point::new(0, 2)..Point::new(2, 2),
1334 Point::new(0, 4)..Point::new(1, 0),
1335 Point::new(1, 2)..Point::new(3, 2),
1336 Point::new(3, 1)..Point::new(4, 1),
1337 ]);
1338 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1339 let fold_ranges = snapshot
1340 .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1341 .map(|fold| {
1342 fold.range.start.to_point(&buffer_snapshot)
1343 ..fold.range.end.to_point(&buffer_snapshot)
1344 })
1345 .collect::<Vec<_>>();
1346 assert_eq!(
1347 fold_ranges,
1348 vec![
1349 Point::new(0, 2)..Point::new(2, 2),
1350 Point::new(1, 2)..Point::new(3, 2)
1351 ]
1352 );
1353 }
1354
1355 #[gpui::test(iterations = 100)]
1356 fn test_random_folds(cx: &mut gpui::AppContext, mut rng: StdRng) {
1357 init_test(cx);
1358 let operations = env::var("OPERATIONS")
1359 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1360 .unwrap_or(10);
1361
1362 let len = rng.gen_range(0..10);
1363 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1364 let buffer = if rng.gen() {
1365 MultiBuffer::build_simple(&text, cx)
1366 } else {
1367 MultiBuffer::build_random(&mut rng, cx)
1368 };
1369 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1370 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1371 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1372
1373 let (mut initial_snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1374 let mut snapshot_edits = Vec::new();
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, Highlights::default())
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(MultiBufferRow(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.range.end, &buffer_snapshot) == Ordering::Less
1577 && end.cmp(&fold.range.start, &buffer_snapshot) == Ordering::Greater
1578 })
1579 .collect::<Vec<_>>();
1580
1581 assert_eq!(
1582 snapshot
1583 .folds_in_range(start..end)
1584 .cloned()
1585 .collect::<Vec<_>>(),
1586 expected_folds
1587 );
1588 }
1589
1590 let text = snapshot.text();
1591 for _ in 0..5 {
1592 let start_row = rng.gen_range(0..=snapshot.max_point().row());
1593 let start_column = rng.gen_range(0..=snapshot.line_len(start_row));
1594 let end_row = rng.gen_range(0..=snapshot.max_point().row());
1595 let end_column = rng.gen_range(0..=snapshot.line_len(end_row));
1596 let mut start =
1597 snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
1598 let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
1599 if start > end {
1600 mem::swap(&mut start, &mut end);
1601 }
1602
1603 let lines = start..end;
1604 let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
1605 assert_eq!(
1606 snapshot.text_summary_for_range(lines),
1607 TextSummary::from(&text[bytes.start.0..bytes.end.0])
1608 )
1609 }
1610
1611 let mut text = initial_snapshot.text();
1612 for (snapshot, edits) in snapshot_edits.drain(..) {
1613 let new_text = snapshot.text();
1614 for edit in edits {
1615 let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
1616 let new_bytes = edit.new.start.0..edit.new.end.0;
1617 text.replace_range(old_bytes, &new_text[new_bytes]);
1618 }
1619
1620 assert_eq!(text, new_text);
1621 initial_snapshot = snapshot;
1622 }
1623 }
1624 }
1625
1626 #[gpui::test]
1627 fn test_buffer_rows(cx: &mut gpui::AppContext) {
1628 let text = sample_text(6, 6, 'a') + "\n";
1629 let buffer = MultiBuffer::build_simple(&text, cx);
1630
1631 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1632 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1633 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1634
1635 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1636 writer.fold(vec![
1637 Point::new(0, 2)..Point::new(2, 2),
1638 Point::new(3, 1)..Point::new(4, 1),
1639 ]);
1640
1641 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1642 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
1643 assert_eq!(
1644 snapshot.buffer_rows(0).collect::<Vec<_>>(),
1645 [Some(0), Some(3), Some(5), Some(6)]
1646 );
1647 assert_eq!(snapshot.buffer_rows(3).collect::<Vec<_>>(), [Some(6)]);
1648 }
1649
1650 fn init_test(cx: &mut gpui::AppContext) {
1651 let store = SettingsStore::test(cx);
1652 cx.set_global(store);
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.range.cmp(&b.range, buffer));
1662 let mut fold_ranges = folds
1663 .iter()
1664 .map(|fold| fold.range.start.to_offset(buffer)..fold.range.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}