fold_map.rs

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