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            let bit_start = (self.inlay_offset - buffer_chunk_start).0;
1440            let bit_end = (chunk_end - buffer_chunk_start).0;
1441            chunk.text = &chunk.text[bit_start..bit_end];
1442
1443            let bit_end = (chunk_end - buffer_chunk_start).0;
1444            let mask = 1u128.unbounded_shl(bit_end as u32).wrapping_sub(1);
1445
1446            chunk.tabs = (chunk.tabs >> bit_start) & mask;
1447            chunk.chars = (chunk.chars >> bit_start) & mask;
1448
1449            if chunk_end == transform_end {
1450                self.transform_cursor.next();
1451            } else if chunk_end == buffer_chunk_end {
1452                self.inlay_chunk.take();
1453            }
1454
1455            self.inlay_offset = chunk_end;
1456            self.output_offset.0 += chunk.text.len();
1457            return Some(Chunk {
1458                text: chunk.text,
1459                tabs: chunk.tabs,
1460                chars: chunk.chars,
1461                syntax_highlight_id: chunk.syntax_highlight_id,
1462                highlight_style: chunk.highlight_style,
1463                diagnostic_severity: chunk.diagnostic_severity,
1464                is_unnecessary: chunk.is_unnecessary,
1465                is_tab: chunk.is_tab,
1466                is_inlay: chunk.is_inlay,
1467                underline: chunk.underline,
1468                renderer: inlay_chunk.renderer,
1469            });
1470        }
1471
1472        None
1473    }
1474}
1475
1476#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1477pub struct FoldOffset(pub usize);
1478
1479impl FoldOffset {
1480    pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1481        let (start, _, item) = snapshot
1482            .transforms
1483            .find::<Dimensions<FoldOffset, TransformSummary>, _>((), &self, Bias::Right);
1484        let overshoot = if item.is_none_or(|t| t.is_fold()) {
1485            Point::new(0, (self.0 - start.0.0) as u32)
1486        } else {
1487            let inlay_offset = start.1.input.len + self.0 - start.0.0;
1488            let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1489            inlay_point.0 - start.1.input.lines
1490        };
1491        FoldPoint(start.1.output.lines + overshoot)
1492    }
1493
1494    #[cfg(test)]
1495    pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1496        let (start, _, _) = snapshot
1497            .transforms
1498            .find::<Dimensions<FoldOffset, InlayOffset>, _>((), &self, Bias::Right);
1499        let overshoot = self.0 - start.0.0;
1500        InlayOffset(start.1.0 + overshoot)
1501    }
1502}
1503
1504impl Add for FoldOffset {
1505    type Output = Self;
1506
1507    fn add(self, rhs: Self) -> Self::Output {
1508        Self(self.0 + rhs.0)
1509    }
1510}
1511
1512impl AddAssign for FoldOffset {
1513    fn add_assign(&mut self, rhs: Self) {
1514        self.0 += rhs.0;
1515    }
1516}
1517
1518impl Sub for FoldOffset {
1519    type Output = Self;
1520
1521    fn sub(self, rhs: Self) -> Self::Output {
1522        Self(self.0 - rhs.0)
1523    }
1524}
1525
1526impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1527    fn zero(_cx: ()) -> Self {
1528        Default::default()
1529    }
1530
1531    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1532        self.0 += &summary.output.len;
1533    }
1534}
1535
1536impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1537    fn zero(_cx: ()) -> Self {
1538        Default::default()
1539    }
1540
1541    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1542        self.0 += &summary.input.lines;
1543    }
1544}
1545
1546impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1547    fn zero(_cx: ()) -> Self {
1548        Default::default()
1549    }
1550
1551    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1552        self.0 += &summary.input.len;
1553    }
1554}
1555
1556pub type FoldEdit = Edit<FoldOffset>;
1557
1558#[cfg(test)]
1559mod tests {
1560    use super::*;
1561    use crate::{MultiBuffer, ToPoint, display_map::inlay_map::InlayMap};
1562    use Bias::{Left, Right};
1563    use collections::HashSet;
1564    use rand::prelude::*;
1565    use settings::SettingsStore;
1566    use std::{env, mem};
1567    use text::Patch;
1568    use util::RandomCharIter;
1569    use util::test::sample_text;
1570
1571    #[gpui::test]
1572    fn test_basic_folds(cx: &mut gpui::App) {
1573        init_test(cx);
1574        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1575        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1576        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1577        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1578        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1579
1580        let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1581        let (snapshot2, edits) = writer.fold(vec![
1582            (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1583            (Point::new(2, 4)..Point::new(4, 1), FoldPlaceholder::test()),
1584        ]);
1585        assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1586        assert_eq!(
1587            edits,
1588            &[
1589                FoldEdit {
1590                    old: FoldOffset(2)..FoldOffset(16),
1591                    new: FoldOffset(2)..FoldOffset(5),
1592                },
1593                FoldEdit {
1594                    old: FoldOffset(18)..FoldOffset(29),
1595                    new: FoldOffset(7)..FoldOffset(10)
1596                },
1597            ]
1598        );
1599
1600        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1601            buffer.edit(
1602                vec![
1603                    (Point::new(0, 0)..Point::new(0, 1), "123"),
1604                    (Point::new(2, 3)..Point::new(2, 3), "123"),
1605                ],
1606                None,
1607                cx,
1608            );
1609            buffer.snapshot(cx)
1610        });
1611
1612        let (inlay_snapshot, inlay_edits) =
1613            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1614        let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1615        assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1616        assert_eq!(
1617            edits,
1618            &[
1619                FoldEdit {
1620                    old: FoldOffset(0)..FoldOffset(1),
1621                    new: FoldOffset(0)..FoldOffset(3),
1622                },
1623                FoldEdit {
1624                    old: FoldOffset(6)..FoldOffset(6),
1625                    new: FoldOffset(8)..FoldOffset(11),
1626                },
1627            ]
1628        );
1629
1630        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1631            buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1632            buffer.snapshot(cx)
1633        });
1634        let (inlay_snapshot, inlay_edits) =
1635            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1636        let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1637        assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1638
1639        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1640        writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1641        let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1642        assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1643
1644        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1645        writer.unfold_intersecting(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1646        let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1647        assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1648    }
1649
1650    #[gpui::test]
1651    fn test_adjacent_folds(cx: &mut gpui::App) {
1652        init_test(cx);
1653        let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1654        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1655        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1656        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1657
1658        {
1659            let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1660
1661            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1662            writer.fold(vec![(5..8, FoldPlaceholder::test())]);
1663            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1664            assert_eq!(snapshot.text(), "abcde⋯ijkl");
1665
1666            // Create an fold adjacent to the start of the first fold.
1667            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1668            writer.fold(vec![
1669                (0..1, FoldPlaceholder::test()),
1670                (2..5, FoldPlaceholder::test()),
1671            ]);
1672            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1673            assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1674
1675            // Create an fold adjacent to the end of the first fold.
1676            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1677            writer.fold(vec![
1678                (11..11, FoldPlaceholder::test()),
1679                (8..10, FoldPlaceholder::test()),
1680            ]);
1681            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1682            assert_eq!(snapshot.text(), "⋯b⋯kl");
1683        }
1684
1685        {
1686            let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1687
1688            // Create two adjacent folds.
1689            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1690            writer.fold(vec![
1691                (0..2, FoldPlaceholder::test()),
1692                (2..5, FoldPlaceholder::test()),
1693            ]);
1694            let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1695            assert_eq!(snapshot.text(), "⋯fghijkl");
1696
1697            // Edit within one of the folds.
1698            let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1699                buffer.edit([(0..1, "12345")], None, cx);
1700                buffer.snapshot(cx)
1701            });
1702            let (inlay_snapshot, inlay_edits) =
1703                inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1704            let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1705            assert_eq!(snapshot.text(), "12345⋯fghijkl");
1706        }
1707    }
1708
1709    #[gpui::test]
1710    fn test_overlapping_folds(cx: &mut gpui::App) {
1711        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1712        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1713        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1714        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1715        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1716        writer.fold(vec![
1717            (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1718            (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1719            (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1720            (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1721        ]);
1722        let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1723        assert_eq!(snapshot.text(), "aa⋯eeeee");
1724    }
1725
1726    #[gpui::test]
1727    fn test_merging_folds_via_edit(cx: &mut gpui::App) {
1728        init_test(cx);
1729        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1730        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1731        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1732        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1733        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1734
1735        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1736        writer.fold(vec![
1737            (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1738            (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1739        ]);
1740        let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1741        assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1742
1743        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1744            buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1745            buffer.snapshot(cx)
1746        });
1747        let (inlay_snapshot, inlay_edits) =
1748            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1749        let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1750        assert_eq!(snapshot.text(), "aa⋯eeeee");
1751    }
1752
1753    #[gpui::test]
1754    fn test_folds_in_range(cx: &mut gpui::App) {
1755        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1756        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1757        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1758        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1759
1760        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1761        writer.fold(vec![
1762            (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
1763            (Point::new(0, 4)..Point::new(1, 0), FoldPlaceholder::test()),
1764            (Point::new(1, 2)..Point::new(3, 2), FoldPlaceholder::test()),
1765            (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
1766        ]);
1767        let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1768        let fold_ranges = snapshot
1769            .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1770            .map(|fold| {
1771                fold.range.start.to_point(&buffer_snapshot)
1772                    ..fold.range.end.to_point(&buffer_snapshot)
1773            })
1774            .collect::<Vec<_>>();
1775        assert_eq!(
1776            fold_ranges,
1777            vec![
1778                Point::new(0, 2)..Point::new(2, 2),
1779                Point::new(1, 2)..Point::new(3, 2)
1780            ]
1781        );
1782    }
1783
1784    #[gpui::test(iterations = 100)]
1785    fn test_random_folds(cx: &mut gpui::App, mut rng: StdRng) {
1786        init_test(cx);
1787        let operations = env::var("OPERATIONS")
1788            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1789            .unwrap_or(10);
1790
1791        let len = rng.random_range(0..10);
1792        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1793        let buffer = if rng.random() {
1794            MultiBuffer::build_simple(&text, cx)
1795        } else {
1796            MultiBuffer::build_random(&mut rng, cx)
1797        };
1798        let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1799        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1800        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1801
1802        let (mut initial_snapshot, _) = map.read(inlay_snapshot, vec![]);
1803        let mut snapshot_edits = Vec::new();
1804
1805        let mut next_inlay_id = 0;
1806        for _ in 0..operations {
1807            log::info!("text: {:?}", buffer_snapshot.text());
1808            let mut buffer_edits = Vec::new();
1809            let mut inlay_edits = Vec::new();
1810            match rng.random_range(0..=100) {
1811                0..=39 => {
1812                    snapshot_edits.extend(map.randomly_mutate(&mut rng));
1813                }
1814                40..=59 => {
1815                    let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1816                    inlay_edits = edits;
1817                }
1818                _ => buffer.update(cx, |buffer, cx| {
1819                    let subscription = buffer.subscribe();
1820                    let edit_count = rng.random_range(1..=5);
1821                    buffer.randomly_mutate(&mut rng, edit_count, cx);
1822                    buffer_snapshot = buffer.snapshot(cx);
1823                    let edits = subscription.consume().into_inner();
1824                    log::info!("editing {:?}", edits);
1825                    buffer_edits.extend(edits);
1826                }),
1827            };
1828
1829            let (inlay_snapshot, new_inlay_edits) =
1830                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1831            log::info!("inlay text {:?}", inlay_snapshot.text());
1832
1833            let inlay_edits = Patch::new(inlay_edits)
1834                .compose(new_inlay_edits)
1835                .into_inner();
1836            let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
1837            snapshot_edits.push((snapshot.clone(), edits));
1838
1839            let mut expected_text: String = inlay_snapshot.text().to_string();
1840            for fold_range in map.merged_folds().into_iter().rev() {
1841                let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
1842                let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
1843                expected_text.replace_range(fold_inlay_start.0..fold_inlay_end.0, "⋯");
1844            }
1845
1846            assert_eq!(snapshot.text(), expected_text);
1847            log::info!(
1848                "fold text {:?} ({} lines)",
1849                expected_text,
1850                expected_text.matches('\n').count() + 1
1851            );
1852
1853            let mut prev_row = 0;
1854            let mut expected_buffer_rows = Vec::new();
1855            for fold_range in map.merged_folds() {
1856                let fold_start = inlay_snapshot
1857                    .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
1858                    .row();
1859                let fold_end = inlay_snapshot
1860                    .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
1861                    .row();
1862                expected_buffer_rows.extend(
1863                    inlay_snapshot
1864                        .row_infos(prev_row)
1865                        .take((1 + fold_start - prev_row) as usize),
1866                );
1867                prev_row = 1 + fold_end;
1868            }
1869            expected_buffer_rows.extend(inlay_snapshot.row_infos(prev_row));
1870
1871            assert_eq!(
1872                expected_buffer_rows.len(),
1873                expected_text.matches('\n').count() + 1,
1874                "wrong expected buffer rows {:?}. text: {:?}",
1875                expected_buffer_rows,
1876                expected_text
1877            );
1878
1879            for (output_row, line) in expected_text.lines().enumerate() {
1880                let line_len = snapshot.line_len(output_row as u32);
1881                assert_eq!(line_len, line.len() as u32);
1882            }
1883
1884            let longest_row = snapshot.longest_row();
1885            let longest_char_column = expected_text
1886                .split('\n')
1887                .nth(longest_row as usize)
1888                .unwrap()
1889                .chars()
1890                .count();
1891            let mut fold_point = FoldPoint::new(0, 0);
1892            let mut fold_offset = FoldOffset(0);
1893            let mut char_column = 0;
1894            for c in expected_text.chars() {
1895                let inlay_point = fold_point.to_inlay_point(&snapshot);
1896                let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
1897                assert_eq!(
1898                    snapshot.to_fold_point(inlay_point, Right),
1899                    fold_point,
1900                    "{:?} -> fold point",
1901                    inlay_point,
1902                );
1903                assert_eq!(
1904                    inlay_snapshot.to_offset(inlay_point),
1905                    inlay_offset,
1906                    "inlay_snapshot.to_offset({:?})",
1907                    inlay_point,
1908                );
1909                assert_eq!(
1910                    fold_point.to_offset(&snapshot),
1911                    fold_offset,
1912                    "fold_point.to_offset({:?})",
1913                    fold_point,
1914                );
1915
1916                if c == '\n' {
1917                    *fold_point.row_mut() += 1;
1918                    *fold_point.column_mut() = 0;
1919                    char_column = 0;
1920                } else {
1921                    *fold_point.column_mut() += c.len_utf8() as u32;
1922                    char_column += 1;
1923                }
1924                fold_offset.0 += c.len_utf8();
1925                if char_column > longest_char_column {
1926                    panic!(
1927                        "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
1928                        longest_row,
1929                        longest_char_column,
1930                        fold_point.row(),
1931                        char_column
1932                    );
1933                }
1934            }
1935
1936            for _ in 0..5 {
1937                let mut start = snapshot.clip_offset(
1938                    FoldOffset(rng.random_range(0..=snapshot.len().0)),
1939                    Bias::Left,
1940                );
1941                let mut end = snapshot.clip_offset(
1942                    FoldOffset(rng.random_range(0..=snapshot.len().0)),
1943                    Bias::Right,
1944                );
1945                if start > end {
1946                    mem::swap(&mut start, &mut end);
1947                }
1948
1949                let text = &expected_text[start.0..end.0];
1950                assert_eq!(
1951                    snapshot
1952                        .chunks(start..end, false, Highlights::default())
1953                        .map(|c| c.text)
1954                        .collect::<String>(),
1955                    text,
1956                );
1957            }
1958
1959            let mut fold_row = 0;
1960            while fold_row < expected_buffer_rows.len() as u32 {
1961                assert_eq!(
1962                    snapshot.row_infos(fold_row).collect::<Vec<_>>(),
1963                    expected_buffer_rows[(fold_row as usize)..],
1964                    "wrong buffer rows starting at fold row {}",
1965                    fold_row,
1966                );
1967                fold_row += 1;
1968            }
1969
1970            let folded_buffer_rows = map
1971                .merged_folds()
1972                .iter()
1973                .flat_map(|fold_range| {
1974                    let start_row = fold_range.start.to_point(&buffer_snapshot).row;
1975                    let end = fold_range.end.to_point(&buffer_snapshot);
1976                    if end.column == 0 {
1977                        start_row..end.row
1978                    } else {
1979                        start_row..end.row + 1
1980                    }
1981                })
1982                .collect::<HashSet<_>>();
1983            for row in 0..=buffer_snapshot.max_point().row {
1984                assert_eq!(
1985                    snapshot.is_line_folded(MultiBufferRow(row)),
1986                    folded_buffer_rows.contains(&row),
1987                    "expected buffer row {}{} to be folded",
1988                    row,
1989                    if folded_buffer_rows.contains(&row) {
1990                        ""
1991                    } else {
1992                        " not"
1993                    }
1994                );
1995            }
1996
1997            for _ in 0..5 {
1998                let end =
1999                    buffer_snapshot.clip_offset(rng.random_range(0..=buffer_snapshot.len()), Right);
2000                let start = buffer_snapshot.clip_offset(rng.random_range(0..=end), Left);
2001                let expected_folds = map
2002                    .snapshot
2003                    .folds
2004                    .items(&buffer_snapshot)
2005                    .into_iter()
2006                    .filter(|fold| {
2007                        let start = buffer_snapshot.anchor_before(start);
2008                        let end = buffer_snapshot.anchor_after(end);
2009                        start.cmp(&fold.range.end, &buffer_snapshot) == Ordering::Less
2010                            && end.cmp(&fold.range.start, &buffer_snapshot) == Ordering::Greater
2011                    })
2012                    .collect::<Vec<_>>();
2013
2014                assert_eq!(
2015                    snapshot
2016                        .folds_in_range(start..end)
2017                        .cloned()
2018                        .collect::<Vec<_>>(),
2019                    expected_folds
2020                );
2021            }
2022
2023            let text = snapshot.text();
2024            for _ in 0..5 {
2025                let start_row = rng.random_range(0..=snapshot.max_point().row());
2026                let start_column = rng.random_range(0..=snapshot.line_len(start_row));
2027                let end_row = rng.random_range(0..=snapshot.max_point().row());
2028                let end_column = rng.random_range(0..=snapshot.line_len(end_row));
2029                let mut start =
2030                    snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
2031                let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
2032                if start > end {
2033                    mem::swap(&mut start, &mut end);
2034                }
2035
2036                let lines = start..end;
2037                let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
2038                assert_eq!(
2039                    snapshot.text_summary_for_range(lines),
2040                    TextSummary::from(&text[bytes.start.0..bytes.end.0])
2041                )
2042            }
2043
2044            let mut text = initial_snapshot.text();
2045            for (snapshot, edits) in snapshot_edits.drain(..) {
2046                let new_text = snapshot.text();
2047                for edit in edits {
2048                    let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
2049                    let new_bytes = edit.new.start.0..edit.new.end.0;
2050                    text.replace_range(old_bytes, &new_text[new_bytes]);
2051                }
2052
2053                assert_eq!(text, new_text);
2054                initial_snapshot = snapshot;
2055            }
2056        }
2057    }
2058
2059    #[gpui::test]
2060    fn test_buffer_rows(cx: &mut gpui::App) {
2061        let text = sample_text(6, 6, 'a') + "\n";
2062        let buffer = MultiBuffer::build_simple(&text, cx);
2063
2064        let buffer_snapshot = buffer.read(cx).snapshot(cx);
2065        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
2066        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
2067
2068        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
2069        writer.fold(vec![
2070            (Point::new(0, 2)..Point::new(2, 2), FoldPlaceholder::test()),
2071            (Point::new(3, 1)..Point::new(4, 1), FoldPlaceholder::test()),
2072        ]);
2073
2074        let (snapshot, _) = map.read(inlay_snapshot, vec![]);
2075        assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
2076        assert_eq!(
2077            snapshot
2078                .row_infos(0)
2079                .map(|info| info.buffer_row)
2080                .collect::<Vec<_>>(),
2081            [Some(0), Some(3), Some(5), Some(6)]
2082        );
2083        assert_eq!(
2084            snapshot
2085                .row_infos(3)
2086                .map(|info| info.buffer_row)
2087                .collect::<Vec<_>>(),
2088            [Some(6)]
2089        );
2090    }
2091
2092    #[gpui::test(iterations = 100)]
2093    fn test_random_chunk_bitmaps(cx: &mut gpui::App, mut rng: StdRng) {
2094        init_test(cx);
2095
2096        // Generate random buffer using existing test infrastructure
2097        let text_len = rng.random_range(0..10000);
2098        let buffer = if rng.random() {
2099            let text = RandomCharIter::new(&mut rng)
2100                .take(text_len)
2101                .collect::<String>();
2102            MultiBuffer::build_simple(&text, cx)
2103        } else {
2104            MultiBuffer::build_random(&mut rng, cx)
2105        };
2106        let buffer_snapshot = buffer.read(cx).snapshot(cx);
2107        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
2108        let (mut fold_map, _) = FoldMap::new(inlay_snapshot.clone());
2109
2110        // Perform random mutations
2111        let mutation_count = rng.random_range(1..10);
2112        for _ in 0..mutation_count {
2113            fold_map.randomly_mutate(&mut rng);
2114        }
2115
2116        let (snapshot, _) = fold_map.read(inlay_snapshot, vec![]);
2117
2118        // Get all chunks and verify their bitmaps
2119        let chunks = snapshot.chunks(
2120            FoldOffset(0)..FoldOffset(snapshot.len().0),
2121            false,
2122            Highlights::default(),
2123        );
2124
2125        for chunk in chunks {
2126            let chunk_text = chunk.text;
2127            let chars_bitmap = chunk.chars;
2128            let tabs_bitmap = chunk.tabs;
2129
2130            // Check empty chunks have empty bitmaps
2131            if chunk_text.is_empty() {
2132                assert_eq!(
2133                    chars_bitmap, 0,
2134                    "Empty chunk should have empty chars bitmap"
2135                );
2136                assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
2137                continue;
2138            }
2139
2140            // Verify that chunk text doesn't exceed 128 bytes
2141            assert!(
2142                chunk_text.len() <= 128,
2143                "Chunk text length {} exceeds 128 bytes",
2144                chunk_text.len()
2145            );
2146
2147            // Verify chars bitmap
2148            let char_indices = chunk_text
2149                .char_indices()
2150                .map(|(i, _)| i)
2151                .collect::<Vec<_>>();
2152
2153            for byte_idx in 0..chunk_text.len() {
2154                let should_have_bit = char_indices.contains(&byte_idx);
2155                let has_bit = chars_bitmap & (1 << byte_idx) != 0;
2156
2157                if has_bit != should_have_bit {
2158                    eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
2159                    eprintln!("Char indices: {:?}", char_indices);
2160                    eprintln!("Chars bitmap: {:#b}", chars_bitmap);
2161                    assert_eq!(
2162                        has_bit, should_have_bit,
2163                        "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
2164                        byte_idx, chunk_text, should_have_bit, has_bit
2165                    );
2166                }
2167            }
2168
2169            // Verify tabs bitmap
2170            for (byte_idx, byte) in chunk_text.bytes().enumerate() {
2171                let is_tab = byte == b'\t';
2172                let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
2173
2174                assert_eq!(
2175                    has_bit, is_tab,
2176                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
2177                    byte_idx, chunk_text, byte as char, is_tab, has_bit
2178                );
2179            }
2180        }
2181    }
2182
2183    fn init_test(cx: &mut gpui::App) {
2184        let store = SettingsStore::test(cx);
2185        cx.set_global(store);
2186    }
2187
2188    impl FoldMap {
2189        fn merged_folds(&self) -> Vec<Range<usize>> {
2190            let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2191            let buffer = &inlay_snapshot.buffer;
2192            let mut folds = self.snapshot.folds.items(buffer);
2193            // Ensure sorting doesn't change how folds get merged and displayed.
2194            folds.sort_by(|a, b| a.range.cmp(&b.range, buffer));
2195            let mut folds = folds
2196                .iter()
2197                .map(|fold| fold.range.start.to_offset(buffer)..fold.range.end.to_offset(buffer))
2198                .peekable();
2199
2200            let mut merged_folds = Vec::new();
2201            while let Some(mut fold_range) = folds.next() {
2202                while let Some(next_range) = folds.peek() {
2203                    if fold_range.end >= next_range.start {
2204                        if next_range.end > fold_range.end {
2205                            fold_range.end = next_range.end;
2206                        }
2207                        folds.next();
2208                    } else {
2209                        break;
2210                    }
2211                }
2212                if fold_range.end > fold_range.start {
2213                    merged_folds.push(fold_range);
2214                }
2215            }
2216            merged_folds
2217        }
2218
2219        pub fn randomly_mutate(
2220            &mut self,
2221            rng: &mut impl Rng,
2222        ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
2223            let mut snapshot_edits = Vec::new();
2224            match rng.random_range(0..=100) {
2225                0..=39 if !self.snapshot.folds.is_empty() => {
2226                    let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2227                    let buffer = &inlay_snapshot.buffer;
2228                    let mut to_unfold = Vec::new();
2229                    for _ in 0..rng.random_range(1..=3) {
2230                        let end = buffer.clip_offset(rng.random_range(0..=buffer.len()), Right);
2231                        let start = buffer.clip_offset(rng.random_range(0..=end), Left);
2232                        to_unfold.push(start..end);
2233                    }
2234                    let inclusive = rng.random();
2235                    log::info!("unfolding {:?} (inclusive: {})", to_unfold, inclusive);
2236                    let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2237                    snapshot_edits.push((snapshot, edits));
2238                    let (snapshot, edits) = writer.unfold_intersecting(to_unfold, inclusive);
2239                    snapshot_edits.push((snapshot, edits));
2240                }
2241                _ => {
2242                    let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
2243                    let buffer = &inlay_snapshot.buffer;
2244                    let mut to_fold = Vec::new();
2245                    for _ in 0..rng.random_range(1..=2) {
2246                        let end = buffer.clip_offset(rng.random_range(0..=buffer.len()), Right);
2247                        let start = buffer.clip_offset(rng.random_range(0..=end), Left);
2248                        to_fold.push((start..end, FoldPlaceholder::test()));
2249                    }
2250                    log::info!("folding {:?}", to_fold);
2251                    let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
2252                    snapshot_edits.push((snapshot, edits));
2253                    let (snapshot, edits) = writer.fold(to_fold);
2254                    snapshot_edits.push((snapshot, edits));
2255                }
2256            }
2257            snapshot_edits
2258        }
2259    }
2260}