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