inlay_map.rs

   1use crate::InlayId;
   2use collections::{BTreeMap, BTreeSet};
   3use gpui::HighlightStyle;
   4use language::{Chunk, Edit, Point, TextSummary};
   5use multi_buffer::{Anchor, MultiBufferChunks, MultiBufferRows, MultiBufferSnapshot, ToOffset};
   6use std::{
   7    any::TypeId,
   8    cmp,
   9    iter::Peekable,
  10    ops::{Add, AddAssign, Range, Sub, SubAssign},
  11    sync::Arc,
  12    vec,
  13};
  14use sum_tree::{Bias, Cursor, SumTree, TreeMap};
  15use text::{Patch, Rope};
  16
  17use super::Highlights;
  18
  19/// Decides where the [`Inlay`]s should be displayed.
  20///
  21/// See the [`display_map` module documentation](crate::display_map) for more information.
  22pub struct InlayMap {
  23    snapshot: InlaySnapshot,
  24    inlays: Vec<Inlay>,
  25}
  26
  27#[derive(Clone)]
  28pub struct InlaySnapshot {
  29    pub buffer: MultiBufferSnapshot,
  30    transforms: SumTree<Transform>,
  31    pub version: usize,
  32}
  33
  34#[derive(Clone, Debug)]
  35enum Transform {
  36    Isomorphic(TextSummary),
  37    Inlay(Inlay),
  38}
  39
  40#[derive(Debug, Clone)]
  41pub(crate) struct Inlay {
  42    pub(crate) id: InlayId,
  43    pub position: Anchor,
  44    pub text: text::Rope,
  45}
  46
  47impl Inlay {
  48    pub fn hint(id: usize, position: Anchor, hint: &project::InlayHint) -> Self {
  49        let mut text = hint.text();
  50        if hint.padding_right && !text.ends_with(' ') {
  51            text.push(' ');
  52        }
  53        if hint.padding_left && !text.starts_with(' ') {
  54            text.insert(0, ' ');
  55        }
  56        Self {
  57            id: InlayId::Hint(id),
  58            position,
  59            text: text.into(),
  60        }
  61    }
  62
  63    pub fn suggestion<T: Into<Rope>>(id: usize, position: Anchor, text: T) -> Self {
  64        Self {
  65            id: InlayId::Suggestion(id),
  66            position,
  67            text: text.into(),
  68        }
  69    }
  70}
  71
  72impl sum_tree::Item for Transform {
  73    type Summary = TransformSummary;
  74
  75    fn summary(&self) -> Self::Summary {
  76        match self {
  77            Transform::Isomorphic(summary) => TransformSummary {
  78                input: summary.clone(),
  79                output: summary.clone(),
  80            },
  81            Transform::Inlay(inlay) => TransformSummary {
  82                input: TextSummary::default(),
  83                output: inlay.text.summary(),
  84            },
  85        }
  86    }
  87}
  88
  89#[derive(Clone, Debug, Default)]
  90struct TransformSummary {
  91    input: TextSummary,
  92    output: TextSummary,
  93}
  94
  95impl sum_tree::Summary for TransformSummary {
  96    type Context = ();
  97
  98    fn add_summary(&mut self, other: &Self, _: &()) {
  99        self.input += &other.input;
 100        self.output += &other.output;
 101    }
 102}
 103
 104pub type InlayEdit = Edit<InlayOffset>;
 105
 106#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 107pub struct InlayOffset(pub usize);
 108
 109impl Add for InlayOffset {
 110    type Output = Self;
 111
 112    fn add(self, rhs: Self) -> Self::Output {
 113        Self(self.0 + rhs.0)
 114    }
 115}
 116
 117impl Sub for InlayOffset {
 118    type Output = Self;
 119
 120    fn sub(self, rhs: Self) -> Self::Output {
 121        Self(self.0 - rhs.0)
 122    }
 123}
 124
 125impl AddAssign for InlayOffset {
 126    fn add_assign(&mut self, rhs: Self) {
 127        self.0 += rhs.0;
 128    }
 129}
 130
 131impl SubAssign for InlayOffset {
 132    fn sub_assign(&mut self, rhs: Self) {
 133        self.0 -= rhs.0;
 134    }
 135}
 136
 137impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
 138    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 139        self.0 += &summary.output.len;
 140    }
 141}
 142
 143#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 144pub struct InlayPoint(pub Point);
 145
 146impl Add for InlayPoint {
 147    type Output = Self;
 148
 149    fn add(self, rhs: Self) -> Self::Output {
 150        Self(self.0 + rhs.0)
 151    }
 152}
 153
 154impl Sub for InlayPoint {
 155    type Output = Self;
 156
 157    fn sub(self, rhs: Self) -> Self::Output {
 158        Self(self.0 - rhs.0)
 159    }
 160}
 161
 162impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
 163    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 164        self.0 += &summary.output.lines;
 165    }
 166}
 167
 168impl<'a> sum_tree::Dimension<'a, TransformSummary> for usize {
 169    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 170        *self += &summary.input.len;
 171    }
 172}
 173
 174impl<'a> sum_tree::Dimension<'a, TransformSummary> for Point {
 175    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 176        *self += &summary.input.lines;
 177    }
 178}
 179
 180#[derive(Clone)]
 181pub struct InlayBufferRows<'a> {
 182    transforms: Cursor<'a, Transform, (InlayPoint, Point)>,
 183    buffer_rows: MultiBufferRows<'a>,
 184    inlay_row: u32,
 185    max_buffer_row: u32,
 186}
 187
 188#[derive(Debug, Copy, Clone, Eq, PartialEq)]
 189struct HighlightEndpoint {
 190    offset: InlayOffset,
 191    is_start: bool,
 192    tag: Option<TypeId>,
 193    style: HighlightStyle,
 194}
 195
 196impl PartialOrd for HighlightEndpoint {
 197    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
 198        Some(self.cmp(other))
 199    }
 200}
 201
 202impl Ord for HighlightEndpoint {
 203    fn cmp(&self, other: &Self) -> cmp::Ordering {
 204        self.offset
 205            .cmp(&other.offset)
 206            .then_with(|| other.is_start.cmp(&self.is_start))
 207    }
 208}
 209
 210pub struct InlayChunks<'a> {
 211    transforms: Cursor<'a, Transform, (InlayOffset, usize)>,
 212    buffer_chunks: MultiBufferChunks<'a>,
 213    buffer_chunk: Option<Chunk<'a>>,
 214    inlay_chunks: Option<text::Chunks<'a>>,
 215    inlay_chunk: Option<&'a str>,
 216    output_offset: InlayOffset,
 217    max_output_offset: InlayOffset,
 218    inlay_highlight_style: Option<HighlightStyle>,
 219    suggestion_highlight_style: Option<HighlightStyle>,
 220    highlight_endpoints: Peekable<vec::IntoIter<HighlightEndpoint>>,
 221    active_highlights: BTreeMap<Option<TypeId>, HighlightStyle>,
 222    highlights: Highlights<'a>,
 223    snapshot: &'a InlaySnapshot,
 224}
 225
 226impl<'a> InlayChunks<'a> {
 227    pub fn seek(&mut self, offset: InlayOffset) {
 228        self.transforms.seek(&offset, Bias::Right, &());
 229
 230        let buffer_offset = self.snapshot.to_buffer_offset(offset);
 231        self.buffer_chunks.seek(buffer_offset);
 232        self.inlay_chunks = None;
 233        self.buffer_chunk = None;
 234        self.output_offset = offset;
 235    }
 236
 237    pub fn offset(&self) -> InlayOffset {
 238        self.output_offset
 239    }
 240}
 241
 242impl<'a> Iterator for InlayChunks<'a> {
 243    type Item = Chunk<'a>;
 244
 245    fn next(&mut self) -> Option<Self::Item> {
 246        if self.output_offset == self.max_output_offset {
 247            return None;
 248        }
 249
 250        let mut next_highlight_endpoint = InlayOffset(usize::MAX);
 251        while let Some(endpoint) = self.highlight_endpoints.peek().copied() {
 252            if endpoint.offset <= self.output_offset {
 253                if endpoint.is_start {
 254                    self.active_highlights.insert(endpoint.tag, endpoint.style);
 255                } else {
 256                    self.active_highlights.remove(&endpoint.tag);
 257                }
 258                self.highlight_endpoints.next();
 259            } else {
 260                next_highlight_endpoint = endpoint.offset;
 261                break;
 262            }
 263        }
 264
 265        let chunk = match self.transforms.item()? {
 266            Transform::Isomorphic(_) => {
 267                let chunk = self
 268                    .buffer_chunk
 269                    .get_or_insert_with(|| self.buffer_chunks.next().unwrap());
 270                if chunk.text.is_empty() {
 271                    *chunk = self.buffer_chunks.next().unwrap();
 272                }
 273
 274                let (prefix, suffix) = chunk.text.split_at(
 275                    chunk
 276                        .text
 277                        .len()
 278                        .min(self.transforms.end(&()).0 .0 - self.output_offset.0)
 279                        .min(next_highlight_endpoint.0 - self.output_offset.0),
 280                );
 281
 282                chunk.text = suffix;
 283                self.output_offset.0 += prefix.len();
 284                let mut prefix = Chunk {
 285                    text: prefix,
 286                    ..*chunk
 287                };
 288                if !self.active_highlights.is_empty() {
 289                    let mut highlight_style = HighlightStyle::default();
 290                    for active_highlight in self.active_highlights.values() {
 291                        highlight_style.highlight(*active_highlight);
 292                    }
 293                    prefix.highlight_style = Some(highlight_style);
 294                }
 295                prefix
 296            }
 297            Transform::Inlay(inlay) => {
 298                let mut inlay_style_and_highlight = None;
 299                if let Some(inlay_highlights) = self.highlights.inlay_highlights {
 300                    for (_, inlay_id_to_data) in inlay_highlights.iter() {
 301                        let style_and_highlight = inlay_id_to_data.get(&inlay.id);
 302                        if style_and_highlight.is_some() {
 303                            inlay_style_and_highlight = style_and_highlight;
 304                            break;
 305                        }
 306                    }
 307                }
 308
 309                let mut highlight_style = match inlay.id {
 310                    InlayId::Suggestion(_) => self.suggestion_highlight_style,
 311                    InlayId::Hint(_) => self.inlay_highlight_style,
 312                };
 313                let next_inlay_highlight_endpoint;
 314                let offset_in_inlay = self.output_offset - self.transforms.start().0;
 315                if let Some((style, highlight)) = inlay_style_and_highlight {
 316                    let range = &highlight.range;
 317                    if offset_in_inlay.0 < range.start {
 318                        next_inlay_highlight_endpoint = range.start - offset_in_inlay.0;
 319                    } else if offset_in_inlay.0 >= range.end {
 320                        next_inlay_highlight_endpoint = usize::MAX;
 321                    } else {
 322                        next_inlay_highlight_endpoint = range.end - offset_in_inlay.0;
 323                        highlight_style
 324                            .get_or_insert_with(|| Default::default())
 325                            .highlight(*style);
 326                    }
 327                } else {
 328                    next_inlay_highlight_endpoint = usize::MAX;
 329                }
 330
 331                let inlay_chunks = self.inlay_chunks.get_or_insert_with(|| {
 332                    let start = offset_in_inlay;
 333                    let end = cmp::min(self.max_output_offset, self.transforms.end(&()).0)
 334                        - self.transforms.start().0;
 335                    inlay.text.chunks_in_range(start.0..end.0)
 336                });
 337                let inlay_chunk = self
 338                    .inlay_chunk
 339                    .get_or_insert_with(|| inlay_chunks.next().unwrap());
 340                let (chunk, remainder) =
 341                    inlay_chunk.split_at(inlay_chunk.len().min(next_inlay_highlight_endpoint));
 342                *inlay_chunk = remainder;
 343                if inlay_chunk.is_empty() {
 344                    self.inlay_chunk = None;
 345                }
 346
 347                self.output_offset.0 += chunk.len();
 348
 349                if !self.active_highlights.is_empty() {
 350                    for active_highlight in self.active_highlights.values() {
 351                        highlight_style
 352                            .get_or_insert(Default::default())
 353                            .highlight(*active_highlight);
 354                    }
 355                }
 356                Chunk {
 357                    text: chunk,
 358                    highlight_style,
 359                    ..Default::default()
 360                }
 361            }
 362        };
 363
 364        if self.output_offset == self.transforms.end(&()).0 {
 365            self.inlay_chunks = None;
 366            self.transforms.next(&());
 367        }
 368
 369        Some(chunk)
 370    }
 371}
 372
 373impl<'a> InlayBufferRows<'a> {
 374    pub fn seek(&mut self, row: u32) {
 375        let inlay_point = InlayPoint::new(row, 0);
 376        self.transforms.seek(&inlay_point, Bias::Left, &());
 377
 378        let mut buffer_point = self.transforms.start().1;
 379        let buffer_row = if row == 0 {
 380            0
 381        } else {
 382            match self.transforms.item() {
 383                Some(Transform::Isomorphic(_)) => {
 384                    buffer_point += inlay_point.0 - self.transforms.start().0 .0;
 385                    buffer_point.row
 386                }
 387                _ => cmp::min(buffer_point.row + 1, self.max_buffer_row),
 388            }
 389        };
 390        self.inlay_row = inlay_point.row();
 391        self.buffer_rows.seek(buffer_row);
 392    }
 393}
 394
 395impl<'a> Iterator for InlayBufferRows<'a> {
 396    type Item = Option<u32>;
 397
 398    fn next(&mut self) -> Option<Self::Item> {
 399        let buffer_row = if self.inlay_row == 0 {
 400            self.buffer_rows.next().unwrap()
 401        } else {
 402            match self.transforms.item()? {
 403                Transform::Inlay(_) => None,
 404                Transform::Isomorphic(_) => self.buffer_rows.next().unwrap(),
 405            }
 406        };
 407
 408        self.inlay_row += 1;
 409        self.transforms
 410            .seek_forward(&InlayPoint::new(self.inlay_row, 0), Bias::Left, &());
 411
 412        Some(buffer_row)
 413    }
 414}
 415
 416impl InlayPoint {
 417    pub fn new(row: u32, column: u32) -> Self {
 418        Self(Point::new(row, column))
 419    }
 420
 421    pub fn row(self) -> u32 {
 422        self.0.row
 423    }
 424}
 425
 426impl InlayMap {
 427    pub fn new(buffer: MultiBufferSnapshot) -> (Self, InlaySnapshot) {
 428        let version = 0;
 429        let snapshot = InlaySnapshot {
 430            buffer: buffer.clone(),
 431            transforms: SumTree::from_iter(Some(Transform::Isomorphic(buffer.text_summary())), &()),
 432            version,
 433        };
 434
 435        (
 436            Self {
 437                snapshot: snapshot.clone(),
 438                inlays: Vec::new(),
 439            },
 440            snapshot,
 441        )
 442    }
 443
 444    pub fn sync(
 445        &mut self,
 446        buffer_snapshot: MultiBufferSnapshot,
 447        mut buffer_edits: Vec<text::Edit<usize>>,
 448    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 449        let snapshot = &mut self.snapshot;
 450
 451        if buffer_edits.is_empty() {
 452            if snapshot.buffer.trailing_excerpt_update_count()
 453                != buffer_snapshot.trailing_excerpt_update_count()
 454            {
 455                buffer_edits.push(Edit {
 456                    old: snapshot.buffer.len()..snapshot.buffer.len(),
 457                    new: buffer_snapshot.len()..buffer_snapshot.len(),
 458                });
 459            }
 460        }
 461
 462        if buffer_edits.is_empty() {
 463            if snapshot.buffer.edit_count() != buffer_snapshot.edit_count()
 464                || snapshot.buffer.parse_count() != buffer_snapshot.parse_count()
 465                || snapshot.buffer.diagnostics_update_count()
 466                    != buffer_snapshot.diagnostics_update_count()
 467                || snapshot.buffer.git_diff_update_count()
 468                    != buffer_snapshot.git_diff_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 = self.buffer.max_point().row;
 991        let mut buffer_point = cursor.start().1;
 992        let buffer_row = if row == 0 {
 993            0
 994        } else {
 995            match cursor.item() {
 996                Some(Transform::Isomorphic(_)) => {
 997                    buffer_point += inlay_point.0 - cursor.start().0 .0;
 998                    buffer_point.row
 999                }
1000                _ => cmp::min(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            inlay_highlight_style: highlights.inlay_highlight_style,
1056            suggestion_highlight_style: highlights.suggestion_highlight_style,
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 = 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                    .collect();
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}