fold_map.rs

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