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