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 was originally a tab character.
1259 pub is_tab: bool,
1260 /// An optional recipe for how the chunk should be presented.
1261 pub renderer: Option<ChunkRenderer>,
1262}
1263
1264/// A recipe for how the chunk should be presented.
1265#[derive(Clone)]
1266pub struct ChunkRenderer {
1267 /// The id of the fold associated with this chunk.
1268 pub id: FoldId,
1269 /// Creates a custom element to represent this chunk.
1270 pub render: Arc<dyn Send + Sync + Fn(&mut ChunkRendererContext) -> AnyElement>,
1271 /// If true, the element is constrained to the shaped width of the text.
1272 pub constrain_width: bool,
1273 /// The width of the element, as measured during the last layout pass.
1274 ///
1275 /// This is None if the element has not been laid out yet.
1276 pub measured_width: Option<Pixels>,
1277}
1278
1279pub struct ChunkRendererContext<'a, 'b> {
1280 pub window: &'a mut Window,
1281 pub context: &'b mut App,
1282 pub max_width: Pixels,
1283}
1284
1285impl fmt::Debug for ChunkRenderer {
1286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1287 f.debug_struct("ChunkRenderer")
1288 .field("constrain_width", &self.constrain_width)
1289 .finish()
1290 }
1291}
1292
1293impl Deref for ChunkRendererContext<'_, '_> {
1294 type Target = App;
1295
1296 fn deref(&self) -> &Self::Target {
1297 self.context
1298 }
1299}
1300
1301impl DerefMut for ChunkRendererContext<'_, '_> {
1302 fn deref_mut(&mut self) -> &mut Self::Target {
1303 self.context
1304 }
1305}
1306
1307pub struct FoldChunks<'a> {
1308 transform_cursor: Cursor<'a, Transform, (FoldOffset, InlayOffset)>,
1309 inlay_chunks: InlayChunks<'a>,
1310 inlay_chunk: Option<(InlayOffset, language::Chunk<'a>)>,
1311 inlay_offset: InlayOffset,
1312 output_offset: FoldOffset,
1313 max_output_offset: FoldOffset,
1314}
1315
1316impl FoldChunks<'_> {
1317 pub(crate) fn seek(&mut self, range: Range<FoldOffset>) {
1318 self.transform_cursor.seek(&range.start, Bias::Right, &());
1319
1320 let inlay_start = {
1321 let overshoot = range.start.0 - self.transform_cursor.start().0.0;
1322 self.transform_cursor.start().1 + InlayOffset(overshoot)
1323 };
1324
1325 let transform_end = self.transform_cursor.end(&());
1326
1327 let inlay_end = if self
1328 .transform_cursor
1329 .item()
1330 .map_or(true, |transform| transform.is_fold())
1331 {
1332 inlay_start
1333 } else if range.end < transform_end.0 {
1334 let overshoot = range.end.0 - self.transform_cursor.start().0.0;
1335 self.transform_cursor.start().1 + InlayOffset(overshoot)
1336 } else {
1337 transform_end.1
1338 };
1339
1340 self.inlay_chunks.seek(inlay_start..inlay_end);
1341 self.inlay_chunk = None;
1342 self.inlay_offset = inlay_start;
1343 self.output_offset = range.start;
1344 self.max_output_offset = range.end;
1345 }
1346}
1347
1348impl<'a> Iterator for FoldChunks<'a> {
1349 type Item = Chunk<'a>;
1350
1351 fn next(&mut self) -> Option<Self::Item> {
1352 if self.output_offset >= self.max_output_offset {
1353 return None;
1354 }
1355
1356 let transform = self.transform_cursor.item()?;
1357
1358 // If we're in a fold, then return the fold's display text and
1359 // advance the transform and buffer cursors to the end of the fold.
1360 if let Some(placeholder) = transform.placeholder.as_ref() {
1361 self.inlay_chunk.take();
1362 self.inlay_offset += InlayOffset(transform.summary.input.len);
1363
1364 while self.inlay_offset >= self.transform_cursor.end(&()).1
1365 && self.transform_cursor.item().is_some()
1366 {
1367 self.transform_cursor.next(&());
1368 }
1369
1370 self.output_offset.0 += placeholder.text.len();
1371 return Some(Chunk {
1372 text: placeholder.text,
1373 renderer: Some(placeholder.renderer.clone()),
1374 ..Default::default()
1375 });
1376 }
1377
1378 // When we reach a non-fold region, seek the underlying text
1379 // chunk iterator to the next unfolded range.
1380 if self.inlay_offset == self.transform_cursor.start().1
1381 && self.inlay_chunks.offset() != self.inlay_offset
1382 {
1383 let transform_start = self.transform_cursor.start();
1384 let transform_end = self.transform_cursor.end(&());
1385 let inlay_end = if self.max_output_offset < transform_end.0 {
1386 let overshoot = self.max_output_offset.0 - transform_start.0.0;
1387 transform_start.1 + InlayOffset(overshoot)
1388 } else {
1389 transform_end.1
1390 };
1391
1392 self.inlay_chunks.seek(self.inlay_offset..inlay_end);
1393 }
1394
1395 // Retrieve a chunk from the current location in the buffer.
1396 if self.inlay_chunk.is_none() {
1397 let chunk_offset = self.inlay_chunks.offset();
1398 self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1399 }
1400
1401 // Otherwise, take a chunk from the buffer's text.
1402 if let Some((buffer_chunk_start, mut chunk)) = self.inlay_chunk.clone() {
1403 let buffer_chunk_end = buffer_chunk_start + InlayOffset(chunk.text.len());
1404 let transform_end = self.transform_cursor.end(&()).1;
1405 let chunk_end = buffer_chunk_end.min(transform_end);
1406
1407 chunk.text = &chunk.text
1408 [(self.inlay_offset - buffer_chunk_start).0..(chunk_end - buffer_chunk_start).0];
1409
1410 if chunk_end == transform_end {
1411 self.transform_cursor.next(&());
1412 } else if chunk_end == buffer_chunk_end {
1413 self.inlay_chunk.take();
1414 }
1415
1416 self.inlay_offset = chunk_end;
1417 self.output_offset.0 += chunk.text.len();
1418 return Some(Chunk {
1419 text: chunk.text,
1420 syntax_highlight_id: chunk.syntax_highlight_id,
1421 highlight_style: chunk.highlight_style,
1422 diagnostic_severity: chunk.diagnostic_severity,
1423 is_unnecessary: chunk.is_unnecessary,
1424 is_tab: chunk.is_tab,
1425 renderer: None,
1426 });
1427 }
1428
1429 None
1430 }
1431}
1432
1433#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1434pub struct FoldOffset(pub usize);
1435
1436impl FoldOffset {
1437 pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1438 let mut cursor = snapshot
1439 .transforms
1440 .cursor::<(FoldOffset, TransformSummary)>(&());
1441 cursor.seek(&self, Bias::Right, &());
1442 let overshoot = if cursor.item().map_or(true, |t| t.is_fold()) {
1443 Point::new(0, (self.0 - cursor.start().0.0) as u32)
1444 } else {
1445 let inlay_offset = cursor.start().1.input.len + self.0 - cursor.start().0.0;
1446 let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1447 inlay_point.0 - cursor.start().1.input.lines
1448 };
1449 FoldPoint(cursor.start().1.output.lines + overshoot)
1450 }
1451
1452 #[cfg(test)]
1453 pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1454 let mut cursor = snapshot.transforms.cursor::<(FoldOffset, InlayOffset)>(&());
1455 cursor.seek(&self, Bias::Right, &());
1456 let overshoot = self.0 - cursor.start().0.0;
1457 InlayOffset(cursor.start().1.0 + overshoot)
1458 }
1459}
1460
1461impl Add for FoldOffset {
1462 type Output = Self;
1463
1464 fn add(self, rhs: Self) -> Self::Output {
1465 Self(self.0 + rhs.0)
1466 }
1467}
1468
1469impl AddAssign for FoldOffset {
1470 fn add_assign(&mut self, rhs: Self) {
1471 self.0 += rhs.0;
1472 }
1473}
1474
1475impl Sub for FoldOffset {
1476 type Output = Self;
1477
1478 fn sub(self, rhs: Self) -> Self::Output {
1479 Self(self.0 - rhs.0)
1480 }
1481}
1482
1483impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1484 fn zero(_cx: &()) -> Self {
1485 Default::default()
1486 }
1487
1488 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1489 self.0 += &summary.output.len;
1490 }
1491}
1492
1493impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1494 fn zero(_cx: &()) -> Self {
1495 Default::default()
1496 }
1497
1498 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1499 self.0 += &summary.input.lines;
1500 }
1501}
1502
1503impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1504 fn zero(_cx: &()) -> Self {
1505 Default::default()
1506 }
1507
1508 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1509 self.0 += &summary.input.len;
1510 }
1511}
1512
1513pub type FoldEdit = Edit<FoldOffset>;
1514
1515#[cfg(test)]
1516mod tests {
1517 use super::*;
1518 use crate::{MultiBuffer, ToPoint, display_map::inlay_map::InlayMap};
1519 use Bias::{Left, Right};
1520 use collections::HashSet;
1521 use rand::prelude::*;
1522 use settings::SettingsStore;
1523 use std::{env, mem};
1524 use text::Patch;
1525 use util::RandomCharIter;
1526 use util::test::sample_text;
1527
1528 #[gpui::test]
1529 fn test_basic_folds(cx: &mut gpui::App) {
1530 init_test(cx);
1531 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1532 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1533 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1534 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1535 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1536
1537 let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1538 let (snapshot2, edits) = writer.fold(vec![
1539 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1540 (Point::new(2, 4)..Point::new(4, 1), FoldPlaceholder::test()),
1541 ]);
1542 assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1543 assert_eq!(
1544 edits,
1545 &[
1546 FoldEdit {
1547 old: FoldOffset(2)..FoldOffset(16),
1548 new: FoldOffset(2)..FoldOffset(5),
1549 },
1550 FoldEdit {
1551 old: FoldOffset(18)..FoldOffset(29),
1552 new: FoldOffset(7)..FoldOffset(10)
1553 },
1554 ]
1555 );
1556
1557 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1558 buffer.edit(
1559 vec![
1560 (Point::new(0, 0)..Point::new(0, 1), "123"),
1561 (Point::new(2, 3)..Point::new(2, 3), "123"),
1562 ],
1563 None,
1564 cx,
1565 );
1566 buffer.snapshot(cx)
1567 });
1568
1569 let (inlay_snapshot, inlay_edits) =
1570 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1571 let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1572 assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1573 assert_eq!(
1574 edits,
1575 &[
1576 FoldEdit {
1577 old: FoldOffset(0)..FoldOffset(1),
1578 new: FoldOffset(0)..FoldOffset(3),
1579 },
1580 FoldEdit {
1581 old: FoldOffset(6)..FoldOffset(6),
1582 new: FoldOffset(8)..FoldOffset(11),
1583 },
1584 ]
1585 );
1586
1587 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1588 buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1589 buffer.snapshot(cx)
1590 });
1591 let (inlay_snapshot, inlay_edits) =
1592 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1593 let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1594 assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1595
1596 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1597 writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1598 let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1599 assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1600
1601 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1602 writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1603 let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1604 assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1605 }
1606
1607 #[gpui::test]
1608 fn test_adjacent_folds(cx: &mut gpui::App) {
1609 init_test(cx);
1610 let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1611 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1612 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1613 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1614
1615 {
1616 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1617
1618 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1619 writer.fold(vec![(5..8, FoldPlaceholder::test())]);
1620 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1621 assert_eq!(snapshot.text(), "abcde⋯ijkl");
1622
1623 // Create an fold adjacent to the start of the first fold.
1624 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1625 writer.fold(vec![
1626 (0..1, FoldPlaceholder::test()),
1627 (2..5, FoldPlaceholder::test()),
1628 ]);
1629 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1630 assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1631
1632 // Create an fold adjacent to the end of the first fold.
1633 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1634 writer.fold(vec![
1635 (11..11, FoldPlaceholder::test()),
1636 (8..10, FoldPlaceholder::test()),
1637 ]);
1638 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1639 assert_eq!(snapshot.text(), "⋯b⋯kl");
1640 }
1641
1642 {
1643 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1644
1645 // Create two adjacent folds.
1646 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1647 writer.fold(vec![
1648 (0..2, FoldPlaceholder::test()),
1649 (2..5, FoldPlaceholder::test()),
1650 ]);
1651 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1652 assert_eq!(snapshot.text(), "⋯fghijkl");
1653
1654 // Edit within one of the folds.
1655 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1656 buffer.edit([(0..1, "12345")], None, cx);
1657 buffer.snapshot(cx)
1658 });
1659 let (inlay_snapshot, inlay_edits) =
1660 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1661 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1662 assert_eq!(snapshot.text(), "12345⋯fghijkl");
1663 }
1664 }
1665
1666 #[gpui::test]
1667 fn test_overlapping_folds(cx: &mut gpui::App) {
1668 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1669 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1670 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1671 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1672 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1673 writer.fold(vec![
1674 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1675 (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1676 (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1677 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1678 ]);
1679 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1680 assert_eq!(snapshot.text(), "aa⋯eeeee");
1681 }
1682
1683 #[gpui::test]
1684 fn test_merging_folds_via_edit(cx: &mut gpui::App) {
1685 init_test(cx);
1686 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1687 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1688 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1689 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1690 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1691
1692 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1693 writer.fold(vec![
1694 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1695 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1696 ]);
1697 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1698 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1699
1700 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1701 buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1702 buffer.snapshot(cx)
1703 });
1704 let (inlay_snapshot, inlay_edits) =
1705 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1706 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1707 assert_eq!(snapshot.text(), "aa⋯eeeee");
1708 }
1709
1710 #[gpui::test]
1711 fn test_folds_in_range(cx: &mut gpui::App) {
1712 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1713 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1714 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1715 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1716
1717 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1718 writer.fold(vec![
1719 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1720 (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1721 (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1722 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1723 ]);
1724 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1725 let fold_ranges = snapshot
1726 .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1727 .map(|fold| {
1728 fold.range.start.to_point(&buffer_snapshot)
1729 ..fold.range.end.to_point(&buffer_snapshot)
1730 })
1731 .collect::<Vec<_>>();
1732 assert_eq!(
1733 fold_ranges,
1734 vec![
1735 Point::new(0, 2)..Point::new(2, 2),
1736 Point::new(1, 2)..Point::new(3, 2)
1737 ]
1738 );
1739 }
1740
1741 #[gpui::test(iterations = 100)]
1742 fn test_random_folds(cx: &mut gpui::App, mut rng: StdRng) {
1743 init_test(cx);
1744 let operations = env::var("OPERATIONS")
1745 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1746 .unwrap_or(10);
1747
1748 let len = rng.gen_range(0..10);
1749 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1750 let buffer = if rng.r#gen() {
1751 MultiBuffer::build_simple(&text, cx)
1752 } else {
1753 MultiBuffer::build_random(&mut rng, cx)
1754 };
1755 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1756 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1757 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1758
1759 let (mut initial_snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1760 let mut snapshot_edits = Vec::new();
1761
1762 let mut next_inlay_id = 0;
1763 for _ in 0..operations {
1764 log::info!("text: {:?}", buffer_snapshot.text());
1765 let mut buffer_edits = Vec::new();
1766 let mut inlay_edits = Vec::new();
1767 match rng.gen_range(0..=100) {
1768 0..=39 => {
1769 snapshot_edits.extend(map.randomly_mutate(&mut rng));
1770 }
1771 40..=59 => {
1772 let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1773 inlay_edits = edits;
1774 }
1775 _ => buffer.update(cx, |buffer, cx| {
1776 let subscription = buffer.subscribe();
1777 let edit_count = rng.gen_range(1..=5);
1778 buffer.randomly_mutate(&mut rng, edit_count, cx);
1779 buffer_snapshot = buffer.snapshot(cx);
1780 let edits = subscription.consume().into_inner();
1781 log::info!("editing {:?}", edits);
1782 buffer_edits.extend(edits);
1783 }),
1784 };
1785
1786 let (inlay_snapshot, new_inlay_edits) =
1787 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1788 log::info!("inlay text {:?}", inlay_snapshot.text());
1789
1790 let inlay_edits = Patch::new(inlay_edits)
1791 .compose(new_inlay_edits)
1792 .into_inner();
1793 let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
1794 snapshot_edits.push((snapshot.clone(), edits));
1795
1796 let mut expected_text: String = inlay_snapshot.text().to_string();
1797 for fold_range in map.merged_folds().into_iter().rev() {
1798 let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
1799 let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
1800 expected_text.replace_range(fold_inlay_start.0..fold_inlay_end.0, "⋯");
1801 }
1802
1803 assert_eq!(snapshot.text(), expected_text);
1804 log::info!(
1805 "fold text {:?} ({} lines)",
1806 expected_text,
1807 expected_text.matches('\n').count() + 1
1808 );
1809
1810 let mut prev_row = 0;
1811 let mut expected_buffer_rows = Vec::new();
1812 for fold_range in map.merged_folds() {
1813 let fold_start = inlay_snapshot
1814 .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
1815 .row();
1816 let fold_end = inlay_snapshot
1817 .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
1818 .row();
1819 expected_buffer_rows.extend(
1820 inlay_snapshot
1821 .row_infos(prev_row)
1822 .take((1 + fold_start - prev_row) as usize),
1823 );
1824 prev_row = 1 + fold_end;
1825 }
1826 expected_buffer_rows.extend(inlay_snapshot.row_infos(prev_row));
1827
1828 assert_eq!(
1829 expected_buffer_rows.len(),
1830 expected_text.matches('\n').count() + 1,
1831 "wrong expected buffer rows {:?}. text: {:?}",
1832 expected_buffer_rows,
1833 expected_text
1834 );
1835
1836 for (output_row, line) in expected_text.lines().enumerate() {
1837 let line_len = snapshot.line_len(output_row as u32);
1838 assert_eq!(line_len, line.len() as u32);
1839 }
1840
1841 let longest_row = snapshot.longest_row();
1842 let longest_char_column = expected_text
1843 .split('\n')
1844 .nth(longest_row as usize)
1845 .unwrap()
1846 .chars()
1847 .count();
1848 let mut fold_point = FoldPoint::new(0, 0);
1849 let mut fold_offset = FoldOffset(0);
1850 let mut char_column = 0;
1851 for c in expected_text.chars() {
1852 let inlay_point = fold_point.to_inlay_point(&snapshot);
1853 let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
1854 assert_eq!(
1855 snapshot.to_fold_point(inlay_point, Right),
1856 fold_point,
1857 "{:?} -> fold point",
1858 inlay_point,
1859 );
1860 assert_eq!(
1861 inlay_snapshot.to_offset(inlay_point),
1862 inlay_offset,
1863 "inlay_snapshot.to_offset({:?})",
1864 inlay_point,
1865 );
1866 assert_eq!(
1867 fold_point.to_offset(&snapshot),
1868 fold_offset,
1869 "fold_point.to_offset({:?})",
1870 fold_point,
1871 );
1872
1873 if c == '\n' {
1874 *fold_point.row_mut() += 1;
1875 *fold_point.column_mut() = 0;
1876 char_column = 0;
1877 } else {
1878 *fold_point.column_mut() += c.len_utf8() as u32;
1879 char_column += 1;
1880 }
1881 fold_offset.0 += c.len_utf8();
1882 if char_column > longest_char_column {
1883 panic!(
1884 "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
1885 longest_row,
1886 longest_char_column,
1887 fold_point.row(),
1888 char_column
1889 );
1890 }
1891 }
1892
1893 for _ in 0..5 {
1894 let mut start = snapshot
1895 .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Left);
1896 let mut end = snapshot
1897 .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Right);
1898 if start > end {
1899 mem::swap(&mut start, &mut end);
1900 }
1901
1902 let text = &expected_text[start.0..end.0];
1903 assert_eq!(
1904 snapshot
1905 .chunks(start..end, false, Highlights::default())
1906 .map(|c| c.text)
1907 .collect::<String>(),
1908 text,
1909 );
1910 }
1911
1912 let mut fold_row = 0;
1913 while fold_row < expected_buffer_rows.len() as u32 {
1914 assert_eq!(
1915 snapshot.row_infos(fold_row).collect::<Vec<_>>(),
1916 expected_buffer_rows[(fold_row as usize)..],
1917 "wrong buffer rows starting at fold row {}",
1918 fold_row,
1919 );
1920 fold_row += 1;
1921 }
1922
1923 let folded_buffer_rows = map
1924 .merged_folds()
1925 .iter()
1926 .flat_map(|fold_range| {
1927 let start_row = fold_range.start.to_point(&buffer_snapshot).row;
1928 let end = fold_range.end.to_point(&buffer_snapshot);
1929 if end.column == 0 {
1930 start_row..end.row
1931 } else {
1932 start_row..end.row + 1
1933 }
1934 })
1935 .collect::<HashSet<_>>();
1936 for row in 0..=buffer_snapshot.max_point().row {
1937 assert_eq!(
1938 snapshot.is_line_folded(MultiBufferRow(row)),
1939 folded_buffer_rows.contains(&row),
1940 "expected buffer row {}{} to be folded",
1941 row,
1942 if folded_buffer_rows.contains(&row) {
1943 ""
1944 } else {
1945 " not"
1946 }
1947 );
1948 }
1949
1950 for _ in 0..5 {
1951 let end =
1952 buffer_snapshot.clip_offset(rng.gen_range(0..=buffer_snapshot.len()), Right);
1953 let start = buffer_snapshot.clip_offset(rng.gen_range(0..=end), Left);
1954 let expected_folds = map
1955 .snapshot
1956 .folds
1957 .items(&buffer_snapshot)
1958 .into_iter()
1959 .filter(|fold| {
1960 let start = buffer_snapshot.anchor_before(start);
1961 let end = buffer_snapshot.anchor_after(end);
1962 start.cmp(&fold.range.end, &buffer_snapshot) == Ordering::Less
1963 && end.cmp(&fold.range.start, &buffer_snapshot) == Ordering::Greater
1964 })
1965 .collect::<Vec<_>>();
1966
1967 assert_eq!(
1968 snapshot
1969 .folds_in_range(start..end)
1970 .cloned()
1971 .collect::<Vec<_>>(),
1972 expected_folds
1973 );
1974 }
1975
1976 let text = snapshot.text();
1977 for _ in 0..5 {
1978 let start_row = rng.gen_range(0..=snapshot.max_point().row());
1979 let start_column = rng.gen_range(0..=snapshot.line_len(start_row));
1980 let end_row = rng.gen_range(0..=snapshot.max_point().row());
1981 let end_column = rng.gen_range(0..=snapshot.line_len(end_row));
1982 let mut start =
1983 snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
1984 let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
1985 if start > end {
1986 mem::swap(&mut start, &mut end);
1987 }
1988
1989 let lines = start..end;
1990 let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
1991 assert_eq!(
1992 snapshot.text_summary_for_range(lines),
1993 TextSummary::from(&text[bytes.start.0..bytes.end.0])
1994 )
1995 }
1996
1997 let mut text = initial_snapshot.text();
1998 for (snapshot, edits) in snapshot_edits.drain(..) {
1999 let new_text = snapshot.text();
2000 for edit in edits {
2001 let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
2002 let new_bytes = edit.new.start.0..edit.new.end.0;
2003 text.replace_range(old_bytes, &new_text[new_bytes]);
2004 }
2005
2006 assert_eq!(text, new_text);
2007 initial_snapshot = snapshot;
2008 }
2009 }
2010 }
2011
2012 #[gpui::test]
2013 fn test_buffer_rows(cx: &mut gpui::App) {
2014 let text = sample_text(6, 6, 'a') + "\n";
2015 let buffer = MultiBuffer::build_simple(&text, cx);
2016
2017 let buffer_snapshot = buffer.read(cx).snapshot(cx);
2018 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
2019 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
2020
2021 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
2022 writer.fold(vec![
2023 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
2024 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
2025 ]);
2026
2027 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
2028 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
2029 assert_eq!(
2030 snapshot
2031 .row_infos(0)
2032 .map(|info| info.buffer_row)
2033 .collect::<Vec<_>>(),
2034 [Some(0), Some(3), Some(5), Some(6)]
2035 );
2036 assert_eq!(
2037 snapshot
2038 .row_infos(3)
2039 .map(|info| info.buffer_row)
2040 .collect::<Vec<_>>(),
2041 [Some(6)]
2042 );
2043 }
2044
2045 fn init_test(cx: &mut gpui::App) {
2046 let store = SettingsStore::test(cx);
2047 cx.set_global(store);
2048 }
2049
2050 impl FoldMap {
2051 fn merged_folds(&self) -> Vec<Range<usize>> {
2052 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2053 let buffer = &inlay_snapshot.buffer;
2054 let mut folds = self.snapshot.folds.items(buffer);
2055 // Ensure sorting doesn't change how folds get merged and displayed.
2056 folds.sort_by(|a, b| a.range.cmp(&b.range, buffer));
2057 let mut folds = folds
2058 .iter()
2059 .map(|fold| fold.range.start.to_offset(buffer)..fold.range.end.to_offset(buffer))
2060 .peekable();
2061
2062 let mut merged_folds = Vec::new();
2063 while let Some(mut fold_range) = folds.next() {
2064 while let Some(next_range) = folds.peek() {
2065 if fold_range.end >= next_range.start {
2066 if next_range.end > fold_range.end {
2067 fold_range.end = next_range.end;
2068 }
2069 folds.next();
2070 } else {
2071 break;
2072 }
2073 }
2074 if fold_range.end > fold_range.start {
2075 merged_folds.push(fold_range);
2076 }
2077 }
2078 merged_folds
2079 }
2080
2081 pub fn randomly_mutate(
2082 &mut self,
2083 rng: &mut impl Rng,
2084 ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
2085 let mut snapshot_edits = Vec::new();
2086 match rng.gen_range(0..=100) {
2087 0..=39 if !self.snapshot.folds.is_empty() => {
2088 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2089 let buffer = &inlay_snapshot.buffer;
2090 let mut to_unfold = Vec::new();
2091 for _ in 0..rng.gen_range(1..=3) {
2092 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
2093 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
2094 to_unfold.push(start..end);
2095 }
2096 let inclusive = rng.r#gen();
2097 log::info!("unfolding {:?} (inclusive: {})", to_unfold, inclusive);
2098 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2099 snapshot_edits.push((snapshot, edits));
2100 let (snapshot, edits) = writer.unfold_intersecting(to_unfold, inclusive);
2101 snapshot_edits.push((snapshot, edits));
2102 }
2103 _ => {
2104 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2105 let buffer = &inlay_snapshot.buffer;
2106 let mut to_fold = Vec::new();
2107 for _ in 0..rng.gen_range(1..=2) {
2108 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
2109 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
2110 to_fold.push((start..end, FoldPlaceholder::test()));
2111 }
2112 log::info!("folding {:?}", to_fold);
2113 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2114 snapshot_edits.push((snapshot, edits));
2115 let (snapshot, edits) = writer.fold(to_fold);
2116 snapshot_edits.push((snapshot, edits));
2117 }
2118 }
2119 snapshot_edits
2120 }
2121 }
2122}