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