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