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