fold_map.rs

   1use super::{
   2    inlay_map::{InlayBufferRows, InlayChunks, InlayEdit, InlayOffset, InlayPoint, InlaySnapshot},
   3    Highlights,
   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, Highlights::default())
 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        highlights: Highlights<'a>,
 655    ) -> FoldChunks<'a> {
 656        let mut transform_cursor = self.transforms.cursor::<(FoldOffset, InlayOffset)>();
 657
 658        let inlay_end = {
 659            transform_cursor.seek(&range.end, Bias::Right, &());
 660            let overshoot = range.end.0 - transform_cursor.start().0 .0;
 661            transform_cursor.start().1 + InlayOffset(overshoot)
 662        };
 663
 664        let inlay_start = {
 665            transform_cursor.seek(&range.start, Bias::Right, &());
 666            let overshoot = range.start.0 - transform_cursor.start().0 .0;
 667            transform_cursor.start().1 + InlayOffset(overshoot)
 668        };
 669
 670        FoldChunks {
 671            transform_cursor,
 672            inlay_chunks: self.inlay_snapshot.chunks(
 673                inlay_start..inlay_end,
 674                language_aware,
 675                highlights,
 676            ),
 677            inlay_chunk: None,
 678            inlay_offset: inlay_start,
 679            output_offset: range.start.0,
 680            max_output_offset: range.end.0,
 681            ellipses_color: self.ellipses_color,
 682        }
 683    }
 684
 685    pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
 686        self.chunks(
 687            start.to_offset(self)..self.len(),
 688            false,
 689            Highlights::default(),
 690        )
 691        .flat_map(|chunk| chunk.text.chars())
 692    }
 693
 694    #[cfg(test)]
 695    pub fn clip_offset(&self, offset: FoldOffset, bias: Bias) -> FoldOffset {
 696        if offset > self.len() {
 697            self.len()
 698        } else {
 699            self.clip_point(offset.to_point(self), bias).to_offset(self)
 700        }
 701    }
 702
 703    pub fn clip_point(&self, point: FoldPoint, bias: Bias) -> FoldPoint {
 704        let mut cursor = self.transforms.cursor::<(FoldPoint, InlayPoint)>();
 705        cursor.seek(&point, Bias::Right, &());
 706        if let Some(transform) = cursor.item() {
 707            let transform_start = cursor.start().0 .0;
 708            if transform.output_text.is_some() {
 709                if point.0 == transform_start || matches!(bias, Bias::Left) {
 710                    FoldPoint(transform_start)
 711                } else {
 712                    FoldPoint(cursor.end(&()).0 .0)
 713                }
 714            } else {
 715                let overshoot = InlayPoint(point.0 - transform_start);
 716                let inlay_point = cursor.start().1 + overshoot;
 717                let clipped_inlay_point = self.inlay_snapshot.clip_point(inlay_point, bias);
 718                FoldPoint(cursor.start().0 .0 + (clipped_inlay_point - cursor.start().1).0)
 719            }
 720        } else {
 721            FoldPoint(self.transforms.summary().output.lines)
 722        }
 723    }
 724}
 725
 726fn intersecting_folds<'a, T>(
 727    inlay_snapshot: &'a InlaySnapshot,
 728    folds: &'a SumTree<Fold>,
 729    range: Range<T>,
 730    inclusive: bool,
 731) -> FilterCursor<'a, impl 'a + FnMut(&FoldSummary) -> bool, Fold, usize>
 732where
 733    T: ToOffset,
 734{
 735    let buffer = &inlay_snapshot.buffer;
 736    let start = buffer.anchor_before(range.start.to_offset(buffer));
 737    let end = buffer.anchor_after(range.end.to_offset(buffer));
 738    let mut cursor = folds.filter::<_, usize>(move |summary| {
 739        let start_cmp = start.cmp(&summary.max_end, buffer);
 740        let end_cmp = end.cmp(&summary.min_start, buffer);
 741
 742        if inclusive {
 743            start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
 744        } else {
 745            start_cmp == Ordering::Less && end_cmp == Ordering::Greater
 746        }
 747    });
 748    cursor.next(buffer);
 749    cursor
 750}
 751
 752fn consolidate_inlay_edits(edits: &mut Vec<InlayEdit>) {
 753    edits.sort_unstable_by(|a, b| {
 754        a.old
 755            .start
 756            .cmp(&b.old.start)
 757            .then_with(|| b.old.end.cmp(&a.old.end))
 758    });
 759
 760    let mut i = 1;
 761    while i < edits.len() {
 762        let edit = edits[i].clone();
 763        let prev_edit = &mut edits[i - 1];
 764        if prev_edit.old.end >= edit.old.start {
 765            prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
 766            prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
 767            prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
 768            edits.remove(i);
 769            continue;
 770        }
 771        i += 1;
 772    }
 773}
 774
 775fn consolidate_fold_edits(edits: &mut Vec<FoldEdit>) {
 776    edits.sort_unstable_by(|a, b| {
 777        a.old
 778            .start
 779            .cmp(&b.old.start)
 780            .then_with(|| b.old.end.cmp(&a.old.end))
 781    });
 782
 783    let mut i = 1;
 784    while i < edits.len() {
 785        let edit = edits[i].clone();
 786        let prev_edit = &mut edits[i - 1];
 787        if prev_edit.old.end >= edit.old.start {
 788            prev_edit.old.end = prev_edit.old.end.max(edit.old.end);
 789            prev_edit.new.start = prev_edit.new.start.min(edit.new.start);
 790            prev_edit.new.end = prev_edit.new.end.max(edit.new.end);
 791            edits.remove(i);
 792            continue;
 793        }
 794        i += 1;
 795    }
 796}
 797
 798#[derive(Clone, Debug, Default, Eq, PartialEq)]
 799struct Transform {
 800    summary: TransformSummary,
 801    output_text: Option<&'static str>,
 802}
 803
 804impl Transform {
 805    fn is_fold(&self) -> bool {
 806        self.output_text.is_some()
 807    }
 808}
 809
 810#[derive(Clone, Debug, Default, Eq, PartialEq)]
 811struct TransformSummary {
 812    output: TextSummary,
 813    input: TextSummary,
 814}
 815
 816impl sum_tree::Item for Transform {
 817    type Summary = TransformSummary;
 818
 819    fn summary(&self) -> Self::Summary {
 820        self.summary.clone()
 821    }
 822}
 823
 824impl sum_tree::Summary for TransformSummary {
 825    type Context = ();
 826
 827    fn add_summary(&mut self, other: &Self, _: &()) {
 828        self.input += &other.input;
 829        self.output += &other.output;
 830    }
 831}
 832
 833#[derive(Clone, Debug)]
 834struct Fold(Range<Anchor>);
 835
 836impl Default for Fold {
 837    fn default() -> Self {
 838        Self(Anchor::min()..Anchor::max())
 839    }
 840}
 841
 842impl sum_tree::Item for Fold {
 843    type Summary = FoldSummary;
 844
 845    fn summary(&self) -> Self::Summary {
 846        FoldSummary {
 847            start: self.0.start.clone(),
 848            end: self.0.end.clone(),
 849            min_start: self.0.start.clone(),
 850            max_end: self.0.end.clone(),
 851            count: 1,
 852        }
 853    }
 854}
 855
 856#[derive(Clone, Debug)]
 857struct FoldSummary {
 858    start: Anchor,
 859    end: Anchor,
 860    min_start: Anchor,
 861    max_end: Anchor,
 862    count: usize,
 863}
 864
 865impl Default for FoldSummary {
 866    fn default() -> Self {
 867        Self {
 868            start: Anchor::min(),
 869            end: Anchor::max(),
 870            min_start: Anchor::max(),
 871            max_end: Anchor::min(),
 872            count: 0,
 873        }
 874    }
 875}
 876
 877impl sum_tree::Summary for FoldSummary {
 878    type Context = MultiBufferSnapshot;
 879
 880    fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
 881        if other.min_start.cmp(&self.min_start, buffer) == Ordering::Less {
 882            self.min_start = other.min_start.clone();
 883        }
 884        if other.max_end.cmp(&self.max_end, buffer) == Ordering::Greater {
 885            self.max_end = other.max_end.clone();
 886        }
 887
 888        #[cfg(debug_assertions)]
 889        {
 890            let start_comparison = self.start.cmp(&other.start, buffer);
 891            assert!(start_comparison <= Ordering::Equal);
 892            if start_comparison == Ordering::Equal {
 893                assert!(self.end.cmp(&other.end, buffer) >= Ordering::Equal);
 894            }
 895        }
 896
 897        self.start = other.start.clone();
 898        self.end = other.end.clone();
 899        self.count += other.count;
 900    }
 901}
 902
 903impl<'a> sum_tree::Dimension<'a, FoldSummary> for Fold {
 904    fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
 905        self.0.start = summary.start.clone();
 906        self.0.end = summary.end.clone();
 907    }
 908}
 909
 910impl<'a> sum_tree::SeekTarget<'a, FoldSummary, Fold> for Fold {
 911    fn cmp(&self, other: &Self, buffer: &MultiBufferSnapshot) -> Ordering {
 912        self.0.cmp(&other.0, buffer)
 913    }
 914}
 915
 916impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
 917    fn add_summary(&mut self, summary: &'a FoldSummary, _: &MultiBufferSnapshot) {
 918        *self += summary.count;
 919    }
 920}
 921
 922#[derive(Clone)]
 923pub struct FoldBufferRows<'a> {
 924    cursor: Cursor<'a, Transform, (FoldPoint, InlayPoint)>,
 925    input_buffer_rows: InlayBufferRows<'a>,
 926    fold_point: FoldPoint,
 927}
 928
 929impl<'a> Iterator for FoldBufferRows<'a> {
 930    type Item = Option<u32>;
 931
 932    fn next(&mut self) -> Option<Self::Item> {
 933        let mut traversed_fold = false;
 934        while self.fold_point > self.cursor.end(&()).0 {
 935            self.cursor.next(&());
 936            traversed_fold = true;
 937            if self.cursor.item().is_none() {
 938                break;
 939            }
 940        }
 941
 942        if self.cursor.item().is_some() {
 943            if traversed_fold {
 944                self.input_buffer_rows.seek(self.cursor.start().1.row());
 945                self.input_buffer_rows.next();
 946            }
 947            *self.fold_point.row_mut() += 1;
 948            self.input_buffer_rows.next()
 949        } else {
 950            None
 951        }
 952    }
 953}
 954
 955pub struct FoldChunks<'a> {
 956    transform_cursor: Cursor<'a, Transform, (FoldOffset, InlayOffset)>,
 957    inlay_chunks: InlayChunks<'a>,
 958    inlay_chunk: Option<(InlayOffset, Chunk<'a>)>,
 959    inlay_offset: InlayOffset,
 960    output_offset: usize,
 961    max_output_offset: usize,
 962    ellipses_color: Option<Color>,
 963}
 964
 965impl<'a> Iterator for FoldChunks<'a> {
 966    type Item = Chunk<'a>;
 967
 968    fn next(&mut self) -> Option<Self::Item> {
 969        if self.output_offset >= self.max_output_offset {
 970            return None;
 971        }
 972
 973        let transform = self.transform_cursor.item()?;
 974
 975        // If we're in a fold, then return the fold's display text and
 976        // advance the transform and buffer cursors to the end of the fold.
 977        if let Some(output_text) = transform.output_text {
 978            self.inlay_chunk.take();
 979            self.inlay_offset += InlayOffset(transform.summary.input.len);
 980            self.inlay_chunks.seek(self.inlay_offset);
 981
 982            while self.inlay_offset >= self.transform_cursor.end(&()).1
 983                && self.transform_cursor.item().is_some()
 984            {
 985                self.transform_cursor.next(&());
 986            }
 987
 988            self.output_offset += output_text.len();
 989            return Some(Chunk {
 990                text: output_text,
 991                highlight_style: self.ellipses_color.map(|color| HighlightStyle {
 992                    color: Some(color),
 993                    ..Default::default()
 994                }),
 995                ..Default::default()
 996            });
 997        }
 998
 999        // Retrieve a chunk from the current location in the buffer.
1000        if self.inlay_chunk.is_none() {
1001            let chunk_offset = self.inlay_chunks.offset();
1002            self.inlay_chunk = self.inlay_chunks.next().map(|chunk| (chunk_offset, chunk));
1003        }
1004
1005        // Otherwise, take a chunk from the buffer's text.
1006        if let Some((buffer_chunk_start, mut chunk)) = self.inlay_chunk {
1007            let buffer_chunk_end = buffer_chunk_start + InlayOffset(chunk.text.len());
1008            let transform_end = self.transform_cursor.end(&()).1;
1009            let chunk_end = buffer_chunk_end.min(transform_end);
1010
1011            chunk.text = &chunk.text
1012                [(self.inlay_offset - buffer_chunk_start).0..(chunk_end - buffer_chunk_start).0];
1013
1014            if chunk_end == transform_end {
1015                self.transform_cursor.next(&());
1016            } else if chunk_end == buffer_chunk_end {
1017                self.inlay_chunk.take();
1018            }
1019
1020            self.inlay_offset = chunk_end;
1021            self.output_offset += chunk.text.len();
1022            return Some(chunk);
1023        }
1024
1025        None
1026    }
1027}
1028
1029#[derive(Copy, Clone, Eq, PartialEq)]
1030struct HighlightEndpoint {
1031    offset: InlayOffset,
1032    is_start: bool,
1033    tag: Option<TypeId>,
1034    style: HighlightStyle,
1035}
1036
1037impl PartialOrd for HighlightEndpoint {
1038    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1039        Some(self.cmp(other))
1040    }
1041}
1042
1043impl Ord for HighlightEndpoint {
1044    fn cmp(&self, other: &Self) -> Ordering {
1045        self.offset
1046            .cmp(&other.offset)
1047            .then_with(|| other.is_start.cmp(&self.is_start))
1048    }
1049}
1050
1051#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
1052pub struct FoldOffset(pub usize);
1053
1054impl FoldOffset {
1055    pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
1056        let mut cursor = snapshot
1057            .transforms
1058            .cursor::<(FoldOffset, TransformSummary)>();
1059        cursor.seek(&self, Bias::Right, &());
1060        let overshoot = if cursor.item().map_or(true, |t| t.is_fold()) {
1061            Point::new(0, (self.0 - cursor.start().0 .0) as u32)
1062        } else {
1063            let inlay_offset = cursor.start().1.input.len + self.0 - cursor.start().0 .0;
1064            let inlay_point = snapshot.inlay_snapshot.to_point(InlayOffset(inlay_offset));
1065            inlay_point.0 - cursor.start().1.input.lines
1066        };
1067        FoldPoint(cursor.start().1.output.lines + overshoot)
1068    }
1069
1070    #[cfg(test)]
1071    pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
1072        let mut cursor = snapshot.transforms.cursor::<(FoldOffset, InlayOffset)>();
1073        cursor.seek(&self, Bias::Right, &());
1074        let overshoot = self.0 - cursor.start().0 .0;
1075        InlayOffset(cursor.start().1 .0 + overshoot)
1076    }
1077}
1078
1079impl Add for FoldOffset {
1080    type Output = Self;
1081
1082    fn add(self, rhs: Self) -> Self::Output {
1083        Self(self.0 + rhs.0)
1084    }
1085}
1086
1087impl AddAssign for FoldOffset {
1088    fn add_assign(&mut self, rhs: Self) {
1089        self.0 += rhs.0;
1090    }
1091}
1092
1093impl Sub for FoldOffset {
1094    type Output = Self;
1095
1096    fn sub(self, rhs: Self) -> Self::Output {
1097        Self(self.0 - rhs.0)
1098    }
1099}
1100
1101impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldOffset {
1102    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1103        self.0 += &summary.output.len;
1104    }
1105}
1106
1107impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
1108    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1109        self.0 += &summary.input.lines;
1110    }
1111}
1112
1113impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
1114    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1115        self.0 += &summary.input.len;
1116    }
1117}
1118
1119pub type FoldEdit = Edit<FoldOffset>;
1120
1121#[cfg(test)]
1122mod tests {
1123    use super::*;
1124    use crate::{display_map::inlay_map::InlayMap, MultiBuffer, ToPoint};
1125    use collections::HashSet;
1126    use rand::prelude::*;
1127    use settings::SettingsStore;
1128    use std::{env, mem};
1129    use text::Patch;
1130    use util::test::sample_text;
1131    use util::RandomCharIter;
1132    use Bias::{Left, Right};
1133
1134    #[gpui::test]
1135    fn test_basic_folds(cx: &mut gpui::AppContext) {
1136        init_test(cx);
1137        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1138        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1139        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1140        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1141        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1142
1143        let (mut writer, _, _) = map.write(inlay_snapshot, vec![]);
1144        let (snapshot2, edits) = writer.fold(vec![
1145            Point::new(0, 2)..Point::new(2, 2),
1146            Point::new(2, 4)..Point::new(4, 1),
1147        ]);
1148        assert_eq!(snapshot2.text(), "aa⋯cc⋯eeeee");
1149        assert_eq!(
1150            edits,
1151            &[
1152                FoldEdit {
1153                    old: FoldOffset(2)..FoldOffset(16),
1154                    new: FoldOffset(2)..FoldOffset(5),
1155                },
1156                FoldEdit {
1157                    old: FoldOffset(18)..FoldOffset(29),
1158                    new: FoldOffset(7)..FoldOffset(10)
1159                },
1160            ]
1161        );
1162
1163        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1164            buffer.edit(
1165                vec![
1166                    (Point::new(0, 0)..Point::new(0, 1), "123"),
1167                    (Point::new(2, 3)..Point::new(2, 3), "123"),
1168                ],
1169                None,
1170                cx,
1171            );
1172            buffer.snapshot(cx)
1173        });
1174
1175        let (inlay_snapshot, inlay_edits) =
1176            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1177        let (snapshot3, edits) = map.read(inlay_snapshot, inlay_edits);
1178        assert_eq!(snapshot3.text(), "123a⋯c123c⋯eeeee");
1179        assert_eq!(
1180            edits,
1181            &[
1182                FoldEdit {
1183                    old: FoldOffset(0)..FoldOffset(1),
1184                    new: FoldOffset(0)..FoldOffset(3),
1185                },
1186                FoldEdit {
1187                    old: FoldOffset(6)..FoldOffset(6),
1188                    new: FoldOffset(8)..FoldOffset(11),
1189                },
1190            ]
1191        );
1192
1193        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1194            buffer.edit([(Point::new(2, 6)..Point::new(4, 3), "456")], None, cx);
1195            buffer.snapshot(cx)
1196        });
1197        let (inlay_snapshot, inlay_edits) =
1198            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1199        let (snapshot4, _) = map.read(inlay_snapshot.clone(), inlay_edits);
1200        assert_eq!(snapshot4.text(), "123a⋯c123456eee");
1201
1202        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1203        writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), false);
1204        let (snapshot5, _) = map.read(inlay_snapshot.clone(), vec![]);
1205        assert_eq!(snapshot5.text(), "123a⋯c123456eee");
1206
1207        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1208        writer.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), true);
1209        let (snapshot6, _) = map.read(inlay_snapshot, vec![]);
1210        assert_eq!(snapshot6.text(), "123aaaaa\nbbbbbb\nccc123456eee");
1211    }
1212
1213    #[gpui::test]
1214    fn test_adjacent_folds(cx: &mut gpui::AppContext) {
1215        init_test(cx);
1216        let buffer = MultiBuffer::build_simple("abcdefghijkl", cx);
1217        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1218        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1219        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1220
1221        {
1222            let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1223
1224            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1225            writer.fold(vec![5..8]);
1226            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1227            assert_eq!(snapshot.text(), "abcde⋯ijkl");
1228
1229            // Create an fold adjacent to the start of the first fold.
1230            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1231            writer.fold(vec![0..1, 2..5]);
1232            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1233            assert_eq!(snapshot.text(), "⋯b⋯ijkl");
1234
1235            // Create an fold adjacent to the end of the first fold.
1236            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1237            writer.fold(vec![11..11, 8..10]);
1238            let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1239            assert_eq!(snapshot.text(), "⋯b⋯kl");
1240        }
1241
1242        {
1243            let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1244
1245            // Create two adjacent folds.
1246            let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1247            writer.fold(vec![0..2, 2..5]);
1248            let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1249            assert_eq!(snapshot.text(), "⋯fghijkl");
1250
1251            // Edit within one of the folds.
1252            let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1253                buffer.edit([(0..1, "12345")], None, cx);
1254                buffer.snapshot(cx)
1255            });
1256            let (inlay_snapshot, inlay_edits) =
1257                inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1258            let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1259            assert_eq!(snapshot.text(), "12345⋯fghijkl");
1260        }
1261    }
1262
1263    #[gpui::test]
1264    fn test_overlapping_folds(cx: &mut gpui::AppContext) {
1265        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1266        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1267        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1268        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1269        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1270        writer.fold(vec![
1271            Point::new(0, 2)..Point::new(2, 2),
1272            Point::new(0, 4)..Point::new(1, 0),
1273            Point::new(1, 2)..Point::new(3, 2),
1274            Point::new(3, 1)..Point::new(4, 1),
1275        ]);
1276        let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1277        assert_eq!(snapshot.text(), "aa⋯eeeee");
1278    }
1279
1280    #[gpui::test]
1281    fn test_merging_folds_via_edit(cx: &mut gpui::AppContext) {
1282        init_test(cx);
1283        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1284        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1285        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1286        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1287        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1288
1289        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1290        writer.fold(vec![
1291            Point::new(0, 2)..Point::new(2, 2),
1292            Point::new(3, 1)..Point::new(4, 1),
1293        ]);
1294        let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1295        assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee");
1296
1297        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1298            buffer.edit([(Point::new(2, 2)..Point::new(3, 1), "")], None, cx);
1299            buffer.snapshot(cx)
1300        });
1301        let (inlay_snapshot, inlay_edits) =
1302            inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1303        let (snapshot, _) = map.read(inlay_snapshot, inlay_edits);
1304        assert_eq!(snapshot.text(), "aa⋯eeeee");
1305    }
1306
1307    #[gpui::test]
1308    fn test_folds_in_range(cx: &mut gpui::AppContext) {
1309        let buffer = MultiBuffer::build_simple(&sample_text(5, 6, 'a'), cx);
1310        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1311        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1312        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1313
1314        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1315        writer.fold(vec![
1316            Point::new(0, 2)..Point::new(2, 2),
1317            Point::new(0, 4)..Point::new(1, 0),
1318            Point::new(1, 2)..Point::new(3, 2),
1319            Point::new(3, 1)..Point::new(4, 1),
1320        ]);
1321        let (snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1322        let fold_ranges = snapshot
1323            .folds_in_range(Point::new(1, 0)..Point::new(1, 3))
1324            .map(|fold| fold.start.to_point(&buffer_snapshot)..fold.end.to_point(&buffer_snapshot))
1325            .collect::<Vec<_>>();
1326        assert_eq!(
1327            fold_ranges,
1328            vec![
1329                Point::new(0, 2)..Point::new(2, 2),
1330                Point::new(1, 2)..Point::new(3, 2)
1331            ]
1332        );
1333    }
1334
1335    #[gpui::test(iterations = 100)]
1336    fn test_random_folds(cx: &mut gpui::AppContext, mut rng: StdRng) {
1337        init_test(cx);
1338        let operations = env::var("OPERATIONS")
1339            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1340            .unwrap_or(10);
1341
1342        let len = rng.gen_range(0..10);
1343        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1344        let buffer = if rng.gen() {
1345            MultiBuffer::build_simple(&text, cx)
1346        } else {
1347            MultiBuffer::build_random(&mut rng, cx)
1348        };
1349        let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1350        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1351        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1352
1353        let (mut initial_snapshot, _) = map.read(inlay_snapshot.clone(), vec![]);
1354        let mut snapshot_edits = Vec::new();
1355
1356        let mut next_inlay_id = 0;
1357        for _ in 0..operations {
1358            log::info!("text: {:?}", buffer_snapshot.text());
1359            let mut buffer_edits = Vec::new();
1360            let mut inlay_edits = Vec::new();
1361            match rng.gen_range(0..=100) {
1362                0..=39 => {
1363                    snapshot_edits.extend(map.randomly_mutate(&mut rng));
1364                }
1365                40..=59 => {
1366                    let (_, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1367                    inlay_edits = edits;
1368                }
1369                _ => buffer.update(cx, |buffer, cx| {
1370                    let subscription = buffer.subscribe();
1371                    let edit_count = rng.gen_range(1..=5);
1372                    buffer.randomly_mutate(&mut rng, edit_count, cx);
1373                    buffer_snapshot = buffer.snapshot(cx);
1374                    let edits = subscription.consume().into_inner();
1375                    log::info!("editing {:?}", edits);
1376                    buffer_edits.extend(edits);
1377                }),
1378            };
1379
1380            let (inlay_snapshot, new_inlay_edits) =
1381                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1382            log::info!("inlay text {:?}", inlay_snapshot.text());
1383
1384            let inlay_edits = Patch::new(inlay_edits)
1385                .compose(new_inlay_edits)
1386                .into_inner();
1387            let (snapshot, edits) = map.read(inlay_snapshot.clone(), inlay_edits);
1388            snapshot_edits.push((snapshot.clone(), edits));
1389
1390            let mut expected_text: String = inlay_snapshot.text().to_string();
1391            for fold_range in map.merged_fold_ranges().into_iter().rev() {
1392                let fold_inlay_start = inlay_snapshot.to_inlay_offset(fold_range.start);
1393                let fold_inlay_end = inlay_snapshot.to_inlay_offset(fold_range.end);
1394                expected_text.replace_range(fold_inlay_start.0..fold_inlay_end.0, "");
1395            }
1396
1397            assert_eq!(snapshot.text(), expected_text);
1398            log::info!(
1399                "fold text {:?} ({} lines)",
1400                expected_text,
1401                expected_text.matches('\n').count() + 1
1402            );
1403
1404            let mut prev_row = 0;
1405            let mut expected_buffer_rows = Vec::new();
1406            for fold_range in map.merged_fold_ranges().into_iter() {
1407                let fold_start = inlay_snapshot
1408                    .to_point(inlay_snapshot.to_inlay_offset(fold_range.start))
1409                    .row();
1410                let fold_end = inlay_snapshot
1411                    .to_point(inlay_snapshot.to_inlay_offset(fold_range.end))
1412                    .row();
1413                expected_buffer_rows.extend(
1414                    inlay_snapshot
1415                        .buffer_rows(prev_row)
1416                        .take((1 + fold_start - prev_row) as usize),
1417                );
1418                prev_row = 1 + fold_end;
1419            }
1420            expected_buffer_rows.extend(inlay_snapshot.buffer_rows(prev_row));
1421
1422            assert_eq!(
1423                expected_buffer_rows.len(),
1424                expected_text.matches('\n').count() + 1,
1425                "wrong expected buffer rows {:?}. text: {:?}",
1426                expected_buffer_rows,
1427                expected_text
1428            );
1429
1430            for (output_row, line) in expected_text.lines().enumerate() {
1431                let line_len = snapshot.line_len(output_row as u32);
1432                assert_eq!(line_len, line.len() as u32);
1433            }
1434
1435            let longest_row = snapshot.longest_row();
1436            let longest_char_column = expected_text
1437                .split('\n')
1438                .nth(longest_row as usize)
1439                .unwrap()
1440                .chars()
1441                .count();
1442            let mut fold_point = FoldPoint::new(0, 0);
1443            let mut fold_offset = FoldOffset(0);
1444            let mut char_column = 0;
1445            for c in expected_text.chars() {
1446                let inlay_point = fold_point.to_inlay_point(&snapshot);
1447                let inlay_offset = fold_offset.to_inlay_offset(&snapshot);
1448                assert_eq!(
1449                    snapshot.to_fold_point(inlay_point, Right),
1450                    fold_point,
1451                    "{:?} -> fold point",
1452                    inlay_point,
1453                );
1454                assert_eq!(
1455                    inlay_snapshot.to_offset(inlay_point),
1456                    inlay_offset,
1457                    "inlay_snapshot.to_offset({:?})",
1458                    inlay_point,
1459                );
1460                assert_eq!(
1461                    fold_point.to_offset(&snapshot),
1462                    fold_offset,
1463                    "fold_point.to_offset({:?})",
1464                    fold_point,
1465                );
1466
1467                if c == '\n' {
1468                    *fold_point.row_mut() += 1;
1469                    *fold_point.column_mut() = 0;
1470                    char_column = 0;
1471                } else {
1472                    *fold_point.column_mut() += c.len_utf8() as u32;
1473                    char_column += 1;
1474                }
1475                fold_offset.0 += c.len_utf8();
1476                if char_column > longest_char_column {
1477                    panic!(
1478                        "invalid longest row {:?} (chars {}), found row {:?} (chars: {})",
1479                        longest_row,
1480                        longest_char_column,
1481                        fold_point.row(),
1482                        char_column
1483                    );
1484                }
1485            }
1486
1487            for _ in 0..5 {
1488                let mut start = snapshot
1489                    .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Left);
1490                let mut end = snapshot
1491                    .clip_offset(FoldOffset(rng.gen_range(0..=snapshot.len().0)), Bias::Right);
1492                if start > end {
1493                    mem::swap(&mut start, &mut end);
1494                }
1495
1496                let text = &expected_text[start.0..end.0];
1497                assert_eq!(
1498                    snapshot
1499                        .chunks(start..end, false, Highlights::default())
1500                        .map(|c| c.text)
1501                        .collect::<String>(),
1502                    text,
1503                );
1504            }
1505
1506            let mut fold_row = 0;
1507            while fold_row < expected_buffer_rows.len() as u32 {
1508                assert_eq!(
1509                    snapshot.buffer_rows(fold_row).collect::<Vec<_>>(),
1510                    expected_buffer_rows[(fold_row as usize)..],
1511                    "wrong buffer rows starting at fold row {}",
1512                    fold_row,
1513                );
1514                fold_row += 1;
1515            }
1516
1517            let folded_buffer_rows = map
1518                .merged_fold_ranges()
1519                .iter()
1520                .flat_map(|range| {
1521                    let start_row = range.start.to_point(&buffer_snapshot).row;
1522                    let end = range.end.to_point(&buffer_snapshot);
1523                    if end.column == 0 {
1524                        start_row..end.row
1525                    } else {
1526                        start_row..end.row + 1
1527                    }
1528                })
1529                .collect::<HashSet<_>>();
1530            for row in 0..=buffer_snapshot.max_point().row {
1531                assert_eq!(
1532                    snapshot.is_line_folded(row),
1533                    folded_buffer_rows.contains(&row),
1534                    "expected buffer row {}{} to be folded",
1535                    row,
1536                    if folded_buffer_rows.contains(&row) {
1537                        ""
1538                    } else {
1539                        " not"
1540                    }
1541                );
1542            }
1543
1544            for _ in 0..5 {
1545                let end =
1546                    buffer_snapshot.clip_offset(rng.gen_range(0..=buffer_snapshot.len()), Right);
1547                let start = buffer_snapshot.clip_offset(rng.gen_range(0..=end), Left);
1548                let expected_folds = map
1549                    .snapshot
1550                    .folds
1551                    .items(&buffer_snapshot)
1552                    .into_iter()
1553                    .filter(|fold| {
1554                        let start = buffer_snapshot.anchor_before(start);
1555                        let end = buffer_snapshot.anchor_after(end);
1556                        start.cmp(&fold.0.end, &buffer_snapshot) == Ordering::Less
1557                            && end.cmp(&fold.0.start, &buffer_snapshot) == Ordering::Greater
1558                    })
1559                    .map(|fold| fold.0)
1560                    .collect::<Vec<_>>();
1561
1562                assert_eq!(
1563                    snapshot
1564                        .folds_in_range(start..end)
1565                        .cloned()
1566                        .collect::<Vec<_>>(),
1567                    expected_folds
1568                );
1569            }
1570
1571            let text = snapshot.text();
1572            for _ in 0..5 {
1573                let start_row = rng.gen_range(0..=snapshot.max_point().row());
1574                let start_column = rng.gen_range(0..=snapshot.line_len(start_row));
1575                let end_row = rng.gen_range(0..=snapshot.max_point().row());
1576                let end_column = rng.gen_range(0..=snapshot.line_len(end_row));
1577                let mut start =
1578                    snapshot.clip_point(FoldPoint::new(start_row, start_column), Bias::Left);
1579                let mut end = snapshot.clip_point(FoldPoint::new(end_row, end_column), Bias::Right);
1580                if start > end {
1581                    mem::swap(&mut start, &mut end);
1582                }
1583
1584                let lines = start..end;
1585                let bytes = start.to_offset(&snapshot)..end.to_offset(&snapshot);
1586                assert_eq!(
1587                    snapshot.text_summary_for_range(lines),
1588                    TextSummary::from(&text[bytes.start.0..bytes.end.0])
1589                )
1590            }
1591
1592            let mut text = initial_snapshot.text();
1593            for (snapshot, edits) in snapshot_edits.drain(..) {
1594                let new_text = snapshot.text();
1595                for edit in edits {
1596                    let old_bytes = edit.new.start.0..edit.new.start.0 + edit.old_len().0;
1597                    let new_bytes = edit.new.start.0..edit.new.end.0;
1598                    text.replace_range(old_bytes, &new_text[new_bytes]);
1599                }
1600
1601                assert_eq!(text, new_text);
1602                initial_snapshot = snapshot;
1603            }
1604        }
1605    }
1606
1607    #[gpui::test]
1608    fn test_buffer_rows(cx: &mut gpui::AppContext) {
1609        let text = sample_text(6, 6, 'a') + "\n";
1610        let buffer = MultiBuffer::build_simple(&text, cx);
1611
1612        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1613        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1614        let mut map = FoldMap::new(inlay_snapshot.clone()).0;
1615
1616        let (mut writer, _, _) = map.write(inlay_snapshot.clone(), vec![]);
1617        writer.fold(vec![
1618            Point::new(0, 2)..Point::new(2, 2),
1619            Point::new(3, 1)..Point::new(4, 1),
1620        ]);
1621
1622        let (snapshot, _) = map.read(inlay_snapshot, vec![]);
1623        assert_eq!(snapshot.text(), "aa⋯cccc\nd⋯eeeee\nffffff\n");
1624        assert_eq!(
1625            snapshot.buffer_rows(0).collect::<Vec<_>>(),
1626            [Some(0), Some(3), Some(5), Some(6)]
1627        );
1628        assert_eq!(snapshot.buffer_rows(3).collect::<Vec<_>>(), [Some(6)]);
1629    }
1630
1631    fn init_test(cx: &mut gpui::AppContext) {
1632        cx.set_global(SettingsStore::test(cx));
1633    }
1634
1635    impl FoldMap {
1636        fn merged_fold_ranges(&self) -> Vec<Range<usize>> {
1637            let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1638            let buffer = &inlay_snapshot.buffer;
1639            let mut folds = self.snapshot.folds.items(buffer);
1640            // Ensure sorting doesn't change how folds get merged and displayed.
1641            folds.sort_by(|a, b| a.0.cmp(&b.0, buffer));
1642            let mut fold_ranges = folds
1643                .iter()
1644                .map(|fold| fold.0.start.to_offset(buffer)..fold.0.end.to_offset(buffer))
1645                .peekable();
1646
1647            let mut merged_ranges = Vec::new();
1648            while let Some(mut fold_range) = fold_ranges.next() {
1649                while let Some(next_range) = fold_ranges.peek() {
1650                    if fold_range.end >= next_range.start {
1651                        if next_range.end > fold_range.end {
1652                            fold_range.end = next_range.end;
1653                        }
1654                        fold_ranges.next();
1655                    } else {
1656                        break;
1657                    }
1658                }
1659                if fold_range.end > fold_range.start {
1660                    merged_ranges.push(fold_range);
1661                }
1662            }
1663            merged_ranges
1664        }
1665
1666        pub fn randomly_mutate(
1667            &mut self,
1668            rng: &mut impl Rng,
1669        ) -> Vec<(FoldSnapshot, Vec<FoldEdit>)> {
1670            let mut snapshot_edits = Vec::new();
1671            match rng.gen_range(0..=100) {
1672                0..=39 if !self.snapshot.folds.is_empty() => {
1673                    let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1674                    let buffer = &inlay_snapshot.buffer;
1675                    let mut to_unfold = Vec::new();
1676                    for _ in 0..rng.gen_range(1..=3) {
1677                        let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1678                        let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1679                        to_unfold.push(start..end);
1680                    }
1681                    log::info!("unfolding {:?}", to_unfold);
1682                    let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
1683                    snapshot_edits.push((snapshot, edits));
1684                    let (snapshot, edits) = writer.fold(to_unfold);
1685                    snapshot_edits.push((snapshot, edits));
1686                }
1687                _ => {
1688                    let inlay_snapshot = self.snapshot.inlay_snapshot.clone();
1689                    let buffer = &inlay_snapshot.buffer;
1690                    let mut to_fold = Vec::new();
1691                    for _ in 0..rng.gen_range(1..=2) {
1692                        let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1693                        let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1694                        to_fold.push(start..end);
1695                    }
1696                    log::info!("folding {:?}", to_fold);
1697                    let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
1698                    snapshot_edits.push((snapshot, edits));
1699                    let (snapshot, edits) = writer.fold(to_fold);
1700                    snapshot_edits.push((snapshot, edits));
1701                }
1702            }
1703            snapshot_edits
1704        }
1705    }
1706}