inlay_map.rs

   1use crate::{HighlightStyles, InlayId};
   2use collections::{BTreeMap, BTreeSet};
   3use gpui::HighlightStyle;
   4use language::{Chunk, Edit, Point, TextSummary};
   5use multi_buffer::{
   6    Anchor, MultiBufferChunks, MultiBufferRow, MultiBufferRows, MultiBufferSnapshot, ToOffset,
   7};
   8use std::{
   9    any::TypeId,
  10    cmp,
  11    iter::Peekable,
  12    ops::{Add, AddAssign, Range, Sub, SubAssign},
  13    sync::Arc,
  14    vec,
  15};
  16use sum_tree::{Bias, Cursor, SumTree, TreeMap};
  17use text::{Patch, Rope};
  18
  19use super::Highlights;
  20
  21/// Decides where the [`Inlay`]s should be displayed.
  22///
  23/// See the [`display_map` module documentation](crate::display_map) for more information.
  24pub struct InlayMap {
  25    snapshot: InlaySnapshot,
  26    inlays: Vec<Inlay>,
  27}
  28
  29#[derive(Clone)]
  30pub struct InlaySnapshot {
  31    pub buffer: MultiBufferSnapshot,
  32    transforms: SumTree<Transform>,
  33    pub version: usize,
  34}
  35
  36#[derive(Clone, Debug)]
  37enum Transform {
  38    Isomorphic(TextSummary),
  39    Inlay(Inlay),
  40}
  41
  42#[derive(Debug, Clone)]
  43pub(crate) struct Inlay {
  44    pub(crate) id: InlayId,
  45    pub position: Anchor,
  46    pub text: text::Rope,
  47}
  48
  49impl Inlay {
  50    pub fn hint(id: usize, position: Anchor, hint: &project::InlayHint) -> Self {
  51        let mut text = hint.text();
  52        if hint.padding_right && !text.ends_with(' ') {
  53            text.push(' ');
  54        }
  55        if hint.padding_left && !text.starts_with(' ') {
  56            text.insert(0, ' ');
  57        }
  58        Self {
  59            id: InlayId::Hint(id),
  60            position,
  61            text: text.into(),
  62        }
  63    }
  64
  65    pub fn suggestion<T: Into<Rope>>(id: usize, position: Anchor, text: T) -> Self {
  66        Self {
  67            id: InlayId::Suggestion(id),
  68            position,
  69            text: text.into(),
  70        }
  71    }
  72}
  73
  74impl sum_tree::Item for Transform {
  75    type Summary = TransformSummary;
  76
  77    fn summary(&self) -> Self::Summary {
  78        match self {
  79            Transform::Isomorphic(summary) => TransformSummary {
  80                input: summary.clone(),
  81                output: summary.clone(),
  82            },
  83            Transform::Inlay(inlay) => TransformSummary {
  84                input: TextSummary::default(),
  85                output: inlay.text.summary(),
  86            },
  87        }
  88    }
  89}
  90
  91#[derive(Clone, Debug, Default)]
  92struct TransformSummary {
  93    input: TextSummary,
  94    output: TextSummary,
  95}
  96
  97impl sum_tree::Summary for TransformSummary {
  98    type Context = ();
  99
 100    fn add_summary(&mut self, other: &Self, _: &()) {
 101        self.input += &other.input;
 102        self.output += &other.output;
 103    }
 104}
 105
 106pub type InlayEdit = Edit<InlayOffset>;
 107
 108#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 109pub struct InlayOffset(pub usize);
 110
 111impl Add for InlayOffset {
 112    type Output = Self;
 113
 114    fn add(self, rhs: Self) -> Self::Output {
 115        Self(self.0 + rhs.0)
 116    }
 117}
 118
 119impl Sub for InlayOffset {
 120    type Output = Self;
 121
 122    fn sub(self, rhs: Self) -> Self::Output {
 123        Self(self.0 - rhs.0)
 124    }
 125}
 126
 127impl AddAssign for InlayOffset {
 128    fn add_assign(&mut self, rhs: Self) {
 129        self.0 += rhs.0;
 130    }
 131}
 132
 133impl SubAssign for InlayOffset {
 134    fn sub_assign(&mut self, rhs: Self) {
 135        self.0 -= rhs.0;
 136    }
 137}
 138
 139impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
 140    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 141        self.0 += &summary.output.len;
 142    }
 143}
 144
 145#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 146pub struct InlayPoint(pub Point);
 147
 148impl Add for InlayPoint {
 149    type Output = Self;
 150
 151    fn add(self, rhs: Self) -> Self::Output {
 152        Self(self.0 + rhs.0)
 153    }
 154}
 155
 156impl Sub for InlayPoint {
 157    type Output = Self;
 158
 159    fn sub(self, rhs: Self) -> Self::Output {
 160        Self(self.0 - rhs.0)
 161    }
 162}
 163
 164impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
 165    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 166        self.0 += &summary.output.lines;
 167    }
 168}
 169
 170impl<'a> sum_tree::Dimension<'a, TransformSummary> for usize {
 171    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 172        *self += &summary.input.len;
 173    }
 174}
 175
 176impl<'a> sum_tree::Dimension<'a, TransformSummary> for Point {
 177    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 178        *self += &summary.input.lines;
 179    }
 180}
 181
 182#[derive(Clone)]
 183pub struct InlayBufferRows<'a> {
 184    transforms: Cursor<'a, Transform, (InlayPoint, Point)>,
 185    buffer_rows: MultiBufferRows<'a>,
 186    inlay_row: u32,
 187    max_buffer_row: MultiBufferRow,
 188}
 189
 190#[derive(Debug, Copy, Clone, Eq, PartialEq)]
 191struct HighlightEndpoint {
 192    offset: InlayOffset,
 193    is_start: bool,
 194    tag: Option<TypeId>,
 195    style: HighlightStyle,
 196}
 197
 198impl PartialOrd for HighlightEndpoint {
 199    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
 200        Some(self.cmp(other))
 201    }
 202}
 203
 204impl Ord for HighlightEndpoint {
 205    fn cmp(&self, other: &Self) -> cmp::Ordering {
 206        self.offset
 207            .cmp(&other.offset)
 208            .then_with(|| other.is_start.cmp(&self.is_start))
 209    }
 210}
 211
 212pub struct InlayChunks<'a> {
 213    transforms: Cursor<'a, Transform, (InlayOffset, usize)>,
 214    buffer_chunks: MultiBufferChunks<'a>,
 215    buffer_chunk: Option<Chunk<'a>>,
 216    inlay_chunks: Option<text::Chunks<'a>>,
 217    inlay_chunk: Option<&'a str>,
 218    output_offset: InlayOffset,
 219    max_output_offset: InlayOffset,
 220    highlight_styles: HighlightStyles,
 221    highlight_endpoints: Peekable<vec::IntoIter<HighlightEndpoint>>,
 222    active_highlights: BTreeMap<Option<TypeId>, HighlightStyle>,
 223    highlights: Highlights<'a>,
 224    snapshot: &'a InlaySnapshot,
 225}
 226
 227impl<'a> InlayChunks<'a> {
 228    pub fn seek(&mut self, offset: InlayOffset) {
 229        self.transforms.seek(&offset, Bias::Right, &());
 230
 231        let buffer_offset = self.snapshot.to_buffer_offset(offset);
 232        self.buffer_chunks.seek(buffer_offset);
 233        self.inlay_chunks = None;
 234        self.buffer_chunk = None;
 235        self.output_offset = offset;
 236    }
 237
 238    pub fn offset(&self) -> InlayOffset {
 239        self.output_offset
 240    }
 241}
 242
 243impl<'a> Iterator for InlayChunks<'a> {
 244    type Item = Chunk<'a>;
 245
 246    fn next(&mut self) -> Option<Self::Item> {
 247        if self.output_offset == self.max_output_offset {
 248            return None;
 249        }
 250
 251        let mut next_highlight_endpoint = InlayOffset(usize::MAX);
 252        while let Some(endpoint) = self.highlight_endpoints.peek().copied() {
 253            if endpoint.offset <= self.output_offset {
 254                if endpoint.is_start {
 255                    self.active_highlights.insert(endpoint.tag, endpoint.style);
 256                } else {
 257                    self.active_highlights.remove(&endpoint.tag);
 258                }
 259                self.highlight_endpoints.next();
 260            } else {
 261                next_highlight_endpoint = endpoint.offset;
 262                break;
 263            }
 264        }
 265
 266        let chunk = match self.transforms.item()? {
 267            Transform::Isomorphic(_) => {
 268                let chunk = self
 269                    .buffer_chunk
 270                    .get_or_insert_with(|| self.buffer_chunks.next().unwrap());
 271                if chunk.text.is_empty() {
 272                    *chunk = self.buffer_chunks.next().unwrap();
 273                }
 274
 275                let (prefix, suffix) = chunk.text.split_at(
 276                    chunk
 277                        .text
 278                        .len()
 279                        .min(self.transforms.end(&()).0 .0 - self.output_offset.0)
 280                        .min(next_highlight_endpoint.0 - self.output_offset.0),
 281                );
 282
 283                chunk.text = suffix;
 284                self.output_offset.0 += prefix.len();
 285                let mut prefix = Chunk {
 286                    text: prefix,
 287                    ..chunk.clone()
 288                };
 289                if !self.active_highlights.is_empty() {
 290                    let mut highlight_style = HighlightStyle::default();
 291                    for active_highlight in self.active_highlights.values() {
 292                        highlight_style.highlight(*active_highlight);
 293                    }
 294                    prefix.highlight_style = Some(highlight_style);
 295                }
 296                prefix
 297            }
 298            Transform::Inlay(inlay) => {
 299                let mut inlay_style_and_highlight = None;
 300                if let Some(inlay_highlights) = self.highlights.inlay_highlights {
 301                    for (_, inlay_id_to_data) in inlay_highlights.iter() {
 302                        let style_and_highlight = inlay_id_to_data.get(&inlay.id);
 303                        if style_and_highlight.is_some() {
 304                            inlay_style_and_highlight = style_and_highlight;
 305                            break;
 306                        }
 307                    }
 308                }
 309
 310                let mut highlight_style = match inlay.id {
 311                    InlayId::Suggestion(_) => self.highlight_styles.suggestion,
 312                    InlayId::Hint(_) => self.highlight_styles.inlay_hint,
 313                };
 314                let next_inlay_highlight_endpoint;
 315                let offset_in_inlay = self.output_offset - self.transforms.start().0;
 316                if let Some((style, highlight)) = inlay_style_and_highlight {
 317                    let range = &highlight.range;
 318                    if offset_in_inlay.0 < range.start {
 319                        next_inlay_highlight_endpoint = range.start - offset_in_inlay.0;
 320                    } else if offset_in_inlay.0 >= range.end {
 321                        next_inlay_highlight_endpoint = usize::MAX;
 322                    } else {
 323                        next_inlay_highlight_endpoint = range.end - offset_in_inlay.0;
 324                        highlight_style
 325                            .get_or_insert_with(|| Default::default())
 326                            .highlight(*style);
 327                    }
 328                } else {
 329                    next_inlay_highlight_endpoint = usize::MAX;
 330                }
 331
 332                let inlay_chunks = self.inlay_chunks.get_or_insert_with(|| {
 333                    let start = offset_in_inlay;
 334                    let end = cmp::min(self.max_output_offset, self.transforms.end(&()).0)
 335                        - self.transforms.start().0;
 336                    inlay.text.chunks_in_range(start.0..end.0)
 337                });
 338                let inlay_chunk = self
 339                    .inlay_chunk
 340                    .get_or_insert_with(|| inlay_chunks.next().unwrap());
 341                let (chunk, remainder) =
 342                    inlay_chunk.split_at(inlay_chunk.len().min(next_inlay_highlight_endpoint));
 343                *inlay_chunk = remainder;
 344                if inlay_chunk.is_empty() {
 345                    self.inlay_chunk = None;
 346                }
 347
 348                self.output_offset.0 += chunk.len();
 349
 350                if !self.active_highlights.is_empty() {
 351                    for active_highlight in self.active_highlights.values() {
 352                        highlight_style
 353                            .get_or_insert(Default::default())
 354                            .highlight(*active_highlight);
 355                    }
 356                }
 357                Chunk {
 358                    text: chunk,
 359                    highlight_style,
 360                    ..Default::default()
 361                }
 362            }
 363        };
 364
 365        if self.output_offset == self.transforms.end(&()).0 {
 366            self.inlay_chunks = None;
 367            self.transforms.next(&());
 368        }
 369
 370        Some(chunk)
 371    }
 372}
 373
 374impl<'a> InlayBufferRows<'a> {
 375    pub fn seek(&mut self, row: u32) {
 376        let inlay_point = InlayPoint::new(row, 0);
 377        self.transforms.seek(&inlay_point, Bias::Left, &());
 378
 379        let mut buffer_point = self.transforms.start().1;
 380        let buffer_row = MultiBufferRow(if row == 0 {
 381            0
 382        } else {
 383            match self.transforms.item() {
 384                Some(Transform::Isomorphic(_)) => {
 385                    buffer_point += inlay_point.0 - self.transforms.start().0 .0;
 386                    buffer_point.row
 387                }
 388                _ => cmp::min(buffer_point.row + 1, self.max_buffer_row.0),
 389            }
 390        });
 391        self.inlay_row = inlay_point.row();
 392        self.buffer_rows.seek(buffer_row);
 393    }
 394}
 395
 396impl<'a> Iterator for InlayBufferRows<'a> {
 397    type Item = Option<u32>;
 398
 399    fn next(&mut self) -> Option<Self::Item> {
 400        let buffer_row = if self.inlay_row == 0 {
 401            self.buffer_rows.next().unwrap()
 402        } else {
 403            match self.transforms.item()? {
 404                Transform::Inlay(_) => None,
 405                Transform::Isomorphic(_) => self.buffer_rows.next().unwrap(),
 406            }
 407        };
 408
 409        self.inlay_row += 1;
 410        self.transforms
 411            .seek_forward(&InlayPoint::new(self.inlay_row, 0), Bias::Left, &());
 412
 413        Some(buffer_row)
 414    }
 415}
 416
 417impl InlayPoint {
 418    pub fn new(row: u32, column: u32) -> Self {
 419        Self(Point::new(row, column))
 420    }
 421
 422    pub fn row(self) -> u32 {
 423        self.0.row
 424    }
 425}
 426
 427impl InlayMap {
 428    pub fn new(buffer: MultiBufferSnapshot) -> (Self, InlaySnapshot) {
 429        let version = 0;
 430        let snapshot = InlaySnapshot {
 431            buffer: buffer.clone(),
 432            transforms: SumTree::from_iter(Some(Transform::Isomorphic(buffer.text_summary())), &()),
 433            version,
 434        };
 435
 436        (
 437            Self {
 438                snapshot: snapshot.clone(),
 439                inlays: Vec::new(),
 440            },
 441            snapshot,
 442        )
 443    }
 444
 445    pub fn sync(
 446        &mut self,
 447        buffer_snapshot: MultiBufferSnapshot,
 448        mut buffer_edits: Vec<text::Edit<usize>>,
 449    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 450        let snapshot = &mut self.snapshot;
 451
 452        if buffer_edits.is_empty() {
 453            if snapshot.buffer.trailing_excerpt_update_count()
 454                != buffer_snapshot.trailing_excerpt_update_count()
 455            {
 456                buffer_edits.push(Edit {
 457                    old: snapshot.buffer.len()..snapshot.buffer.len(),
 458                    new: buffer_snapshot.len()..buffer_snapshot.len(),
 459                });
 460            }
 461        }
 462
 463        if buffer_edits.is_empty() {
 464            if snapshot.buffer.edit_count() != buffer_snapshot.edit_count()
 465                || snapshot.buffer.parse_count() != buffer_snapshot.parse_count()
 466                || snapshot.buffer.diagnostics_update_count()
 467                    != buffer_snapshot.diagnostics_update_count()
 468                || snapshot.buffer.git_diff_update_count()
 469                    != buffer_snapshot.git_diff_update_count()
 470                || snapshot.buffer.trailing_excerpt_update_count()
 471                    != buffer_snapshot.trailing_excerpt_update_count()
 472            {
 473                snapshot.version += 1;
 474            }
 475
 476            snapshot.buffer = buffer_snapshot;
 477            (snapshot.clone(), Vec::new())
 478        } else {
 479            let mut inlay_edits = Patch::default();
 480            let mut new_transforms = SumTree::new();
 481            let mut cursor = snapshot.transforms.cursor::<(usize, InlayOffset)>();
 482            let mut buffer_edits_iter = buffer_edits.iter().peekable();
 483            while let Some(buffer_edit) = buffer_edits_iter.next() {
 484                new_transforms.append(cursor.slice(&buffer_edit.old.start, Bias::Left, &()), &());
 485                if let Some(Transform::Isomorphic(transform)) = cursor.item() {
 486                    if cursor.end(&()).0 == buffer_edit.old.start {
 487                        push_isomorphic(&mut new_transforms, transform.clone());
 488                        cursor.next(&());
 489                    }
 490                }
 491
 492                // Remove all the inlays and transforms contained by the edit.
 493                let old_start =
 494                    cursor.start().1 + InlayOffset(buffer_edit.old.start - cursor.start().0);
 495                cursor.seek(&buffer_edit.old.end, Bias::Right, &());
 496                let old_end =
 497                    cursor.start().1 + InlayOffset(buffer_edit.old.end - cursor.start().0);
 498
 499                // Push the unchanged prefix.
 500                let prefix_start = new_transforms.summary().input.len;
 501                let prefix_end = buffer_edit.new.start;
 502                push_isomorphic(
 503                    &mut new_transforms,
 504                    buffer_snapshot.text_summary_for_range(prefix_start..prefix_end),
 505                );
 506                let new_start = InlayOffset(new_transforms.summary().output.len);
 507
 508                let start_ix = match self.inlays.binary_search_by(|probe| {
 509                    probe
 510                        .position
 511                        .to_offset(&buffer_snapshot)
 512                        .cmp(&buffer_edit.new.start)
 513                        .then(std::cmp::Ordering::Greater)
 514                }) {
 515                    Ok(ix) | Err(ix) => ix,
 516                };
 517
 518                for inlay in &self.inlays[start_ix..] {
 519                    let buffer_offset = inlay.position.to_offset(&buffer_snapshot);
 520                    if buffer_offset > buffer_edit.new.end {
 521                        break;
 522                    }
 523
 524                    let prefix_start = new_transforms.summary().input.len;
 525                    let prefix_end = buffer_offset;
 526                    push_isomorphic(
 527                        &mut new_transforms,
 528                        buffer_snapshot.text_summary_for_range(prefix_start..prefix_end),
 529                    );
 530
 531                    if inlay.position.is_valid(&buffer_snapshot) {
 532                        new_transforms.push(Transform::Inlay(inlay.clone()), &());
 533                    }
 534                }
 535
 536                // Apply the rest of the edit.
 537                let transform_start = new_transforms.summary().input.len;
 538                push_isomorphic(
 539                    &mut new_transforms,
 540                    buffer_snapshot.text_summary_for_range(transform_start..buffer_edit.new.end),
 541                );
 542                let new_end = InlayOffset(new_transforms.summary().output.len);
 543                inlay_edits.push(Edit {
 544                    old: old_start..old_end,
 545                    new: new_start..new_end,
 546                });
 547
 548                // If the next edit doesn't intersect the current isomorphic transform, then
 549                // we can push its remainder.
 550                if buffer_edits_iter
 551                    .peek()
 552                    .map_or(true, |edit| edit.old.start >= cursor.end(&()).0)
 553                {
 554                    let transform_start = new_transforms.summary().input.len;
 555                    let transform_end =
 556                        buffer_edit.new.end + (cursor.end(&()).0 - buffer_edit.old.end);
 557                    push_isomorphic(
 558                        &mut new_transforms,
 559                        buffer_snapshot.text_summary_for_range(transform_start..transform_end),
 560                    );
 561                    cursor.next(&());
 562                }
 563            }
 564
 565            new_transforms.append(cursor.suffix(&()), &());
 566            if new_transforms.is_empty() {
 567                new_transforms.push(Transform::Isomorphic(Default::default()), &());
 568            }
 569
 570            drop(cursor);
 571            snapshot.transforms = new_transforms;
 572            snapshot.version += 1;
 573            snapshot.buffer = buffer_snapshot;
 574            snapshot.check_invariants();
 575
 576            (snapshot.clone(), inlay_edits.into_inner())
 577        }
 578    }
 579
 580    pub fn splice(
 581        &mut self,
 582        to_remove: Vec<InlayId>,
 583        to_insert: Vec<Inlay>,
 584    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 585        let snapshot = &mut self.snapshot;
 586        let mut edits = BTreeSet::new();
 587
 588        self.inlays.retain(|inlay| {
 589            let retain = !to_remove.contains(&inlay.id);
 590            if !retain {
 591                let offset = inlay.position.to_offset(&snapshot.buffer);
 592                edits.insert(offset);
 593            }
 594            retain
 595        });
 596
 597        for inlay_to_insert in to_insert {
 598            // Avoid inserting empty inlays.
 599            if inlay_to_insert.text.is_empty() {
 600                continue;
 601            }
 602
 603            let offset = inlay_to_insert.position.to_offset(&snapshot.buffer);
 604            match self.inlays.binary_search_by(|probe| {
 605                probe
 606                    .position
 607                    .cmp(&inlay_to_insert.position, &snapshot.buffer)
 608            }) {
 609                Ok(ix) | Err(ix) => {
 610                    self.inlays.insert(ix, inlay_to_insert);
 611                }
 612            }
 613
 614            edits.insert(offset);
 615        }
 616
 617        let buffer_edits = edits
 618            .into_iter()
 619            .map(|offset| Edit {
 620                old: offset..offset,
 621                new: offset..offset,
 622            })
 623            .collect();
 624        let buffer_snapshot = snapshot.buffer.clone();
 625        let (snapshot, edits) = self.sync(buffer_snapshot, buffer_edits);
 626        (snapshot, edits)
 627    }
 628
 629    pub fn current_inlays(&self) -> impl Iterator<Item = &Inlay> {
 630        self.inlays.iter()
 631    }
 632
 633    #[cfg(test)]
 634    pub(crate) fn randomly_mutate(
 635        &mut self,
 636        next_inlay_id: &mut usize,
 637        rng: &mut rand::rngs::StdRng,
 638    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 639        use rand::prelude::*;
 640        use util::post_inc;
 641
 642        let mut to_remove = Vec::new();
 643        let mut to_insert = Vec::new();
 644        let snapshot = &mut self.snapshot;
 645        for i in 0..rng.gen_range(1..=5) {
 646            if self.inlays.is_empty() || rng.gen() {
 647                let position = snapshot.buffer.random_byte_range(0, rng).start;
 648                let bias = if rng.gen() { Bias::Left } else { Bias::Right };
 649                let len = if rng.gen_bool(0.01) {
 650                    0
 651                } else {
 652                    rng.gen_range(1..=5)
 653                };
 654                let text = util::RandomCharIter::new(&mut *rng)
 655                    .filter(|ch| *ch != '\r')
 656                    .take(len)
 657                    .collect::<String>();
 658
 659                let inlay_id = if i % 2 == 0 {
 660                    InlayId::Hint(post_inc(next_inlay_id))
 661                } else {
 662                    InlayId::Suggestion(post_inc(next_inlay_id))
 663                };
 664                log::info!(
 665                    "creating inlay {:?} at buffer offset {} with bias {:?} and text {:?}",
 666                    inlay_id,
 667                    position,
 668                    bias,
 669                    text
 670                );
 671
 672                to_insert.push(Inlay {
 673                    id: inlay_id,
 674                    position: snapshot.buffer.anchor_at(position, bias),
 675                    text: text.into(),
 676                });
 677            } else {
 678                to_remove.push(
 679                    self.inlays
 680                        .iter()
 681                        .choose(rng)
 682                        .map(|inlay| inlay.id)
 683                        .unwrap(),
 684                );
 685            }
 686        }
 687        log::info!("removing inlays: {:?}", to_remove);
 688
 689        let (snapshot, edits) = self.splice(to_remove, to_insert);
 690        (snapshot, edits)
 691    }
 692}
 693
 694impl InlaySnapshot {
 695    pub fn to_point(&self, offset: InlayOffset) -> InlayPoint {
 696        let mut cursor = self
 697            .transforms
 698            .cursor::<(InlayOffset, (InlayPoint, usize))>();
 699        cursor.seek(&offset, Bias::Right, &());
 700        let overshoot = offset.0 - cursor.start().0 .0;
 701        match cursor.item() {
 702            Some(Transform::Isomorphic(_)) => {
 703                let buffer_offset_start = cursor.start().1 .1;
 704                let buffer_offset_end = buffer_offset_start + overshoot;
 705                let buffer_start = self.buffer.offset_to_point(buffer_offset_start);
 706                let buffer_end = self.buffer.offset_to_point(buffer_offset_end);
 707                InlayPoint(cursor.start().1 .0 .0 + (buffer_end - buffer_start))
 708            }
 709            Some(Transform::Inlay(inlay)) => {
 710                let overshoot = inlay.text.offset_to_point(overshoot);
 711                InlayPoint(cursor.start().1 .0 .0 + overshoot)
 712            }
 713            None => self.max_point(),
 714        }
 715    }
 716
 717    pub fn len(&self) -> InlayOffset {
 718        InlayOffset(self.transforms.summary().output.len)
 719    }
 720
 721    pub fn max_point(&self) -> InlayPoint {
 722        InlayPoint(self.transforms.summary().output.lines)
 723    }
 724
 725    pub fn to_offset(&self, point: InlayPoint) -> InlayOffset {
 726        let mut cursor = self
 727            .transforms
 728            .cursor::<(InlayPoint, (InlayOffset, Point))>();
 729        cursor.seek(&point, Bias::Right, &());
 730        let overshoot = point.0 - cursor.start().0 .0;
 731        match cursor.item() {
 732            Some(Transform::Isomorphic(_)) => {
 733                let buffer_point_start = cursor.start().1 .1;
 734                let buffer_point_end = buffer_point_start + overshoot;
 735                let buffer_offset_start = self.buffer.point_to_offset(buffer_point_start);
 736                let buffer_offset_end = self.buffer.point_to_offset(buffer_point_end);
 737                InlayOffset(cursor.start().1 .0 .0 + (buffer_offset_end - buffer_offset_start))
 738            }
 739            Some(Transform::Inlay(inlay)) => {
 740                let overshoot = inlay.text.point_to_offset(overshoot);
 741                InlayOffset(cursor.start().1 .0 .0 + overshoot)
 742            }
 743            None => self.len(),
 744        }
 745    }
 746
 747    pub fn to_buffer_point(&self, point: InlayPoint) -> Point {
 748        let mut cursor = self.transforms.cursor::<(InlayPoint, Point)>();
 749        cursor.seek(&point, Bias::Right, &());
 750        match cursor.item() {
 751            Some(Transform::Isomorphic(_)) => {
 752                let overshoot = point.0 - cursor.start().0 .0;
 753                cursor.start().1 + overshoot
 754            }
 755            Some(Transform::Inlay(_)) => cursor.start().1,
 756            None => self.buffer.max_point(),
 757        }
 758    }
 759
 760    pub fn to_buffer_offset(&self, offset: InlayOffset) -> usize {
 761        let mut cursor = self.transforms.cursor::<(InlayOffset, usize)>();
 762        cursor.seek(&offset, Bias::Right, &());
 763        match cursor.item() {
 764            Some(Transform::Isomorphic(_)) => {
 765                let overshoot = offset - cursor.start().0;
 766                cursor.start().1 + overshoot.0
 767            }
 768            Some(Transform::Inlay(_)) => cursor.start().1,
 769            None => self.buffer.len(),
 770        }
 771    }
 772
 773    pub fn to_inlay_offset(&self, offset: usize) -> InlayOffset {
 774        let mut cursor = self.transforms.cursor::<(usize, InlayOffset)>();
 775        cursor.seek(&offset, Bias::Left, &());
 776        loop {
 777            match cursor.item() {
 778                Some(Transform::Isomorphic(_)) => {
 779                    if offset == cursor.end(&()).0 {
 780                        while let Some(Transform::Inlay(inlay)) = cursor.next_item() {
 781                            if inlay.position.bias() == Bias::Right {
 782                                break;
 783                            } else {
 784                                cursor.next(&());
 785                            }
 786                        }
 787                        return cursor.end(&()).1;
 788                    } else {
 789                        let overshoot = offset - cursor.start().0;
 790                        return InlayOffset(cursor.start().1 .0 + overshoot);
 791                    }
 792                }
 793                Some(Transform::Inlay(inlay)) => {
 794                    if inlay.position.bias() == Bias::Left {
 795                        cursor.next(&());
 796                    } else {
 797                        return cursor.start().1;
 798                    }
 799                }
 800                None => {
 801                    return self.len();
 802                }
 803            }
 804        }
 805    }
 806
 807    pub fn to_inlay_point(&self, point: Point) -> InlayPoint {
 808        let mut cursor = self.transforms.cursor::<(Point, InlayPoint)>();
 809        cursor.seek(&point, Bias::Left, &());
 810        loop {
 811            match cursor.item() {
 812                Some(Transform::Isomorphic(_)) => {
 813                    if point == cursor.end(&()).0 {
 814                        while let Some(Transform::Inlay(inlay)) = cursor.next_item() {
 815                            if inlay.position.bias() == Bias::Right {
 816                                break;
 817                            } else {
 818                                cursor.next(&());
 819                            }
 820                        }
 821                        return cursor.end(&()).1;
 822                    } else {
 823                        let overshoot = point - cursor.start().0;
 824                        return InlayPoint(cursor.start().1 .0 + overshoot);
 825                    }
 826                }
 827                Some(Transform::Inlay(inlay)) => {
 828                    if inlay.position.bias() == Bias::Left {
 829                        cursor.next(&());
 830                    } else {
 831                        return cursor.start().1;
 832                    }
 833                }
 834                None => {
 835                    return self.max_point();
 836                }
 837            }
 838        }
 839    }
 840
 841    pub fn clip_point(&self, mut point: InlayPoint, mut bias: Bias) -> InlayPoint {
 842        let mut cursor = self.transforms.cursor::<(InlayPoint, Point)>();
 843        cursor.seek(&point, Bias::Left, &());
 844        loop {
 845            match cursor.item() {
 846                Some(Transform::Isomorphic(transform)) => {
 847                    if cursor.start().0 == point {
 848                        if let Some(Transform::Inlay(inlay)) = cursor.prev_item() {
 849                            if inlay.position.bias() == Bias::Left {
 850                                return point;
 851                            } else if bias == Bias::Left {
 852                                cursor.prev(&());
 853                            } else if transform.first_line_chars == 0 {
 854                                point.0 += Point::new(1, 0);
 855                            } else {
 856                                point.0 += Point::new(0, 1);
 857                            }
 858                        } else {
 859                            return point;
 860                        }
 861                    } else if cursor.end(&()).0 == point {
 862                        if let Some(Transform::Inlay(inlay)) = cursor.next_item() {
 863                            if inlay.position.bias() == Bias::Right {
 864                                return point;
 865                            } else if bias == Bias::Right {
 866                                cursor.next(&());
 867                            } else if point.0.column == 0 {
 868                                point.0.row -= 1;
 869                                point.0.column = self.line_len(point.0.row);
 870                            } else {
 871                                point.0.column -= 1;
 872                            }
 873                        } else {
 874                            return point;
 875                        }
 876                    } else {
 877                        let overshoot = point.0 - cursor.start().0 .0;
 878                        let buffer_point = cursor.start().1 + overshoot;
 879                        let clipped_buffer_point = self.buffer.clip_point(buffer_point, bias);
 880                        let clipped_overshoot = clipped_buffer_point - cursor.start().1;
 881                        let clipped_point = InlayPoint(cursor.start().0 .0 + clipped_overshoot);
 882                        if clipped_point == point {
 883                            return clipped_point;
 884                        } else {
 885                            point = clipped_point;
 886                        }
 887                    }
 888                }
 889                Some(Transform::Inlay(inlay)) => {
 890                    if point == cursor.start().0 && inlay.position.bias() == Bias::Right {
 891                        match cursor.prev_item() {
 892                            Some(Transform::Inlay(inlay)) => {
 893                                if inlay.position.bias() == Bias::Left {
 894                                    return point;
 895                                }
 896                            }
 897                            _ => return point,
 898                        }
 899                    } else if point == cursor.end(&()).0 && inlay.position.bias() == Bias::Left {
 900                        match cursor.next_item() {
 901                            Some(Transform::Inlay(inlay)) => {
 902                                if inlay.position.bias() == Bias::Right {
 903                                    return point;
 904                                }
 905                            }
 906                            _ => return point,
 907                        }
 908                    }
 909
 910                    if bias == Bias::Left {
 911                        point = cursor.start().0;
 912                        cursor.prev(&());
 913                    } else {
 914                        cursor.next(&());
 915                        point = cursor.start().0;
 916                    }
 917                }
 918                None => {
 919                    bias = bias.invert();
 920                    if bias == Bias::Left {
 921                        point = cursor.start().0;
 922                        cursor.prev(&());
 923                    } else {
 924                        cursor.next(&());
 925                        point = cursor.start().0;
 926                    }
 927                }
 928            }
 929        }
 930    }
 931
 932    pub fn text_summary(&self) -> TextSummary {
 933        self.transforms.summary().output.clone()
 934    }
 935
 936    pub fn text_summary_for_range(&self, range: Range<InlayOffset>) -> TextSummary {
 937        let mut summary = TextSummary::default();
 938
 939        let mut cursor = self.transforms.cursor::<(InlayOffset, usize)>();
 940        cursor.seek(&range.start, Bias::Right, &());
 941
 942        let overshoot = range.start.0 - cursor.start().0 .0;
 943        match cursor.item() {
 944            Some(Transform::Isomorphic(_)) => {
 945                let buffer_start = cursor.start().1;
 946                let suffix_start = buffer_start + overshoot;
 947                let suffix_end =
 948                    buffer_start + (cmp::min(cursor.end(&()).0, range.end).0 - cursor.start().0 .0);
 949                summary = self.buffer.text_summary_for_range(suffix_start..suffix_end);
 950                cursor.next(&());
 951            }
 952            Some(Transform::Inlay(inlay)) => {
 953                let suffix_start = overshoot;
 954                let suffix_end = cmp::min(cursor.end(&()).0, range.end).0 - cursor.start().0 .0;
 955                summary = inlay.text.cursor(suffix_start).summary(suffix_end);
 956                cursor.next(&());
 957            }
 958            None => {}
 959        }
 960
 961        if range.end > cursor.start().0 {
 962            summary += cursor
 963                .summary::<_, TransformSummary>(&range.end, Bias::Right, &())
 964                .output;
 965
 966            let overshoot = range.end.0 - cursor.start().0 .0;
 967            match cursor.item() {
 968                Some(Transform::Isomorphic(_)) => {
 969                    let prefix_start = cursor.start().1;
 970                    let prefix_end = prefix_start + overshoot;
 971                    summary += self
 972                        .buffer
 973                        .text_summary_for_range::<TextSummary, _>(prefix_start..prefix_end);
 974                }
 975                Some(Transform::Inlay(inlay)) => {
 976                    let prefix_end = overshoot;
 977                    summary += inlay.text.cursor(0).summary::<TextSummary>(prefix_end);
 978                }
 979                None => {}
 980            }
 981        }
 982
 983        summary
 984    }
 985
 986    pub fn buffer_rows(&self, row: u32) -> InlayBufferRows<'_> {
 987        let mut cursor = self.transforms.cursor::<(InlayPoint, Point)>();
 988        let inlay_point = InlayPoint::new(row, 0);
 989        cursor.seek(&inlay_point, Bias::Left, &());
 990
 991        let max_buffer_row = MultiBufferRow(self.buffer.max_point().row);
 992        let mut buffer_point = cursor.start().1;
 993        let buffer_row = if row == 0 {
 994            MultiBufferRow(0)
 995        } else {
 996            match cursor.item() {
 997                Some(Transform::Isomorphic(_)) => {
 998                    buffer_point += inlay_point.0 - cursor.start().0 .0;
 999                    MultiBufferRow(buffer_point.row)
1000                }
1001                _ => cmp::min(MultiBufferRow(buffer_point.row + 1), max_buffer_row),
1002            }
1003        };
1004
1005        InlayBufferRows {
1006            transforms: cursor,
1007            inlay_row: inlay_point.row(),
1008            buffer_rows: self.buffer.buffer_rows(buffer_row),
1009            max_buffer_row,
1010        }
1011    }
1012
1013    pub fn line_len(&self, row: u32) -> u32 {
1014        let line_start = self.to_offset(InlayPoint::new(row, 0)).0;
1015        let line_end = if row >= self.max_point().row() {
1016            self.len().0
1017        } else {
1018            self.to_offset(InlayPoint::new(row + 1, 0)).0 - 1
1019        };
1020        (line_end - line_start) as u32
1021    }
1022
1023    pub(crate) fn chunks<'a>(
1024        &'a self,
1025        range: Range<InlayOffset>,
1026        language_aware: bool,
1027        highlights: Highlights<'a>,
1028    ) -> InlayChunks<'a> {
1029        let mut cursor = self.transforms.cursor::<(InlayOffset, usize)>();
1030        cursor.seek(&range.start, Bias::Right, &());
1031
1032        let mut highlight_endpoints = Vec::new();
1033        if let Some(text_highlights) = highlights.text_highlights {
1034            if !text_highlights.is_empty() {
1035                self.apply_text_highlights(
1036                    &mut cursor,
1037                    &range,
1038                    text_highlights,
1039                    &mut highlight_endpoints,
1040                );
1041                cursor.seek(&range.start, Bias::Right, &());
1042            }
1043        }
1044        highlight_endpoints.sort();
1045        let buffer_range = self.to_buffer_offset(range.start)..self.to_buffer_offset(range.end);
1046        let buffer_chunks = self.buffer.chunks(buffer_range, language_aware);
1047
1048        InlayChunks {
1049            transforms: cursor,
1050            buffer_chunks,
1051            inlay_chunks: None,
1052            inlay_chunk: None,
1053            buffer_chunk: None,
1054            output_offset: range.start,
1055            max_output_offset: range.end,
1056            highlight_styles: highlights.styles,
1057            highlight_endpoints: highlight_endpoints.into_iter().peekable(),
1058            active_highlights: Default::default(),
1059            highlights,
1060            snapshot: self,
1061        }
1062    }
1063
1064    fn apply_text_highlights(
1065        &self,
1066        cursor: &mut Cursor<'_, Transform, (InlayOffset, usize)>,
1067        range: &Range<InlayOffset>,
1068        text_highlights: &TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>,
1069        highlight_endpoints: &mut Vec<HighlightEndpoint>,
1070    ) {
1071        while cursor.start().0 < range.end {
1072            let transform_start = self
1073                .buffer
1074                .anchor_after(self.to_buffer_offset(cmp::max(range.start, cursor.start().0)));
1075            let transform_end =
1076                {
1077                    let overshoot = InlayOffset(range.end.0 - cursor.start().0 .0);
1078                    self.buffer.anchor_before(self.to_buffer_offset(cmp::min(
1079                        cursor.end(&()).0,
1080                        cursor.start().0 + overshoot,
1081                    )))
1082                };
1083
1084            for (tag, text_highlights) in text_highlights.iter() {
1085                let style = text_highlights.0;
1086                let ranges = &text_highlights.1;
1087
1088                let start_ix = match ranges.binary_search_by(|probe| {
1089                    let cmp = probe.end.cmp(&transform_start, &self.buffer);
1090                    if cmp.is_gt() {
1091                        cmp::Ordering::Greater
1092                    } else {
1093                        cmp::Ordering::Less
1094                    }
1095                }) {
1096                    Ok(i) | Err(i) => i,
1097                };
1098                for range in &ranges[start_ix..] {
1099                    if range.start.cmp(&transform_end, &self.buffer).is_ge() {
1100                        break;
1101                    }
1102
1103                    highlight_endpoints.push(HighlightEndpoint {
1104                        offset: self.to_inlay_offset(range.start.to_offset(&self.buffer)),
1105                        is_start: true,
1106                        tag: *tag,
1107                        style,
1108                    });
1109                    highlight_endpoints.push(HighlightEndpoint {
1110                        offset: self.to_inlay_offset(range.end.to_offset(&self.buffer)),
1111                        is_start: false,
1112                        tag: *tag,
1113                        style,
1114                    });
1115                }
1116            }
1117
1118            cursor.next(&());
1119        }
1120    }
1121
1122    #[cfg(test)]
1123    pub fn text(&self) -> String {
1124        self.chunks(Default::default()..self.len(), false, Highlights::default())
1125            .map(|chunk| chunk.text)
1126            .collect()
1127    }
1128
1129    fn check_invariants(&self) {
1130        #[cfg(any(debug_assertions, feature = "test-support"))]
1131        {
1132            assert_eq!(self.transforms.summary().input, self.buffer.text_summary());
1133            let mut transforms = self.transforms.iter().peekable();
1134            while let Some(transform) = transforms.next() {
1135                let transform_is_isomorphic = matches!(transform, Transform::Isomorphic(_));
1136                if let Some(next_transform) = transforms.peek() {
1137                    let next_transform_is_isomorphic =
1138                        matches!(next_transform, Transform::Isomorphic(_));
1139                    assert!(
1140                        !transform_is_isomorphic || !next_transform_is_isomorphic,
1141                        "two adjacent isomorphic transforms"
1142                    );
1143                }
1144            }
1145        }
1146    }
1147}
1148
1149fn push_isomorphic(sum_tree: &mut SumTree<Transform>, summary: TextSummary) {
1150    if summary.len == 0 {
1151        return;
1152    }
1153
1154    let mut summary = Some(summary);
1155    sum_tree.update_last(
1156        |transform| {
1157            if let Transform::Isomorphic(transform) = transform {
1158                *transform += summary.take().unwrap();
1159            }
1160        },
1161        &(),
1162    );
1163
1164    if let Some(summary) = summary {
1165        sum_tree.push(Transform::Isomorphic(summary), &());
1166    }
1167}
1168
1169#[cfg(test)]
1170mod tests {
1171    use super::*;
1172    use crate::{
1173        display_map::{InlayHighlights, TextHighlights},
1174        hover_links::InlayHighlight,
1175        InlayId, MultiBuffer,
1176    };
1177    use gpui::AppContext;
1178    use project::{InlayHint, InlayHintLabel, ResolveState};
1179    use rand::prelude::*;
1180    use settings::SettingsStore;
1181    use std::{cmp::Reverse, env, sync::Arc};
1182    use text::Patch;
1183    use util::post_inc;
1184
1185    #[test]
1186    fn test_inlay_properties_label_padding() {
1187        assert_eq!(
1188            Inlay::hint(
1189                0,
1190                Anchor::min(),
1191                &InlayHint {
1192                    label: InlayHintLabel::String("a".to_string()),
1193                    position: text::Anchor::default(),
1194                    padding_left: false,
1195                    padding_right: false,
1196                    tooltip: None,
1197                    kind: None,
1198                    resolve_state: ResolveState::Resolved,
1199                },
1200            )
1201            .text
1202            .to_string(),
1203            "a",
1204            "Should not pad label if not requested"
1205        );
1206
1207        assert_eq!(
1208            Inlay::hint(
1209                0,
1210                Anchor::min(),
1211                &InlayHint {
1212                    label: InlayHintLabel::String("a".to_string()),
1213                    position: text::Anchor::default(),
1214                    padding_left: true,
1215                    padding_right: true,
1216                    tooltip: None,
1217                    kind: None,
1218                    resolve_state: ResolveState::Resolved,
1219                },
1220            )
1221            .text
1222            .to_string(),
1223            " a ",
1224            "Should pad label for every side requested"
1225        );
1226
1227        assert_eq!(
1228            Inlay::hint(
1229                0,
1230                Anchor::min(),
1231                &InlayHint {
1232                    label: InlayHintLabel::String(" a ".to_string()),
1233                    position: text::Anchor::default(),
1234                    padding_left: false,
1235                    padding_right: false,
1236                    tooltip: None,
1237                    kind: None,
1238                    resolve_state: ResolveState::Resolved,
1239                },
1240            )
1241            .text
1242            .to_string(),
1243            " a ",
1244            "Should not change already padded label"
1245        );
1246
1247        assert_eq!(
1248            Inlay::hint(
1249                0,
1250                Anchor::min(),
1251                &InlayHint {
1252                    label: InlayHintLabel::String(" a ".to_string()),
1253                    position: text::Anchor::default(),
1254                    padding_left: true,
1255                    padding_right: true,
1256                    tooltip: None,
1257                    kind: None,
1258                    resolve_state: ResolveState::Resolved,
1259                },
1260            )
1261            .text
1262            .to_string(),
1263            " a ",
1264            "Should not change already padded label"
1265        );
1266    }
1267
1268    #[gpui::test]
1269    fn test_basic_inlays(cx: &mut AppContext) {
1270        let buffer = MultiBuffer::build_simple("abcdefghi", cx);
1271        let buffer_edits = buffer.update(cx, |buffer, _| buffer.subscribe());
1272        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
1273        assert_eq!(inlay_snapshot.text(), "abcdefghi");
1274        let mut next_inlay_id = 0;
1275
1276        let (inlay_snapshot, _) = inlay_map.splice(
1277            Vec::new(),
1278            vec![Inlay {
1279                id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1280                position: buffer.read(cx).snapshot(cx).anchor_after(3),
1281                text: "|123|".into(),
1282            }],
1283        );
1284        assert_eq!(inlay_snapshot.text(), "abc|123|defghi");
1285        assert_eq!(
1286            inlay_snapshot.to_inlay_point(Point::new(0, 0)),
1287            InlayPoint::new(0, 0)
1288        );
1289        assert_eq!(
1290            inlay_snapshot.to_inlay_point(Point::new(0, 1)),
1291            InlayPoint::new(0, 1)
1292        );
1293        assert_eq!(
1294            inlay_snapshot.to_inlay_point(Point::new(0, 2)),
1295            InlayPoint::new(0, 2)
1296        );
1297        assert_eq!(
1298            inlay_snapshot.to_inlay_point(Point::new(0, 3)),
1299            InlayPoint::new(0, 3)
1300        );
1301        assert_eq!(
1302            inlay_snapshot.to_inlay_point(Point::new(0, 4)),
1303            InlayPoint::new(0, 9)
1304        );
1305        assert_eq!(
1306            inlay_snapshot.to_inlay_point(Point::new(0, 5)),
1307            InlayPoint::new(0, 10)
1308        );
1309        assert_eq!(
1310            inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Left),
1311            InlayPoint::new(0, 0)
1312        );
1313        assert_eq!(
1314            inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Right),
1315            InlayPoint::new(0, 0)
1316        );
1317        assert_eq!(
1318            inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Left),
1319            InlayPoint::new(0, 3)
1320        );
1321        assert_eq!(
1322            inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Right),
1323            InlayPoint::new(0, 3)
1324        );
1325        assert_eq!(
1326            inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Left),
1327            InlayPoint::new(0, 3)
1328        );
1329        assert_eq!(
1330            inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Right),
1331            InlayPoint::new(0, 9)
1332        );
1333
1334        // Edits before or after the inlay should not affect it.
1335        buffer.update(cx, |buffer, cx| {
1336            buffer.edit([(2..3, "x"), (3..3, "y"), (4..4, "z")], None, cx)
1337        });
1338        let (inlay_snapshot, _) = inlay_map.sync(
1339            buffer.read(cx).snapshot(cx),
1340            buffer_edits.consume().into_inner(),
1341        );
1342        assert_eq!(inlay_snapshot.text(), "abxy|123|dzefghi");
1343
1344        // An edit surrounding the inlay should invalidate it.
1345        buffer.update(cx, |buffer, cx| buffer.edit([(4..5, "D")], None, cx));
1346        let (inlay_snapshot, _) = inlay_map.sync(
1347            buffer.read(cx).snapshot(cx),
1348            buffer_edits.consume().into_inner(),
1349        );
1350        assert_eq!(inlay_snapshot.text(), "abxyDzefghi");
1351
1352        let (inlay_snapshot, _) = inlay_map.splice(
1353            Vec::new(),
1354            vec![
1355                Inlay {
1356                    id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1357                    position: buffer.read(cx).snapshot(cx).anchor_before(3),
1358                    text: "|123|".into(),
1359                },
1360                Inlay {
1361                    id: InlayId::Suggestion(post_inc(&mut next_inlay_id)),
1362                    position: buffer.read(cx).snapshot(cx).anchor_after(3),
1363                    text: "|456|".into(),
1364                },
1365            ],
1366        );
1367        assert_eq!(inlay_snapshot.text(), "abx|123||456|yDzefghi");
1368
1369        // Edits ending where the inlay starts should not move it if it has a left bias.
1370        buffer.update(cx, |buffer, cx| buffer.edit([(3..3, "JKL")], None, cx));
1371        let (inlay_snapshot, _) = inlay_map.sync(
1372            buffer.read(cx).snapshot(cx),
1373            buffer_edits.consume().into_inner(),
1374        );
1375        assert_eq!(inlay_snapshot.text(), "abx|123|JKL|456|yDzefghi");
1376
1377        assert_eq!(
1378            inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Left),
1379            InlayPoint::new(0, 0)
1380        );
1381        assert_eq!(
1382            inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Right),
1383            InlayPoint::new(0, 0)
1384        );
1385
1386        assert_eq!(
1387            inlay_snapshot.clip_point(InlayPoint::new(0, 1), Bias::Left),
1388            InlayPoint::new(0, 1)
1389        );
1390        assert_eq!(
1391            inlay_snapshot.clip_point(InlayPoint::new(0, 1), Bias::Right),
1392            InlayPoint::new(0, 1)
1393        );
1394
1395        assert_eq!(
1396            inlay_snapshot.clip_point(InlayPoint::new(0, 2), Bias::Left),
1397            InlayPoint::new(0, 2)
1398        );
1399        assert_eq!(
1400            inlay_snapshot.clip_point(InlayPoint::new(0, 2), Bias::Right),
1401            InlayPoint::new(0, 2)
1402        );
1403
1404        assert_eq!(
1405            inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Left),
1406            InlayPoint::new(0, 2)
1407        );
1408        assert_eq!(
1409            inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Right),
1410            InlayPoint::new(0, 8)
1411        );
1412
1413        assert_eq!(
1414            inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Left),
1415            InlayPoint::new(0, 2)
1416        );
1417        assert_eq!(
1418            inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Right),
1419            InlayPoint::new(0, 8)
1420        );
1421
1422        assert_eq!(
1423            inlay_snapshot.clip_point(InlayPoint::new(0, 5), Bias::Left),
1424            InlayPoint::new(0, 2)
1425        );
1426        assert_eq!(
1427            inlay_snapshot.clip_point(InlayPoint::new(0, 5), Bias::Right),
1428            InlayPoint::new(0, 8)
1429        );
1430
1431        assert_eq!(
1432            inlay_snapshot.clip_point(InlayPoint::new(0, 6), Bias::Left),
1433            InlayPoint::new(0, 2)
1434        );
1435        assert_eq!(
1436            inlay_snapshot.clip_point(InlayPoint::new(0, 6), Bias::Right),
1437            InlayPoint::new(0, 8)
1438        );
1439
1440        assert_eq!(
1441            inlay_snapshot.clip_point(InlayPoint::new(0, 7), Bias::Left),
1442            InlayPoint::new(0, 2)
1443        );
1444        assert_eq!(
1445            inlay_snapshot.clip_point(InlayPoint::new(0, 7), Bias::Right),
1446            InlayPoint::new(0, 8)
1447        );
1448
1449        assert_eq!(
1450            inlay_snapshot.clip_point(InlayPoint::new(0, 8), Bias::Left),
1451            InlayPoint::new(0, 8)
1452        );
1453        assert_eq!(
1454            inlay_snapshot.clip_point(InlayPoint::new(0, 8), Bias::Right),
1455            InlayPoint::new(0, 8)
1456        );
1457
1458        assert_eq!(
1459            inlay_snapshot.clip_point(InlayPoint::new(0, 9), Bias::Left),
1460            InlayPoint::new(0, 9)
1461        );
1462        assert_eq!(
1463            inlay_snapshot.clip_point(InlayPoint::new(0, 9), Bias::Right),
1464            InlayPoint::new(0, 9)
1465        );
1466
1467        assert_eq!(
1468            inlay_snapshot.clip_point(InlayPoint::new(0, 10), Bias::Left),
1469            InlayPoint::new(0, 10)
1470        );
1471        assert_eq!(
1472            inlay_snapshot.clip_point(InlayPoint::new(0, 10), Bias::Right),
1473            InlayPoint::new(0, 10)
1474        );
1475
1476        assert_eq!(
1477            inlay_snapshot.clip_point(InlayPoint::new(0, 11), Bias::Left),
1478            InlayPoint::new(0, 11)
1479        );
1480        assert_eq!(
1481            inlay_snapshot.clip_point(InlayPoint::new(0, 11), Bias::Right),
1482            InlayPoint::new(0, 11)
1483        );
1484
1485        assert_eq!(
1486            inlay_snapshot.clip_point(InlayPoint::new(0, 12), Bias::Left),
1487            InlayPoint::new(0, 11)
1488        );
1489        assert_eq!(
1490            inlay_snapshot.clip_point(InlayPoint::new(0, 12), Bias::Right),
1491            InlayPoint::new(0, 17)
1492        );
1493
1494        assert_eq!(
1495            inlay_snapshot.clip_point(InlayPoint::new(0, 13), Bias::Left),
1496            InlayPoint::new(0, 11)
1497        );
1498        assert_eq!(
1499            inlay_snapshot.clip_point(InlayPoint::new(0, 13), Bias::Right),
1500            InlayPoint::new(0, 17)
1501        );
1502
1503        assert_eq!(
1504            inlay_snapshot.clip_point(InlayPoint::new(0, 14), Bias::Left),
1505            InlayPoint::new(0, 11)
1506        );
1507        assert_eq!(
1508            inlay_snapshot.clip_point(InlayPoint::new(0, 14), Bias::Right),
1509            InlayPoint::new(0, 17)
1510        );
1511
1512        assert_eq!(
1513            inlay_snapshot.clip_point(InlayPoint::new(0, 15), Bias::Left),
1514            InlayPoint::new(0, 11)
1515        );
1516        assert_eq!(
1517            inlay_snapshot.clip_point(InlayPoint::new(0, 15), Bias::Right),
1518            InlayPoint::new(0, 17)
1519        );
1520
1521        assert_eq!(
1522            inlay_snapshot.clip_point(InlayPoint::new(0, 16), Bias::Left),
1523            InlayPoint::new(0, 11)
1524        );
1525        assert_eq!(
1526            inlay_snapshot.clip_point(InlayPoint::new(0, 16), Bias::Right),
1527            InlayPoint::new(0, 17)
1528        );
1529
1530        assert_eq!(
1531            inlay_snapshot.clip_point(InlayPoint::new(0, 17), Bias::Left),
1532            InlayPoint::new(0, 17)
1533        );
1534        assert_eq!(
1535            inlay_snapshot.clip_point(InlayPoint::new(0, 17), Bias::Right),
1536            InlayPoint::new(0, 17)
1537        );
1538
1539        assert_eq!(
1540            inlay_snapshot.clip_point(InlayPoint::new(0, 18), Bias::Left),
1541            InlayPoint::new(0, 18)
1542        );
1543        assert_eq!(
1544            inlay_snapshot.clip_point(InlayPoint::new(0, 18), Bias::Right),
1545            InlayPoint::new(0, 18)
1546        );
1547
1548        // The inlays can be manually removed.
1549        let (inlay_snapshot, _) = inlay_map.splice(
1550            inlay_map.inlays.iter().map(|inlay| inlay.id).collect(),
1551            Vec::new(),
1552        );
1553        assert_eq!(inlay_snapshot.text(), "abxJKLyDzefghi");
1554    }
1555
1556    #[gpui::test]
1557    fn test_inlay_buffer_rows(cx: &mut AppContext) {
1558        let buffer = MultiBuffer::build_simple("abc\ndef\nghi", cx);
1559        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
1560        assert_eq!(inlay_snapshot.text(), "abc\ndef\nghi");
1561        let mut next_inlay_id = 0;
1562
1563        let (inlay_snapshot, _) = inlay_map.splice(
1564            Vec::new(),
1565            vec![
1566                Inlay {
1567                    id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1568                    position: buffer.read(cx).snapshot(cx).anchor_before(0),
1569                    text: "|123|\n".into(),
1570                },
1571                Inlay {
1572                    id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1573                    position: buffer.read(cx).snapshot(cx).anchor_before(4),
1574                    text: "|456|".into(),
1575                },
1576                Inlay {
1577                    id: InlayId::Suggestion(post_inc(&mut next_inlay_id)),
1578                    position: buffer.read(cx).snapshot(cx).anchor_before(7),
1579                    text: "\n|567|\n".into(),
1580                },
1581            ],
1582        );
1583        assert_eq!(inlay_snapshot.text(), "|123|\nabc\n|456|def\n|567|\n\nghi");
1584        assert_eq!(
1585            inlay_snapshot.buffer_rows(0).collect::<Vec<_>>(),
1586            vec![Some(0), None, Some(1), None, None, Some(2)]
1587        );
1588    }
1589
1590    #[gpui::test(iterations = 100)]
1591    fn test_random_inlays(cx: &mut AppContext, mut rng: StdRng) {
1592        init_test(cx);
1593
1594        let operations = env::var("OPERATIONS")
1595            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1596            .unwrap_or(10);
1597
1598        let len = rng.gen_range(0..30);
1599        let buffer = if rng.gen() {
1600            let text = util::RandomCharIter::new(&mut rng)
1601                .take(len)
1602                .collect::<String>();
1603            MultiBuffer::build_simple(&text, cx)
1604        } else {
1605            MultiBuffer::build_random(&mut rng, cx)
1606        };
1607        let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1608        let mut next_inlay_id = 0;
1609        log::info!("buffer text: {:?}", buffer_snapshot.text());
1610        let (mut inlay_map, mut inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1611        for _ in 0..operations {
1612            let mut inlay_edits = Patch::default();
1613
1614            let mut prev_inlay_text = inlay_snapshot.text();
1615            let mut buffer_edits = Vec::new();
1616            match rng.gen_range(0..=100) {
1617                0..=50 => {
1618                    let (snapshot, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1619                    log::info!("mutated text: {:?}", snapshot.text());
1620                    inlay_edits = Patch::new(edits);
1621                }
1622                _ => buffer.update(cx, |buffer, cx| {
1623                    let subscription = buffer.subscribe();
1624                    let edit_count = rng.gen_range(1..=5);
1625                    buffer.randomly_mutate(&mut rng, edit_count, cx);
1626                    buffer_snapshot = buffer.snapshot(cx);
1627                    let edits = subscription.consume().into_inner();
1628                    log::info!("editing {:?}", edits);
1629                    buffer_edits.extend(edits);
1630                }),
1631            };
1632
1633            let (new_inlay_snapshot, new_inlay_edits) =
1634                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1635            inlay_snapshot = new_inlay_snapshot;
1636            inlay_edits = inlay_edits.compose(new_inlay_edits);
1637
1638            log::info!("buffer text: {:?}", buffer_snapshot.text());
1639            log::info!("inlay text: {:?}", inlay_snapshot.text());
1640
1641            let inlays = inlay_map
1642                .inlays
1643                .iter()
1644                .filter(|inlay| inlay.position.is_valid(&buffer_snapshot))
1645                .map(|inlay| {
1646                    let offset = inlay.position.to_offset(&buffer_snapshot);
1647                    (offset, inlay.clone())
1648                })
1649                .collect::<Vec<_>>();
1650            let mut expected_text = Rope::from(buffer_snapshot.text());
1651            for (offset, inlay) in inlays.iter().rev() {
1652                expected_text.replace(*offset..*offset, &inlay.text.to_string());
1653            }
1654            assert_eq!(inlay_snapshot.text(), expected_text.to_string());
1655
1656            let expected_buffer_rows = inlay_snapshot.buffer_rows(0).collect::<Vec<_>>();
1657            assert_eq!(
1658                expected_buffer_rows.len() as u32,
1659                expected_text.max_point().row + 1
1660            );
1661            for row_start in 0..expected_buffer_rows.len() {
1662                assert_eq!(
1663                    inlay_snapshot
1664                        .buffer_rows(row_start as u32)
1665                        .collect::<Vec<_>>(),
1666                    &expected_buffer_rows[row_start..],
1667                    "incorrect buffer rows starting at {}",
1668                    row_start
1669                );
1670            }
1671
1672            let mut text_highlights = TextHighlights::default();
1673            let text_highlight_count = rng.gen_range(0_usize..10);
1674            let mut text_highlight_ranges = (0..text_highlight_count)
1675                .map(|_| buffer_snapshot.random_byte_range(0, &mut rng))
1676                .collect::<Vec<_>>();
1677            text_highlight_ranges.sort_by_key(|range| (range.start, Reverse(range.end)));
1678            log::info!("highlighting text ranges {text_highlight_ranges:?}");
1679            text_highlights.insert(
1680                Some(TypeId::of::<()>()),
1681                Arc::new((
1682                    HighlightStyle::default(),
1683                    text_highlight_ranges
1684                        .into_iter()
1685                        .map(|range| {
1686                            buffer_snapshot.anchor_before(range.start)
1687                                ..buffer_snapshot.anchor_after(range.end)
1688                        })
1689                        .collect(),
1690                )),
1691            );
1692
1693            let mut inlay_highlights = InlayHighlights::default();
1694            if !inlays.is_empty() {
1695                let inlay_highlight_count = rng.gen_range(0..inlays.len());
1696                let mut inlay_indices = BTreeSet::default();
1697                while inlay_indices.len() < inlay_highlight_count {
1698                    inlay_indices.insert(rng.gen_range(0..inlays.len()));
1699                }
1700                let new_highlights = TreeMap::from_ordered_entries(
1701                    inlay_indices
1702                        .into_iter()
1703                        .filter_map(|i| {
1704                            let (_, inlay) = &inlays[i];
1705                            let inlay_text_len = inlay.text.len();
1706                            match inlay_text_len {
1707                                0 => None,
1708                                1 => Some(InlayHighlight {
1709                                    inlay: inlay.id,
1710                                    inlay_position: inlay.position,
1711                                    range: 0..1,
1712                                }),
1713                                n => {
1714                                    let inlay_text = inlay.text.to_string();
1715                                    let mut highlight_end = rng.gen_range(1..n);
1716                                    let mut highlight_start = rng.gen_range(0..highlight_end);
1717                                    while !inlay_text.is_char_boundary(highlight_end) {
1718                                        highlight_end += 1;
1719                                    }
1720                                    while !inlay_text.is_char_boundary(highlight_start) {
1721                                        highlight_start -= 1;
1722                                    }
1723                                    Some(InlayHighlight {
1724                                        inlay: inlay.id,
1725                                        inlay_position: inlay.position,
1726                                        range: highlight_start..highlight_end,
1727                                    })
1728                                }
1729                            }
1730                        })
1731                        .map(|highlight| (highlight.inlay, (HighlightStyle::default(), highlight))),
1732                );
1733                log::info!("highlighting inlay ranges {new_highlights:?}");
1734                inlay_highlights.insert(TypeId::of::<()>(), new_highlights);
1735            }
1736
1737            for _ in 0..5 {
1738                let mut end = rng.gen_range(0..=inlay_snapshot.len().0);
1739                end = expected_text.clip_offset(end, Bias::Right);
1740                let mut start = rng.gen_range(0..=end);
1741                start = expected_text.clip_offset(start, Bias::Right);
1742
1743                let range = InlayOffset(start)..InlayOffset(end);
1744                log::info!("calling inlay_snapshot.chunks({range:?})");
1745                let actual_text = inlay_snapshot
1746                    .chunks(
1747                        range,
1748                        false,
1749                        Highlights {
1750                            text_highlights: Some(&text_highlights),
1751                            inlay_highlights: Some(&inlay_highlights),
1752                            ..Highlights::default()
1753                        },
1754                    )
1755                    .map(|chunk| chunk.text)
1756                    .collect::<String>();
1757                assert_eq!(
1758                    actual_text,
1759                    expected_text.slice(start..end).to_string(),
1760                    "incorrect text in range {:?}",
1761                    start..end
1762                );
1763
1764                assert_eq!(
1765                    inlay_snapshot.text_summary_for_range(InlayOffset(start)..InlayOffset(end)),
1766                    expected_text.slice(start..end).summary()
1767                );
1768            }
1769
1770            for edit in inlay_edits {
1771                prev_inlay_text.replace_range(
1772                    edit.new.start.0..edit.new.start.0 + edit.old_len().0,
1773                    &inlay_snapshot.text()[edit.new.start.0..edit.new.end.0],
1774                );
1775            }
1776            assert_eq!(prev_inlay_text, inlay_snapshot.text());
1777
1778            assert_eq!(expected_text.max_point(), inlay_snapshot.max_point().0);
1779            assert_eq!(expected_text.len(), inlay_snapshot.len().0);
1780
1781            let mut buffer_point = Point::default();
1782            let mut inlay_point = inlay_snapshot.to_inlay_point(buffer_point);
1783            let mut buffer_chars = buffer_snapshot.chars_at(0);
1784            loop {
1785                // Ensure conversion from buffer coordinates to inlay coordinates
1786                // is consistent.
1787                let buffer_offset = buffer_snapshot.point_to_offset(buffer_point);
1788                assert_eq!(
1789                    inlay_snapshot.to_point(inlay_snapshot.to_inlay_offset(buffer_offset)),
1790                    inlay_point
1791                );
1792
1793                // No matter which bias we clip an inlay point with, it doesn't move
1794                // because it was constructed from a buffer point.
1795                assert_eq!(
1796                    inlay_snapshot.clip_point(inlay_point, Bias::Left),
1797                    inlay_point,
1798                    "invalid inlay point for buffer point {:?} when clipped left",
1799                    buffer_point
1800                );
1801                assert_eq!(
1802                    inlay_snapshot.clip_point(inlay_point, Bias::Right),
1803                    inlay_point,
1804                    "invalid inlay point for buffer point {:?} when clipped right",
1805                    buffer_point
1806                );
1807
1808                if let Some(ch) = buffer_chars.next() {
1809                    if ch == '\n' {
1810                        buffer_point += Point::new(1, 0);
1811                    } else {
1812                        buffer_point += Point::new(0, ch.len_utf8() as u32);
1813                    }
1814
1815                    // Ensure that moving forward in the buffer always moves the inlay point forward as well.
1816                    let new_inlay_point = inlay_snapshot.to_inlay_point(buffer_point);
1817                    assert!(new_inlay_point > inlay_point);
1818                    inlay_point = new_inlay_point;
1819                } else {
1820                    break;
1821                }
1822            }
1823
1824            let mut inlay_point = InlayPoint::default();
1825            let mut inlay_offset = InlayOffset::default();
1826            for ch in expected_text.chars() {
1827                assert_eq!(
1828                    inlay_snapshot.to_offset(inlay_point),
1829                    inlay_offset,
1830                    "invalid to_offset({:?})",
1831                    inlay_point
1832                );
1833                assert_eq!(
1834                    inlay_snapshot.to_point(inlay_offset),
1835                    inlay_point,
1836                    "invalid to_point({:?})",
1837                    inlay_offset
1838                );
1839
1840                let mut bytes = [0; 4];
1841                for byte in ch.encode_utf8(&mut bytes).as_bytes() {
1842                    inlay_offset.0 += 1;
1843                    if *byte == b'\n' {
1844                        inlay_point.0 += Point::new(1, 0);
1845                    } else {
1846                        inlay_point.0 += Point::new(0, 1);
1847                    }
1848
1849                    let clipped_left_point = inlay_snapshot.clip_point(inlay_point, Bias::Left);
1850                    let clipped_right_point = inlay_snapshot.clip_point(inlay_point, Bias::Right);
1851                    assert!(
1852                        clipped_left_point <= clipped_right_point,
1853                        "inlay point {:?} when clipped left is greater than when clipped right ({:?} > {:?})",
1854                        inlay_point,
1855                        clipped_left_point,
1856                        clipped_right_point
1857                    );
1858
1859                    // Ensure the clipped points are at valid text locations.
1860                    assert_eq!(
1861                        clipped_left_point.0,
1862                        expected_text.clip_point(clipped_left_point.0, Bias::Left)
1863                    );
1864                    assert_eq!(
1865                        clipped_right_point.0,
1866                        expected_text.clip_point(clipped_right_point.0, Bias::Right)
1867                    );
1868
1869                    // Ensure the clipped points never overshoot the end of the map.
1870                    assert!(clipped_left_point <= inlay_snapshot.max_point());
1871                    assert!(clipped_right_point <= inlay_snapshot.max_point());
1872
1873                    // Ensure the clipped points are at valid buffer locations.
1874                    assert_eq!(
1875                        inlay_snapshot
1876                            .to_inlay_point(inlay_snapshot.to_buffer_point(clipped_left_point)),
1877                        clipped_left_point,
1878                        "to_buffer_point({:?}) = {:?}",
1879                        clipped_left_point,
1880                        inlay_snapshot.to_buffer_point(clipped_left_point),
1881                    );
1882                    assert_eq!(
1883                        inlay_snapshot
1884                            .to_inlay_point(inlay_snapshot.to_buffer_point(clipped_right_point)),
1885                        clipped_right_point,
1886                        "to_buffer_point({:?}) = {:?}",
1887                        clipped_right_point,
1888                        inlay_snapshot.to_buffer_point(clipped_right_point),
1889                    );
1890                }
1891            }
1892        }
1893    }
1894
1895    fn init_test(cx: &mut AppContext) {
1896        let store = SettingsStore::test(cx);
1897        cx.set_global(store);
1898        theme::init(theme::LoadThemes::JustBase, cx);
1899    }
1900}