fold_map.rs

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