fold_map.rs

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