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