fold_map.rs

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