fold_map.rs

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