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