fold_map.rs

   1use super::{
   2    inlay_map::{InlayBufferRows, InlayChunks, InlayEdit, InlayOffset, InlayPoint, InlaySnapshot},
   3    InlayHighlights, TextHighlights,
   4};
   5use crate::{Anchor, AnchorRangeExt, MultiBufferSnapshot, ToOffset};
   6use gpui::{color::Color, fonts::HighlightStyle};
   7use language::{Chunk, Edit, Point, TextSummary};
   8use std::{
   9    any::TypeId,
  10    cmp::{self, Ordering},
  11    iter,
  12    ops::{Add, AddAssign, Range, Sub},
  13};
  14use sum_tree::{Bias, Cursor, FilterCursor, SumTree};
  15
  16#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
  17pub struct FoldPoint(pub Point);
  18
  19impl FoldPoint {
  20    pub fn new(row: u32, column: u32) -> Self {
  21        Self(Point::new(row, column))
  22    }
  23
  24    pub fn row(self) -> u32 {
  25        self.0.row
  26    }
  27
  28    pub fn column(self) -> u32 {
  29        self.0.column
  30    }
  31
  32    pub fn row_mut(&mut self) -> &mut u32 {
  33        &mut self.0.row
  34    }
  35
  36    #[cfg(test)]
  37    pub fn column_mut(&mut self) -> &mut u32 {
  38        &mut self.0.column
  39    }
  40
  41    pub fn to_inlay_point(self, snapshot: &FoldSnapshot) -> InlayPoint {
  42        let mut cursor = snapshot.transforms.cursor::<(FoldPoint, InlayPoint)>();
  43        cursor.seek(&self, Bias::Right, &());
  44        let overshoot = self.0 - cursor.start().0 .0;
  45        InlayPoint(cursor.start().1 .0 + overshoot)
  46    }
  47
  48    pub fn to_offset(self, snapshot: &FoldSnapshot) -> FoldOffset {
  49        let mut cursor = snapshot
  50            .transforms
  51            .cursor::<(FoldPoint, TransformSummary)>();
  52        cursor.seek(&self, Bias::Right, &());
  53        let overshoot = self.0 - cursor.start().1.output.lines;
  54        let mut offset = cursor.start().1.output.len;
  55        if !overshoot.is_zero() {
  56            let transform = cursor.item().expect("display point out of range");
  57            assert!(transform.output_text.is_none());
  58            let end_inlay_offset = snapshot
  59                .inlay_snapshot
  60                .to_offset(InlayPoint(cursor.start().1.input.lines + overshoot));
  61            offset += end_inlay_offset.0 - cursor.start().1.input.len;
  62        }
  63        FoldOffset(offset)
  64    }
  65}
  66
  67impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldPoint {
  68    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
  69        self.0 += &summary.output.lines;
  70    }
  71}
  72
  73pub struct FoldMapWriter<'a>(&'a mut FoldMap);
  74
  75impl<'a> FoldMapWriter<'a> {
  76    pub fn fold<T: ToOffset>(
  77        &mut self,
  78        ranges: impl IntoIterator<Item = Range<T>>,
  79    ) -> (FoldSnapshot, Vec<FoldEdit>) {
  80        let mut edits = Vec::new();
  81        let mut folds = Vec::new();
  82        let snapshot = self.0.snapshot.inlay_snapshot.clone();
  83        for range in ranges.into_iter() {
  84            let buffer = &snapshot.buffer;
  85            let range = range.start.to_offset(&buffer)..range.end.to_offset(&buffer);
  86
  87            // Ignore any empty ranges.
  88            if range.start == range.end {
  89                continue;
  90            }
  91
  92            // For now, ignore any ranges that span an excerpt boundary.
  93            let fold = Fold(buffer.anchor_after(range.start)..buffer.anchor_before(range.end));
  94            if fold.0.start.excerpt_id() != fold.0.end.excerpt_id() {
  95                continue;
  96            }
  97
  98            folds.push(fold);
  99
 100            let inlay_range =
 101                snapshot.to_inlay_offset(range.start)..snapshot.to_inlay_offset(range.end);
 102            edits.push(InlayEdit {
 103                old: inlay_range.clone(),
 104                new: inlay_range,
 105            });
 106        }
 107
 108        let buffer = &snapshot.buffer;
 109        folds.sort_unstable_by(|a, b| sum_tree::SeekTarget::cmp(a, b, buffer));
 110
 111        self.0.snapshot.folds = {
 112            let mut new_tree = SumTree::new();
 113            let mut cursor = self.0.snapshot.folds.cursor::<Fold>();
 114            for fold in folds {
 115                new_tree.append(cursor.slice(&fold, Bias::Right, buffer), buffer);
 116                new_tree.push(fold, buffer);
 117            }
 118            new_tree.append(cursor.suffix(buffer), buffer);
 119            new_tree
 120        };
 121
 122        consolidate_inlay_edits(&mut edits);
 123        let edits = self.0.sync(snapshot.clone(), edits);
 124        (self.0.snapshot.clone(), edits)
 125    }
 126
 127    pub fn unfold<T: ToOffset>(
 128        &mut self,
 129        ranges: impl IntoIterator<Item = Range<T>>,
 130        inclusive: bool,
 131    ) -> (FoldSnapshot, Vec<FoldEdit>) {
 132        let mut edits = Vec::new();
 133        let mut fold_ixs_to_delete = Vec::new();
 134        let snapshot = self.0.snapshot.inlay_snapshot.clone();
 135        let buffer = &snapshot.buffer;
 136        for range in ranges.into_iter() {
 137            // Remove intersecting folds and add their ranges to edits that are passed to sync.
 138            let mut folds_cursor =
 139                intersecting_folds(&snapshot, &self.0.snapshot.folds, range, inclusive);
 140            while let Some(fold) = folds_cursor.item() {
 141                let offset_range = fold.0.start.to_offset(buffer)..fold.0.end.to_offset(buffer);
 142                if offset_range.end > offset_range.start {
 143                    let inlay_range = snapshot.to_inlay_offset(offset_range.start)
 144                        ..snapshot.to_inlay_offset(offset_range.end);
 145                    edits.push(InlayEdit {
 146                        old: inlay_range.clone(),
 147                        new: inlay_range,
 148                    });
 149                }
 150                fold_ixs_to_delete.push(*folds_cursor.start());
 151                folds_cursor.next(buffer);
 152            }
 153        }
 154
 155        fold_ixs_to_delete.sort_unstable();
 156        fold_ixs_to_delete.dedup();
 157
 158        self.0.snapshot.folds = {
 159            let mut cursor = self.0.snapshot.folds.cursor::<usize>();
 160            let mut folds = SumTree::new();
 161            for fold_ix in fold_ixs_to_delete {
 162                folds.append(cursor.slice(&fold_ix, Bias::Right, buffer), buffer);
 163                cursor.next(buffer);
 164            }
 165            folds.append(cursor.suffix(buffer), buffer);
 166            folds
 167        };
 168
 169        consolidate_inlay_edits(&mut edits);
 170        let edits = self.0.sync(snapshot.clone(), edits);
 171        (self.0.snapshot.clone(), edits)
 172    }
 173}
 174
 175pub struct FoldMap {
 176    snapshot: FoldSnapshot,
 177    ellipses_color: Option<Color>,
 178}
 179
 180impl FoldMap {
 181    pub fn new(inlay_snapshot: InlaySnapshot) -> (Self, FoldSnapshot) {
 182        let this = Self {
 183            snapshot: FoldSnapshot {
 184                folds: Default::default(),
 185                transforms: SumTree::from_item(
 186                    Transform {
 187                        summary: TransformSummary {
 188                            input: inlay_snapshot.text_summary(),
 189                            output: inlay_snapshot.text_summary(),
 190                        },
 191                        output_text: None,
 192                    },
 193                    &(),
 194                ),
 195                inlay_snapshot: inlay_snapshot.clone(),
 196                version: 0,
 197                ellipses_color: None,
 198            },
 199            ellipses_color: None,
 200        };
 201        let snapshot = this.snapshot.clone();
 202        (this, snapshot)
 203    }
 204
 205    pub fn read(
 206        &mut self,
 207        inlay_snapshot: InlaySnapshot,
 208        edits: Vec<InlayEdit>,
 209    ) -> (FoldSnapshot, Vec<FoldEdit>) {
 210        let edits = self.sync(inlay_snapshot, edits);
 211        self.check_invariants();
 212        (self.snapshot.clone(), edits)
 213    }
 214
 215    pub fn write(
 216        &mut self,
 217        inlay_snapshot: InlaySnapshot,
 218        edits: Vec<InlayEdit>,
 219    ) -> (FoldMapWriter, FoldSnapshot, Vec<FoldEdit>) {
 220        let (snapshot, edits) = self.read(inlay_snapshot, edits);
 221        (FoldMapWriter(self), snapshot, edits)
 222    }
 223
 224    pub fn set_ellipses_color(&mut self, color: Color) -> bool {
 225        if self.ellipses_color != Some(color) {
 226            self.ellipses_color = Some(color);
 227            true
 228        } else {
 229            false
 230        }
 231    }
 232
 233    fn check_invariants(&self) {
 234        if cfg!(test) {
 235            assert_eq!(
 236                self.snapshot.transforms.summary().input.len,
 237                self.snapshot.inlay_snapshot.len().0,
 238                "transform tree does not match inlay snapshot's length"
 239            );
 240
 241            let mut folds = self.snapshot.folds.iter().peekable();
 242            while let Some(fold) = folds.next() {
 243                if let Some(next_fold) = folds.peek() {
 244                    let comparison = fold
 245                        .0
 246                        .cmp(&next_fold.0, &self.snapshot.inlay_snapshot.buffer);
 247                    assert!(comparison.is_le());
 248                }
 249            }
 250        }
 251    }
 252
 253    fn sync(
 254        &mut self,
 255        inlay_snapshot: InlaySnapshot,
 256        inlay_edits: Vec<InlayEdit>,
 257    ) -> Vec<FoldEdit> {
 258        if inlay_edits.is_empty() {
 259            if self.snapshot.inlay_snapshot.version != inlay_snapshot.version {
 260                self.snapshot.version += 1;
 261            }
 262            self.snapshot.inlay_snapshot = inlay_snapshot;
 263            Vec::new()
 264        } else {
 265            let mut inlay_edits_iter = inlay_edits.iter().cloned().peekable();
 266
 267            let mut new_transforms = SumTree::new();
 268            let mut cursor = self.snapshot.transforms.cursor::<InlayOffset>();
 269            cursor.seek(&InlayOffset(0), Bias::Right, &());
 270
 271            while let Some(mut edit) = inlay_edits_iter.next() {
 272                new_transforms.append(cursor.slice(&edit.old.start, Bias::Left, &()), &());
 273                edit.new.start -= edit.old.start - *cursor.start();
 274                edit.old.start = *cursor.start();
 275
 276                cursor.seek(&edit.old.end, Bias::Right, &());
 277                cursor.next(&());
 278
 279                let mut delta = edit.new_len().0 as isize - edit.old_len().0 as isize;
 280                loop {
 281                    edit.old.end = *cursor.start();
 282
 283                    if let Some(next_edit) = inlay_edits_iter.peek() {
 284                        if next_edit.old.start > edit.old.end {
 285                            break;
 286                        }
 287
 288                        let next_edit = inlay_edits_iter.next().unwrap();
 289                        delta += next_edit.new_len().0 as isize - next_edit.old_len().0 as isize;
 290
 291                        if next_edit.old.end >= edit.old.end {
 292                            edit.old.end = next_edit.old.end;
 293                            cursor.seek(&edit.old.end, Bias::Right, &());
 294                            cursor.next(&());
 295                        }
 296                    } else {
 297                        break;
 298                    }
 299                }
 300
 301                edit.new.end =
 302                    InlayOffset(((edit.new.start + edit.old_len()).0 as isize + delta) as usize);
 303
 304                let anchor = inlay_snapshot
 305                    .buffer
 306                    .anchor_before(inlay_snapshot.to_buffer_offset(edit.new.start));
 307                let mut folds_cursor = self.snapshot.folds.cursor::<Fold>();
 308                folds_cursor.seek(
 309                    &Fold(anchor..Anchor::max()),
 310                    Bias::Left,
 311                    &inlay_snapshot.buffer,
 312                );
 313
 314                let mut folds = iter::from_fn({
 315                    let inlay_snapshot = &inlay_snapshot;
 316                    move || {
 317                        let item = folds_cursor.item().map(|f| {
 318                            let buffer_start = f.0.start.to_offset(&inlay_snapshot.buffer);
 319                            let buffer_end = f.0.end.to_offset(&inlay_snapshot.buffer);
 320                            inlay_snapshot.to_inlay_offset(buffer_start)
 321                                ..inlay_snapshot.to_inlay_offset(buffer_end)
 322                        });
 323                        folds_cursor.next(&inlay_snapshot.buffer);
 324                        item
 325                    }
 326                })
 327                .peekable();
 328
 329                while folds.peek().map_or(false, |fold| fold.start < edit.new.end) {
 330                    let mut fold = folds.next().unwrap();
 331                    let sum = new_transforms.summary();
 332
 333                    assert!(fold.start.0 >= sum.input.len);
 334
 335                    while folds
 336                        .peek()
 337                        .map_or(false, |next_fold| next_fold.start <= fold.end)
 338                    {
 339                        let next_fold = folds.next().unwrap();
 340                        if next_fold.end > fold.end {
 341                            fold.end = next_fold.end;
 342                        }
 343                    }
 344
 345                    if fold.start.0 > sum.input.len {
 346                        let text_summary = inlay_snapshot
 347                            .text_summary_for_range(InlayOffset(sum.input.len)..fold.start);
 348                        new_transforms.push(
 349                            Transform {
 350                                summary: TransformSummary {
 351                                    output: text_summary.clone(),
 352                                    input: text_summary,
 353                                },
 354                                output_text: None,
 355                            },
 356                            &(),
 357                        );
 358                    }
 359
 360                    if fold.end > fold.start {
 361                        let output_text = "";
 362                        new_transforms.push(
 363                            Transform {
 364                                summary: TransformSummary {
 365                                    output: TextSummary::from(output_text),
 366                                    input: inlay_snapshot
 367                                        .text_summary_for_range(fold.start..fold.end),
 368                                },
 369                                output_text: Some(output_text),
 370                            },
 371                            &(),
 372                        );
 373                    }
 374                }
 375
 376                let sum = new_transforms.summary();
 377                if sum.input.len < edit.new.end.0 {
 378                    let text_summary = inlay_snapshot
 379                        .text_summary_for_range(InlayOffset(sum.input.len)..edit.new.end);
 380                    new_transforms.push(
 381                        Transform {
 382                            summary: TransformSummary {
 383                                output: text_summary.clone(),
 384                                input: text_summary,
 385                            },
 386                            output_text: None,
 387                        },
 388                        &(),
 389                    );
 390                }
 391            }
 392
 393            new_transforms.append(cursor.suffix(&()), &());
 394            if new_transforms.is_empty() {
 395                let text_summary = inlay_snapshot.text_summary();
 396                new_transforms.push(
 397                    Transform {
 398                        summary: TransformSummary {
 399                            output: text_summary.clone(),
 400                            input: text_summary,
 401                        },
 402                        output_text: None,
 403                    },
 404                    &(),
 405                );
 406            }
 407
 408            drop(cursor);
 409
 410            let mut fold_edits = Vec::with_capacity(inlay_edits.len());
 411            {
 412                let mut old_transforms = self
 413                    .snapshot
 414                    .transforms
 415                    .cursor::<(InlayOffset, FoldOffset)>();
 416                let mut new_transforms = new_transforms.cursor::<(InlayOffset, FoldOffset)>();
 417
 418                for mut edit in inlay_edits {
 419                    old_transforms.seek(&edit.old.start, Bias::Left, &());
 420                    if old_transforms.item().map_or(false, |t| t.is_fold()) {
 421                        edit.old.start = old_transforms.start().0;
 422                    }
 423                    let old_start =
 424                        old_transforms.start().1 .0 + (edit.old.start - old_transforms.start().0).0;
 425
 426                    old_transforms.seek_forward(&edit.old.end, Bias::Right, &());
 427                    if old_transforms.item().map_or(false, |t| t.is_fold()) {
 428                        old_transforms.next(&());
 429                        edit.old.end = old_transforms.start().0;
 430                    }
 431                    let old_end =
 432                        old_transforms.start().1 .0 + (edit.old.end - old_transforms.start().0).0;
 433
 434                    new_transforms.seek(&edit.new.start, Bias::Left, &());
 435                    if new_transforms.item().map_or(false, |t| t.is_fold()) {
 436                        edit.new.start = new_transforms.start().0;
 437                    }
 438                    let new_start =
 439                        new_transforms.start().1 .0 + (edit.new.start - new_transforms.start().0).0;
 440
 441                    new_transforms.seek_forward(&edit.new.end, Bias::Right, &());
 442                    if new_transforms.item().map_or(false, |t| t.is_fold()) {
 443                        new_transforms.next(&());
 444                        edit.new.end = new_transforms.start().0;
 445                    }
 446                    let new_end =
 447                        new_transforms.start().1 .0 + (edit.new.end - new_transforms.start().0).0;
 448
 449                    fold_edits.push(FoldEdit {
 450                        old: FoldOffset(old_start)..FoldOffset(old_end),
 451                        new: FoldOffset(new_start)..FoldOffset(new_end),
 452                    });
 453                }
 454
 455                consolidate_fold_edits(&mut fold_edits);
 456            }
 457
 458            self.snapshot.transforms = new_transforms;
 459            self.snapshot.inlay_snapshot = inlay_snapshot;
 460            self.snapshot.version += 1;
 461            fold_edits
 462        }
 463    }
 464}
 465
 466#[derive(Clone)]
 467pub struct FoldSnapshot {
 468    transforms: SumTree<Transform>,
 469    folds: SumTree<Fold>,
 470    pub inlay_snapshot: InlaySnapshot,
 471    pub version: usize,
 472    pub ellipses_color: Option<Color>,
 473}
 474
 475impl FoldSnapshot {
 476    #[cfg(test)]
 477    pub fn text(&self) -> String {
 478        self.chunks(FoldOffset(0)..self.len(), false, None, None, None, None)
 479            .map(|c| c.text)
 480            .collect()
 481    }
 482
 483    #[cfg(test)]
 484    pub fn fold_count(&self) -> usize {
 485        self.folds.items(&self.inlay_snapshot.buffer).len()
 486    }
 487
 488    pub fn text_summary_for_range(&self, range: Range<FoldPoint>) -> TextSummary {
 489        let mut summary = TextSummary::default();
 490
 491        let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
 492        cursor.seek(&range.start, Bias::Right, &());
 493        if let Some(transform) = cursor.item() {
 494            let start_in_transform = range.start.0 - cursor.start().0 .0;
 495            let end_in_transform = cmp::min(range.end, cursor.end(&()).0).0 - cursor.start().0 .0;
 496            if let Some(output_text) = transform.output_text {
 497                summary = TextSummary::from(
 498                    &output_text
 499                        [start_in_transform.column as usize..end_in_transform.column as usize],
 500                );
 501            } else {
 502                let inlay_start = self
 503                    .inlay_snapshot
 504                    .to_offset(InlayPoint(cursor.start().1 .0 + start_in_transform));
 505                let inlay_end = self
 506                    .inlay_snapshot
 507                    .to_offset(InlayPoint(cursor.start().1 .0 + end_in_transform));
 508                summary = self
 509                    .inlay_snapshot
 510                    .text_summary_for_range(inlay_start..inlay_end);
 511            }
 512        }
 513
 514        if range.end > cursor.end(&()).0 {
 515            cursor.next(&());
 516            summary += &cursor
 517                .summary::<_, TransformSummary>(&range.end, Bias::Right, &())
 518                .output;
 519            if let Some(transform) = cursor.item() {
 520                let end_in_transform = range.end.0 - cursor.start().0 .0;
 521                if let Some(output_text) = transform.output_text {
 522                    summary += TextSummary::from(&output_text[..end_in_transform.column as usize]);
 523                } else {
 524                    let inlay_start = self.inlay_snapshot.to_offset(cursor.start().1);
 525                    let inlay_end = self
 526                        .inlay_snapshot
 527                        .to_offset(InlayPoint(cursor.start().1 .0 + end_in_transform));
 528                    summary += self
 529                        .inlay_snapshot
 530                        .text_summary_for_range(inlay_start..inlay_end);
 531                }
 532            }
 533        }
 534
 535        summary
 536    }
 537
 538    pub fn to_fold_point(&self, point: InlayPoint, bias: Bias) -> FoldPoint {
 539        let mut cursor = self.transforms.cursor::<(InlayPoint, FoldPoint)>();
 540        cursor.seek(&point, Bias::Right, &());
 541        if cursor.item().map_or(false, |t| t.is_fold()) {
 542            if bias == Bias::Left || point == cursor.start().0 {
 543                cursor.start().1
 544            } else {
 545                cursor.end(&()).1
 546            }
 547        } else {
 548            let overshoot = point.0 - cursor.start().0 .0;
 549            FoldPoint(cmp::min(
 550                cursor.start().1 .0 + overshoot,
 551                cursor.end(&()).1 .0,
 552            ))
 553        }
 554    }
 555
 556    pub fn len(&self) -> FoldOffset {
 557        FoldOffset(self.transforms.summary().output.len)
 558    }
 559
 560    pub fn line_len(&self, row: u32) -> u32 {
 561        let line_start = FoldPoint::new(row, 0).to_offset(self).0;
 562        let line_end = if row >= self.max_point().row() {
 563            self.len().0
 564        } else {
 565            FoldPoint::new(row + 1, 0).to_offset(self).0 - 1
 566        };
 567        (line_end - line_start) as u32
 568    }
 569
 570    pub fn buffer_rows(&self, start_row: u32) -> FoldBufferRows {
 571        if start_row > self.transforms.summary().output.lines.row {
 572            panic!("invalid display row {}", start_row);
 573        }
 574
 575        let fold_point = FoldPoint::new(start_row, 0);
 576        let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
 577        cursor.seek(&fold_point, Bias::Left, &());
 578
 579        let overshoot = fold_point.0 - cursor.start().0 .0;
 580        let inlay_point = InlayPoint(cursor.start().1 .0 + overshoot);
 581        let input_buffer_rows = self.inlay_snapshot.buffer_rows(inlay_point.row());
 582
 583        FoldBufferRows {
 584            fold_point,
 585            input_buffer_rows,
 586            cursor,
 587        }
 588    }
 589
 590    pub fn max_point(&self) -> FoldPoint {
 591        FoldPoint(self.transforms.summary().output.lines)
 592    }
 593
 594    #[cfg(test)]
 595    pub fn longest_row(&self) -> u32 {
 596        self.transforms.summary().output.longest_row
 597    }
 598
 599    pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Range<Anchor>>
 600    where
 601        T: ToOffset,
 602    {
 603        let mut folds = intersecting_folds(&self.inlay_snapshot, &self.folds, range, false);
 604        iter::from_fn(move || {
 605            let item = folds.item().map(|f| &f.0);
 606            folds.next(&self.inlay_snapshot.buffer);
 607            item
 608        })
 609    }
 610
 611    pub fn intersects_fold<T>(&self, offset: T) -> bool
 612    where
 613        T: ToOffset,
 614    {
 615        let buffer_offset = offset.to_offset(&self.inlay_snapshot.buffer);
 616        let inlay_offset = self.inlay_snapshot.to_inlay_offset(buffer_offset);
 617        let mut cursor = self.transforms.cursor::<InlayOffset>();
 618        cursor.seek(&inlay_offset, Bias::Right, &());
 619        cursor.item().map_or(false, |t| t.output_text.is_some())
 620    }
 621
 622    pub fn is_line_folded(&self, buffer_row: u32) -> bool {
 623        let mut inlay_point = self
 624            .inlay_snapshot
 625            .to_inlay_point(Point::new(buffer_row, 0));
 626        let mut cursor = self.transforms.cursor::<InlayPoint>();
 627        cursor.seek(&inlay_point, Bias::Right, &());
 628        loop {
 629            match cursor.item() {
 630                Some(transform) => {
 631                    let buffer_point = self.inlay_snapshot.to_buffer_point(inlay_point);
 632                    if buffer_point.row != buffer_row {
 633                        return false;
 634                    } else if transform.output_text.is_some() {
 635                        return true;
 636                    }
 637                }
 638                None => return false,
 639            }
 640
 641            if cursor.end(&()).row() == inlay_point.row() {
 642                cursor.next(&());
 643            } else {
 644                inlay_point.0 += Point::new(1, 0);
 645                cursor.seek(&inlay_point, Bias::Right, &());
 646            }
 647        }
 648    }
 649
 650    pub fn chunks<'a>(
 651        &'a self,
 652        range: Range<FoldOffset>,
 653        language_aware: bool,
 654        text_highlights: Option<&'a TextHighlights>,
 655        inlay_highlights: Option<&'a InlayHighlights>,
 656        inlay_highlight_style: Option<HighlightStyle>,
 657        suggestion_highlight_style: Option<HighlightStyle>,
 658    ) -> FoldChunks<'a> {
 659        let mut transform_cursor = self.transforms.cursor::<(FoldOffset, InlayOffset)>();
 660
 661        let inlay_end = {
 662            transform_cursor.seek(&range.end, Bias::Right, &());
 663            let overshoot = range.end.0 - transform_cursor.start().0 .0;
 664            transform_cursor.start().1 + InlayOffset(overshoot)
 665        };
 666
 667        let inlay_start = {
 668            transform_cursor.seek(&range.start, Bias::Right, &());
 669            let overshoot = range.start.0 - transform_cursor.start().0 .0;
 670            transform_cursor.start().1 + InlayOffset(overshoot)
 671        };
 672
 673        FoldChunks {
 674            transform_cursor,
 675            inlay_chunks: self.inlay_snapshot.chunks(
 676                inlay_start..inlay_end,
 677                language_aware,
 678                text_highlights,
 679                inlay_highlights,
 680                inlay_highlight_style,
 681                suggestion_highlight_style,
 682            ),
 683            inlay_chunk: None,
 684            inlay_offset: inlay_start,
 685            output_offset: range.start.0,
 686            max_output_offset: range.end.0,
 687            ellipses_color: self.ellipses_color,
 688        }
 689    }
 690
 691    pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
 692        self.chunks(
 693            start.to_offset(self)..self.len(),
 694            false,
 695            None,
 696            None,
 697            None,
 698            None,
 699        )
 700        .flat_map(|chunk| chunk.text.chars())
 701    }
 702
 703    #[cfg(test)]
 704    pub fn clip_offset(&self, offset: FoldOffset, bias: Bias) -> FoldOffset {
 705        if offset > self.len() {
 706            self.len()
 707        } else {
 708            self.clip_point(offset.to_point(self), bias).to_offset(self)
 709        }
 710    }
 711
 712    pub fn clip_point(&self, point: FoldPoint, bias: Bias) -> FoldPoint {
 713        let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
 714        cursor.seek(&point, Bias::Right, &());
 715        if let Some(transform) = cursor.item() {
 716            let transform_start = cursor.start().0 .0;
 717            if transform.output_text.is_some() {
 718                if point.0 == transform_start || matches!(bias, Bias::Left) {
 719                    FoldPoint(transform_start)
 720                } else {
 721                    FoldPoint(cursor.end(&()).0 .0)
 722                }
 723            } else {
 724                let overshoot = InlayPoint(point.0 - transform_start);
 725                let inlay_point = cursor.start().1 + overshoot;
 726                let clipped_inlay_point = self.inlay_snapshot.clip_point(inlay_point, bias);
 727                FoldPoint(cursor.start().0 .0 + (clipped_inlay_point - cursor.start().1).0)
 728            }
 729        } else {
 730            FoldPoint(self.transforms.summary().output.lines)
 731        }
 732    }
 733}
 734
 735fn intersecting_folds<'a, T>(
 736    inlay_snapshot: &'a InlaySnapshot,
 737    folds: &'a SumTree<Fold>,
 738    range: Range<T>,
 739    inclusive: bool,
 740) -> FilterCursor<'a, impl 'a + FnMut(&FoldSummary) -> bool, Fold, usize>
 741where
 742    T: ToOffset,
 743{
 744    let buffer = &inlay_snapshot.buffer;
 745    let start = buffer.anchor_before(range.start.to_offset(buffer));
 746    let end = buffer.anchor_after(range.end.to_offset(buffer));
 747    let mut cursor = folds.filter::<_, usize>(move |summary| {
 748        let start_cmp = start.cmp(&summary.max_end, buffer);
 749        let end_cmp = end.cmp(&summary.min_start, buffer);
 750
 751        if inclusive {
 752            start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
 753        } else {
 754            start_cmp == Ordering::Less && end_cmp == Ordering::Greater
 755        }
 756    });
 757    cursor.next(buffer);
 758    cursor
 759}
 760
 761fn consolidate_inlay_edits(edits: &mut Vec<InlayEdit>) {
 762    edits.sort_unstable_by(|a, b| {
 763        a.old
 764            .start
 765            .cmp(&b.old.start)
 766            .then_with(|| b.old.end.cmp(&a.old.end))
 767    });
 768
 769    let mut i = 1;
 770    while i < edits.len() {
 771        let edit = edits[i].clone();
 772        let prev_edit = &mut edits[i - 1];
 773        if prev_edit.old.end >= edit.old.start {
 774            prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
 775            prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
 776            prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
 777            edits.remove(i);
 778            continue;
 779        }
 780        i += 1;
 781    }
 782}
 783
 784fn consolidate_fold_edits(edits: &mut Vec<FoldEdit>) {
 785    edits.sort_unstable_by(|a, b| {
 786        a.old
 787            .start
 788            .cmp(&b.old.start)
 789            .then_with(|| b.old.end.cmp(&a.old.end))
 790    });
 791
 792    let mut i = 1;
 793    while i < edits.len() {
 794        let edit = edits[i].clone();
 795        let prev_edit = &mut edits[i - 1];
 796        if prev_edit.old.end >= edit.old.start {
 797            prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
 798            prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
 799            prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
 800            edits.remove(i);
 801            continue;
 802        }
 803        i += 1;
 804    }
 805}
 806
 807#[derive(Clone, Debug, Default, Eq, PartialEq)]
 808struct Transform {
 809    summary: TransformSummary,
 810    output_text: Option<&'static str>,
 811}
 812
 813impl Transform {
 814    fn is_fold(&self) -> bool {
 815        self.output_text.is_some()
 816    }
 817}
 818
 819#[derive(Clone, Debug, Default, Eq, PartialEq)]
 820struct TransformSummary {
 821    output: TextSummary,
 822    input: TextSummary,
 823}
 824
 825impl sum_tree::Item for Transform {
 826    type Summary = TransformSummary;
 827
 828    fn summary(&self) -> Self::Summary {
 829        self.summary.clone()
 830    }
 831}
 832
 833impl sum_tree::Summary for TransformSummary {
 834    type Context = ();
 835
 836    fn add_summary(&mut self, other: &Self, _: &()) {
 837        self.input += &other.input;
 838        self.output += &other.output;
 839    }
 840}
 841
 842#[derive(Clone, Debug)]
 843struct Fold(Range<Anchor>);
 844
 845impl Default for Fold {
 846    fn default() -> Self {
 847        Self(Anchor::min()..Anchor::max())
 848    }
 849}
 850
 851impl sum_tree::Item for Fold {
 852    type Summary = FoldSummary;
 853
 854    fn summary(&self) -> Self::Summary {
 855        FoldSummary {
 856            start: self.0.start.clone(),
 857            end: self.0.end.clone(),
 858            min_start: self.0.start.clone(),
 859            max_end: self.0.end.clone(),
 860            count: 1,
 861        }
 862    }
 863}
 864
 865#[derive(Clone, Debug)]
 866struct FoldSummary {
 867    start: Anchor,
 868    end: Anchor,
 869    min_start: Anchor,
 870    max_end: Anchor,
 871    count: usize,
 872}
 873
 874impl Default for FoldSummary {
 875    fn default() -> Self {
 876        Self {
 877            start: Anchor::min(),
 878            end: Anchor::max(),
 879            min_start: Anchor::max(),
 880            max_end: Anchor::min(),
 881            count: 0,
 882        }
 883    }
 884}
 885
 886impl sum_tree::Summary for FoldSummary {
 887    type Context = MultiBufferSnapshot;
 888
 889    fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
 890        if other.min_start.cmp(&self.min_start, buffer) == Ordering::Less {
 891            self.min_start = other.min_start.clone();
 892        }
 893        if other.max_end.cmp(&self.max_end, buffer) == Ordering::Greater {
 894            self.max_end = other.max_end.clone();
 895        }
 896
 897        #[cfg(debug_assertions)]
 898        {
 899            let start_comparison = self.start.cmp(&other.start, buffer);
 900            assert!(start_comparison <= Ordering::Equal);
 901            if start_comparison == Ordering::Equal {
 902                assert!(self.end.cmp(&other.end, buffer) >= Ordering::Equal);
 903            }
 904        }
 905
 906        self.start = other.start.clone();
 907        self.end = other.end.clone();
 908        self.count += other.count;
 909    }
 910}
 911
 912impl<'a> sum_tree::Dimension<'a, FoldSummary> for Fold {
 913    fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
 914        self.0.start = summary.start.clone();
 915        self.0.end = summary.end.clone();
 916    }
 917}
 918
 919impl<'a> sum_tree::SeekTarget<'a, FoldSummary, Fold> for Fold {
 920    fn cmp(&self, other: &Self, buffer: &MultiBufferSnapshot) -> Ordering {
 921        self.0.cmp(&other.0, buffer)
 922    }
 923}
 924
 925impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
 926    fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
 927        *self += summary.count;
 928    }
 929}
 930
 931#[derive(Clone)]
 932pub struct FoldBufferRows<'a> {
 933    cursor: Cursor<'a, Transform, (FoldPoint, InlayPoint)>,
 934    input_buffer_rows: InlayBufferRows<'a>,
 935    fold_point: FoldPoint,
 936}
 937
 938impl<'a> Iterator for FoldBufferRows<'a> {
 939    type Item = Option<u32>;
 940
 941    fn next(&mut self) -> Option<Self::Item> {
 942        let mut traversed_fold = false;
 943        while self.fold_point > self.cursor.end(&()).0 {
 944            self.cursor.next(&());
 945            traversed_fold = true;
 946            if self.cursor.item().is_none() {
 947                break;
 948            }
 949        }
 950
 951        if self.cursor.item().is_some() {
 952            if traversed_fold {
 953                self.input_buffer_rows.seek(self.cursor.start().1.row());
 954                self.input_buffer_rows.next();
 955            }
 956            *self.fold_point.row_mut() += 1;
 957            self.input_buffer_rows.next()
 958        } else {
 959            None
 960        }
 961    }
 962}
 963
 964pub struct FoldChunks<'a> {
 965    transform_cursor: Cursor<'a, Transform, (FoldOffset, InlayOffset)>,
 966    inlay_chunks: InlayChunks<'a>,
 967    inlay_chunk: Option<(InlayOffset, Chunk<'a>)>,
 968    inlay_offset: InlayOffset,
 969    output_offset: usize,
 970    max_output_offset: usize,
 971    ellipses_color: Option<Color>,
 972}
 973
 974impl<'a> Iterator for FoldChunks<'a> {
 975    type Item = Chunk<'a>;
 976
 977    fn next(&mut self) -> Option<Self::Item> {
 978        if self.output_offset >= self.max_output_offset {
 979            return None;
 980        }
 981
 982        let transform = self.transform_cursor.item()?;
 983
 984        // If we're in a fold, then return the fold's display text and
 985        // advance the transform and buffer cursors to the end of the fold.
 986        if let Some(output_text) = transform.output_text {
 987            self.inlay_chunk.take();
 988            self.inlay_offset += InlayOffset(transform.summary.input.len);
 989            self.inlay_chunks.seek(self.inlay_offset);
 990
 991            while self.inlay_offset >= self.transform_cursor.end(&()).1
 992                && self.transform_cursor.item().is_some()
 993            {
 994                self.transform_cursor.next(&());
 995            }
 996
 997            self.output_offset += output_text.len();
 998            return Some(Chunk {
 999                text: output_text,
1000                highlight_style: self.ellipses_color.map(|color| HighlightStyle {
1001                    color: Some(color),
1002                    ..Default::default()
1003                }),
1004                ..Default::default()
1005            });
1006        }
1007
1008        // Retrieve a chunk from the current location in the buffer.
1009        if self.inlay_chunk.is_none() {
1010            let chunk_offset = self.inlay_chunks.offset();
1011            self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1012        }
1013
1014        // Otherwise, take a chunk from the buffer's text.
1015        if let Some((buffer_chunk_start, mut chunk)) = self.inlay_chunk {
1016            let buffer_chunk_end = buffer_chunk_start + InlayOffset(chunk.text.len());
1017            let transform_end = self.transform_cursor.end(&()).1;
1018            let chunk_end = buffer_chunk_end.min(transform_end);
1019
1020            chunk.text = &chunk.text
1021                [(self.inlay_offset - buffer_chunk_start).0..(chunk_end - buffer_chunk_start).0];
1022
1023            if chunk_end == transform_end {
1024                self.transform_cursor.next(&());
1025            } else if chunk_end == buffer_chunk_end {
1026                self.inlay_chunk.take();
1027            }
1028
1029            self.inlay_offset = chunk_end;
1030            self.output_offset += chunk.text.len();
1031            return Some(chunk);
1032        }
1033
1034        None
1035    }
1036}
1037
1038#[derive(Copy, Clone, Eq, PartialEq)]
1039struct HighlightEndpoint {
1040    offset: InlayOffset,
1041    is_start: bool,
1042    tag: Option<TypeId>,
1043    style: HighlightStyle,
1044}
1045
1046impl PartialOrd for HighlightEndpoint {
1047    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1048        Some(self.cmp(other))
1049    }
1050}
1051
1052impl Ord for HighlightEndpoint {
1053    fn cmp(&self, other: &Self) -> Ordering {
1054        self.offset
1055            .cmp(&other.offset)
1056            .then_with(|| other.is_start.cmp(&self.is_start))
1057    }
1058}
1059
1060#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1061pub struct FoldOffset(pub usize);
1062
1063impl FoldOffset {
1064    pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1065        let mut cursor = snapshot
1066            .transforms
1067            .cursor::<(FoldOffset, TransformSummary)>();
1068        cursor.seek(&self, Bias::Right, &());
1069        let overshoot = if cursor.item().map_or(true, |t| t.is_fold()) {
1070            Point::new(0, (self.0 - cursor.start().0 .0) as u32)
1071        } else {
1072            let inlay_offset = cursor.start().1.input.len + self.0 - cursor.start().0 .0;
1073            let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1074            inlay_point.0 - cursor.start().1.input.lines
1075        };
1076        FoldPoint(cursor.start().1.output.lines + overshoot)
1077    }
1078
1079    #[cfg(test)]
1080    pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1081        let mut cursor = snapshot.transforms.cursor::<(FoldOffset, InlayOffset)>();
1082        cursor.seek(&self, Bias::Right, &());
1083        let overshoot = self.0 - cursor.start().0 .0;
1084        InlayOffset(cursor.start().1 .0 + overshoot)
1085    }
1086}
1087
1088impl Add for FoldOffset {
1089    type Output = Self;
1090
1091    fn add(self, rhs: Self) -> Self::Output {
1092        Self(self.0 + rhs.0)
1093    }
1094}
1095
1096impl AddAssign for FoldOffset {
1097    fn add_assign(&mut self, rhs: Self) {
1098        self.0 += rhs.0;
1099    }
1100}
1101
1102impl Sub for FoldOffset {
1103    type Output = Self;
1104
1105    fn sub(self, rhs: Self) -> Self::Output {
1106        Self(self.0 - rhs.0)
1107    }
1108}
1109
1110impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1111    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1112        self.0 += &summary.output.len;
1113    }
1114}
1115
1116impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1117    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1118        self.0 += &summary.input.lines;
1119    }
1120}
1121
1122impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1123    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1124        self.0 += &summary.input.len;
1125    }
1126}
1127
1128pub type FoldEdit = Edit<FoldOffset>;
1129
1130#[cfg(test)]
1131mod tests {
1132    use super::*;
1133    use crate::{display_map::inlay_map::InlayMap, MultiBuffer, ToPoint};
1134    use collections::HashSet;
1135    use rand::prelude::*;
1136    use settings::SettingsStore;
1137    use std::{env, mem};
1138    use text::Patch;
1139    use util::test::sample_text;
1140    use util::RandomCharIter;
1141    use Bias::{Left, Right};
1142
1143    #[gpui::test]
1144    fn test_basic_folds(cx: &mut gpui::AppContext) {
1145        init_test(cx);
1146        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1147        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1148        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1149        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1150        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1151
1152        let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1153        let (snapshot2, edits) = writer.fold(vec![
1154            Point::new(0, 2)..Point::new(2, 2),
1155            Point::new(2, 4)..Point::new(4, 1),
1156        ]);
1157        assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1158        assert_eq!(
1159            edits,
1160            &[
1161                FoldEdit {
1162                    old: FoldOffset(2)..FoldOffset(16),
1163                    new: FoldOffset(2)..FoldOffset(5),
1164                },
1165                FoldEdit {
1166                    old: FoldOffset(18)..FoldOffset(29),
1167                    new: FoldOffset(7)..FoldOffset(10)
1168                },
1169            ]
1170        );
1171
1172        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1173            buffer.edit(
1174                vec![
1175                    (Point::new(0, 0)..Point::new(0, 1), "123"),
1176                    (Point::new(2, 3)..Point::new(2, 3), "123"),
1177                ],
1178                None,
1179                cx,
1180            );
1181            buffer.snapshot(cx)
1182        });
1183
1184        let (inlay_snapshot, inlay_edits) =
1185            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1186        let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1187        assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1188        assert_eq!(
1189            edits,
1190            &[
1191                FoldEdit {
1192                    old: FoldOffset(0)..FoldOffset(1),
1193                    new: FoldOffset(0)..FoldOffset(3),
1194                },
1195                FoldEdit {
1196                    old: FoldOffset(6)..FoldOffset(6),
1197                    new: FoldOffset(8)..FoldOffset(11),
1198                },
1199            ]
1200        );
1201
1202        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1203            buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1204            buffer.snapshot(cx)
1205        });
1206        let (inlay_snapshot, inlay_edits) =
1207            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1208        let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1209        assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1210
1211        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1212        writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1213        let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1214        assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1215
1216        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1217        writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1218        let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1219        assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1220    }
1221
1222    #[gpui::test]
1223    fn test_adjacent_folds(cx: &mut gpui::AppContext) {
1224        init_test(cx);
1225        let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1226        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1227        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1228        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1229
1230        {
1231            let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1232
1233            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1234            writer.fold(vec![5..8]);
1235            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1236            assert_eq!(snapshot.text(), "abcde⋯ijkl");
1237
1238            // Create an fold adjacent to the start of the first fold.
1239            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1240            writer.fold(vec![0..1, 2..5]);
1241            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1242            assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1243
1244            // Create an fold adjacent to the end of the first fold.
1245            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1246            writer.fold(vec![11..11, 8..10]);
1247            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1248            assert_eq!(snapshot.text(), "⋯b⋯kl");
1249        }
1250
1251        {
1252            let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1253
1254            // Create two adjacent folds.
1255            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1256            writer.fold(vec![0..2, 2..5]);
1257            let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1258            assert_eq!(snapshot.text(), "⋯fghijkl");
1259
1260            // Edit within one of the folds.
1261            let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1262                buffer.edit([(0..1, "12345")], None, cx);
1263                buffer.snapshot(cx)
1264            });
1265            let (inlay_snapshot, inlay_edits) =
1266                inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1267            let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1268            assert_eq!(snapshot.text(), "12345⋯fghijkl");
1269        }
1270    }
1271
1272    #[gpui::test]
1273    fn test_overlapping_folds(cx: &mut gpui::AppContext) {
1274        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1275        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1276        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1277        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1278        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1279        writer.fold(vec![
1280            Point::new(0, 2)..Point::new(2, 2),
1281            Point::new(0, 4)..Point::new(1, 0),
1282            Point::new(1, 2)..Point::new(3, 2),
1283            Point::new(3, 1)..Point::new(4, 1),
1284        ]);
1285        let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1286        assert_eq!(snapshot.text(), "aa⋯eeeee");
1287    }
1288
1289    #[gpui::test]
1290    fn test_merging_folds_via_edit(cx: &mut gpui::AppContext) {
1291        init_test(cx);
1292        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1293        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1294        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1295        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1296        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1297
1298        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1299        writer.fold(vec![
1300            Point::new(0, 2)..Point::new(2, 2),
1301            Point::new(3, 1)..Point::new(4, 1),
1302        ]);
1303        let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1304        assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1305
1306        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1307            buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1308            buffer.snapshot(cx)
1309        });
1310        let (inlay_snapshot, inlay_edits) =
1311            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1312        let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1313        assert_eq!(snapshot.text(), "aa⋯eeeee");
1314    }
1315
1316    #[gpui::test]
1317    fn test_folds_in_range(cx: &mut gpui::AppContext) {
1318        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1319        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1320        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1321        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1322
1323        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1324        writer.fold(vec![
1325            Point::new(0, 2)..Point::new(2, 2),
1326            Point::new(0, 4)..Point::new(1, 0),
1327            Point::new(1, 2)..Point::new(3, 2),
1328            Point::new(3, 1)..Point::new(4, 1),
1329        ]);
1330        let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1331        let fold_ranges = snapshot
1332            .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1333            .map(|fold| fold.start.to_point(&buffer_snapshot)..fold.end.to_point(&buffer_snapshot))
1334            .collect::<Vec<_>>();
1335        assert_eq!(
1336            fold_ranges,
1337            vec![
1338                Point::new(0, 2)..Point::new(2, 2),
1339                Point::new(1, 2)..Point::new(3, 2)
1340            ]
1341        );
1342    }
1343
1344    #[gpui::test(iterations = 100)]
1345    fn test_random_folds(cx: &mut gpui::AppContext, mut rng: StdRng) {
1346        init_test(cx);
1347        let operations = env::var("OPERATIONS")
1348            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1349            .unwrap_or(10);
1350
1351        let len = rng.gen_range(0..10);
1352        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1353        let buffer = if rng.gen() {
1354            MultiBuffer::build_simple(&text, cx)
1355        } else {
1356            MultiBuffer::build_random(&mut rng, cx)
1357        };
1358        let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1359        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1360        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1361
1362        let (mut initial_snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1363        let mut snapshot_edits = Vec::new();
1364
1365        let mut next_inlay_id = 0;
1366        for _ in 0..operations {
1367            log::info!("text: {:?}", buffer_snapshot.text());
1368            let mut buffer_edits = Vec::new();
1369            let mut inlay_edits = Vec::new();
1370            match rng.gen_range(0..=100) {
1371                0..=39 => {
1372                    snapshot_edits.extend(map.randomly_mutate(&mut rng));
1373                }
1374                40..=59 => {
1375                    let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1376                    inlay_edits = edits;
1377                }
1378                _ => buffer.update(cx, |buffer, cx| {
1379                    let subscription = buffer.subscribe();
1380                    let edit_count = rng.gen_range(1..=5);
1381                    buffer.randomly_mutate(&mut rng, edit_count, cx);
1382                    buffer_snapshot = buffer.snapshot(cx);
1383                    let edits = subscription.consume().into_inner();
1384                    log::info!("editing {:?}", edits);
1385                    buffer_edits.extend(edits);
1386                }),
1387            };
1388
1389            let (inlay_snapshot, new_inlay_edits) =
1390                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1391            log::info!("inlay text {:?}", inlay_snapshot.text());
1392
1393            let inlay_edits = Patch::new(inlay_edits)
1394                .compose(new_inlay_edits)
1395                .into_inner();
1396            let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
1397            snapshot_edits.push((snapshot.clone(), edits));
1398
1399            let mut expected_text: String = inlay_snapshot.text().to_string();
1400            for fold_range in map.merged_fold_ranges().into_iter().rev() {
1401                let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
1402                let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
1403                expected_text.replace_range(fold_inlay_start.0..fold_inlay_end.0, "");
1404            }
1405
1406            assert_eq!(snapshot.text(), expected_text);
1407            log::info!(
1408                "fold text {:?} ({} lines)",
1409                expected_text,
1410                expected_text.matches('\n').count() + 1
1411            );
1412
1413            let mut prev_row = 0;
1414            let mut expected_buffer_rows = Vec::new();
1415            for fold_range in map.merged_fold_ranges().into_iter() {
1416                let fold_start = inlay_snapshot
1417                    .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
1418                    .row();
1419                let fold_end = inlay_snapshot
1420                    .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
1421                    .row();
1422                expected_buffer_rows.extend(
1423                    inlay_snapshot
1424                        .buffer_rows(prev_row)
1425                        .take((1 + fold_start - prev_row) as usize),
1426                );
1427                prev_row = 1 + fold_end;
1428            }
1429            expected_buffer_rows.extend(inlay_snapshot.buffer_rows(prev_row));
1430
1431            assert_eq!(
1432                expected_buffer_rows.len(),
1433                expected_text.matches('\n').count() + 1,
1434                "wrong expected buffer rows {:?}. text: {:?}",
1435                expected_buffer_rows,
1436                expected_text
1437            );
1438
1439            for (output_row, line) in expected_text.lines().enumerate() {
1440                let line_len = snapshot.line_len(output_row as u32);
1441                assert_eq!(line_len, line.len() as u32);
1442            }
1443
1444            let longest_row = snapshot.longest_row();
1445            let longest_char_column = expected_text
1446                .split('\n')
1447                .nth(longest_row as usize)
1448                .unwrap()
1449                .chars()
1450                .count();
1451            let mut fold_point = FoldPoint::new(0, 0);
1452            let mut fold_offset = FoldOffset(0);
1453            let mut char_column = 0;
1454            for c in expected_text.chars() {
1455                let inlay_point = fold_point.to_inlay_point(&snapshot);
1456                let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
1457                assert_eq!(
1458                    snapshot.to_fold_point(inlay_point, Right),
1459                    fold_point,
1460                    "{:?} -> fold point",
1461                    inlay_point,
1462                );
1463                assert_eq!(
1464                    inlay_snapshot.to_offset(inlay_point),
1465                    inlay_offset,
1466                    "inlay_snapshot.to_offset({:?})",
1467                    inlay_point,
1468                );
1469                assert_eq!(
1470                    fold_point.to_offset(&snapshot),
1471                    fold_offset,
1472                    "fold_point.to_offset({:?})",
1473                    fold_point,
1474                );
1475
1476                if c == '\n' {
1477                    *fold_point.row_mut() += 1;
1478                    *fold_point.column_mut() = 0;
1479                    char_column = 0;
1480                } else {
1481                    *fold_point.column_mut() += c.len_utf8() as u32;
1482                    char_column += 1;
1483                }
1484                fold_offset.0 += c.len_utf8();
1485                if char_column > longest_char_column {
1486                    panic!(
1487                        "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
1488                        longest_row,
1489                        longest_char_column,
1490                        fold_point.row(),
1491                        char_column
1492                    );
1493                }
1494            }
1495
1496            for _ in 0..5 {
1497                let mut start = snapshot
1498                    .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Left);
1499                let mut end = snapshot
1500                    .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Right);
1501                if start > end {
1502                    mem::swap(&mut start, &mut end);
1503                }
1504
1505                let text = &expected_text[start.0..end.0];
1506                assert_eq!(
1507                    snapshot
1508                        .chunks(start..end, false, None, None, None, None)
1509                        .map(|c| c.text)
1510                        .collect::<String>(),
1511                    text,
1512                );
1513            }
1514
1515            let mut fold_row = 0;
1516            while fold_row < expected_buffer_rows.len() as u32 {
1517                assert_eq!(
1518                    snapshot.buffer_rows(fold_row).collect::<Vec<_>>(),
1519                    expected_buffer_rows[(fold_row as usize)..],
1520                    "wrong buffer rows starting at fold row {}",
1521                    fold_row,
1522                );
1523                fold_row += 1;
1524            }
1525
1526            let folded_buffer_rows = map
1527                .merged_fold_ranges()
1528                .iter()
1529                .flat_map(|range| {
1530                    let start_row = range.start.to_point(&buffer_snapshot).row;
1531                    let end = range.end.to_point(&buffer_snapshot);
1532                    if end.column == 0 {
1533                        start_row..end.row
1534                    } else {
1535                        start_row..end.row + 1
1536                    }
1537                })
1538                .collect::<HashSet<_>>();
1539            for row in 0..=buffer_snapshot.max_point().row {
1540                assert_eq!(
1541                    snapshot.is_line_folded(row),
1542                    folded_buffer_rows.contains(&row),
1543                    "expected buffer row {}{} to be folded",
1544                    row,
1545                    if folded_buffer_rows.contains(&row) {
1546                        ""
1547                    } else {
1548                        " not"
1549                    }
1550                );
1551            }
1552
1553            for _ in 0..5 {
1554                let end =
1555                    buffer_snapshot.clip_offset(rng.gen_range(0..=buffer_snapshot.len()), Right);
1556                let start = buffer_snapshot.clip_offset(rng.gen_range(0..=end), Left);
1557                let expected_folds = map
1558                    .snapshot
1559                    .folds
1560                    .items(&buffer_snapshot)
1561                    .into_iter()
1562                    .filter(|fold| {
1563                        let start = buffer_snapshot.anchor_before(start);
1564                        let end = buffer_snapshot.anchor_after(end);
1565                        start.cmp(&fold.0.end, &buffer_snapshot) == Ordering::Less
1566                            && end.cmp(&fold.0.start, &buffer_snapshot) == Ordering::Greater
1567                    })
1568                    .map(|fold| fold.0)
1569                    .collect::<Vec<_>>();
1570
1571                assert_eq!(
1572                    snapshot
1573                        .folds_in_range(start..end)
1574                        .cloned()
1575                        .collect::<Vec<_>>(),
1576                    expected_folds
1577                );
1578            }
1579
1580            let text = snapshot.text();
1581            for _ in 0..5 {
1582                let start_row = rng.gen_range(0..=snapshot.max_point().row());
1583                let start_column = rng.gen_range(0..=snapshot.line_len(start_row));
1584                let end_row = rng.gen_range(0..=snapshot.max_point().row());
1585                let end_column = rng.gen_range(0..=snapshot.line_len(end_row));
1586                let mut start =
1587                    snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
1588                let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
1589                if start > end {
1590                    mem::swap(&mut start, &mut end);
1591                }
1592
1593                let lines = start..end;
1594                let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
1595                assert_eq!(
1596                    snapshot.text_summary_for_range(lines),
1597                    TextSummary::from(&text[bytes.start.0..bytes.end.0])
1598                )
1599            }
1600
1601            let mut text = initial_snapshot.text();
1602            for (snapshot, edits) in snapshot_edits.drain(..) {
1603                let new_text = snapshot.text();
1604                for edit in edits {
1605                    let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
1606                    let new_bytes = edit.new.start.0..edit.new.end.0;
1607                    text.replace_range(old_bytes, &new_text[new_bytes]);
1608                }
1609
1610                assert_eq!(text, new_text);
1611                initial_snapshot = snapshot;
1612            }
1613        }
1614    }
1615
1616    #[gpui::test]
1617    fn test_buffer_rows(cx: &mut gpui::AppContext) {
1618        let text = sample_text(6, 6, 'a') + "\n";
1619        let buffer = MultiBuffer::build_simple(&text, cx);
1620
1621        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1622        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1623        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1624
1625        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1626        writer.fold(vec![
1627            Point::new(0, 2)..Point::new(2, 2),
1628            Point::new(3, 1)..Point::new(4, 1),
1629        ]);
1630
1631        let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1632        assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
1633        assert_eq!(
1634            snapshot.buffer_rows(0).collect::<Vec<_>>(),
1635            [Some(0), Some(3), Some(5), Some(6)]
1636        );
1637        assert_eq!(snapshot.buffer_rows(3).collect::<Vec<_>>(), [Some(6)]);
1638    }
1639
1640    fn init_test(cx: &mut gpui::AppContext) {
1641        cx.set_global(SettingsStore::test(cx));
1642    }
1643
1644    impl FoldMap {
1645        fn merged_fold_ranges(&self) -> Vec<Range<usize>> {
1646            let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1647            let buffer = &inlay_snapshot.buffer;
1648            let mut folds = self.snapshot.folds.items(buffer);
1649            // Ensure sorting doesn't change how folds get merged and displayed.
1650            folds.sort_by(|a, b| a.0.cmp(&b.0, buffer));
1651            let mut fold_ranges = folds
1652                .iter()
1653                .map(|fold| fold.0.start.to_offset(buffer)..fold.0.end.to_offset(buffer))
1654                .peekable();
1655
1656            let mut merged_ranges = Vec::new();
1657            while let Some(mut fold_range) = fold_ranges.next() {
1658                while let Some(next_range) = fold_ranges.peek() {
1659                    if fold_range.end >= next_range.start {
1660                        if next_range.end > fold_range.end {
1661                            fold_range.end = next_range.end;
1662                        }
1663                        fold_ranges.next();
1664                    } else {
1665                        break;
1666                    }
1667                }
1668                if fold_range.end > fold_range.start {
1669                    merged_ranges.push(fold_range);
1670                }
1671            }
1672            merged_ranges
1673        }
1674
1675        pub fn randomly_mutate(
1676            &mut self,
1677            rng: &mut impl Rng,
1678        ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
1679            let mut snapshot_edits = Vec::new();
1680            match rng.gen_range(0..=100) {
1681                0..=39 if !self.snapshot.folds.is_empty() => {
1682                    let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1683                    let buffer = &inlay_snapshot.buffer;
1684                    let mut to_unfold = Vec::new();
1685                    for _ in 0..rng.gen_range(1..=3) {
1686                        let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1687                        let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1688                        to_unfold.push(start..end);
1689                    }
1690                    log::info!("unfolding {:?}", to_unfold);
1691                    let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
1692                    snapshot_edits.push((snapshot, edits));
1693                    let (snapshot, edits) = writer.fold(to_unfold);
1694                    snapshot_edits.push((snapshot, edits));
1695                }
1696                _ => {
1697                    let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1698                    let buffer = &inlay_snapshot.buffer;
1699                    let mut to_fold = Vec::new();
1700                    for _ in 0..rng.gen_range(1..=2) {
1701                        let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1702                        let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1703                        to_fold.push(start..end);
1704                    }
1705                    log::info!("folding {:?}", to_fold);
1706                    let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
1707                    snapshot_edits.push((snapshot, edits));
1708                    let (snapshot, edits) = writer.fold(to_fold);
1709                    snapshot_edits.push((snapshot, edits));
1710                }
1711            }
1712            snapshot_edits
1713        }
1714    }
1715}