1use crate::{InlayId, display_map::inlay_map::InlayChunk};
2
3use super::{
4 Highlights,
5 inlay_map::{InlayBufferRows, InlayChunks, InlayEdit, InlayOffset, InlayPoint, InlaySnapshot},
6};
7use gpui::{AnyElement, App, ElementId, HighlightStyle, Pixels, Window};
8use language::{Edit, HighlightId, Point, TextSummary};
9use multi_buffer::{
10 Anchor, AnchorRangeExt, MultiBufferRow, MultiBufferSnapshot, RowInfo, ToOffset,
11};
12use std::{
13 any::TypeId,
14 cmp::{self, Ordering},
15 fmt, iter,
16 ops::{Add, AddAssign, Deref, DerefMut, Range, Sub},
17 sync::Arc,
18 usize,
19};
20use sum_tree::{Bias, Cursor, Dimensions, FilterCursor, SumTree, Summary, TreeMap};
21use ui::IntoElement as _;
22use util::post_inc;
23
24#[derive(Clone)]
25pub struct FoldPlaceholder {
26 /// Creates an element to represent this fold's placeholder.
27 pub render: Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement>,
28 /// If true, the element is constrained to the shaped width of an ellipsis.
29 pub constrain_width: bool,
30 /// If true, merges the fold with an adjacent one.
31 pub merge_adjacent: bool,
32 /// Category of the fold. Useful for carefully removing from overlapping folds.
33 pub type_tag: Option<TypeId>,
34}
35
36impl Default for FoldPlaceholder {
37 fn default() -> Self {
38 Self {
39 render: Arc::new(|_, _, _| gpui::Empty.into_any_element()),
40 constrain_width: true,
41 merge_adjacent: true,
42 type_tag: None,
43 }
44 }
45}
46
47impl FoldPlaceholder {
48 #[cfg(any(test, feature = "test-support"))]
49 pub fn test() -> Self {
50 Self {
51 render: Arc::new(|_id, _range, _cx| gpui::Empty.into_any_element()),
52 constrain_width: true,
53 merge_adjacent: true,
54 type_tag: None,
55 }
56 }
57}
58
59impl fmt::Debug for FoldPlaceholder {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.debug_struct("FoldPlaceholder")
62 .field("constrain_width", &self.constrain_width)
63 .finish()
64 }
65}
66
67impl Eq for FoldPlaceholder {}
68
69impl PartialEq for FoldPlaceholder {
70 fn eq(&self, other: &Self) -> bool {
71 Arc::ptr_eq(&self.render, &other.render) && self.constrain_width == other.constrain_width
72 }
73}
74
75#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
76pub struct FoldPoint(pub Point);
77
78impl FoldPoint {
79 pub fn new(row: u32, column: u32) -> Self {
80 Self(Point::new(row, column))
81 }
82
83 pub fn row(self) -> u32 {
84 self.0.row
85 }
86
87 pub fn column(self) -> u32 {
88 self.0.column
89 }
90
91 pub fn row_mut(&mut self) -> &mut u32 {
92 &mut self.0.row
93 }
94
95 #[cfg(test)]
96 pub fn column_mut(&mut self) -> &mut u32 {
97 &mut self.0.column
98 }
99
100 pub fn to_inlay_point(self, snapshot: &FoldSnapshot) -> InlayPoint {
101 let mut cursor = snapshot
102 .transforms
103 .cursor::<Dimensions<FoldPoint, InlayPoint>>(&());
104 cursor.seek(&self, Bias::Right);
105 let overshoot = self.0 - cursor.start().0.0;
106 InlayPoint(cursor.start().1.0 + overshoot)
107 }
108
109 pub fn to_offset(self, snapshot: &FoldSnapshot) -> FoldOffset {
110 let mut cursor = snapshot
111 .transforms
112 .cursor::<Dimensions<FoldPoint, TransformSummary>>(&());
113 cursor.seek(&self, Bias::Right);
114 let overshoot = self.0 - cursor.start().1.output.lines;
115 let mut offset = cursor.start().1.output.len;
116 if !overshoot.is_zero() {
117 let transform = cursor.item().expect("display point out of range");
118 assert!(transform.placeholder.is_none());
119 let end_inlay_offset = snapshot
120 .inlay_snapshot
121 .to_offset(InlayPoint(cursor.start().1.input.lines + overshoot));
122 offset += end_inlay_offset.0 - cursor.start().1.input.len;
123 }
124 FoldOffset(offset)
125 }
126}
127
128impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldPoint {
129 fn zero(_cx: &()) -> Self {
130 Default::default()
131 }
132
133 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
134 self.0 += &summary.output.lines;
135 }
136}
137
138pub(crate) struct FoldMapWriter<'a>(&'a mut FoldMap);
139
140impl FoldMapWriter<'_> {
141 pub(crate) fn fold<T: ToOffset>(
142 &mut self,
143 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
144 ) -> (FoldSnapshot, Vec<FoldEdit>) {
145 let mut edits = Vec::new();
146 let mut folds = Vec::new();
147 let snapshot = self.0.snapshot.inlay_snapshot.clone();
148 for (range, fold_text) in ranges.into_iter() {
149 let buffer = &snapshot.buffer;
150 let range = range.start.to_offset(buffer)..range.end.to_offset(buffer);
151
152 // Ignore any empty ranges.
153 if range.start == range.end {
154 continue;
155 }
156
157 // For now, ignore any ranges that span an excerpt boundary.
158 let fold_range =
159 FoldRange(buffer.anchor_after(range.start)..buffer.anchor_before(range.end));
160 if fold_range.0.start.excerpt_id != fold_range.0.end.excerpt_id {
161 continue;
162 }
163
164 folds.push(Fold {
165 id: FoldId(post_inc(&mut self.0.next_fold_id.0)),
166 range: fold_range,
167 placeholder: fold_text,
168 });
169
170 let inlay_range =
171 snapshot.to_inlay_offset(range.start)..snapshot.to_inlay_offset(range.end);
172 edits.push(InlayEdit {
173 old: inlay_range.clone(),
174 new: inlay_range,
175 });
176 }
177
178 let buffer = &snapshot.buffer;
179 folds.sort_unstable_by(|a, b| sum_tree::SeekTarget::cmp(&a.range, &b.range, buffer));
180
181 self.0.snapshot.folds = {
182 let mut new_tree = SumTree::new(buffer);
183 let mut cursor = self.0.snapshot.folds.cursor::<FoldRange>(buffer);
184 for fold in folds {
185 self.0.snapshot.fold_metadata_by_id.insert(
186 fold.id,
187 FoldMetadata {
188 range: fold.range.clone(),
189 width: None,
190 },
191 );
192 new_tree.append(cursor.slice(&fold.range, Bias::Right), buffer);
193 new_tree.push(fold, buffer);
194 }
195 new_tree.append(cursor.suffix(), buffer);
196 new_tree
197 };
198
199 let edits = consolidate_inlay_edits(edits);
200 let edits = self.0.sync(snapshot.clone(), edits);
201 (self.0.snapshot.clone(), edits)
202 }
203
204 /// Removes any folds with the given ranges.
205 pub(crate) fn remove_folds<T: ToOffset>(
206 &mut self,
207 ranges: impl IntoIterator<Item = Range<T>>,
208 type_id: TypeId,
209 ) -> (FoldSnapshot, Vec<FoldEdit>) {
210 self.remove_folds_with(
211 ranges,
212 |fold| fold.placeholder.type_tag == Some(type_id),
213 false,
214 )
215 }
216
217 /// Removes any folds whose ranges intersect the given ranges.
218 pub(crate) fn unfold_intersecting<T: ToOffset>(
219 &mut self,
220 ranges: impl IntoIterator<Item = Range<T>>,
221 inclusive: bool,
222 ) -> (FoldSnapshot, Vec<FoldEdit>) {
223 self.remove_folds_with(ranges, |_| true, inclusive)
224 }
225
226 /// Removes any folds that intersect the given ranges and for which the given predicate
227 /// returns true.
228 fn remove_folds_with<T: ToOffset>(
229 &mut self,
230 ranges: impl IntoIterator<Item = Range<T>>,
231 should_unfold: impl Fn(&Fold) -> bool,
232 inclusive: bool,
233 ) -> (FoldSnapshot, Vec<FoldEdit>) {
234 let mut edits = Vec::new();
235 let mut fold_ixs_to_delete = Vec::new();
236 let snapshot = self.0.snapshot.inlay_snapshot.clone();
237 let buffer = &snapshot.buffer;
238 for range in ranges.into_iter() {
239 let range = range.start.to_offset(buffer)..range.end.to_offset(buffer);
240 let mut folds_cursor =
241 intersecting_folds(&snapshot, &self.0.snapshot.folds, range.clone(), inclusive);
242 while let Some(fold) = folds_cursor.item() {
243 let offset_range =
244 fold.range.start.to_offset(buffer)..fold.range.end.to_offset(buffer);
245 if should_unfold(fold) {
246 if offset_range.end > offset_range.start {
247 let inlay_range = snapshot.to_inlay_offset(offset_range.start)
248 ..snapshot.to_inlay_offset(offset_range.end);
249 edits.push(InlayEdit {
250 old: inlay_range.clone(),
251 new: inlay_range,
252 });
253 }
254 fold_ixs_to_delete.push(*folds_cursor.start());
255 self.0.snapshot.fold_metadata_by_id.remove(&fold.id);
256 }
257 folds_cursor.next();
258 }
259 }
260
261 fold_ixs_to_delete.sort_unstable();
262 fold_ixs_to_delete.dedup();
263
264 self.0.snapshot.folds = {
265 let mut cursor = self.0.snapshot.folds.cursor::<usize>(buffer);
266 let mut folds = SumTree::new(buffer);
267 for fold_ix in fold_ixs_to_delete {
268 folds.append(cursor.slice(&fold_ix, Bias::Right), buffer);
269 cursor.next();
270 }
271 folds.append(cursor.suffix(), buffer);
272 folds
273 };
274
275 let edits = consolidate_inlay_edits(edits);
276 let edits = self.0.sync(snapshot.clone(), edits);
277 (self.0.snapshot.clone(), edits)
278 }
279
280 pub(crate) fn update_fold_widths(
281 &mut self,
282 new_widths: impl IntoIterator<Item = (ChunkRendererId, Pixels)>,
283 ) -> (FoldSnapshot, Vec<FoldEdit>) {
284 let mut edits = Vec::new();
285 let inlay_snapshot = self.0.snapshot.inlay_snapshot.clone();
286 let buffer = &inlay_snapshot.buffer;
287
288 for (id, new_width) in new_widths {
289 let ChunkRendererId::Fold(id) = id else {
290 continue;
291 };
292 if let Some(metadata) = self.0.snapshot.fold_metadata_by_id.get(&id).cloned()
293 && Some(new_width) != metadata.width
294 {
295 let buffer_start = metadata.range.start.to_offset(buffer);
296 let buffer_end = metadata.range.end.to_offset(buffer);
297 let inlay_range = inlay_snapshot.to_inlay_offset(buffer_start)
298 ..inlay_snapshot.to_inlay_offset(buffer_end);
299 edits.push(InlayEdit {
300 old: inlay_range.clone(),
301 new: inlay_range.clone(),
302 });
303
304 self.0.snapshot.fold_metadata_by_id.insert(
305 id,
306 FoldMetadata {
307 range: metadata.range,
308 width: Some(new_width),
309 },
310 );
311 }
312 }
313
314 let edits = consolidate_inlay_edits(edits);
315 let edits = self.0.sync(inlay_snapshot, edits);
316 (self.0.snapshot.clone(), edits)
317 }
318}
319
320/// Decides where the fold indicators should be; also tracks parts of a source file that are currently folded.
321///
322/// See the [`display_map` module documentation](crate::display_map) for more information.
323pub(crate) struct FoldMap {
324 snapshot: FoldSnapshot,
325 next_fold_id: FoldId,
326}
327
328impl FoldMap {
329 pub(crate) fn new(inlay_snapshot: InlaySnapshot) -> (Self, FoldSnapshot) {
330 let this = Self {
331 snapshot: FoldSnapshot {
332 folds: SumTree::new(&inlay_snapshot.buffer),
333 transforms: SumTree::from_item(
334 Transform {
335 summary: TransformSummary {
336 input: inlay_snapshot.text_summary(),
337 output: inlay_snapshot.text_summary(),
338 },
339 placeholder: None,
340 },
341 &(),
342 ),
343 inlay_snapshot: inlay_snapshot.clone(),
344 version: 0,
345 fold_metadata_by_id: TreeMap::default(),
346 },
347 next_fold_id: FoldId::default(),
348 };
349 let snapshot = this.snapshot.clone();
350 (this, snapshot)
351 }
352
353 pub fn read(
354 &mut self,
355 inlay_snapshot: InlaySnapshot,
356 edits: Vec<InlayEdit>,
357 ) -> (FoldSnapshot, Vec<FoldEdit>) {
358 let edits = self.sync(inlay_snapshot, edits);
359 self.check_invariants();
360 (self.snapshot.clone(), edits)
361 }
362
363 pub fn write(
364 &mut self,
365 inlay_snapshot: InlaySnapshot,
366 edits: Vec<InlayEdit>,
367 ) -> (FoldMapWriter<'_>, FoldSnapshot, Vec<FoldEdit>) {
368 let (snapshot, edits) = self.read(inlay_snapshot, edits);
369 (FoldMapWriter(self), snapshot, edits)
370 }
371
372 fn check_invariants(&self) {
373 if cfg!(test) {
374 assert_eq!(
375 self.snapshot.transforms.summary().input.len,
376 self.snapshot.inlay_snapshot.len().0,
377 "transform tree does not match inlay snapshot's length"
378 );
379
380 let mut prev_transform_isomorphic = false;
381 for transform in self.snapshot.transforms.iter() {
382 if !transform.is_fold() && prev_transform_isomorphic {
383 panic!(
384 "found adjacent isomorphic transforms: {:?}",
385 self.snapshot.transforms.items(&())
386 );
387 }
388 prev_transform_isomorphic = !transform.is_fold();
389 }
390
391 let mut folds = self.snapshot.folds.iter().peekable();
392 while let Some(fold) = folds.next() {
393 if let Some(next_fold) = folds.peek() {
394 let comparison = fold.range.cmp(&next_fold.range, self.snapshot.buffer());
395 assert!(comparison.is_le());
396 }
397 }
398 }
399 }
400
401 fn sync(
402 &mut self,
403 inlay_snapshot: InlaySnapshot,
404 inlay_edits: Vec<InlayEdit>,
405 ) -> Vec<FoldEdit> {
406 if inlay_edits.is_empty() {
407 if self.snapshot.inlay_snapshot.version != inlay_snapshot.version {
408 self.snapshot.version += 1;
409 }
410 self.snapshot.inlay_snapshot = inlay_snapshot;
411 Vec::new()
412 } else {
413 let mut inlay_edits_iter = inlay_edits.iter().cloned().peekable();
414
415 let mut new_transforms = SumTree::<Transform>::default();
416 let mut cursor = self.snapshot.transforms.cursor::<InlayOffset>(&());
417 cursor.seek(&InlayOffset(0), Bias::Right);
418
419 while let Some(mut edit) = inlay_edits_iter.next() {
420 if let Some(item) = cursor.item()
421 && !item.is_fold()
422 {
423 new_transforms.update_last(
424 |transform| {
425 if !transform.is_fold() {
426 transform.summary.add_summary(&item.summary, &());
427 cursor.next();
428 }
429 },
430 &(),
431 );
432 }
433 new_transforms.append(cursor.slice(&edit.old.start, Bias::Left), &());
434 edit.new.start -= edit.old.start - *cursor.start();
435 edit.old.start = *cursor.start();
436
437 cursor.seek(&edit.old.end, Bias::Right);
438 cursor.next();
439
440 let mut delta = edit.new_len().0 as isize - edit.old_len().0 as isize;
441 loop {
442 edit.old.end = *cursor.start();
443
444 if let Some(next_edit) = inlay_edits_iter.peek() {
445 if next_edit.old.start > edit.old.end {
446 break;
447 }
448
449 let next_edit = inlay_edits_iter.next().unwrap();
450 delta += next_edit.new_len().0 as isize - next_edit.old_len().0 as isize;
451
452 if next_edit.old.end >= edit.old.end {
453 edit.old.end = next_edit.old.end;
454 cursor.seek(&edit.old.end, Bias::Right);
455 cursor.next();
456 }
457 } else {
458 break;
459 }
460 }
461
462 edit.new.end =
463 InlayOffset(((edit.new.start + edit.old_len()).0 as isize + delta) as usize);
464
465 let anchor = inlay_snapshot
466 .buffer
467 .anchor_before(inlay_snapshot.to_buffer_offset(edit.new.start));
468 let mut folds_cursor = self
469 .snapshot
470 .folds
471 .cursor::<FoldRange>(&inlay_snapshot.buffer);
472 folds_cursor.seek(&FoldRange(anchor..Anchor::max()), Bias::Left);
473
474 let mut folds = iter::from_fn({
475 let inlay_snapshot = &inlay_snapshot;
476 move || {
477 let item = folds_cursor.item().map(|fold| {
478 let buffer_start = fold.range.start.to_offset(&inlay_snapshot.buffer);
479 let buffer_end = fold.range.end.to_offset(&inlay_snapshot.buffer);
480 (
481 fold.clone(),
482 inlay_snapshot.to_inlay_offset(buffer_start)
483 ..inlay_snapshot.to_inlay_offset(buffer_end),
484 )
485 });
486 folds_cursor.next();
487 item
488 }
489 })
490 .peekable();
491
492 while folds
493 .peek()
494 .is_some_and(|(_, fold_range)| fold_range.start < edit.new.end)
495 {
496 let (fold, mut fold_range) = folds.next().unwrap();
497 let sum = new_transforms.summary();
498
499 assert!(fold_range.start.0 >= sum.input.len);
500
501 while folds.peek().is_some_and(|(next_fold, next_fold_range)| {
502 next_fold_range.start < fold_range.end
503 || (next_fold_range.start == fold_range.end
504 && fold.placeholder.merge_adjacent
505 && next_fold.placeholder.merge_adjacent)
506 }) {
507 let (_, next_fold_range) = folds.next().unwrap();
508 if next_fold_range.end > fold_range.end {
509 fold_range.end = next_fold_range.end;
510 }
511 }
512
513 if fold_range.start.0 > sum.input.len {
514 let text_summary = inlay_snapshot
515 .text_summary_for_range(InlayOffset(sum.input.len)..fold_range.start);
516 push_isomorphic(&mut new_transforms, text_summary);
517 }
518
519 if fold_range.end > fold_range.start {
520 const ELLIPSIS: &str = "⋯";
521
522 let fold_id = fold.id;
523 new_transforms.push(
524 Transform {
525 summary: TransformSummary {
526 output: TextSummary::from(ELLIPSIS),
527 input: inlay_snapshot
528 .text_summary_for_range(fold_range.start..fold_range.end),
529 },
530 placeholder: Some(TransformPlaceholder {
531 text: ELLIPSIS,
532 renderer: ChunkRenderer {
533 id: ChunkRendererId::Fold(fold.id),
534 render: Arc::new(move |cx| {
535 (fold.placeholder.render)(
536 fold_id,
537 fold.range.0.clone(),
538 cx.context,
539 )
540 }),
541 constrain_width: fold.placeholder.constrain_width,
542 measured_width: self.snapshot.fold_width(&fold_id),
543 },
544 }),
545 },
546 &(),
547 );
548 }
549 }
550
551 let sum = new_transforms.summary();
552 if sum.input.len < edit.new.end.0 {
553 let text_summary = inlay_snapshot
554 .text_summary_for_range(InlayOffset(sum.input.len)..edit.new.end);
555 push_isomorphic(&mut new_transforms, text_summary);
556 }
557 }
558
559 new_transforms.append(cursor.suffix(), &());
560 if new_transforms.is_empty() {
561 let text_summary = inlay_snapshot.text_summary();
562 push_isomorphic(&mut new_transforms, text_summary);
563 }
564
565 drop(cursor);
566
567 let mut fold_edits = Vec::with_capacity(inlay_edits.len());
568 {
569 let mut old_transforms = self
570 .snapshot
571 .transforms
572 .cursor::<Dimensions<InlayOffset, FoldOffset>>(&());
573 let mut new_transforms =
574 new_transforms.cursor::<Dimensions<InlayOffset, FoldOffset>>(&());
575
576 for mut edit in inlay_edits {
577 old_transforms.seek(&edit.old.start, Bias::Left);
578 if old_transforms.item().is_some_and(|t| t.is_fold()) {
579 edit.old.start = old_transforms.start().0;
580 }
581 let old_start =
582 old_transforms.start().1.0 + (edit.old.start - old_transforms.start().0).0;
583
584 old_transforms.seek_forward(&edit.old.end, Bias::Right);
585 if old_transforms.item().is_some_and(|t| t.is_fold()) {
586 old_transforms.next();
587 edit.old.end = old_transforms.start().0;
588 }
589 let old_end =
590 old_transforms.start().1.0 + (edit.old.end - old_transforms.start().0).0;
591
592 new_transforms.seek(&edit.new.start, Bias::Left);
593 if new_transforms.item().is_some_and(|t| t.is_fold()) {
594 edit.new.start = new_transforms.start().0;
595 }
596 let new_start =
597 new_transforms.start().1.0 + (edit.new.start - new_transforms.start().0).0;
598
599 new_transforms.seek_forward(&edit.new.end, Bias::Right);
600 if new_transforms.item().is_some_and(|t| t.is_fold()) {
601 new_transforms.next();
602 edit.new.end = new_transforms.start().0;
603 }
604 let new_end =
605 new_transforms.start().1.0 + (edit.new.end - new_transforms.start().0).0;
606
607 fold_edits.push(FoldEdit {
608 old: FoldOffset(old_start)..FoldOffset(old_end),
609 new: FoldOffset(new_start)..FoldOffset(new_end),
610 });
611 }
612
613 fold_edits = consolidate_fold_edits(fold_edits);
614 }
615
616 self.snapshot.transforms = new_transforms;
617 self.snapshot.inlay_snapshot = inlay_snapshot;
618 self.snapshot.version += 1;
619 fold_edits
620 }
621 }
622}
623
624#[derive(Clone)]
625pub struct FoldSnapshot {
626 transforms: SumTree<Transform>,
627 folds: SumTree<Fold>,
628 fold_metadata_by_id: TreeMap<FoldId, FoldMetadata>,
629 pub inlay_snapshot: InlaySnapshot,
630 pub version: usize,
631}
632
633impl FoldSnapshot {
634 pub fn buffer(&self) -> &MultiBufferSnapshot {
635 &self.inlay_snapshot.buffer
636 }
637
638 fn fold_width(&self, fold_id: &FoldId) -> Option<Pixels> {
639 self.fold_metadata_by_id.get(fold_id)?.width
640 }
641
642 #[cfg(test)]
643 pub fn text(&self) -> String {
644 self.chunks(FoldOffset(0)..self.len(), false, Highlights::default())
645 .map(|c| c.text)
646 .collect()
647 }
648
649 #[cfg(test)]
650 pub fn fold_count(&self) -> usize {
651 self.folds.items(&self.inlay_snapshot.buffer).len()
652 }
653
654 pub fn text_summary_for_range(&self, range: Range<FoldPoint>) -> TextSummary {
655 let mut summary = TextSummary::default();
656
657 let mut cursor = self
658 .transforms
659 .cursor::<Dimensions<FoldPoint, InlayPoint>>(&());
660 cursor.seek(&range.start, Bias::Right);
661 if let Some(transform) = cursor.item() {
662 let start_in_transform = range.start.0 - cursor.start().0.0;
663 let end_in_transform = cmp::min(range.end, cursor.end().0).0 - cursor.start().0.0;
664 if let Some(placeholder) = transform.placeholder.as_ref() {
665 summary = TextSummary::from(
666 &placeholder.text
667 [start_in_transform.column as usize..end_in_transform.column as usize],
668 );
669 } else {
670 let inlay_start = self
671 .inlay_snapshot
672 .to_offset(InlayPoint(cursor.start().1.0 + start_in_transform));
673 let inlay_end = self
674 .inlay_snapshot
675 .to_offset(InlayPoint(cursor.start().1.0 + end_in_transform));
676 summary = self
677 .inlay_snapshot
678 .text_summary_for_range(inlay_start..inlay_end);
679 }
680 }
681
682 if range.end > cursor.end().0 {
683 cursor.next();
684 summary += &cursor
685 .summary::<_, TransformSummary>(&range.end, Bias::Right)
686 .output;
687 if let Some(transform) = cursor.item() {
688 let end_in_transform = range.end.0 - cursor.start().0.0;
689 if let Some(placeholder) = transform.placeholder.as_ref() {
690 summary +=
691 TextSummary::from(&placeholder.text[..end_in_transform.column as usize]);
692 } else {
693 let inlay_start = self.inlay_snapshot.to_offset(cursor.start().1);
694 let inlay_end = self
695 .inlay_snapshot
696 .to_offset(InlayPoint(cursor.start().1.0 + end_in_transform));
697 summary += self
698 .inlay_snapshot
699 .text_summary_for_range(inlay_start..inlay_end);
700 }
701 }
702 }
703
704 summary
705 }
706
707 pub fn to_fold_point(&self, point: InlayPoint, bias: Bias) -> FoldPoint {
708 let mut cursor = self
709 .transforms
710 .cursor::<Dimensions<InlayPoint, FoldPoint>>(&());
711 cursor.seek(&point, Bias::Right);
712 if cursor.item().is_some_and(|t| t.is_fold()) {
713 if bias == Bias::Left || point == cursor.start().0 {
714 cursor.start().1
715 } else {
716 cursor.end().1
717 }
718 } else {
719 let overshoot = point.0 - cursor.start().0.0;
720 FoldPoint(cmp::min(cursor.start().1.0 + overshoot, cursor.end().1.0))
721 }
722 }
723
724 pub fn len(&self) -> FoldOffset {
725 FoldOffset(self.transforms.summary().output.len)
726 }
727
728 pub fn line_len(&self, row: u32) -> u32 {
729 let line_start = FoldPoint::new(row, 0).to_offset(self).0;
730 let line_end = if row >= self.max_point().row() {
731 self.len().0
732 } else {
733 FoldPoint::new(row + 1, 0).to_offset(self).0 - 1
734 };
735 (line_end - line_start) as u32
736 }
737
738 pub fn row_infos(&self, start_row: u32) -> FoldRows<'_> {
739 if start_row > self.transforms.summary().output.lines.row {
740 panic!("invalid display row {}", start_row);
741 }
742
743 let fold_point = FoldPoint::new(start_row, 0);
744 let mut cursor = self
745 .transforms
746 .cursor::<Dimensions<FoldPoint, InlayPoint>>(&());
747 cursor.seek(&fold_point, Bias::Left);
748
749 let overshoot = fold_point.0 - cursor.start().0.0;
750 let inlay_point = InlayPoint(cursor.start().1.0 + overshoot);
751 let input_rows = self.inlay_snapshot.row_infos(inlay_point.row());
752
753 FoldRows {
754 fold_point,
755 input_rows,
756 cursor,
757 }
758 }
759
760 pub fn max_point(&self) -> FoldPoint {
761 FoldPoint(self.transforms.summary().output.lines)
762 }
763
764 #[cfg(test)]
765 pub fn longest_row(&self) -> u32 {
766 self.transforms.summary().output.longest_row
767 }
768
769 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Fold>
770 where
771 T: ToOffset,
772 {
773 let buffer = &self.inlay_snapshot.buffer;
774 let range = range.start.to_offset(buffer)..range.end.to_offset(buffer);
775 let mut folds = intersecting_folds(&self.inlay_snapshot, &self.folds, range, false);
776 iter::from_fn(move || {
777 let item = folds.item();
778 folds.next();
779 item
780 })
781 }
782
783 pub fn intersects_fold<T>(&self, offset: T) -> bool
784 where
785 T: ToOffset,
786 {
787 let buffer_offset = offset.to_offset(&self.inlay_snapshot.buffer);
788 let inlay_offset = self.inlay_snapshot.to_inlay_offset(buffer_offset);
789 let mut cursor = self.transforms.cursor::<InlayOffset>(&());
790 cursor.seek(&inlay_offset, Bias::Right);
791 cursor.item().is_some_and(|t| t.placeholder.is_some())
792 }
793
794 pub fn is_line_folded(&self, buffer_row: MultiBufferRow) -> bool {
795 let mut inlay_point = self
796 .inlay_snapshot
797 .to_inlay_point(Point::new(buffer_row.0, 0));
798 let mut cursor = self.transforms.cursor::<InlayPoint>(&());
799 cursor.seek(&inlay_point, Bias::Right);
800 loop {
801 match cursor.item() {
802 Some(transform) => {
803 let buffer_point = self.inlay_snapshot.to_buffer_point(inlay_point);
804 if buffer_point.row != buffer_row.0 {
805 return false;
806 } else if transform.placeholder.is_some() {
807 return true;
808 }
809 }
810 None => return false,
811 }
812
813 if cursor.end().row() == inlay_point.row() {
814 cursor.next();
815 } else {
816 inlay_point.0 += Point::new(1, 0);
817 cursor.seek(&inlay_point, Bias::Right);
818 }
819 }
820 }
821
822 pub(crate) fn chunks<'a>(
823 &'a self,
824 range: Range<FoldOffset>,
825 language_aware: bool,
826 highlights: Highlights<'a>,
827 ) -> FoldChunks<'a> {
828 let mut transform_cursor = self
829 .transforms
830 .cursor::<Dimensions<FoldOffset, InlayOffset>>(&());
831 transform_cursor.seek(&range.start, Bias::Right);
832
833 let inlay_start = {
834 let overshoot = range.start.0 - transform_cursor.start().0.0;
835 transform_cursor.start().1 + InlayOffset(overshoot)
836 };
837
838 let transform_end = transform_cursor.end();
839
840 let inlay_end = if transform_cursor
841 .item()
842 .is_none_or(|transform| transform.is_fold())
843 {
844 inlay_start
845 } else if range.end < transform_end.0 {
846 let overshoot = range.end.0 - transform_cursor.start().0.0;
847 transform_cursor.start().1 + InlayOffset(overshoot)
848 } else {
849 transform_end.1
850 };
851
852 FoldChunks {
853 transform_cursor,
854 inlay_chunks: self.inlay_snapshot.chunks(
855 inlay_start..inlay_end,
856 language_aware,
857 highlights,
858 ),
859 inlay_chunk: None,
860 inlay_offset: inlay_start,
861 output_offset: range.start,
862 max_output_offset: range.end,
863 }
864 }
865
866 pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
867 self.chunks(
868 start.to_offset(self)..self.len(),
869 false,
870 Highlights::default(),
871 )
872 .flat_map(|chunk| chunk.text.chars())
873 }
874
875 #[cfg(test)]
876 pub fn clip_offset(&self, offset: FoldOffset, bias: Bias) -> FoldOffset {
877 if offset > self.len() {
878 self.len()
879 } else {
880 self.clip_point(offset.to_point(self), bias).to_offset(self)
881 }
882 }
883
884 pub fn clip_point(&self, point: FoldPoint, bias: Bias) -> FoldPoint {
885 let mut cursor = self
886 .transforms
887 .cursor::<Dimensions<FoldPoint, InlayPoint>>(&());
888 cursor.seek(&point, Bias::Right);
889 if let Some(transform) = cursor.item() {
890 let transform_start = cursor.start().0.0;
891 if transform.placeholder.is_some() {
892 if point.0 == transform_start || matches!(bias, Bias::Left) {
893 FoldPoint(transform_start)
894 } else {
895 FoldPoint(cursor.end().0.0)
896 }
897 } else {
898 let overshoot = InlayPoint(point.0 - transform_start);
899 let inlay_point = cursor.start().1 + overshoot;
900 let clipped_inlay_point = self.inlay_snapshot.clip_point(inlay_point, bias);
901 FoldPoint(cursor.start().0.0 + (clipped_inlay_point - cursor.start().1).0)
902 }
903 } else {
904 FoldPoint(self.transforms.summary().output.lines)
905 }
906 }
907}
908
909fn push_isomorphic(transforms: &mut SumTree<Transform>, summary: TextSummary) {
910 let mut did_merge = false;
911 transforms.update_last(
912 |last| {
913 if !last.is_fold() {
914 last.summary.input += summary;
915 last.summary.output += summary;
916 did_merge = true;
917 }
918 },
919 &(),
920 );
921 if !did_merge {
922 transforms.push(
923 Transform {
924 summary: TransformSummary {
925 input: summary,
926 output: summary,
927 },
928 placeholder: None,
929 },
930 &(),
931 )
932 }
933}
934
935fn intersecting_folds<'a>(
936 inlay_snapshot: &'a InlaySnapshot,
937 folds: &'a SumTree<Fold>,
938 range: Range<usize>,
939 inclusive: bool,
940) -> FilterCursor<'a, impl 'a + FnMut(&FoldSummary) -> bool, Fold, usize> {
941 let buffer = &inlay_snapshot.buffer;
942 let start = buffer.anchor_before(range.start.to_offset(buffer));
943 let end = buffer.anchor_after(range.end.to_offset(buffer));
944 let mut cursor = folds.filter::<_, usize>(buffer, move |summary| {
945 let start_cmp = start.cmp(&summary.max_end, buffer);
946 let end_cmp = end.cmp(&summary.min_start, buffer);
947
948 if inclusive {
949 start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
950 } else {
951 start_cmp == Ordering::Less && end_cmp == Ordering::Greater
952 }
953 });
954 cursor.next();
955 cursor
956}
957
958fn consolidate_inlay_edits(mut edits: Vec<InlayEdit>) -> Vec<InlayEdit> {
959 edits.sort_unstable_by(|a, b| {
960 a.old
961 .start
962 .cmp(&b.old.start)
963 .then_with(|| b.old.end.cmp(&a.old.end))
964 });
965
966 let _old_alloc_ptr = edits.as_ptr();
967 let mut inlay_edits = edits.into_iter();
968
969 if let Some(mut first_edit) = inlay_edits.next() {
970 // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
971 #[allow(clippy::filter_map_identity)]
972 let mut v: Vec<_> = inlay_edits
973 .scan(&mut first_edit, |prev_edit, edit| {
974 if prev_edit.old.end >= edit.old.start {
975 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
976 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
977 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
978 Some(None) // Skip this edit, it's merged
979 } else {
980 let prev = std::mem::replace(*prev_edit, edit);
981 Some(Some(prev)) // Yield the previous edit
982 }
983 })
984 .filter_map(|x| x)
985 .collect();
986 v.push(first_edit.clone());
987 debug_assert_eq!(_old_alloc_ptr, v.as_ptr(), "Inlay edits were reallocated");
988 v
989 } else {
990 vec![]
991 }
992}
993
994fn consolidate_fold_edits(mut edits: Vec<FoldEdit>) -> Vec<FoldEdit> {
995 edits.sort_unstable_by(|a, b| {
996 a.old
997 .start
998 .cmp(&b.old.start)
999 .then_with(|| b.old.end.cmp(&a.old.end))
1000 });
1001 let _old_alloc_ptr = edits.as_ptr();
1002 let mut fold_edits = edits.into_iter();
1003
1004 if let Some(mut first_edit) = fold_edits.next() {
1005 // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1006 #[allow(clippy::filter_map_identity)]
1007 let mut v: Vec<_> = fold_edits
1008 .scan(&mut first_edit, |prev_edit, edit| {
1009 if prev_edit.old.end >= edit.old.start {
1010 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
1011 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
1012 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
1013 Some(None) // Skip this edit, it's merged
1014 } else {
1015 let prev = std::mem::replace(*prev_edit, edit);
1016 Some(Some(prev)) // Yield the previous edit
1017 }
1018 })
1019 .filter_map(|x| x)
1020 .collect();
1021 v.push(first_edit.clone());
1022 v
1023 } else {
1024 vec![]
1025 }
1026}
1027
1028#[derive(Clone, Debug, Default)]
1029struct Transform {
1030 summary: TransformSummary,
1031 placeholder: Option<TransformPlaceholder>,
1032}
1033
1034#[derive(Clone, Debug)]
1035struct TransformPlaceholder {
1036 text: &'static str,
1037 renderer: ChunkRenderer,
1038}
1039
1040impl Transform {
1041 fn is_fold(&self) -> bool {
1042 self.placeholder.is_some()
1043 }
1044}
1045
1046#[derive(Clone, Debug, Default, Eq, PartialEq)]
1047struct TransformSummary {
1048 output: TextSummary,
1049 input: TextSummary,
1050}
1051
1052impl sum_tree::Item for Transform {
1053 type Summary = TransformSummary;
1054
1055 fn summary(&self, _cx: &()) -> Self::Summary {
1056 self.summary.clone()
1057 }
1058}
1059
1060impl sum_tree::Summary for TransformSummary {
1061 type Context = ();
1062
1063 fn zero(_cx: &()) -> Self {
1064 Default::default()
1065 }
1066
1067 fn add_summary(&mut self, other: &Self, _: &()) {
1068 self.input += &other.input;
1069 self.output += &other.output;
1070 }
1071}
1072
1073#[derive(Copy, Clone, Eq, PartialEq, Debug, Default, Ord, PartialOrd, Hash)]
1074pub struct FoldId(pub(super) usize);
1075
1076impl From<FoldId> for ElementId {
1077 fn from(val: FoldId) -> Self {
1078 val.0.into()
1079 }
1080}
1081
1082#[derive(Clone, Debug, Eq, PartialEq)]
1083pub struct Fold {
1084 pub id: FoldId,
1085 pub range: FoldRange,
1086 pub placeholder: FoldPlaceholder,
1087}
1088
1089#[derive(Clone, Debug, Eq, PartialEq)]
1090pub struct FoldRange(Range<Anchor>);
1091
1092impl Deref for FoldRange {
1093 type Target = Range<Anchor>;
1094
1095 fn deref(&self) -> &Self::Target {
1096 &self.0
1097 }
1098}
1099
1100impl DerefMut for FoldRange {
1101 fn deref_mut(&mut self) -> &mut Self::Target {
1102 &mut self.0
1103 }
1104}
1105
1106impl Default for FoldRange {
1107 fn default() -> Self {
1108 Self(Anchor::min()..Anchor::max())
1109 }
1110}
1111
1112#[derive(Clone, Debug)]
1113struct FoldMetadata {
1114 range: FoldRange,
1115 width: Option<Pixels>,
1116}
1117
1118impl sum_tree::Item for Fold {
1119 type Summary = FoldSummary;
1120
1121 fn summary(&self, _cx: &MultiBufferSnapshot) -> Self::Summary {
1122 FoldSummary {
1123 start: self.range.start,
1124 end: self.range.end,
1125 min_start: self.range.start,
1126 max_end: self.range.end,
1127 count: 1,
1128 }
1129 }
1130}
1131
1132#[derive(Clone, Debug)]
1133pub struct FoldSummary {
1134 start: Anchor,
1135 end: Anchor,
1136 min_start: Anchor,
1137 max_end: Anchor,
1138 count: usize,
1139}
1140
1141impl Default for FoldSummary {
1142 fn default() -> Self {
1143 Self {
1144 start: Anchor::min(),
1145 end: Anchor::max(),
1146 min_start: Anchor::max(),
1147 max_end: Anchor::min(),
1148 count: 0,
1149 }
1150 }
1151}
1152
1153impl sum_tree::Summary for FoldSummary {
1154 type Context = MultiBufferSnapshot;
1155
1156 fn zero(_cx: &MultiBufferSnapshot) -> Self {
1157 Default::default()
1158 }
1159
1160 fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
1161 if other.min_start.cmp(&self.min_start, buffer) == Ordering::Less {
1162 self.min_start = other.min_start;
1163 }
1164 if other.max_end.cmp(&self.max_end, buffer) == Ordering::Greater {
1165 self.max_end = other.max_end;
1166 }
1167
1168 #[cfg(debug_assertions)]
1169 {
1170 let start_comparison = self.start.cmp(&other.start, buffer);
1171 assert!(start_comparison <= Ordering::Equal);
1172 if start_comparison == Ordering::Equal {
1173 assert!(self.end.cmp(&other.end, buffer) >= Ordering::Equal);
1174 }
1175 }
1176
1177 self.start = other.start;
1178 self.end = other.end;
1179 self.count += other.count;
1180 }
1181}
1182
1183impl<'a> sum_tree::Dimension<'a, FoldSummary> for FoldRange {
1184 fn zero(_cx: &MultiBufferSnapshot) -> Self {
1185 Default::default()
1186 }
1187
1188 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
1189 self.0.start = summary.start;
1190 self.0.end = summary.end;
1191 }
1192}
1193
1194impl sum_tree::SeekTarget<'_, FoldSummary, FoldRange> for FoldRange {
1195 fn cmp(&self, other: &Self, buffer: &MultiBufferSnapshot) -> Ordering {
1196 AnchorRangeExt::cmp(&self.0, &other.0, buffer)
1197 }
1198}
1199
1200impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
1201 fn zero(_cx: &MultiBufferSnapshot) -> Self {
1202 Default::default()
1203 }
1204
1205 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
1206 *self += summary.count;
1207 }
1208}
1209
1210#[derive(Clone)]
1211pub struct FoldRows<'a> {
1212 cursor: Cursor<'a, Transform, Dimensions<FoldPoint, InlayPoint>>,
1213 input_rows: InlayBufferRows<'a>,
1214 fold_point: FoldPoint,
1215}
1216
1217impl FoldRows<'_> {
1218 pub(crate) fn seek(&mut self, row: u32) {
1219 let fold_point = FoldPoint::new(row, 0);
1220 self.cursor.seek(&fold_point, Bias::Left);
1221 let overshoot = fold_point.0 - self.cursor.start().0.0;
1222 let inlay_point = InlayPoint(self.cursor.start().1.0 + overshoot);
1223 self.input_rows.seek(inlay_point.row());
1224 self.fold_point = fold_point;
1225 }
1226}
1227
1228impl Iterator for FoldRows<'_> {
1229 type Item = RowInfo;
1230
1231 fn next(&mut self) -> Option<Self::Item> {
1232 let mut traversed_fold = false;
1233 while self.fold_point > self.cursor.end().0 {
1234 self.cursor.next();
1235 traversed_fold = true;
1236 if self.cursor.item().is_none() {
1237 break;
1238 }
1239 }
1240
1241 if self.cursor.item().is_some() {
1242 if traversed_fold {
1243 self.input_rows.seek(self.cursor.start().1.0.row);
1244 self.input_rows.next();
1245 }
1246 *self.fold_point.row_mut() += 1;
1247 self.input_rows.next()
1248 } else {
1249 None
1250 }
1251 }
1252}
1253
1254/// A chunk of a buffer's text, along with its syntax highlight and
1255/// diagnostic status.
1256#[derive(Clone, Debug, Default)]
1257pub struct Chunk<'a> {
1258 /// The text of the chunk.
1259 pub text: &'a str,
1260 /// The syntax highlighting style of the chunk.
1261 pub syntax_highlight_id: Option<HighlightId>,
1262 /// The highlight style that has been applied to this chunk in
1263 /// the editor.
1264 pub highlight_style: Option<HighlightStyle>,
1265 /// The severity of diagnostic associated with this chunk, if any.
1266 pub diagnostic_severity: Option<lsp::DiagnosticSeverity>,
1267 /// Whether this chunk of text is marked as unnecessary.
1268 pub is_unnecessary: bool,
1269 /// Whether this chunk of text should be underlined.
1270 pub underline: bool,
1271 /// Whether this chunk of text was originally a tab character.
1272 pub is_tab: bool,
1273 /// Whether this chunk of text was originally a tab character.
1274 pub is_inlay: bool,
1275 /// An optional recipe for how the chunk should be presented.
1276 pub renderer: Option<ChunkRenderer>,
1277}
1278
1279#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1280pub enum ChunkRendererId {
1281 Fold(FoldId),
1282 Inlay(InlayId),
1283}
1284
1285/// A recipe for how the chunk should be presented.
1286#[derive(Clone)]
1287pub struct ChunkRenderer {
1288 /// The id of the renderer associated with this chunk.
1289 pub id: ChunkRendererId,
1290 /// Creates a custom element to represent this chunk.
1291 pub render: Arc<dyn Send + Sync + Fn(&mut ChunkRendererContext) -> AnyElement>,
1292 /// If true, the element is constrained to the shaped width of the text.
1293 pub constrain_width: bool,
1294 /// The width of the element, as measured during the last layout pass.
1295 ///
1296 /// This is None if the element has not been laid out yet.
1297 pub measured_width: Option<Pixels>,
1298}
1299
1300pub struct ChunkRendererContext<'a, 'b> {
1301 pub window: &'a mut Window,
1302 pub context: &'b mut App,
1303 pub max_width: Pixels,
1304}
1305
1306impl fmt::Debug for ChunkRenderer {
1307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1308 f.debug_struct("ChunkRenderer")
1309 .field("constrain_width", &self.constrain_width)
1310 .finish()
1311 }
1312}
1313
1314impl Deref for ChunkRendererContext<'_, '_> {
1315 type Target = App;
1316
1317 fn deref(&self) -> &Self::Target {
1318 self.context
1319 }
1320}
1321
1322impl DerefMut for ChunkRendererContext<'_, '_> {
1323 fn deref_mut(&mut self) -> &mut Self::Target {
1324 self.context
1325 }
1326}
1327
1328pub struct FoldChunks<'a> {
1329 transform_cursor: Cursor<'a, Transform, Dimensions<FoldOffset, InlayOffset>>,
1330 inlay_chunks: InlayChunks<'a>,
1331 inlay_chunk: Option<(InlayOffset, InlayChunk<'a>)>,
1332 inlay_offset: InlayOffset,
1333 output_offset: FoldOffset,
1334 max_output_offset: FoldOffset,
1335}
1336
1337impl FoldChunks<'_> {
1338 pub(crate) fn seek(&mut self, range: Range<FoldOffset>) {
1339 self.transform_cursor.seek(&range.start, Bias::Right);
1340
1341 let inlay_start = {
1342 let overshoot = range.start.0 - self.transform_cursor.start().0.0;
1343 self.transform_cursor.start().1 + InlayOffset(overshoot)
1344 };
1345
1346 let transform_end = self.transform_cursor.end();
1347
1348 let inlay_end = if self
1349 .transform_cursor
1350 .item()
1351 .is_none_or(|transform| transform.is_fold())
1352 {
1353 inlay_start
1354 } else if range.end < transform_end.0 {
1355 let overshoot = range.end.0 - self.transform_cursor.start().0.0;
1356 self.transform_cursor.start().1 + InlayOffset(overshoot)
1357 } else {
1358 transform_end.1
1359 };
1360
1361 self.inlay_chunks.seek(inlay_start..inlay_end);
1362 self.inlay_chunk = None;
1363 self.inlay_offset = inlay_start;
1364 self.output_offset = range.start;
1365 self.max_output_offset = range.end;
1366 }
1367}
1368
1369impl<'a> Iterator for FoldChunks<'a> {
1370 type Item = Chunk<'a>;
1371
1372 fn next(&mut self) -> Option<Self::Item> {
1373 if self.output_offset >= self.max_output_offset {
1374 return None;
1375 }
1376
1377 let transform = self.transform_cursor.item()?;
1378
1379 // If we're in a fold, then return the fold's display text and
1380 // advance the transform and buffer cursors to the end of the fold.
1381 if let Some(placeholder) = transform.placeholder.as_ref() {
1382 self.inlay_chunk.take();
1383 self.inlay_offset += InlayOffset(transform.summary.input.len);
1384
1385 while self.inlay_offset >= self.transform_cursor.end().1
1386 && self.transform_cursor.item().is_some()
1387 {
1388 self.transform_cursor.next();
1389 }
1390
1391 self.output_offset.0 += placeholder.text.len();
1392 return Some(Chunk {
1393 text: placeholder.text,
1394 renderer: Some(placeholder.renderer.clone()),
1395 ..Default::default()
1396 });
1397 }
1398
1399 // When we reach a non-fold region, seek the underlying text
1400 // chunk iterator to the next unfolded range.
1401 if self.inlay_offset == self.transform_cursor.start().1
1402 && self.inlay_chunks.offset() != self.inlay_offset
1403 {
1404 let transform_start = self.transform_cursor.start();
1405 let transform_end = self.transform_cursor.end();
1406 let inlay_end = if self.max_output_offset < transform_end.0 {
1407 let overshoot = self.max_output_offset.0 - transform_start.0.0;
1408 transform_start.1 + InlayOffset(overshoot)
1409 } else {
1410 transform_end.1
1411 };
1412
1413 self.inlay_chunks.seek(self.inlay_offset..inlay_end);
1414 }
1415
1416 // Retrieve a chunk from the current location in the buffer.
1417 if self.inlay_chunk.is_none() {
1418 let chunk_offset = self.inlay_chunks.offset();
1419 self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1420 }
1421
1422 // Otherwise, take a chunk from the buffer's text.
1423 if let Some((buffer_chunk_start, mut inlay_chunk)) = self.inlay_chunk.clone() {
1424 let chunk = &mut inlay_chunk.chunk;
1425 let buffer_chunk_end = buffer_chunk_start + InlayOffset(chunk.text.len());
1426 let transform_end = self.transform_cursor.end().1;
1427 let chunk_end = buffer_chunk_end.min(transform_end);
1428
1429 chunk.text = &chunk.text
1430 [(self.inlay_offset - buffer_chunk_start).0..(chunk_end - buffer_chunk_start).0];
1431
1432 if chunk_end == transform_end {
1433 self.transform_cursor.next();
1434 } else if chunk_end == buffer_chunk_end {
1435 self.inlay_chunk.take();
1436 }
1437
1438 self.inlay_offset = chunk_end;
1439 self.output_offset.0 += chunk.text.len();
1440 return Some(Chunk {
1441 text: chunk.text,
1442 syntax_highlight_id: chunk.syntax_highlight_id,
1443 highlight_style: chunk.highlight_style,
1444 diagnostic_severity: chunk.diagnostic_severity,
1445 is_unnecessary: chunk.is_unnecessary,
1446 is_tab: chunk.is_tab,
1447 is_inlay: chunk.is_inlay,
1448 underline: chunk.underline,
1449 renderer: inlay_chunk.renderer,
1450 });
1451 }
1452
1453 None
1454 }
1455}
1456
1457#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1458pub struct FoldOffset(pub usize);
1459
1460impl FoldOffset {
1461 pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1462 let mut cursor = snapshot
1463 .transforms
1464 .cursor::<Dimensions<FoldOffset, TransformSummary>>(&());
1465 cursor.seek(&self, Bias::Right);
1466 let overshoot = if cursor.item().is_none_or(|t| t.is_fold()) {
1467 Point::new(0, (self.0 - cursor.start().0.0) as u32)
1468 } else {
1469 let inlay_offset = cursor.start().1.input.len + self.0 - cursor.start().0.0;
1470 let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1471 inlay_point.0 - cursor.start().1.input.lines
1472 };
1473 FoldPoint(cursor.start().1.output.lines + overshoot)
1474 }
1475
1476 #[cfg(test)]
1477 pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1478 let mut cursor = snapshot
1479 .transforms
1480 .cursor::<Dimensions<FoldOffset, InlayOffset>>(&());
1481 cursor.seek(&self, Bias::Right);
1482 let overshoot = self.0 - cursor.start().0.0;
1483 InlayOffset(cursor.start().1.0 + overshoot)
1484 }
1485}
1486
1487impl Add for FoldOffset {
1488 type Output = Self;
1489
1490 fn add(self, rhs: Self) -> Self::Output {
1491 Self(self.0 + rhs.0)
1492 }
1493}
1494
1495impl AddAssign for FoldOffset {
1496 fn add_assign(&mut self, rhs: Self) {
1497 self.0 += rhs.0;
1498 }
1499}
1500
1501impl Sub for FoldOffset {
1502 type Output = Self;
1503
1504 fn sub(self, rhs: Self) -> Self::Output {
1505 Self(self.0 - rhs.0)
1506 }
1507}
1508
1509impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1510 fn zero(_cx: &()) -> Self {
1511 Default::default()
1512 }
1513
1514 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1515 self.0 += &summary.output.len;
1516 }
1517}
1518
1519impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1520 fn zero(_cx: &()) -> Self {
1521 Default::default()
1522 }
1523
1524 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1525 self.0 += &summary.input.lines;
1526 }
1527}
1528
1529impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1530 fn zero(_cx: &()) -> Self {
1531 Default::default()
1532 }
1533
1534 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1535 self.0 += &summary.input.len;
1536 }
1537}
1538
1539pub type FoldEdit = Edit<FoldOffset>;
1540
1541#[cfg(test)]
1542mod tests {
1543 use super::*;
1544 use crate::{MultiBuffer, ToPoint, display_map::inlay_map::InlayMap};
1545 use Bias::{Left, Right};
1546 use collections::HashSet;
1547 use rand::prelude::*;
1548 use settings::SettingsStore;
1549 use std::{env, mem};
1550 use text::Patch;
1551 use util::RandomCharIter;
1552 use util::test::sample_text;
1553
1554 #[gpui::test]
1555 fn test_basic_folds(cx: &mut gpui::App) {
1556 init_test(cx);
1557 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1558 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1559 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1560 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1561 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1562
1563 let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1564 let (snapshot2, edits) = writer.fold(vec![
1565 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1566 (Point::new(2, 4)..Point::new(4, 1), FoldPlaceholder::test()),
1567 ]);
1568 assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1569 assert_eq!(
1570 edits,
1571 &[
1572 FoldEdit {
1573 old: FoldOffset(2)..FoldOffset(16),
1574 new: FoldOffset(2)..FoldOffset(5),
1575 },
1576 FoldEdit {
1577 old: FoldOffset(18)..FoldOffset(29),
1578 new: FoldOffset(7)..FoldOffset(10)
1579 },
1580 ]
1581 );
1582
1583 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1584 buffer.edit(
1585 vec![
1586 (Point::new(0, 0)..Point::new(0, 1), "123"),
1587 (Point::new(2, 3)..Point::new(2, 3), "123"),
1588 ],
1589 None,
1590 cx,
1591 );
1592 buffer.snapshot(cx)
1593 });
1594
1595 let (inlay_snapshot, inlay_edits) =
1596 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1597 let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1598 assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1599 assert_eq!(
1600 edits,
1601 &[
1602 FoldEdit {
1603 old: FoldOffset(0)..FoldOffset(1),
1604 new: FoldOffset(0)..FoldOffset(3),
1605 },
1606 FoldEdit {
1607 old: FoldOffset(6)..FoldOffset(6),
1608 new: FoldOffset(8)..FoldOffset(11),
1609 },
1610 ]
1611 );
1612
1613 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1614 buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1615 buffer.snapshot(cx)
1616 });
1617 let (inlay_snapshot, inlay_edits) =
1618 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1619 let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1620 assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1621
1622 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1623 writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1624 let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1625 assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1626
1627 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1628 writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1629 let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1630 assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1631 }
1632
1633 #[gpui::test]
1634 fn test_adjacent_folds(cx: &mut gpui::App) {
1635 init_test(cx);
1636 let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1637 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1638 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1639 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1640
1641 {
1642 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1643
1644 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1645 writer.fold(vec![(5..8, FoldPlaceholder::test())]);
1646 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1647 assert_eq!(snapshot.text(), "abcde⋯ijkl");
1648
1649 // Create an fold adjacent to the start of the first fold.
1650 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1651 writer.fold(vec![
1652 (0..1, FoldPlaceholder::test()),
1653 (2..5, FoldPlaceholder::test()),
1654 ]);
1655 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1656 assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1657
1658 // Create an fold adjacent to the end of the first fold.
1659 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1660 writer.fold(vec![
1661 (11..11, FoldPlaceholder::test()),
1662 (8..10, FoldPlaceholder::test()),
1663 ]);
1664 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1665 assert_eq!(snapshot.text(), "⋯b⋯kl");
1666 }
1667
1668 {
1669 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1670
1671 // Create two adjacent folds.
1672 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1673 writer.fold(vec![
1674 (0..2, FoldPlaceholder::test()),
1675 (2..5, FoldPlaceholder::test()),
1676 ]);
1677 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1678 assert_eq!(snapshot.text(), "⋯fghijkl");
1679
1680 // Edit within one of the folds.
1681 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1682 buffer.edit([(0..1, "12345")], None, cx);
1683 buffer.snapshot(cx)
1684 });
1685 let (inlay_snapshot, inlay_edits) =
1686 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1687 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1688 assert_eq!(snapshot.text(), "12345⋯fghijkl");
1689 }
1690 }
1691
1692 #[gpui::test]
1693 fn test_overlapping_folds(cx: &mut gpui::App) {
1694 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1695 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1696 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1697 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1698 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1699 writer.fold(vec![
1700 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1701 (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1702 (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1703 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1704 ]);
1705 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1706 assert_eq!(snapshot.text(), "aa⋯eeeee");
1707 }
1708
1709 #[gpui::test]
1710 fn test_merging_folds_via_edit(cx: &mut gpui::App) {
1711 init_test(cx);
1712 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1713 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1714 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1715 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1716 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1717
1718 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1719 writer.fold(vec![
1720 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1721 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1722 ]);
1723 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1724 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1725
1726 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1727 buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1728 buffer.snapshot(cx)
1729 });
1730 let (inlay_snapshot, inlay_edits) =
1731 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1732 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1733 assert_eq!(snapshot.text(), "aa⋯eeeee");
1734 }
1735
1736 #[gpui::test]
1737 fn test_folds_in_range(cx: &mut gpui::App) {
1738 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1739 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1740 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1741 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1742
1743 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1744 writer.fold(vec![
1745 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1746 (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1747 (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1748 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1749 ]);
1750 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1751 let fold_ranges = snapshot
1752 .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1753 .map(|fold| {
1754 fold.range.start.to_point(&buffer_snapshot)
1755 ..fold.range.end.to_point(&buffer_snapshot)
1756 })
1757 .collect::<Vec<_>>();
1758 assert_eq!(
1759 fold_ranges,
1760 vec![
1761 Point::new(0, 2)..Point::new(2, 2),
1762 Point::new(1, 2)..Point::new(3, 2)
1763 ]
1764 );
1765 }
1766
1767 #[gpui::test(iterations = 100)]
1768 fn test_random_folds(cx: &mut gpui::App, mut rng: StdRng) {
1769 init_test(cx);
1770 let operations = env::var("OPERATIONS")
1771 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1772 .unwrap_or(10);
1773
1774 let len = rng.random_range(0..10);
1775 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1776 let buffer = if rng.random() {
1777 MultiBuffer::build_simple(&text, cx)
1778 } else {
1779 MultiBuffer::build_random(&mut rng, cx)
1780 };
1781 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1782 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1783 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1784
1785 let (mut initial_snapshot, _) = map.read(inlay_snapshot, vec![]);
1786 let mut snapshot_edits = Vec::new();
1787
1788 let mut next_inlay_id = 0;
1789 for _ in 0..operations {
1790 log::info!("text: {:?}", buffer_snapshot.text());
1791 let mut buffer_edits = Vec::new();
1792 let mut inlay_edits = Vec::new();
1793 match rng.random_range(0..=100) {
1794 0..=39 => {
1795 snapshot_edits.extend(map.randomly_mutate(&mut rng));
1796 }
1797 40..=59 => {
1798 let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1799 inlay_edits = edits;
1800 }
1801 _ => buffer.update(cx, |buffer, cx| {
1802 let subscription = buffer.subscribe();
1803 let edit_count = rng.random_range(1..=5);
1804 buffer.randomly_mutate(&mut rng, edit_count, cx);
1805 buffer_snapshot = buffer.snapshot(cx);
1806 let edits = subscription.consume().into_inner();
1807 log::info!("editing {:?}", edits);
1808 buffer_edits.extend(edits);
1809 }),
1810 };
1811
1812 let (inlay_snapshot, new_inlay_edits) =
1813 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1814 log::info!("inlay text {:?}", inlay_snapshot.text());
1815
1816 let inlay_edits = Patch::new(inlay_edits)
1817 .compose(new_inlay_edits)
1818 .into_inner();
1819 let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
1820 snapshot_edits.push((snapshot.clone(), edits));
1821
1822 let mut expected_text: String = inlay_snapshot.text().to_string();
1823 for fold_range in map.merged_folds().into_iter().rev() {
1824 let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
1825 let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
1826 expected_text.replace_range(fold_inlay_start.0..fold_inlay_end.0, "⋯");
1827 }
1828
1829 assert_eq!(snapshot.text(), expected_text);
1830 log::info!(
1831 "fold text {:?} ({} lines)",
1832 expected_text,
1833 expected_text.matches('\n').count() + 1
1834 );
1835
1836 let mut prev_row = 0;
1837 let mut expected_buffer_rows = Vec::new();
1838 for fold_range in map.merged_folds() {
1839 let fold_start = inlay_snapshot
1840 .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
1841 .row();
1842 let fold_end = inlay_snapshot
1843 .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
1844 .row();
1845 expected_buffer_rows.extend(
1846 inlay_snapshot
1847 .row_infos(prev_row)
1848 .take((1 + fold_start - prev_row) as usize),
1849 );
1850 prev_row = 1 + fold_end;
1851 }
1852 expected_buffer_rows.extend(inlay_snapshot.row_infos(prev_row));
1853
1854 assert_eq!(
1855 expected_buffer_rows.len(),
1856 expected_text.matches('\n').count() + 1,
1857 "wrong expected buffer rows {:?}. text: {:?}",
1858 expected_buffer_rows,
1859 expected_text
1860 );
1861
1862 for (output_row, line) in expected_text.lines().enumerate() {
1863 let line_len = snapshot.line_len(output_row as u32);
1864 assert_eq!(line_len, line.len() as u32);
1865 }
1866
1867 let longest_row = snapshot.longest_row();
1868 let longest_char_column = expected_text
1869 .split('\n')
1870 .nth(longest_row as usize)
1871 .unwrap()
1872 .chars()
1873 .count();
1874 let mut fold_point = FoldPoint::new(0, 0);
1875 let mut fold_offset = FoldOffset(0);
1876 let mut char_column = 0;
1877 for c in expected_text.chars() {
1878 let inlay_point = fold_point.to_inlay_point(&snapshot);
1879 let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
1880 assert_eq!(
1881 snapshot.to_fold_point(inlay_point, Right),
1882 fold_point,
1883 "{:?} -> fold point",
1884 inlay_point,
1885 );
1886 assert_eq!(
1887 inlay_snapshot.to_offset(inlay_point),
1888 inlay_offset,
1889 "inlay_snapshot.to_offset({:?})",
1890 inlay_point,
1891 );
1892 assert_eq!(
1893 fold_point.to_offset(&snapshot),
1894 fold_offset,
1895 "fold_point.to_offset({:?})",
1896 fold_point,
1897 );
1898
1899 if c == '\n' {
1900 *fold_point.row_mut() += 1;
1901 *fold_point.column_mut() = 0;
1902 char_column = 0;
1903 } else {
1904 *fold_point.column_mut() += c.len_utf8() as u32;
1905 char_column += 1;
1906 }
1907 fold_offset.0 += c.len_utf8();
1908 if char_column > longest_char_column {
1909 panic!(
1910 "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
1911 longest_row,
1912 longest_char_column,
1913 fold_point.row(),
1914 char_column
1915 );
1916 }
1917 }
1918
1919 for _ in 0..5 {
1920 let mut start = snapshot.clip_offset(
1921 FoldOffset(rng.random_range(0..=snapshot.len().0)),
1922 Bias::Left,
1923 );
1924 let mut end = snapshot.clip_offset(
1925 FoldOffset(rng.random_range(0..=snapshot.len().0)),
1926 Bias::Right,
1927 );
1928 if start > end {
1929 mem::swap(&mut start, &mut end);
1930 }
1931
1932 let text = &expected_text[start.0..end.0];
1933 assert_eq!(
1934 snapshot
1935 .chunks(start..end, false, Highlights::default())
1936 .map(|c| c.text)
1937 .collect::<String>(),
1938 text,
1939 );
1940 }
1941
1942 let mut fold_row = 0;
1943 while fold_row < expected_buffer_rows.len() as u32 {
1944 assert_eq!(
1945 snapshot.row_infos(fold_row).collect::<Vec<_>>(),
1946 expected_buffer_rows[(fold_row as usize)..],
1947 "wrong buffer rows starting at fold row {}",
1948 fold_row,
1949 );
1950 fold_row += 1;
1951 }
1952
1953 let folded_buffer_rows = map
1954 .merged_folds()
1955 .iter()
1956 .flat_map(|fold_range| {
1957 let start_row = fold_range.start.to_point(&buffer_snapshot).row;
1958 let end = fold_range.end.to_point(&buffer_snapshot);
1959 if end.column == 0 {
1960 start_row..end.row
1961 } else {
1962 start_row..end.row + 1
1963 }
1964 })
1965 .collect::<HashSet<_>>();
1966 for row in 0..=buffer_snapshot.max_point().row {
1967 assert_eq!(
1968 snapshot.is_line_folded(MultiBufferRow(row)),
1969 folded_buffer_rows.contains(&row),
1970 "expected buffer row {}{} to be folded",
1971 row,
1972 if folded_buffer_rows.contains(&row) {
1973 ""
1974 } else {
1975 " not"
1976 }
1977 );
1978 }
1979
1980 for _ in 0..5 {
1981 let end =
1982 buffer_snapshot.clip_offset(rng.random_range(0..=buffer_snapshot.len()), Right);
1983 let start = buffer_snapshot.clip_offset(rng.random_range(0..=end), Left);
1984 let expected_folds = map
1985 .snapshot
1986 .folds
1987 .items(&buffer_snapshot)
1988 .into_iter()
1989 .filter(|fold| {
1990 let start = buffer_snapshot.anchor_before(start);
1991 let end = buffer_snapshot.anchor_after(end);
1992 start.cmp(&fold.range.end, &buffer_snapshot) == Ordering::Less
1993 && end.cmp(&fold.range.start, &buffer_snapshot) == Ordering::Greater
1994 })
1995 .collect::<Vec<_>>();
1996
1997 assert_eq!(
1998 snapshot
1999 .folds_in_range(start..end)
2000 .cloned()
2001 .collect::<Vec<_>>(),
2002 expected_folds
2003 );
2004 }
2005
2006 let text = snapshot.text();
2007 for _ in 0..5 {
2008 let start_row = rng.random_range(0..=snapshot.max_point().row());
2009 let start_column = rng.random_range(0..=snapshot.line_len(start_row));
2010 let end_row = rng.random_range(0..=snapshot.max_point().row());
2011 let end_column = rng.random_range(0..=snapshot.line_len(end_row));
2012 let mut start =
2013 snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
2014 let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
2015 if start > end {
2016 mem::swap(&mut start, &mut end);
2017 }
2018
2019 let lines = start..end;
2020 let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
2021 assert_eq!(
2022 snapshot.text_summary_for_range(lines),
2023 TextSummary::from(&text[bytes.start.0..bytes.end.0])
2024 )
2025 }
2026
2027 let mut text = initial_snapshot.text();
2028 for (snapshot, edits) in snapshot_edits.drain(..) {
2029 let new_text = snapshot.text();
2030 for edit in edits {
2031 let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
2032 let new_bytes = edit.new.start.0..edit.new.end.0;
2033 text.replace_range(old_bytes, &new_text[new_bytes]);
2034 }
2035
2036 assert_eq!(text, new_text);
2037 initial_snapshot = snapshot;
2038 }
2039 }
2040 }
2041
2042 #[gpui::test]
2043 fn test_buffer_rows(cx: &mut gpui::App) {
2044 let text = sample_text(6, 6, 'a') + "\n";
2045 let buffer = MultiBuffer::build_simple(&text, cx);
2046
2047 let buffer_snapshot = buffer.read(cx).snapshot(cx);
2048 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
2049 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
2050
2051 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
2052 writer.fold(vec![
2053 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
2054 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
2055 ]);
2056
2057 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
2058 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
2059 assert_eq!(
2060 snapshot
2061 .row_infos(0)
2062 .map(|info| info.buffer_row)
2063 .collect::<Vec<_>>(),
2064 [Some(0), Some(3), Some(5), Some(6)]
2065 );
2066 assert_eq!(
2067 snapshot
2068 .row_infos(3)
2069 .map(|info| info.buffer_row)
2070 .collect::<Vec<_>>(),
2071 [Some(6)]
2072 );
2073 }
2074
2075 fn init_test(cx: &mut gpui::App) {
2076 let store = SettingsStore::test(cx);
2077 cx.set_global(store);
2078 }
2079
2080 impl FoldMap {
2081 fn merged_folds(&self) -> Vec<Range<usize>> {
2082 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2083 let buffer = &inlay_snapshot.buffer;
2084 let mut folds = self.snapshot.folds.items(buffer);
2085 // Ensure sorting doesn't change how folds get merged and displayed.
2086 folds.sort_by(|a, b| a.range.cmp(&b.range, buffer));
2087 let mut folds = folds
2088 .iter()
2089 .map(|fold| fold.range.start.to_offset(buffer)..fold.range.end.to_offset(buffer))
2090 .peekable();
2091
2092 let mut merged_folds = Vec::new();
2093 while let Some(mut fold_range) = folds.next() {
2094 while let Some(next_range) = folds.peek() {
2095 if fold_range.end >= next_range.start {
2096 if next_range.end > fold_range.end {
2097 fold_range.end = next_range.end;
2098 }
2099 folds.next();
2100 } else {
2101 break;
2102 }
2103 }
2104 if fold_range.end > fold_range.start {
2105 merged_folds.push(fold_range);
2106 }
2107 }
2108 merged_folds
2109 }
2110
2111 pub fn randomly_mutate(
2112 &mut self,
2113 rng: &mut impl Rng,
2114 ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
2115 let mut snapshot_edits = Vec::new();
2116 match rng.random_range(0..=100) {
2117 0..=39 if !self.snapshot.folds.is_empty() => {
2118 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2119 let buffer = &inlay_snapshot.buffer;
2120 let mut to_unfold = Vec::new();
2121 for _ in 0..rng.random_range(1..=3) {
2122 let end = buffer.clip_offset(rng.random_range(0..=buffer.len()), Right);
2123 let start = buffer.clip_offset(rng.random_range(0..=end), Left);
2124 to_unfold.push(start..end);
2125 }
2126 let inclusive = rng.random();
2127 log::info!("unfolding {:?} (inclusive: {})", to_unfold, inclusive);
2128 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2129 snapshot_edits.push((snapshot, edits));
2130 let (snapshot, edits) = writer.unfold_intersecting(to_unfold, inclusive);
2131 snapshot_edits.push((snapshot, edits));
2132 }
2133 _ => {
2134 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2135 let buffer = &inlay_snapshot.buffer;
2136 let mut to_fold = Vec::new();
2137 for _ in 0..rng.random_range(1..=2) {
2138 let end = buffer.clip_offset(rng.random_range(0..=buffer.len()), Right);
2139 let start = buffer.clip_offset(rng.random_range(0..=end), Left);
2140 to_fold.push((start..end, FoldPlaceholder::test()));
2141 }
2142 log::info!("folding {:?}", to_fold);
2143 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2144 snapshot_edits.push((snapshot, edits));
2145 let (snapshot, edits) = writer.fold(to_fold);
2146 snapshot_edits.push((snapshot, edits));
2147 }
2148 }
2149 snapshot_edits
2150 }
2151 }
2152}