fold_map.rs

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