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