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