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