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