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