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}
1404
1405#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1406pub enum ChunkRendererId {
1407 Fold(FoldId),
1408 Inlay(InlayId),
1409}
1410
1411/// A recipe for how the chunk should be presented.
1412#[derive(Clone)]
1413pub struct ChunkRenderer {
1414 /// The id of the renderer associated with this chunk.
1415 pub id: ChunkRendererId,
1416 /// Creates a custom element to represent this chunk.
1417 pub render: Arc<dyn Send + Sync + Fn(&mut ChunkRendererContext) -> AnyElement>,
1418 /// If true, the element is constrained to the shaped width of the text.
1419 pub constrain_width: bool,
1420 /// The width of the element, as measured during the last layout pass.
1421 ///
1422 /// This is None if the element has not been laid out yet.
1423 pub measured_width: Option<Pixels>,
1424}
1425
1426pub struct ChunkRendererContext<'a, 'b> {
1427 pub window: &'a mut Window,
1428 pub context: &'b mut App,
1429 pub max_width: Pixels,
1430}
1431
1432impl fmt::Debug for ChunkRenderer {
1433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1434 f.debug_struct("ChunkRenderer")
1435 .field("constrain_width", &self.constrain_width)
1436 .finish()
1437 }
1438}
1439
1440impl Deref for ChunkRendererContext<'_, '_> {
1441 type Target = App;
1442
1443 fn deref(&self) -> &Self::Target {
1444 self.context
1445 }
1446}
1447
1448impl DerefMut for ChunkRendererContext<'_, '_> {
1449 fn deref_mut(&mut self) -> &mut Self::Target {
1450 self.context
1451 }
1452}
1453
1454pub struct FoldChunks<'a> {
1455 transform_cursor: Cursor<'a, 'static, Transform, Dimensions<FoldOffset, InlayOffset>>,
1456 inlay_chunks: InlayChunks<'a>,
1457 inlay_chunk: Option<(InlayOffset, InlayChunk<'a>)>,
1458 inlay_offset: InlayOffset,
1459 output_offset: FoldOffset,
1460 max_output_offset: FoldOffset,
1461}
1462
1463impl FoldChunks<'_> {
1464 #[ztracing::instrument(skip_all)]
1465 pub(crate) fn seek(&mut self, range: Range<FoldOffset>) {
1466 self.transform_cursor.seek(&range.start, Bias::Right);
1467
1468 let inlay_start = {
1469 let overshoot = range.start - self.transform_cursor.start().0;
1470 self.transform_cursor.start().1 + overshoot
1471 };
1472
1473 let transform_end = self.transform_cursor.end();
1474
1475 let inlay_end = if self
1476 .transform_cursor
1477 .item()
1478 .is_none_or(|transform| transform.is_fold())
1479 {
1480 inlay_start
1481 } else if range.end < transform_end.0 {
1482 let overshoot = range.end - self.transform_cursor.start().0;
1483 self.transform_cursor.start().1 + overshoot
1484 } else {
1485 transform_end.1
1486 };
1487
1488 self.inlay_chunks.seek(inlay_start..inlay_end);
1489 self.inlay_chunk = None;
1490 self.inlay_offset = inlay_start;
1491 self.output_offset = range.start;
1492 self.max_output_offset = range.end;
1493 }
1494}
1495
1496impl<'a> Iterator for FoldChunks<'a> {
1497 type Item = Chunk<'a>;
1498
1499 #[ztracing::instrument(skip_all)]
1500 fn next(&mut self) -> Option<Self::Item> {
1501 if self.output_offset >= self.max_output_offset {
1502 return None;
1503 }
1504
1505 let transform = self.transform_cursor.item()?;
1506
1507 // If we're in a fold, then return the fold's display text and
1508 // advance the transform and buffer cursors to the end of the fold.
1509 if let Some(placeholder) = transform.placeholder.as_ref() {
1510 self.inlay_chunk.take();
1511 self.inlay_offset += InlayOffset(transform.summary.input.len);
1512
1513 while self.inlay_offset >= self.transform_cursor.end().1
1514 && self.transform_cursor.item().is_some()
1515 {
1516 self.transform_cursor.next();
1517 }
1518
1519 self.output_offset.0 += placeholder.text.len();
1520 return Some(Chunk {
1521 text: &placeholder.text,
1522 chars: placeholder.chars,
1523 renderer: Some(placeholder.renderer.clone()),
1524 ..Default::default()
1525 });
1526 }
1527
1528 // When we reach a non-fold region, seek the underlying text
1529 // chunk iterator to the next unfolded range.
1530 if self.inlay_offset == self.transform_cursor.start().1
1531 && self.inlay_chunks.offset() != self.inlay_offset
1532 {
1533 let transform_start = self.transform_cursor.start();
1534 let transform_end = self.transform_cursor.end();
1535 let inlay_end = if self.max_output_offset < transform_end.0 {
1536 let overshoot = self.max_output_offset - transform_start.0;
1537 transform_start.1 + overshoot
1538 } else {
1539 transform_end.1
1540 };
1541
1542 self.inlay_chunks.seek(self.inlay_offset..inlay_end);
1543 }
1544
1545 // Retrieve a chunk from the current location in the buffer.
1546 if self.inlay_chunk.is_none() {
1547 let chunk_offset = self.inlay_chunks.offset();
1548 self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1549 }
1550
1551 // Otherwise, take a chunk from the buffer's text.
1552 if let Some((buffer_chunk_start, mut inlay_chunk)) = self.inlay_chunk.clone() {
1553 let chunk = &mut inlay_chunk.chunk;
1554 let buffer_chunk_end = buffer_chunk_start + chunk.text.len();
1555 let transform_end = self.transform_cursor.end().1;
1556 let chunk_end = buffer_chunk_end.min(transform_end);
1557
1558 let bit_start = self.inlay_offset - buffer_chunk_start;
1559 let bit_end = chunk_end - buffer_chunk_start;
1560 chunk.text = &chunk.text[bit_start..bit_end];
1561
1562 let bit_end = chunk_end - buffer_chunk_start;
1563 let mask = 1u128.unbounded_shl(bit_end as u32).wrapping_sub(1);
1564
1565 chunk.tabs = (chunk.tabs >> bit_start) & mask;
1566 chunk.chars = (chunk.chars >> bit_start) & mask;
1567
1568 if chunk_end == transform_end {
1569 self.transform_cursor.next();
1570 } else if chunk_end == buffer_chunk_end {
1571 self.inlay_chunk.take();
1572 }
1573
1574 self.inlay_offset = chunk_end;
1575 self.output_offset.0 += chunk.text.len();
1576 return Some(Chunk {
1577 text: chunk.text,
1578 tabs: chunk.tabs,
1579 chars: chunk.chars,
1580 syntax_highlight_id: chunk.syntax_highlight_id,
1581 highlight_style: chunk.highlight_style,
1582 diagnostic_severity: chunk.diagnostic_severity,
1583 is_unnecessary: chunk.is_unnecessary,
1584 is_tab: chunk.is_tab,
1585 is_inlay: chunk.is_inlay,
1586 underline: chunk.underline,
1587 renderer: inlay_chunk.renderer,
1588 });
1589 }
1590
1591 None
1592 }
1593}
1594
1595#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1596pub struct FoldOffset(pub MultiBufferOffset);
1597
1598impl FoldOffset {
1599 #[ztracing::instrument(skip_all)]
1600 pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1601 let (start, _, item) = snapshot
1602 .transforms
1603 .find::<Dimensions<FoldOffset, TransformSummary>, _>((), &self, Bias::Right);
1604 let overshoot = if item.is_none_or(|t| t.is_fold()) {
1605 Point::new(0, (self.0 - start.0.0) as u32)
1606 } else {
1607 let inlay_offset = start.1.input.len + (self - start.0);
1608 let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1609 inlay_point.0 - start.1.input.lines
1610 };
1611 FoldPoint(start.1.output.lines + overshoot)
1612 }
1613
1614 #[cfg(test)]
1615 #[ztracing::instrument(skip_all)]
1616 pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1617 let (start, _, _) = snapshot
1618 .transforms
1619 .find::<Dimensions<FoldOffset, InlayOffset>, _>((), &self, Bias::Right);
1620 let overshoot = self - start.0;
1621 InlayOffset(start.1.0 + overshoot)
1622 }
1623}
1624
1625impl Add for FoldOffset {
1626 type Output = Self;
1627
1628 fn add(self, rhs: Self) -> Self::Output {
1629 Self(self.0 + rhs.0)
1630 }
1631}
1632
1633impl Sub for FoldOffset {
1634 type Output = <MultiBufferOffset as Sub>::Output;
1635
1636 fn sub(self, rhs: Self) -> Self::Output {
1637 self.0 - rhs.0
1638 }
1639}
1640
1641impl<T> SubAssign<T> for FoldOffset
1642where
1643 MultiBufferOffset: SubAssign<T>,
1644{
1645 fn sub_assign(&mut self, rhs: T) {
1646 self.0 -= rhs;
1647 }
1648}
1649
1650impl<T> Add<T> for FoldOffset
1651where
1652 MultiBufferOffset: Add<T, Output = MultiBufferOffset>,
1653{
1654 type Output = Self;
1655
1656 fn add(self, rhs: T) -> Self::Output {
1657 Self(self.0 + rhs)
1658 }
1659}
1660
1661impl AddAssign for FoldOffset {
1662 fn add_assign(&mut self, rhs: Self) {
1663 self.0 += rhs.0;
1664 }
1665}
1666
1667impl<T> AddAssign<T> for FoldOffset
1668where
1669 MultiBufferOffset: AddAssign<T>,
1670{
1671 fn add_assign(&mut self, rhs: T) {
1672 self.0 += rhs;
1673 }
1674}
1675
1676impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1677 fn zero(_cx: ()) -> Self {
1678 Default::default()
1679 }
1680
1681 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1682 self.0 += summary.output.len;
1683 }
1684}
1685
1686impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1687 fn zero(_cx: ()) -> Self {
1688 Default::default()
1689 }
1690
1691 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1692 self.0 += &summary.input.lines;
1693 }
1694}
1695
1696impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1697 fn zero(_cx: ()) -> Self {
1698 Default::default()
1699 }
1700
1701 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1702 self.0 += summary.input.len;
1703 }
1704}
1705
1706pub type FoldEdit = Edit<FoldOffset>;
1707
1708#[cfg(test)]
1709mod tests {
1710 use super::*;
1711 use crate::{MultiBuffer, ToPoint, display_map::inlay_map::InlayMap};
1712 use Bias::{Left, Right};
1713 use collections::HashSet;
1714 use rand::prelude::*;
1715 use settings::SettingsStore;
1716 use std::{env, mem};
1717 use text::Patch;
1718 use util::RandomCharIter;
1719 use util::test::sample_text;
1720
1721 #[gpui::test]
1722 fn test_basic_folds(cx: &mut gpui::App) {
1723 init_test(cx);
1724 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1725 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1726 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1727 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1728 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1729
1730 let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1731 let (snapshot2, edits) = writer.fold(vec![
1732 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1733 (Point::new(2, 4)..Point::new(4, 1), FoldPlaceholder::test()),
1734 ]);
1735 assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1736 assert_eq!(
1737 edits,
1738 &[
1739 FoldEdit {
1740 old: FoldOffset(MultiBufferOffset(2))..FoldOffset(MultiBufferOffset(16)),
1741 new: FoldOffset(MultiBufferOffset(2))..FoldOffset(MultiBufferOffset(5)),
1742 },
1743 FoldEdit {
1744 old: FoldOffset(MultiBufferOffset(18))..FoldOffset(MultiBufferOffset(29)),
1745 new: FoldOffset(MultiBufferOffset(7))..FoldOffset(MultiBufferOffset(10)),
1746 },
1747 ]
1748 );
1749
1750 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1751 buffer.edit(
1752 vec![
1753 (Point::new(0, 0)..Point::new(0, 1), "123"),
1754 (Point::new(2, 3)..Point::new(2, 3), "123"),
1755 ],
1756 None,
1757 cx,
1758 );
1759 buffer.snapshot(cx)
1760 });
1761
1762 let (inlay_snapshot, inlay_edits) =
1763 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1764 let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1765 assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1766 assert_eq!(
1767 edits,
1768 &[
1769 FoldEdit {
1770 old: FoldOffset(MultiBufferOffset(0))..FoldOffset(MultiBufferOffset(1)),
1771 new: FoldOffset(MultiBufferOffset(0))..FoldOffset(MultiBufferOffset(3)),
1772 },
1773 FoldEdit {
1774 old: FoldOffset(MultiBufferOffset(6))..FoldOffset(MultiBufferOffset(6)),
1775 new: FoldOffset(MultiBufferOffset(8))..FoldOffset(MultiBufferOffset(11)),
1776 },
1777 ]
1778 );
1779
1780 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1781 buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1782 buffer.snapshot(cx)
1783 });
1784 let (inlay_snapshot, inlay_edits) =
1785 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1786 let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1787 assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1788
1789 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1790 writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1791 let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1792 assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1793
1794 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1795 writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1796 let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1797 assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1798 }
1799
1800 #[gpui::test]
1801 fn test_adjacent_folds(cx: &mut gpui::App) {
1802 init_test(cx);
1803 let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1804 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1805 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1806 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1807
1808 {
1809 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1810
1811 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1812 writer.fold(vec![(
1813 MultiBufferOffset(5)..MultiBufferOffset(8),
1814 FoldPlaceholder::test(),
1815 )]);
1816 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1817 assert_eq!(snapshot.text(), "abcde⋯ijkl");
1818
1819 // Create an fold adjacent to the start of the first fold.
1820 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1821 writer.fold(vec![
1822 (
1823 MultiBufferOffset(0)..MultiBufferOffset(1),
1824 FoldPlaceholder::test(),
1825 ),
1826 (
1827 MultiBufferOffset(2)..MultiBufferOffset(5),
1828 FoldPlaceholder::test(),
1829 ),
1830 ]);
1831 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1832 assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1833
1834 // Create an fold adjacent to the end of the first fold.
1835 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1836 writer.fold(vec![
1837 (
1838 MultiBufferOffset(11)..MultiBufferOffset(11),
1839 FoldPlaceholder::test(),
1840 ),
1841 (
1842 MultiBufferOffset(8)..MultiBufferOffset(10),
1843 FoldPlaceholder::test(),
1844 ),
1845 ]);
1846 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1847 assert_eq!(snapshot.text(), "⋯b⋯kl");
1848 }
1849
1850 {
1851 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1852
1853 // Create two adjacent folds.
1854 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1855 writer.fold(vec![
1856 (
1857 MultiBufferOffset(0)..MultiBufferOffset(2),
1858 FoldPlaceholder::test(),
1859 ),
1860 (
1861 MultiBufferOffset(2)..MultiBufferOffset(5),
1862 FoldPlaceholder::test(),
1863 ),
1864 ]);
1865 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1866 assert_eq!(snapshot.text(), "⋯fghijkl");
1867
1868 // Edit within one of the folds.
1869 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1870 buffer.edit(
1871 [(MultiBufferOffset(0)..MultiBufferOffset(1), "12345")],
1872 None,
1873 cx,
1874 );
1875 buffer.snapshot(cx)
1876 });
1877 let (inlay_snapshot, inlay_edits) =
1878 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1879 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1880 assert_eq!(snapshot.text(), "12345⋯fghijkl");
1881 }
1882 }
1883
1884 #[gpui::test]
1885 fn test_overlapping_folds(cx: &mut gpui::App) {
1886 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1887 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1888 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1889 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1890 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1891 writer.fold(vec![
1892 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1893 (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1894 (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1895 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1896 ]);
1897 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1898 assert_eq!(snapshot.text(), "aa⋯eeeee");
1899 }
1900
1901 #[gpui::test]
1902 fn test_merging_folds_via_edit(cx: &mut gpui::App) {
1903 init_test(cx);
1904 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1905 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1906 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1907 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1908 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1909
1910 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1911 writer.fold(vec![
1912 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1913 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1914 ]);
1915 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1916 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1917
1918 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1919 buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1920 buffer.snapshot(cx)
1921 });
1922 let (inlay_snapshot, inlay_edits) =
1923 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1924 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1925 assert_eq!(snapshot.text(), "aa⋯eeeee");
1926 }
1927
1928 #[gpui::test]
1929 fn test_folds_in_range(cx: &mut gpui::App) {
1930 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1931 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1932 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1933 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1934
1935 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1936 writer.fold(vec![
1937 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1938 (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1939 (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1940 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1941 ]);
1942 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1943 let fold_ranges = snapshot
1944 .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1945 .map(|fold| {
1946 fold.range.start.to_point(&buffer_snapshot)
1947 ..fold.range.end.to_point(&buffer_snapshot)
1948 })
1949 .collect::<Vec<_>>();
1950 assert_eq!(
1951 fold_ranges,
1952 vec![
1953 Point::new(0, 2)..Point::new(2, 2),
1954 Point::new(1, 2)..Point::new(3, 2)
1955 ]
1956 );
1957 }
1958
1959 #[gpui::test(iterations = 100)]
1960 fn test_random_folds(cx: &mut gpui::App, mut rng: StdRng) {
1961 init_test(cx);
1962 let operations = env::var("OPERATIONS")
1963 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1964 .unwrap_or(10);
1965
1966 let len = rng.random_range(0..10);
1967 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1968 let buffer = if rng.random() {
1969 MultiBuffer::build_simple(&text, cx)
1970 } else {
1971 MultiBuffer::build_random(&mut rng, cx)
1972 };
1973 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1974 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1975 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1976
1977 let (mut initial_snapshot, _) = map.read(inlay_snapshot, vec![]);
1978 let mut snapshot_edits = Vec::new();
1979
1980 let mut next_inlay_id = 0;
1981 for _ in 0..operations {
1982 log::info!("text: {:?}", buffer_snapshot.text());
1983 let mut buffer_edits = Vec::new();
1984 let mut inlay_edits = Vec::new();
1985 match rng.random_range(0..=100) {
1986 0..=39 => {
1987 snapshot_edits.extend(map.randomly_mutate(&mut rng));
1988 }
1989 40..=59 => {
1990 let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1991 inlay_edits = edits;
1992 }
1993 _ => buffer.update(cx, |buffer, cx| {
1994 let subscription = buffer.subscribe();
1995 let edit_count = rng.random_range(1..=5);
1996 buffer.randomly_mutate(&mut rng, edit_count, cx);
1997 buffer_snapshot = buffer.snapshot(cx);
1998 let edits = subscription.consume().into_inner();
1999 log::info!("editing {:?}", edits);
2000 buffer_edits.extend(edits);
2001 }),
2002 };
2003
2004 let (inlay_snapshot, new_inlay_edits) =
2005 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
2006 log::info!("inlay text {:?}", inlay_snapshot.text());
2007
2008 let inlay_edits = Patch::new(inlay_edits)
2009 .compose(new_inlay_edits)
2010 .into_inner();
2011 let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
2012 snapshot_edits.push((snapshot.clone(), edits));
2013
2014 let mut expected_text: String = inlay_snapshot.text().to_string();
2015 for fold_range in map.merged_folds().into_iter().rev() {
2016 let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
2017 let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
2018 expected_text.replace_range(fold_inlay_start.0.0..fold_inlay_end.0.0, "⋯");
2019 }
2020
2021 assert_eq!(snapshot.text(), expected_text);
2022 log::info!(
2023 "fold text {:?} ({} lines)",
2024 expected_text,
2025 expected_text.matches('\n').count() + 1
2026 );
2027
2028 let mut prev_row = 0;
2029 let mut expected_buffer_rows = Vec::new();
2030 for fold_range in map.merged_folds() {
2031 let fold_start = inlay_snapshot
2032 .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
2033 .row();
2034 let fold_end = inlay_snapshot
2035 .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
2036 .row();
2037 expected_buffer_rows.extend(
2038 inlay_snapshot
2039 .row_infos(prev_row)
2040 .take((1 + fold_start - prev_row) as usize),
2041 );
2042 prev_row = 1 + fold_end;
2043 }
2044 expected_buffer_rows.extend(inlay_snapshot.row_infos(prev_row));
2045
2046 assert_eq!(
2047 expected_buffer_rows.len(),
2048 expected_text.matches('\n').count() + 1,
2049 "wrong expected buffer rows {:?}. text: {:?}",
2050 expected_buffer_rows,
2051 expected_text
2052 );
2053
2054 for (output_row, line) in expected_text.lines().enumerate() {
2055 let line_len = snapshot.line_len(output_row as u32);
2056 assert_eq!(line_len, line.len() as u32);
2057 }
2058
2059 let longest_row = snapshot.longest_row();
2060 let longest_char_column = expected_text
2061 .split('\n')
2062 .nth(longest_row as usize)
2063 .unwrap()
2064 .chars()
2065 .count();
2066 let mut fold_point = FoldPoint::new(0, 0);
2067 let mut fold_offset = FoldOffset(MultiBufferOffset(0));
2068 let mut char_column = 0;
2069 for c in expected_text.chars() {
2070 let inlay_point = fold_point.to_inlay_point(&snapshot);
2071 let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
2072 assert_eq!(
2073 snapshot.to_fold_point(inlay_point, Right),
2074 fold_point,
2075 "{:?} -> fold point",
2076 inlay_point,
2077 );
2078 assert_eq!(
2079 inlay_snapshot.to_offset(inlay_point),
2080 inlay_offset,
2081 "inlay_snapshot.to_offset({:?})",
2082 inlay_point,
2083 );
2084 assert_eq!(
2085 fold_point.to_offset(&snapshot),
2086 fold_offset,
2087 "fold_point.to_offset({:?})",
2088 fold_point,
2089 );
2090
2091 if c == '\n' {
2092 *fold_point.row_mut() += 1;
2093 *fold_point.column_mut() = 0;
2094 char_column = 0;
2095 } else {
2096 *fold_point.column_mut() += c.len_utf8() as u32;
2097 char_column += 1;
2098 }
2099 fold_offset.0 += c.len_utf8();
2100 if char_column > longest_char_column {
2101 panic!(
2102 "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
2103 longest_row,
2104 longest_char_column,
2105 fold_point.row(),
2106 char_column
2107 );
2108 }
2109 }
2110
2111 for _ in 0..5 {
2112 let mut start = snapshot.clip_offset(
2113 FoldOffset(rng.random_range(MultiBufferOffset(0)..=snapshot.len().0)),
2114 Bias::Left,
2115 );
2116 let mut end = snapshot.clip_offset(
2117 FoldOffset(rng.random_range(MultiBufferOffset(0)..=snapshot.len().0)),
2118 Bias::Right,
2119 );
2120 if start > end {
2121 mem::swap(&mut start, &mut end);
2122 }
2123
2124 let text = &expected_text[start.0.0..end.0.0];
2125 assert_eq!(
2126 snapshot
2127 .chunks(start..end, false, Highlights::default())
2128 .map(|c| c.text)
2129 .collect::<String>(),
2130 text,
2131 );
2132 }
2133
2134 let mut fold_row = 0;
2135 while fold_row < expected_buffer_rows.len() as u32 {
2136 assert_eq!(
2137 snapshot.row_infos(fold_row).collect::<Vec<_>>(),
2138 expected_buffer_rows[(fold_row as usize)..],
2139 "wrong buffer rows starting at fold row {}",
2140 fold_row,
2141 );
2142 fold_row += 1;
2143 }
2144
2145 let folded_buffer_rows = map
2146 .merged_folds()
2147 .iter()
2148 .flat_map(|fold_range| {
2149 let start_row = fold_range.start.to_point(&buffer_snapshot).row;
2150 let end = fold_range.end.to_point(&buffer_snapshot);
2151 if end.column == 0 {
2152 start_row..end.row
2153 } else {
2154 start_row..end.row + 1
2155 }
2156 })
2157 .collect::<HashSet<_>>();
2158 for row in 0..=buffer_snapshot.max_point().row {
2159 assert_eq!(
2160 snapshot.is_line_folded(MultiBufferRow(row)),
2161 folded_buffer_rows.contains(&row),
2162 "expected buffer row {}{} to be folded",
2163 row,
2164 if folded_buffer_rows.contains(&row) {
2165 ""
2166 } else {
2167 " not"
2168 }
2169 );
2170 }
2171
2172 for _ in 0..5 {
2173 let end = buffer_snapshot.clip_offset(
2174 rng.random_range(MultiBufferOffset(0)..=buffer_snapshot.len()),
2175 Right,
2176 );
2177 let start =
2178 buffer_snapshot.clip_offset(rng.random_range(MultiBufferOffset(0)..=end), Left);
2179 let expected_folds = map
2180 .snapshot
2181 .folds
2182 .items(&buffer_snapshot)
2183 .into_iter()
2184 .filter(|fold| {
2185 let start = buffer_snapshot.anchor_before(start);
2186 let end = buffer_snapshot.anchor_after(end);
2187 start.cmp(&fold.range.end, &buffer_snapshot) == Ordering::Less
2188 && end.cmp(&fold.range.start, &buffer_snapshot) == Ordering::Greater
2189 })
2190 .collect::<Vec<_>>();
2191
2192 assert_eq!(
2193 snapshot
2194 .folds_in_range(start..end)
2195 .cloned()
2196 .collect::<Vec<_>>(),
2197 expected_folds
2198 );
2199 }
2200
2201 let text = snapshot.text();
2202 for _ in 0..5 {
2203 let start_row = rng.random_range(0..=snapshot.max_point().row());
2204 let start_column = rng.random_range(0..=snapshot.line_len(start_row));
2205 let end_row = rng.random_range(0..=snapshot.max_point().row());
2206 let end_column = rng.random_range(0..=snapshot.line_len(end_row));
2207 let mut start =
2208 snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
2209 let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
2210 if start > end {
2211 mem::swap(&mut start, &mut end);
2212 }
2213
2214 let lines = start..end;
2215 let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
2216 assert_eq!(
2217 snapshot.text_summary_for_range(lines),
2218 MBTextSummary::from(&text[bytes.start.0.0..bytes.end.0.0])
2219 )
2220 }
2221
2222 let mut text = initial_snapshot.text();
2223 for (snapshot, edits) in snapshot_edits.drain(..) {
2224 let new_text = snapshot.text();
2225 for edit in edits {
2226 let old_bytes = edit.new.start.0.0..edit.new.start.0.0 + edit.old_len();
2227 let new_bytes = edit.new.start.0.0..edit.new.end.0.0;
2228 text.replace_range(old_bytes, &new_text[new_bytes]);
2229 }
2230
2231 assert_eq!(text, new_text);
2232 initial_snapshot = snapshot;
2233 }
2234 }
2235 }
2236
2237 #[gpui::test]
2238 fn test_buffer_rows(cx: &mut gpui::App) {
2239 let text = sample_text(6, 6, 'a') + "\n";
2240 let buffer = MultiBuffer::build_simple(&text, cx);
2241
2242 let buffer_snapshot = buffer.read(cx).snapshot(cx);
2243 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
2244 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
2245
2246 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
2247 writer.fold(vec![
2248 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
2249 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
2250 ]);
2251
2252 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
2253 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
2254 assert_eq!(
2255 snapshot
2256 .row_infos(0)
2257 .map(|info| info.buffer_row)
2258 .collect::<Vec<_>>(),
2259 [Some(0), Some(3), Some(5), Some(6)]
2260 );
2261 assert_eq!(
2262 snapshot
2263 .row_infos(3)
2264 .map(|info| info.buffer_row)
2265 .collect::<Vec<_>>(),
2266 [Some(6)]
2267 );
2268 }
2269
2270 #[gpui::test(iterations = 100)]
2271 fn test_random_chunk_bitmaps(cx: &mut gpui::App, mut rng: StdRng) {
2272 init_test(cx);
2273
2274 // Generate random buffer using existing test infrastructure
2275 let text_len = rng.random_range(0..10000);
2276 let buffer = if rng.random() {
2277 let text = RandomCharIter::new(&mut rng)
2278 .take(text_len)
2279 .collect::<String>();
2280 MultiBuffer::build_simple(&text, cx)
2281 } else {
2282 MultiBuffer::build_random(&mut rng, cx)
2283 };
2284 let buffer_snapshot = buffer.read(cx).snapshot(cx);
2285 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
2286 let (mut fold_map, _) = FoldMap::new(inlay_snapshot.clone());
2287
2288 // Perform random mutations
2289 let mutation_count = rng.random_range(1..10);
2290 for _ in 0..mutation_count {
2291 fold_map.randomly_mutate(&mut rng);
2292 }
2293
2294 let (snapshot, _) = fold_map.read(inlay_snapshot, vec![]);
2295
2296 // Get all chunks and verify their bitmaps
2297 let chunks = snapshot.chunks(
2298 FoldOffset(MultiBufferOffset(0))..FoldOffset(snapshot.len().0),
2299 false,
2300 Highlights::default(),
2301 );
2302
2303 for chunk in chunks {
2304 let chunk_text = chunk.text;
2305 let chars_bitmap = chunk.chars;
2306 let tabs_bitmap = chunk.tabs;
2307
2308 // Check empty chunks have empty bitmaps
2309 if chunk_text.is_empty() {
2310 assert_eq!(
2311 chars_bitmap, 0,
2312 "Empty chunk should have empty chars bitmap"
2313 );
2314 assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
2315 continue;
2316 }
2317
2318 // Verify that chunk text doesn't exceed 128 bytes
2319 assert!(
2320 chunk_text.len() <= 128,
2321 "Chunk text length {} exceeds 128 bytes",
2322 chunk_text.len()
2323 );
2324
2325 // Verify chars bitmap
2326 let char_indices = chunk_text
2327 .char_indices()
2328 .map(|(i, _)| i)
2329 .collect::<Vec<_>>();
2330
2331 for byte_idx in 0..chunk_text.len() {
2332 let should_have_bit = char_indices.contains(&byte_idx);
2333 let has_bit = chars_bitmap & (1 << byte_idx) != 0;
2334
2335 if has_bit != should_have_bit {
2336 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
2337 eprintln!("Char indices: {:?}", char_indices);
2338 eprintln!("Chars bitmap: {:#b}", chars_bitmap);
2339 assert_eq!(
2340 has_bit, should_have_bit,
2341 "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
2342 byte_idx, chunk_text, should_have_bit, has_bit
2343 );
2344 }
2345 }
2346
2347 // Verify tabs bitmap
2348 for (byte_idx, byte) in chunk_text.bytes().enumerate() {
2349 let is_tab = byte == b'\t';
2350 let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
2351
2352 assert_eq!(
2353 has_bit, is_tab,
2354 "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
2355 byte_idx, chunk_text, byte as char, is_tab, has_bit
2356 );
2357 }
2358 }
2359 }
2360
2361 fn init_test(cx: &mut gpui::App) {
2362 let store = SettingsStore::test(cx);
2363 cx.set_global(store);
2364 }
2365
2366 impl FoldMap {
2367 fn merged_folds(&self) -> Vec<Range<MultiBufferOffset>> {
2368 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2369 let buffer = &inlay_snapshot.buffer;
2370 let mut folds = self.snapshot.folds.items(buffer);
2371 // Ensure sorting doesn't change how folds get merged and displayed.
2372 folds.sort_by(|a, b| a.range.cmp(&b.range, buffer));
2373 let mut folds = folds
2374 .iter()
2375 .map(|fold| fold.range.start.to_offset(buffer)..fold.range.end.to_offset(buffer))
2376 .peekable();
2377
2378 let mut merged_folds = Vec::new();
2379 while let Some(mut fold_range) = folds.next() {
2380 while let Some(next_range) = folds.peek() {
2381 if fold_range.end >= next_range.start {
2382 if next_range.end > fold_range.end {
2383 fold_range.end = next_range.end;
2384 }
2385 folds.next();
2386 } else {
2387 break;
2388 }
2389 }
2390 if fold_range.end > fold_range.start {
2391 merged_folds.push(fold_range);
2392 }
2393 }
2394 merged_folds
2395 }
2396
2397 pub fn randomly_mutate(
2398 &mut self,
2399 rng: &mut impl Rng,
2400 ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
2401 let mut snapshot_edits = Vec::new();
2402 match rng.random_range(0..=100) {
2403 0..=39 if !self.snapshot.folds.is_empty() => {
2404 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2405 let buffer = &inlay_snapshot.buffer;
2406 let mut to_unfold = Vec::new();
2407 for _ in 0..rng.random_range(1..=3) {
2408 let end = buffer.clip_offset(
2409 rng.random_range(MultiBufferOffset(0)..=buffer.len()),
2410 Right,
2411 );
2412 let start =
2413 buffer.clip_offset(rng.random_range(MultiBufferOffset(0)..=end), Left);
2414 to_unfold.push(start..end);
2415 }
2416 let inclusive = rng.random();
2417 log::info!("unfolding {:?} (inclusive: {})", to_unfold, inclusive);
2418 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2419 snapshot_edits.push((snapshot, edits));
2420 let (snapshot, edits) = writer.unfold_intersecting(to_unfold, inclusive);
2421 snapshot_edits.push((snapshot, edits));
2422 }
2423 _ => {
2424 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2425 let buffer = &inlay_snapshot.buffer;
2426 let mut to_fold = Vec::new();
2427 for _ in 0..rng.random_range(1..=2) {
2428 let end = buffer.clip_offset(
2429 rng.random_range(MultiBufferOffset(0)..=buffer.len()),
2430 Right,
2431 );
2432 let start =
2433 buffer.clip_offset(rng.random_range(MultiBufferOffset(0)..=end), Left);
2434 to_fold.push((start..end, FoldPlaceholder::test()));
2435 }
2436 log::info!("folding {:?}", to_fold);
2437 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2438 snapshot_edits.push((snapshot, edits));
2439 let (snapshot, edits) = writer.fold(to_fold);
2440 snapshot_edits.push((snapshot, edits));
2441 }
2442 }
2443 snapshot_edits
2444 }
2445 }
2446}