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 Deref for FoldSnapshot {
634 type Target = InlaySnapshot;
635
636 fn deref(&self) -> &Self::Target {
637 &self.inlay_snapshot
638 }
639}
640
641impl FoldSnapshot {
642 pub fn buffer(&self) -> &MultiBufferSnapshot {
643 &self.inlay_snapshot.buffer
644 }
645
646 fn fold_width(&self, fold_id: &FoldId) -> Option<Pixels> {
647 self.fold_metadata_by_id.get(fold_id)?.width
648 }
649
650 #[cfg(test)]
651 pub fn text(&self) -> String {
652 self.chunks(FoldOffset(0)..self.len(), false, Highlights::default())
653 .map(|c| c.text)
654 .collect()
655 }
656
657 #[cfg(test)]
658 pub fn fold_count(&self) -> usize {
659 self.folds.items(&self.inlay_snapshot.buffer).len()
660 }
661
662 pub fn text_summary_for_range(&self, range: Range<FoldPoint>) -> TextSummary {
663 let mut summary = TextSummary::default();
664
665 let mut cursor = self
666 .transforms
667 .cursor::<Dimensions<FoldPoint, InlayPoint>>(());
668 cursor.seek(&range.start, Bias::Right);
669 if let Some(transform) = cursor.item() {
670 let start_in_transform = range.start.0 - cursor.start().0.0;
671 let end_in_transform = cmp::min(range.end, cursor.end().0).0 - cursor.start().0.0;
672 if let Some(placeholder) = transform.placeholder.as_ref() {
673 summary = TextSummary::from(
674 &placeholder.text
675 [start_in_transform.column as usize..end_in_transform.column as usize],
676 );
677 } else {
678 let inlay_start = self
679 .inlay_snapshot
680 .to_offset(InlayPoint(cursor.start().1.0 + start_in_transform));
681 let inlay_end = self
682 .inlay_snapshot
683 .to_offset(InlayPoint(cursor.start().1.0 + end_in_transform));
684 summary = self
685 .inlay_snapshot
686 .text_summary_for_range(inlay_start..inlay_end);
687 }
688 }
689
690 if range.end > cursor.end().0 {
691 cursor.next();
692 summary += &cursor
693 .summary::<_, TransformSummary>(&range.end, Bias::Right)
694 .output;
695 if let Some(transform) = cursor.item() {
696 let end_in_transform = range.end.0 - cursor.start().0.0;
697 if let Some(placeholder) = transform.placeholder.as_ref() {
698 summary +=
699 TextSummary::from(&placeholder.text[..end_in_transform.column as usize]);
700 } else {
701 let inlay_start = self.inlay_snapshot.to_offset(cursor.start().1);
702 let inlay_end = self
703 .inlay_snapshot
704 .to_offset(InlayPoint(cursor.start().1.0 + end_in_transform));
705 summary += self
706 .inlay_snapshot
707 .text_summary_for_range(inlay_start..inlay_end);
708 }
709 }
710 }
711
712 summary
713 }
714
715 pub fn to_fold_point(&self, point: InlayPoint, bias: Bias) -> FoldPoint {
716 let (start, end, item) = self
717 .transforms
718 .find::<Dimensions<InlayPoint, FoldPoint>, _>((), &point, Bias::Right);
719 if item.is_some_and(|t| t.is_fold()) {
720 if bias == Bias::Left || point == start.0 {
721 start.1
722 } else {
723 end.1
724 }
725 } else {
726 let overshoot = point.0 - start.0.0;
727 FoldPoint(cmp::min(start.1.0 + overshoot, end.1.0))
728 }
729 }
730
731 pub fn len(&self) -> FoldOffset {
732 FoldOffset(self.transforms.summary().output.len)
733 }
734
735 pub fn line_len(&self, row: u32) -> u32 {
736 let line_start = FoldPoint::new(row, 0).to_offset(self).0;
737 let line_end = if row >= self.max_point().row() {
738 self.len().0
739 } else {
740 FoldPoint::new(row + 1, 0).to_offset(self).0 - 1
741 };
742 (line_end - line_start) as u32
743 }
744
745 pub fn row_infos(&self, start_row: u32) -> FoldRows<'_> {
746 if start_row > self.transforms.summary().output.lines.row {
747 panic!("invalid display row {}", start_row);
748 }
749
750 let fold_point = FoldPoint::new(start_row, 0);
751 let mut cursor = self
752 .transforms
753 .cursor::<Dimensions<FoldPoint, InlayPoint>>(());
754 cursor.seek(&fold_point, Bias::Left);
755
756 let overshoot = fold_point.0 - cursor.start().0.0;
757 let inlay_point = InlayPoint(cursor.start().1.0 + overshoot);
758 let input_rows = self.inlay_snapshot.row_infos(inlay_point.row());
759
760 FoldRows {
761 fold_point,
762 input_rows,
763 cursor,
764 }
765 }
766
767 pub fn max_point(&self) -> FoldPoint {
768 FoldPoint(self.transforms.summary().output.lines)
769 }
770
771 #[cfg(test)]
772 pub fn longest_row(&self) -> u32 {
773 self.transforms.summary().output.longest_row
774 }
775
776 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Fold>
777 where
778 T: ToOffset,
779 {
780 let buffer = &self.inlay_snapshot.buffer;
781 let range = range.start.to_offset(buffer)..range.end.to_offset(buffer);
782 let mut folds = intersecting_folds(&self.inlay_snapshot, &self.folds, range, false);
783 iter::from_fn(move || {
784 let item = folds.item();
785 folds.next();
786 item
787 })
788 }
789
790 pub fn intersects_fold<T>(&self, offset: T) -> bool
791 where
792 T: ToOffset,
793 {
794 let buffer_offset = offset.to_offset(&self.inlay_snapshot.buffer);
795 let inlay_offset = self.inlay_snapshot.to_inlay_offset(buffer_offset);
796 let (_, _, item) = self
797 .transforms
798 .find::<InlayOffset, _>((), &inlay_offset, Bias::Right);
799 item.is_some_and(|t| t.placeholder.is_some())
800 }
801
802 pub fn is_line_folded(&self, buffer_row: MultiBufferRow) -> bool {
803 let mut inlay_point = self
804 .inlay_snapshot
805 .to_inlay_point(Point::new(buffer_row.0, 0));
806 let mut cursor = self.transforms.cursor::<InlayPoint>(());
807 cursor.seek(&inlay_point, Bias::Right);
808 loop {
809 match cursor.item() {
810 Some(transform) => {
811 let buffer_point = self.inlay_snapshot.to_buffer_point(inlay_point);
812 if buffer_point.row != buffer_row.0 {
813 return false;
814 } else if transform.placeholder.is_some() {
815 return true;
816 }
817 }
818 None => return false,
819 }
820
821 if cursor.end().row() == inlay_point.row() {
822 cursor.next();
823 } else {
824 inlay_point.0 += Point::new(1, 0);
825 cursor.seek(&inlay_point, Bias::Right);
826 }
827 }
828 }
829
830 pub(crate) fn chunks<'a>(
831 &'a self,
832 range: Range<FoldOffset>,
833 language_aware: bool,
834 highlights: Highlights<'a>,
835 ) -> FoldChunks<'a> {
836 let mut transform_cursor = self
837 .transforms
838 .cursor::<Dimensions<FoldOffset, InlayOffset>>(());
839 transform_cursor.seek(&range.start, Bias::Right);
840
841 let inlay_start = {
842 let overshoot = range.start.0 - transform_cursor.start().0.0;
843 transform_cursor.start().1 + InlayOffset(overshoot)
844 };
845
846 let transform_end = transform_cursor.end();
847
848 let inlay_end = if transform_cursor
849 .item()
850 .is_none_or(|transform| transform.is_fold())
851 {
852 inlay_start
853 } else if range.end < transform_end.0 {
854 let overshoot = range.end.0 - transform_cursor.start().0.0;
855 transform_cursor.start().1 + InlayOffset(overshoot)
856 } else {
857 transform_end.1
858 };
859
860 FoldChunks {
861 transform_cursor,
862 inlay_chunks: self.inlay_snapshot.chunks(
863 inlay_start..inlay_end,
864 language_aware,
865 highlights,
866 ),
867 inlay_chunk: None,
868 inlay_offset: inlay_start,
869 output_offset: range.start,
870 max_output_offset: range.end,
871 }
872 }
873
874 pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
875 self.chunks(
876 start.to_offset(self)..self.len(),
877 false,
878 Highlights::default(),
879 )
880 .flat_map(|chunk| chunk.text.chars())
881 }
882
883 pub fn chunks_at(&self, start: FoldPoint) -> FoldChunks<'_> {
884 self.chunks(
885 start.to_offset(self)..self.len(),
886 false,
887 Highlights::default(),
888 )
889 }
890
891 #[cfg(test)]
892 pub fn clip_offset(&self, offset: FoldOffset, bias: Bias) -> FoldOffset {
893 if offset > self.len() {
894 self.len()
895 } else {
896 self.clip_point(offset.to_point(self), bias).to_offset(self)
897 }
898 }
899
900 pub fn clip_point(&self, point: FoldPoint, bias: Bias) -> FoldPoint {
901 let (start, end, item) = self
902 .transforms
903 .find::<Dimensions<FoldPoint, InlayPoint>, _>((), &point, Bias::Right);
904 if let Some(transform) = item {
905 let transform_start = start.0.0;
906 if transform.placeholder.is_some() {
907 if point.0 == transform_start || matches!(bias, Bias::Left) {
908 FoldPoint(transform_start)
909 } else {
910 FoldPoint(end.0.0)
911 }
912 } else {
913 let overshoot = InlayPoint(point.0 - transform_start);
914 let inlay_point = start.1 + overshoot;
915 let clipped_inlay_point = self.inlay_snapshot.clip_point(inlay_point, bias);
916 FoldPoint(start.0.0 + (clipped_inlay_point - start.1).0)
917 }
918 } else {
919 FoldPoint(self.transforms.summary().output.lines)
920 }
921 }
922}
923
924fn push_isomorphic(transforms: &mut SumTree<Transform>, summary: TextSummary) {
925 let mut did_merge = false;
926 transforms.update_last(
927 |last| {
928 if !last.is_fold() {
929 last.summary.input += summary;
930 last.summary.output += summary;
931 did_merge = true;
932 }
933 },
934 (),
935 );
936 if !did_merge {
937 transforms.push(
938 Transform {
939 summary: TransformSummary {
940 input: summary,
941 output: summary,
942 },
943 placeholder: None,
944 },
945 (),
946 )
947 }
948}
949
950fn intersecting_folds<'a>(
951 inlay_snapshot: &'a InlaySnapshot,
952 folds: &'a SumTree<Fold>,
953 range: Range<usize>,
954 inclusive: bool,
955) -> FilterCursor<'a, 'a, impl 'a + FnMut(&FoldSummary) -> bool, Fold, usize> {
956 let buffer = &inlay_snapshot.buffer;
957 let start = buffer.anchor_before(range.start.to_offset(buffer));
958 let end = buffer.anchor_after(range.end.to_offset(buffer));
959 let mut cursor = folds.filter::<_, usize>(buffer, move |summary| {
960 let start_cmp = start.cmp(&summary.max_end, buffer);
961 let end_cmp = end.cmp(&summary.min_start, buffer);
962
963 if inclusive {
964 start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
965 } else {
966 start_cmp == Ordering::Less && end_cmp == Ordering::Greater
967 }
968 });
969 cursor.next();
970 cursor
971}
972
973fn consolidate_inlay_edits(mut edits: Vec<InlayEdit>) -> Vec<InlayEdit> {
974 edits.sort_unstable_by(|a, b| {
975 a.old
976 .start
977 .cmp(&b.old.start)
978 .then_with(|| b.old.end.cmp(&a.old.end))
979 });
980
981 let _old_alloc_ptr = edits.as_ptr();
982 let mut inlay_edits = edits.into_iter();
983
984 if let Some(mut first_edit) = inlay_edits.next() {
985 // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
986 #[allow(clippy::filter_map_identity)]
987 let mut v: Vec<_> = inlay_edits
988 .scan(&mut first_edit, |prev_edit, edit| {
989 if prev_edit.old.end >= edit.old.start {
990 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
991 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
992 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
993 Some(None) // Skip this edit, it's merged
994 } else {
995 let prev = std::mem::replace(*prev_edit, edit);
996 Some(Some(prev)) // Yield the previous edit
997 }
998 })
999 .filter_map(|x| x)
1000 .collect();
1001 v.push(first_edit.clone());
1002 debug_assert_eq!(_old_alloc_ptr, v.as_ptr(), "Inlay edits were reallocated");
1003 v
1004 } else {
1005 vec![]
1006 }
1007}
1008
1009fn consolidate_fold_edits(mut edits: Vec<FoldEdit>) -> Vec<FoldEdit> {
1010 edits.sort_unstable_by(|a, b| {
1011 a.old
1012 .start
1013 .cmp(&b.old.start)
1014 .then_with(|| b.old.end.cmp(&a.old.end))
1015 });
1016 let _old_alloc_ptr = edits.as_ptr();
1017 let mut fold_edits = edits.into_iter();
1018
1019 if let Some(mut first_edit) = fold_edits.next() {
1020 // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1021 #[allow(clippy::filter_map_identity)]
1022 let mut v: Vec<_> = fold_edits
1023 .scan(&mut first_edit, |prev_edit, edit| {
1024 if prev_edit.old.end >= edit.old.start {
1025 prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
1026 prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
1027 prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
1028 Some(None) // Skip this edit, it's merged
1029 } else {
1030 let prev = std::mem::replace(*prev_edit, edit);
1031 Some(Some(prev)) // Yield the previous edit
1032 }
1033 })
1034 .filter_map(|x| x)
1035 .collect();
1036 v.push(first_edit.clone());
1037 v
1038 } else {
1039 vec![]
1040 }
1041}
1042
1043#[derive(Clone, Debug, Default)]
1044struct Transform {
1045 summary: TransformSummary,
1046 placeholder: Option<TransformPlaceholder>,
1047}
1048
1049#[derive(Clone, Debug)]
1050struct TransformPlaceholder {
1051 text: &'static str,
1052 chars: u128,
1053 renderer: ChunkRenderer,
1054}
1055
1056impl Transform {
1057 fn is_fold(&self) -> bool {
1058 self.placeholder.is_some()
1059 }
1060}
1061
1062#[derive(Clone, Debug, Default, Eq, PartialEq)]
1063struct TransformSummary {
1064 output: TextSummary,
1065 input: TextSummary,
1066}
1067
1068impl sum_tree::Item for Transform {
1069 type Summary = TransformSummary;
1070
1071 fn summary(&self, _cx: ()) -> Self::Summary {
1072 self.summary.clone()
1073 }
1074}
1075
1076impl sum_tree::ContextLessSummary for TransformSummary {
1077 fn zero() -> Self {
1078 Default::default()
1079 }
1080
1081 fn add_summary(&mut self, other: &Self) {
1082 self.input += &other.input;
1083 self.output += &other.output;
1084 }
1085}
1086
1087#[derive(Copy, Clone, Eq, PartialEq, Debug, Default, Ord, PartialOrd, Hash)]
1088pub struct FoldId(pub(super) usize);
1089
1090impl From<FoldId> for ElementId {
1091 fn from(val: FoldId) -> Self {
1092 val.0.into()
1093 }
1094}
1095
1096#[derive(Clone, Debug, Eq, PartialEq)]
1097pub struct Fold {
1098 pub id: FoldId,
1099 pub range: FoldRange,
1100 pub placeholder: FoldPlaceholder,
1101}
1102
1103#[derive(Clone, Debug, Eq, PartialEq)]
1104pub struct FoldRange(Range<Anchor>);
1105
1106impl Deref for FoldRange {
1107 type Target = Range<Anchor>;
1108
1109 fn deref(&self) -> &Self::Target {
1110 &self.0
1111 }
1112}
1113
1114impl DerefMut for FoldRange {
1115 fn deref_mut(&mut self) -> &mut Self::Target {
1116 &mut self.0
1117 }
1118}
1119
1120impl Default for FoldRange {
1121 fn default() -> Self {
1122 Self(Anchor::min()..Anchor::max())
1123 }
1124}
1125
1126#[derive(Clone, Debug)]
1127struct FoldMetadata {
1128 range: FoldRange,
1129 width: Option<Pixels>,
1130}
1131
1132impl sum_tree::Item for Fold {
1133 type Summary = FoldSummary;
1134
1135 fn summary(&self, _cx: &MultiBufferSnapshot) -> Self::Summary {
1136 FoldSummary {
1137 start: self.range.start,
1138 end: self.range.end,
1139 min_start: self.range.start,
1140 max_end: self.range.end,
1141 count: 1,
1142 }
1143 }
1144}
1145
1146#[derive(Clone, Debug)]
1147pub struct FoldSummary {
1148 start: Anchor,
1149 end: Anchor,
1150 min_start: Anchor,
1151 max_end: Anchor,
1152 count: usize,
1153}
1154
1155impl Default for FoldSummary {
1156 fn default() -> Self {
1157 Self {
1158 start: Anchor::min(),
1159 end: Anchor::max(),
1160 min_start: Anchor::max(),
1161 max_end: Anchor::min(),
1162 count: 0,
1163 }
1164 }
1165}
1166
1167impl sum_tree::Summary for FoldSummary {
1168 type Context<'a> = &'a MultiBufferSnapshot;
1169
1170 fn zero(_cx: &MultiBufferSnapshot) -> Self {
1171 Default::default()
1172 }
1173
1174 fn add_summary(&mut self, other: &Self, buffer: Self::Context<'_>) {
1175 if other.min_start.cmp(&self.min_start, buffer) == Ordering::Less {
1176 self.min_start = other.min_start;
1177 }
1178 if other.max_end.cmp(&self.max_end, buffer) == Ordering::Greater {
1179 self.max_end = other.max_end;
1180 }
1181
1182 #[cfg(debug_assertions)]
1183 {
1184 let start_comparison = self.start.cmp(&other.start, buffer);
1185 assert!(start_comparison <= Ordering::Equal);
1186 if start_comparison == Ordering::Equal {
1187 assert!(self.end.cmp(&other.end, buffer) >= Ordering::Equal);
1188 }
1189 }
1190
1191 self.start = other.start;
1192 self.end = other.end;
1193 self.count += other.count;
1194 }
1195}
1196
1197impl<'a> sum_tree::Dimension<'a, FoldSummary> for FoldRange {
1198 fn zero(_cx: &MultiBufferSnapshot) -> Self {
1199 Default::default()
1200 }
1201
1202 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
1203 self.0.start = summary.start;
1204 self.0.end = summary.end;
1205 }
1206}
1207
1208impl sum_tree::SeekTarget<'_, FoldSummary, FoldRange> for FoldRange {
1209 fn cmp(&self, other: &Self, buffer: &MultiBufferSnapshot) -> Ordering {
1210 AnchorRangeExt::cmp(&self.0, &other.0, buffer)
1211 }
1212}
1213
1214impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
1215 fn zero(_cx: &MultiBufferSnapshot) -> Self {
1216 Default::default()
1217 }
1218
1219 fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
1220 *self += summary.count;
1221 }
1222}
1223
1224#[derive(Clone)]
1225pub struct FoldRows<'a> {
1226 cursor: Cursor<'a, 'static, Transform, Dimensions<FoldPoint, InlayPoint>>,
1227 input_rows: InlayBufferRows<'a>,
1228 fold_point: FoldPoint,
1229}
1230
1231impl FoldRows<'_> {
1232 pub(crate) fn seek(&mut self, row: u32) {
1233 let fold_point = FoldPoint::new(row, 0);
1234 self.cursor.seek(&fold_point, Bias::Left);
1235 let overshoot = fold_point.0 - self.cursor.start().0.0;
1236 let inlay_point = InlayPoint(self.cursor.start().1.0 + overshoot);
1237 self.input_rows.seek(inlay_point.row());
1238 self.fold_point = fold_point;
1239 }
1240}
1241
1242impl Iterator for FoldRows<'_> {
1243 type Item = RowInfo;
1244
1245 fn next(&mut self) -> Option<Self::Item> {
1246 let mut traversed_fold = false;
1247 while self.fold_point > self.cursor.end().0 {
1248 self.cursor.next();
1249 traversed_fold = true;
1250 if self.cursor.item().is_none() {
1251 break;
1252 }
1253 }
1254
1255 if self.cursor.item().is_some() {
1256 if traversed_fold {
1257 self.input_rows.seek(self.cursor.start().1.0.row);
1258 self.input_rows.next();
1259 }
1260 *self.fold_point.row_mut() += 1;
1261 self.input_rows.next()
1262 } else {
1263 None
1264 }
1265 }
1266}
1267
1268/// A chunk of a buffer's text, along with its syntax highlight and
1269/// diagnostic status.
1270#[derive(Clone, Debug, Default)]
1271pub struct Chunk<'a> {
1272 /// The text of the chunk.
1273 pub text: &'a str,
1274 /// The syntax highlighting style of the chunk.
1275 pub syntax_highlight_id: Option<HighlightId>,
1276 /// The highlight style that has been applied to this chunk in
1277 /// the editor.
1278 pub highlight_style: Option<HighlightStyle>,
1279 /// The severity of diagnostic associated with this chunk, if any.
1280 pub diagnostic_severity: Option<lsp::DiagnosticSeverity>,
1281 /// Whether this chunk of text is marked as unnecessary.
1282 pub is_unnecessary: bool,
1283 /// Whether this chunk of text should be underlined.
1284 pub underline: bool,
1285 /// Whether this chunk of text was originally a tab character.
1286 pub is_tab: bool,
1287 /// Whether this chunk of text was originally a tab character.
1288 pub is_inlay: bool,
1289 /// An optional recipe for how the chunk should be presented.
1290 pub renderer: Option<ChunkRenderer>,
1291 /// Bitmap of tab character locations in chunk
1292 pub tabs: u128,
1293 /// Bitmap of character locations in chunk
1294 pub chars: u128,
1295}
1296
1297#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1298pub enum ChunkRendererId {
1299 Fold(FoldId),
1300 Inlay(InlayId),
1301}
1302
1303/// A recipe for how the chunk should be presented.
1304#[derive(Clone)]
1305pub struct ChunkRenderer {
1306 /// The id of the renderer associated with this chunk.
1307 pub id: ChunkRendererId,
1308 /// Creates a custom element to represent this chunk.
1309 pub render: Arc<dyn Send + Sync + Fn(&mut ChunkRendererContext) -> AnyElement>,
1310 /// If true, the element is constrained to the shaped width of the text.
1311 pub constrain_width: bool,
1312 /// The width of the element, as measured during the last layout pass.
1313 ///
1314 /// This is None if the element has not been laid out yet.
1315 pub measured_width: Option<Pixels>,
1316}
1317
1318pub struct ChunkRendererContext<'a, 'b> {
1319 pub window: &'a mut Window,
1320 pub context: &'b mut App,
1321 pub max_width: Pixels,
1322}
1323
1324impl fmt::Debug for ChunkRenderer {
1325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1326 f.debug_struct("ChunkRenderer")
1327 .field("constrain_width", &self.constrain_width)
1328 .finish()
1329 }
1330}
1331
1332impl Deref for ChunkRendererContext<'_, '_> {
1333 type Target = App;
1334
1335 fn deref(&self) -> &Self::Target {
1336 self.context
1337 }
1338}
1339
1340impl DerefMut for ChunkRendererContext<'_, '_> {
1341 fn deref_mut(&mut self) -> &mut Self::Target {
1342 self.context
1343 }
1344}
1345
1346pub struct FoldChunks<'a> {
1347 transform_cursor: Cursor<'a, 'static, Transform, Dimensions<FoldOffset, InlayOffset>>,
1348 inlay_chunks: InlayChunks<'a>,
1349 inlay_chunk: Option<(InlayOffset, InlayChunk<'a>)>,
1350 inlay_offset: InlayOffset,
1351 output_offset: FoldOffset,
1352 max_output_offset: FoldOffset,
1353}
1354
1355impl FoldChunks<'_> {
1356 pub(crate) fn seek(&mut self, range: Range<FoldOffset>) {
1357 self.transform_cursor.seek(&range.start, Bias::Right);
1358
1359 let inlay_start = {
1360 let overshoot = range.start.0 - self.transform_cursor.start().0.0;
1361 self.transform_cursor.start().1 + InlayOffset(overshoot)
1362 };
1363
1364 let transform_end = self.transform_cursor.end();
1365
1366 let inlay_end = if self
1367 .transform_cursor
1368 .item()
1369 .is_none_or(|transform| transform.is_fold())
1370 {
1371 inlay_start
1372 } else if range.end < transform_end.0 {
1373 let overshoot = range.end.0 - self.transform_cursor.start().0.0;
1374 self.transform_cursor.start().1 + InlayOffset(overshoot)
1375 } else {
1376 transform_end.1
1377 };
1378
1379 self.inlay_chunks.seek(inlay_start..inlay_end);
1380 self.inlay_chunk = None;
1381 self.inlay_offset = inlay_start;
1382 self.output_offset = range.start;
1383 self.max_output_offset = range.end;
1384 }
1385}
1386
1387impl<'a> Iterator for FoldChunks<'a> {
1388 type Item = Chunk<'a>;
1389
1390 fn next(&mut self) -> Option<Self::Item> {
1391 if self.output_offset >= self.max_output_offset {
1392 return None;
1393 }
1394
1395 let transform = self.transform_cursor.item()?;
1396
1397 // If we're in a fold, then return the fold's display text and
1398 // advance the transform and buffer cursors to the end of the fold.
1399 if let Some(placeholder) = transform.placeholder.as_ref() {
1400 self.inlay_chunk.take();
1401 self.inlay_offset += InlayOffset(transform.summary.input.len);
1402
1403 while self.inlay_offset >= self.transform_cursor.end().1
1404 && self.transform_cursor.item().is_some()
1405 {
1406 self.transform_cursor.next();
1407 }
1408
1409 self.output_offset.0 += placeholder.text.len();
1410 return Some(Chunk {
1411 text: placeholder.text,
1412 chars: placeholder.chars,
1413 renderer: Some(placeholder.renderer.clone()),
1414 ..Default::default()
1415 });
1416 }
1417
1418 // When we reach a non-fold region, seek the underlying text
1419 // chunk iterator to the next unfolded range.
1420 if self.inlay_offset == self.transform_cursor.start().1
1421 && self.inlay_chunks.offset() != self.inlay_offset
1422 {
1423 let transform_start = self.transform_cursor.start();
1424 let transform_end = self.transform_cursor.end();
1425 let inlay_end = if self.max_output_offset < transform_end.0 {
1426 let overshoot = self.max_output_offset.0 - transform_start.0.0;
1427 transform_start.1 + InlayOffset(overshoot)
1428 } else {
1429 transform_end.1
1430 };
1431
1432 self.inlay_chunks.seek(self.inlay_offset..inlay_end);
1433 }
1434
1435 // Retrieve a chunk from the current location in the buffer.
1436 if self.inlay_chunk.is_none() {
1437 let chunk_offset = self.inlay_chunks.offset();
1438 self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1439 }
1440
1441 // Otherwise, take a chunk from the buffer's text.
1442 if let Some((buffer_chunk_start, mut inlay_chunk)) = self.inlay_chunk.clone() {
1443 let chunk = &mut inlay_chunk.chunk;
1444 let buffer_chunk_end = buffer_chunk_start + InlayOffset(chunk.text.len());
1445 let transform_end = self.transform_cursor.end().1;
1446 let chunk_end = buffer_chunk_end.min(transform_end);
1447
1448 let bit_start = (self.inlay_offset - buffer_chunk_start).0;
1449 let bit_end = (chunk_end - buffer_chunk_start).0;
1450 chunk.text = &chunk.text[bit_start..bit_end];
1451
1452 let bit_end = (chunk_end - buffer_chunk_start).0;
1453 let mask = 1u128.unbounded_shl(bit_end as u32).wrapping_sub(1);
1454
1455 chunk.tabs = (chunk.tabs >> bit_start) & mask;
1456 chunk.chars = (chunk.chars >> bit_start) & mask;
1457
1458 if chunk_end == transform_end {
1459 self.transform_cursor.next();
1460 } else if chunk_end == buffer_chunk_end {
1461 self.inlay_chunk.take();
1462 }
1463
1464 self.inlay_offset = chunk_end;
1465 self.output_offset.0 += chunk.text.len();
1466 return Some(Chunk {
1467 text: chunk.text,
1468 tabs: chunk.tabs,
1469 chars: chunk.chars,
1470 syntax_highlight_id: chunk.syntax_highlight_id,
1471 highlight_style: chunk.highlight_style,
1472 diagnostic_severity: chunk.diagnostic_severity,
1473 is_unnecessary: chunk.is_unnecessary,
1474 is_tab: chunk.is_tab,
1475 is_inlay: chunk.is_inlay,
1476 underline: chunk.underline,
1477 renderer: inlay_chunk.renderer,
1478 });
1479 }
1480
1481 None
1482 }
1483}
1484
1485#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1486pub struct FoldOffset(pub usize);
1487
1488impl FoldOffset {
1489 pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1490 let (start, _, item) = snapshot
1491 .transforms
1492 .find::<Dimensions<FoldOffset, TransformSummary>, _>((), &self, Bias::Right);
1493 let overshoot = if item.is_none_or(|t| t.is_fold()) {
1494 Point::new(0, (self.0 - start.0.0) as u32)
1495 } else {
1496 let inlay_offset = start.1.input.len + self.0 - start.0.0;
1497 let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1498 inlay_point.0 - start.1.input.lines
1499 };
1500 FoldPoint(start.1.output.lines + overshoot)
1501 }
1502
1503 #[cfg(test)]
1504 pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1505 let (start, _, _) = snapshot
1506 .transforms
1507 .find::<Dimensions<FoldOffset, InlayOffset>, _>((), &self, Bias::Right);
1508 let overshoot = self.0 - start.0.0;
1509 InlayOffset(start.1.0 + overshoot)
1510 }
1511}
1512
1513impl Add for FoldOffset {
1514 type Output = Self;
1515
1516 fn add(self, rhs: Self) -> Self::Output {
1517 Self(self.0 + rhs.0)
1518 }
1519}
1520
1521impl AddAssign for FoldOffset {
1522 fn add_assign(&mut self, rhs: Self) {
1523 self.0 += rhs.0;
1524 }
1525}
1526
1527impl Sub for FoldOffset {
1528 type Output = Self;
1529
1530 fn sub(self, rhs: Self) -> Self::Output {
1531 Self(self.0 - rhs.0)
1532 }
1533}
1534
1535impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1536 fn zero(_cx: ()) -> Self {
1537 Default::default()
1538 }
1539
1540 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1541 self.0 += &summary.output.len;
1542 }
1543}
1544
1545impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1546 fn zero(_cx: ()) -> Self {
1547 Default::default()
1548 }
1549
1550 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1551 self.0 += &summary.input.lines;
1552 }
1553}
1554
1555impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1556 fn zero(_cx: ()) -> Self {
1557 Default::default()
1558 }
1559
1560 fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1561 self.0 += &summary.input.len;
1562 }
1563}
1564
1565pub type FoldEdit = Edit<FoldOffset>;
1566
1567#[cfg(test)]
1568mod tests {
1569 use super::*;
1570 use crate::{MultiBuffer, ToPoint, display_map::inlay_map::InlayMap};
1571 use Bias::{Left, Right};
1572 use collections::HashSet;
1573 use rand::prelude::*;
1574 use settings::SettingsStore;
1575 use std::{env, mem};
1576 use text::Patch;
1577 use util::RandomCharIter;
1578 use util::test::sample_text;
1579
1580 #[gpui::test]
1581 fn test_basic_folds(cx: &mut gpui::App) {
1582 init_test(cx);
1583 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1584 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1585 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1586 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1587 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1588
1589 let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1590 let (snapshot2, edits) = writer.fold(vec![
1591 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1592 (Point::new(2, 4)..Point::new(4, 1), FoldPlaceholder::test()),
1593 ]);
1594 assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1595 assert_eq!(
1596 edits,
1597 &[
1598 FoldEdit {
1599 old: FoldOffset(2)..FoldOffset(16),
1600 new: FoldOffset(2)..FoldOffset(5),
1601 },
1602 FoldEdit {
1603 old: FoldOffset(18)..FoldOffset(29),
1604 new: FoldOffset(7)..FoldOffset(10)
1605 },
1606 ]
1607 );
1608
1609 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1610 buffer.edit(
1611 vec![
1612 (Point::new(0, 0)..Point::new(0, 1), "123"),
1613 (Point::new(2, 3)..Point::new(2, 3), "123"),
1614 ],
1615 None,
1616 cx,
1617 );
1618 buffer.snapshot(cx)
1619 });
1620
1621 let (inlay_snapshot, inlay_edits) =
1622 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1623 let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1624 assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1625 assert_eq!(
1626 edits,
1627 &[
1628 FoldEdit {
1629 old: FoldOffset(0)..FoldOffset(1),
1630 new: FoldOffset(0)..FoldOffset(3),
1631 },
1632 FoldEdit {
1633 old: FoldOffset(6)..FoldOffset(6),
1634 new: FoldOffset(8)..FoldOffset(11),
1635 },
1636 ]
1637 );
1638
1639 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1640 buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1641 buffer.snapshot(cx)
1642 });
1643 let (inlay_snapshot, inlay_edits) =
1644 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1645 let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1646 assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1647
1648 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1649 writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1650 let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1651 assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1652
1653 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1654 writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1655 let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1656 assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1657 }
1658
1659 #[gpui::test]
1660 fn test_adjacent_folds(cx: &mut gpui::App) {
1661 init_test(cx);
1662 let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1663 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1664 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1665 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1666
1667 {
1668 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1669
1670 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1671 writer.fold(vec![(5..8, FoldPlaceholder::test())]);
1672 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1673 assert_eq!(snapshot.text(), "abcde⋯ijkl");
1674
1675 // Create an fold adjacent to the start of the first fold.
1676 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1677 writer.fold(vec![
1678 (0..1, FoldPlaceholder::test()),
1679 (2..5, FoldPlaceholder::test()),
1680 ]);
1681 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1682 assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1683
1684 // Create an fold adjacent to the end of the first fold.
1685 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1686 writer.fold(vec![
1687 (11..11, FoldPlaceholder::test()),
1688 (8..10, FoldPlaceholder::test()),
1689 ]);
1690 let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1691 assert_eq!(snapshot.text(), "⋯b⋯kl");
1692 }
1693
1694 {
1695 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1696
1697 // Create two adjacent folds.
1698 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1699 writer.fold(vec![
1700 (0..2, FoldPlaceholder::test()),
1701 (2..5, FoldPlaceholder::test()),
1702 ]);
1703 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1704 assert_eq!(snapshot.text(), "⋯fghijkl");
1705
1706 // Edit within one of the folds.
1707 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1708 buffer.edit([(0..1, "12345")], None, cx);
1709 buffer.snapshot(cx)
1710 });
1711 let (inlay_snapshot, inlay_edits) =
1712 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1713 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1714 assert_eq!(snapshot.text(), "12345⋯fghijkl");
1715 }
1716 }
1717
1718 #[gpui::test]
1719 fn test_overlapping_folds(cx: &mut gpui::App) {
1720 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1721 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1722 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1723 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1724 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1725 writer.fold(vec![
1726 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1727 (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1728 (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1729 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1730 ]);
1731 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1732 assert_eq!(snapshot.text(), "aa⋯eeeee");
1733 }
1734
1735 #[gpui::test]
1736 fn test_merging_folds_via_edit(cx: &mut gpui::App) {
1737 init_test(cx);
1738 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1739 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1740 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1741 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1742 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1743
1744 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1745 writer.fold(vec![
1746 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1747 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1748 ]);
1749 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1750 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1751
1752 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1753 buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1754 buffer.snapshot(cx)
1755 });
1756 let (inlay_snapshot, inlay_edits) =
1757 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1758 let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1759 assert_eq!(snapshot.text(), "aa⋯eeeee");
1760 }
1761
1762 #[gpui::test]
1763 fn test_folds_in_range(cx: &mut gpui::App) {
1764 let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1765 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1766 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1767 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1768
1769 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1770 writer.fold(vec![
1771 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1772 (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1773 (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1774 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1775 ]);
1776 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1777 let fold_ranges = snapshot
1778 .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1779 .map(|fold| {
1780 fold.range.start.to_point(&buffer_snapshot)
1781 ..fold.range.end.to_point(&buffer_snapshot)
1782 })
1783 .collect::<Vec<_>>();
1784 assert_eq!(
1785 fold_ranges,
1786 vec![
1787 Point::new(0, 2)..Point::new(2, 2),
1788 Point::new(1, 2)..Point::new(3, 2)
1789 ]
1790 );
1791 }
1792
1793 #[gpui::test(iterations = 100)]
1794 fn test_random_folds(cx: &mut gpui::App, mut rng: StdRng) {
1795 init_test(cx);
1796 let operations = env::var("OPERATIONS")
1797 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1798 .unwrap_or(10);
1799
1800 let len = rng.random_range(0..10);
1801 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1802 let buffer = if rng.random() {
1803 MultiBuffer::build_simple(&text, cx)
1804 } else {
1805 MultiBuffer::build_random(&mut rng, cx)
1806 };
1807 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1808 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1809 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1810
1811 let (mut initial_snapshot, _) = map.read(inlay_snapshot, vec![]);
1812 let mut snapshot_edits = Vec::new();
1813
1814 let mut next_inlay_id = 0;
1815 for _ in 0..operations {
1816 log::info!("text: {:?}", buffer_snapshot.text());
1817 let mut buffer_edits = Vec::new();
1818 let mut inlay_edits = Vec::new();
1819 match rng.random_range(0..=100) {
1820 0..=39 => {
1821 snapshot_edits.extend(map.randomly_mutate(&mut rng));
1822 }
1823 40..=59 => {
1824 let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1825 inlay_edits = edits;
1826 }
1827 _ => buffer.update(cx, |buffer, cx| {
1828 let subscription = buffer.subscribe();
1829 let edit_count = rng.random_range(1..=5);
1830 buffer.randomly_mutate(&mut rng, edit_count, cx);
1831 buffer_snapshot = buffer.snapshot(cx);
1832 let edits = subscription.consume().into_inner();
1833 log::info!("editing {:?}", edits);
1834 buffer_edits.extend(edits);
1835 }),
1836 };
1837
1838 let (inlay_snapshot, new_inlay_edits) =
1839 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1840 log::info!("inlay text {:?}", inlay_snapshot.text());
1841
1842 let inlay_edits = Patch::new(inlay_edits)
1843 .compose(new_inlay_edits)
1844 .into_inner();
1845 let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
1846 snapshot_edits.push((snapshot.clone(), edits));
1847
1848 let mut expected_text: String = inlay_snapshot.text().to_string();
1849 for fold_range in map.merged_folds().into_iter().rev() {
1850 let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
1851 let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
1852 expected_text.replace_range(fold_inlay_start.0..fold_inlay_end.0, "⋯");
1853 }
1854
1855 assert_eq!(snapshot.text(), expected_text);
1856 log::info!(
1857 "fold text {:?} ({} lines)",
1858 expected_text,
1859 expected_text.matches('\n').count() + 1
1860 );
1861
1862 let mut prev_row = 0;
1863 let mut expected_buffer_rows = Vec::new();
1864 for fold_range in map.merged_folds() {
1865 let fold_start = inlay_snapshot
1866 .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
1867 .row();
1868 let fold_end = inlay_snapshot
1869 .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
1870 .row();
1871 expected_buffer_rows.extend(
1872 inlay_snapshot
1873 .row_infos(prev_row)
1874 .take((1 + fold_start - prev_row) as usize),
1875 );
1876 prev_row = 1 + fold_end;
1877 }
1878 expected_buffer_rows.extend(inlay_snapshot.row_infos(prev_row));
1879
1880 assert_eq!(
1881 expected_buffer_rows.len(),
1882 expected_text.matches('\n').count() + 1,
1883 "wrong expected buffer rows {:?}. text: {:?}",
1884 expected_buffer_rows,
1885 expected_text
1886 );
1887
1888 for (output_row, line) in expected_text.lines().enumerate() {
1889 let line_len = snapshot.line_len(output_row as u32);
1890 assert_eq!(line_len, line.len() as u32);
1891 }
1892
1893 let longest_row = snapshot.longest_row();
1894 let longest_char_column = expected_text
1895 .split('\n')
1896 .nth(longest_row as usize)
1897 .unwrap()
1898 .chars()
1899 .count();
1900 let mut fold_point = FoldPoint::new(0, 0);
1901 let mut fold_offset = FoldOffset(0);
1902 let mut char_column = 0;
1903 for c in expected_text.chars() {
1904 let inlay_point = fold_point.to_inlay_point(&snapshot);
1905 let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
1906 assert_eq!(
1907 snapshot.to_fold_point(inlay_point, Right),
1908 fold_point,
1909 "{:?} -> fold point",
1910 inlay_point,
1911 );
1912 assert_eq!(
1913 inlay_snapshot.to_offset(inlay_point),
1914 inlay_offset,
1915 "inlay_snapshot.to_offset({:?})",
1916 inlay_point,
1917 );
1918 assert_eq!(
1919 fold_point.to_offset(&snapshot),
1920 fold_offset,
1921 "fold_point.to_offset({:?})",
1922 fold_point,
1923 );
1924
1925 if c == '\n' {
1926 *fold_point.row_mut() += 1;
1927 *fold_point.column_mut() = 0;
1928 char_column = 0;
1929 } else {
1930 *fold_point.column_mut() += c.len_utf8() as u32;
1931 char_column += 1;
1932 }
1933 fold_offset.0 += c.len_utf8();
1934 if char_column > longest_char_column {
1935 panic!(
1936 "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
1937 longest_row,
1938 longest_char_column,
1939 fold_point.row(),
1940 char_column
1941 );
1942 }
1943 }
1944
1945 for _ in 0..5 {
1946 let mut start = snapshot.clip_offset(
1947 FoldOffset(rng.random_range(0..=snapshot.len().0)),
1948 Bias::Left,
1949 );
1950 let mut end = snapshot.clip_offset(
1951 FoldOffset(rng.random_range(0..=snapshot.len().0)),
1952 Bias::Right,
1953 );
1954 if start > end {
1955 mem::swap(&mut start, &mut end);
1956 }
1957
1958 let text = &expected_text[start.0..end.0];
1959 assert_eq!(
1960 snapshot
1961 .chunks(start..end, false, Highlights::default())
1962 .map(|c| c.text)
1963 .collect::<String>(),
1964 text,
1965 );
1966 }
1967
1968 let mut fold_row = 0;
1969 while fold_row < expected_buffer_rows.len() as u32 {
1970 assert_eq!(
1971 snapshot.row_infos(fold_row).collect::<Vec<_>>(),
1972 expected_buffer_rows[(fold_row as usize)..],
1973 "wrong buffer rows starting at fold row {}",
1974 fold_row,
1975 );
1976 fold_row += 1;
1977 }
1978
1979 let folded_buffer_rows = map
1980 .merged_folds()
1981 .iter()
1982 .flat_map(|fold_range| {
1983 let start_row = fold_range.start.to_point(&buffer_snapshot).row;
1984 let end = fold_range.end.to_point(&buffer_snapshot);
1985 if end.column == 0 {
1986 start_row..end.row
1987 } else {
1988 start_row..end.row + 1
1989 }
1990 })
1991 .collect::<HashSet<_>>();
1992 for row in 0..=buffer_snapshot.max_point().row {
1993 assert_eq!(
1994 snapshot.is_line_folded(MultiBufferRow(row)),
1995 folded_buffer_rows.contains(&row),
1996 "expected buffer row {}{} to be folded",
1997 row,
1998 if folded_buffer_rows.contains(&row) {
1999 ""
2000 } else {
2001 " not"
2002 }
2003 );
2004 }
2005
2006 for _ in 0..5 {
2007 let end =
2008 buffer_snapshot.clip_offset(rng.random_range(0..=buffer_snapshot.len()), Right);
2009 let start = buffer_snapshot.clip_offset(rng.random_range(0..=end), Left);
2010 let expected_folds = map
2011 .snapshot
2012 .folds
2013 .items(&buffer_snapshot)
2014 .into_iter()
2015 .filter(|fold| {
2016 let start = buffer_snapshot.anchor_before(start);
2017 let end = buffer_snapshot.anchor_after(end);
2018 start.cmp(&fold.range.end, &buffer_snapshot) == Ordering::Less
2019 && end.cmp(&fold.range.start, &buffer_snapshot) == Ordering::Greater
2020 })
2021 .collect::<Vec<_>>();
2022
2023 assert_eq!(
2024 snapshot
2025 .folds_in_range(start..end)
2026 .cloned()
2027 .collect::<Vec<_>>(),
2028 expected_folds
2029 );
2030 }
2031
2032 let text = snapshot.text();
2033 for _ in 0..5 {
2034 let start_row = rng.random_range(0..=snapshot.max_point().row());
2035 let start_column = rng.random_range(0..=snapshot.line_len(start_row));
2036 let end_row = rng.random_range(0..=snapshot.max_point().row());
2037 let end_column = rng.random_range(0..=snapshot.line_len(end_row));
2038 let mut start =
2039 snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
2040 let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
2041 if start > end {
2042 mem::swap(&mut start, &mut end);
2043 }
2044
2045 let lines = start..end;
2046 let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
2047 assert_eq!(
2048 snapshot.text_summary_for_range(lines),
2049 TextSummary::from(&text[bytes.start.0..bytes.end.0])
2050 )
2051 }
2052
2053 let mut text = initial_snapshot.text();
2054 for (snapshot, edits) in snapshot_edits.drain(..) {
2055 let new_text = snapshot.text();
2056 for edit in edits {
2057 let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
2058 let new_bytes = edit.new.start.0..edit.new.end.0;
2059 text.replace_range(old_bytes, &new_text[new_bytes]);
2060 }
2061
2062 assert_eq!(text, new_text);
2063 initial_snapshot = snapshot;
2064 }
2065 }
2066 }
2067
2068 #[gpui::test]
2069 fn test_buffer_rows(cx: &mut gpui::App) {
2070 let text = sample_text(6, 6, 'a') + "\n";
2071 let buffer = MultiBuffer::build_simple(&text, cx);
2072
2073 let buffer_snapshot = buffer.read(cx).snapshot(cx);
2074 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
2075 let mut map = FoldMap::new(inlay_snapshot.clone()).0;
2076
2077 let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
2078 writer.fold(vec![
2079 (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
2080 (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
2081 ]);
2082
2083 let (snapshot, _) = map.read(inlay_snapshot, vec![]);
2084 assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
2085 assert_eq!(
2086 snapshot
2087 .row_infos(0)
2088 .map(|info| info.buffer_row)
2089 .collect::<Vec<_>>(),
2090 [Some(0), Some(3), Some(5), Some(6)]
2091 );
2092 assert_eq!(
2093 snapshot
2094 .row_infos(3)
2095 .map(|info| info.buffer_row)
2096 .collect::<Vec<_>>(),
2097 [Some(6)]
2098 );
2099 }
2100
2101 #[gpui::test(iterations = 100)]
2102 fn test_random_chunk_bitmaps(cx: &mut gpui::App, mut rng: StdRng) {
2103 init_test(cx);
2104
2105 // Generate random buffer using existing test infrastructure
2106 let text_len = rng.random_range(0..10000);
2107 let buffer = if rng.random() {
2108 let text = RandomCharIter::new(&mut rng)
2109 .take(text_len)
2110 .collect::<String>();
2111 MultiBuffer::build_simple(&text, cx)
2112 } else {
2113 MultiBuffer::build_random(&mut rng, cx)
2114 };
2115 let buffer_snapshot = buffer.read(cx).snapshot(cx);
2116 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
2117 let (mut fold_map, _) = FoldMap::new(inlay_snapshot.clone());
2118
2119 // Perform random mutations
2120 let mutation_count = rng.random_range(1..10);
2121 for _ in 0..mutation_count {
2122 fold_map.randomly_mutate(&mut rng);
2123 }
2124
2125 let (snapshot, _) = fold_map.read(inlay_snapshot, vec![]);
2126
2127 // Get all chunks and verify their bitmaps
2128 let chunks = snapshot.chunks(
2129 FoldOffset(0)..FoldOffset(snapshot.len().0),
2130 false,
2131 Highlights::default(),
2132 );
2133
2134 for chunk in chunks {
2135 let chunk_text = chunk.text;
2136 let chars_bitmap = chunk.chars;
2137 let tabs_bitmap = chunk.tabs;
2138
2139 // Check empty chunks have empty bitmaps
2140 if chunk_text.is_empty() {
2141 assert_eq!(
2142 chars_bitmap, 0,
2143 "Empty chunk should have empty chars bitmap"
2144 );
2145 assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
2146 continue;
2147 }
2148
2149 // Verify that chunk text doesn't exceed 128 bytes
2150 assert!(
2151 chunk_text.len() <= 128,
2152 "Chunk text length {} exceeds 128 bytes",
2153 chunk_text.len()
2154 );
2155
2156 // Verify chars bitmap
2157 let char_indices = chunk_text
2158 .char_indices()
2159 .map(|(i, _)| i)
2160 .collect::<Vec<_>>();
2161
2162 for byte_idx in 0..chunk_text.len() {
2163 let should_have_bit = char_indices.contains(&byte_idx);
2164 let has_bit = chars_bitmap & (1 << byte_idx) != 0;
2165
2166 if has_bit != should_have_bit {
2167 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
2168 eprintln!("Char indices: {:?}", char_indices);
2169 eprintln!("Chars bitmap: {:#b}", chars_bitmap);
2170 assert_eq!(
2171 has_bit, should_have_bit,
2172 "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
2173 byte_idx, chunk_text, should_have_bit, has_bit
2174 );
2175 }
2176 }
2177
2178 // Verify tabs bitmap
2179 for (byte_idx, byte) in chunk_text.bytes().enumerate() {
2180 let is_tab = byte == b'\t';
2181 let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
2182
2183 assert_eq!(
2184 has_bit, is_tab,
2185 "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
2186 byte_idx, chunk_text, byte as char, is_tab, has_bit
2187 );
2188 }
2189 }
2190 }
2191
2192 fn init_test(cx: &mut gpui::App) {
2193 let store = SettingsStore::test(cx);
2194 cx.set_global(store);
2195 }
2196
2197 impl FoldMap {
2198 fn merged_folds(&self) -> Vec<Range<usize>> {
2199 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2200 let buffer = &inlay_snapshot.buffer;
2201 let mut folds = self.snapshot.folds.items(buffer);
2202 // Ensure sorting doesn't change how folds get merged and displayed.
2203 folds.sort_by(|a, b| a.range.cmp(&b.range, buffer));
2204 let mut folds = folds
2205 .iter()
2206 .map(|fold| fold.range.start.to_offset(buffer)..fold.range.end.to_offset(buffer))
2207 .peekable();
2208
2209 let mut merged_folds = Vec::new();
2210 while let Some(mut fold_range) = folds.next() {
2211 while let Some(next_range) = folds.peek() {
2212 if fold_range.end >= next_range.start {
2213 if next_range.end > fold_range.end {
2214 fold_range.end = next_range.end;
2215 }
2216 folds.next();
2217 } else {
2218 break;
2219 }
2220 }
2221 if fold_range.end > fold_range.start {
2222 merged_folds.push(fold_range);
2223 }
2224 }
2225 merged_folds
2226 }
2227
2228 pub fn randomly_mutate(
2229 &mut self,
2230 rng: &mut impl Rng,
2231 ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
2232 let mut snapshot_edits = Vec::new();
2233 match rng.random_range(0..=100) {
2234 0..=39 if !self.snapshot.folds.is_empty() => {
2235 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2236 let buffer = &inlay_snapshot.buffer;
2237 let mut to_unfold = Vec::new();
2238 for _ in 0..rng.random_range(1..=3) {
2239 let end = buffer.clip_offset(rng.random_range(0..=buffer.len()), Right);
2240 let start = buffer.clip_offset(rng.random_range(0..=end), Left);
2241 to_unfold.push(start..end);
2242 }
2243 let inclusive = rng.random();
2244 log::info!("unfolding {:?} (inclusive: {})", to_unfold, inclusive);
2245 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2246 snapshot_edits.push((snapshot, edits));
2247 let (snapshot, edits) = writer.unfold_intersecting(to_unfold, inclusive);
2248 snapshot_edits.push((snapshot, edits));
2249 }
2250 _ => {
2251 let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2252 let buffer = &inlay_snapshot.buffer;
2253 let mut to_fold = Vec::new();
2254 for _ in 0..rng.random_range(1..=2) {
2255 let end = buffer.clip_offset(rng.random_range(0..=buffer.len()), Right);
2256 let start = buffer.clip_offset(rng.random_range(0..=end), Left);
2257 to_fold.push((start..end, FoldPlaceholder::test()));
2258 }
2259 log::info!("folding {:?}", to_fold);
2260 let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2261 snapshot_edits.push((snapshot, edits));
2262 let (snapshot, edits) = writer.fold(to_fold);
2263 snapshot_edits.push((snapshot, edits));
2264 }
2265 }
2266 snapshot_edits
2267 }
2268 }
2269}