fold_map.rs

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