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