inlay_map.rs

   1use crate::{
   2    multi_buffer::{MultiBufferChunks, MultiBufferRows},
   3    Anchor, InlayId, MultiBufferSnapshot, ToOffset,
   4};
   5use collections::{BTreeMap, BTreeSet};
   6use gpui::fonts::HighlightStyle;
   7use language::{Chunk, Edit, Point, TextSummary};
   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
  21pub struct InlayMap {
  22    snapshot: InlaySnapshot,
  23}
  24
  25#[derive(Clone)]
  26pub struct InlaySnapshot {
  27    pub buffer: MultiBufferSnapshot,
  28    transforms: SumTree<Transform>,
  29    inlays: Vec<Inlay>,
  30    pub version: usize,
  31}
  32
  33#[derive(Clone, Debug)]
  34enum Transform {
  35    Isomorphic(TextSummary),
  36    Inlay(Inlay),
  37}
  38
  39#[derive(Debug, Clone)]
  40pub struct Inlay {
  41    pub id: InlayId,
  42    pub position: Anchor,
  43    pub text: text::Rope,
  44}
  45
  46impl Inlay {
  47    pub fn hint(id: usize, position: Anchor, hint: &project::InlayHint) -> Self {
  48        let mut text = hint.text();
  49        if hint.padding_right && !text.ends_with(' ') {
  50            text.push(' ');
  51        }
  52        if hint.padding_left && !text.starts_with(' ') {
  53            text.insert(0, ' ');
  54        }
  55        Self {
  56            id: InlayId::Hint(id),
  57            position,
  58            text: text.into(),
  59        }
  60    }
  61
  62    pub fn suggestion<T: Into<Rope>>(id: usize, position: Anchor, text: T) -> Self {
  63        Self {
  64            id: InlayId::Suggestion(id),
  65            position,
  66            text: text.into(),
  67        }
  68    }
  69}
  70
  71impl sum_tree::Item for Transform {
  72    type Summary = TransformSummary;
  73
  74    fn summary(&self) -> Self::Summary {
  75        match self {
  76            Transform::Isomorphic(summary) => TransformSummary {
  77                input: summary.clone(),
  78                output: summary.clone(),
  79            },
  80            Transform::Inlay(inlay) => TransformSummary {
  81                input: TextSummary::default(),
  82                output: inlay.text.summary(),
  83            },
  84        }
  85    }
  86}
  87
  88#[derive(Clone, Debug, Default)]
  89struct TransformSummary {
  90    input: TextSummary,
  91    output: TextSummary,
  92}
  93
  94impl sum_tree::Summary for TransformSummary {
  95    type Context = ();
  96
  97    fn add_summary(&mut self, other: &Self, _: &()) {
  98        self.input += &other.input;
  99        self.output += &other.output;
 100    }
 101}
 102
 103pub type InlayEdit = Edit<InlayOffset>;
 104
 105#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 106pub struct InlayOffset(pub usize);
 107
 108impl Add for InlayOffset {
 109    type Output = Self;
 110
 111    fn add(self, rhs: Self) -> Self::Output {
 112        Self(self.0 + rhs.0)
 113    }
 114}
 115
 116impl Sub for InlayOffset {
 117    type Output = Self;
 118
 119    fn sub(self, rhs: Self) -> Self::Output {
 120        Self(self.0 - rhs.0)
 121    }
 122}
 123
 124impl AddAssign for InlayOffset {
 125    fn add_assign(&mut self, rhs: Self) {
 126        self.0 += rhs.0;
 127    }
 128}
 129
 130impl SubAssign for InlayOffset {
 131    fn sub_assign(&mut self, rhs: Self) {
 132        self.0 -= rhs.0;
 133    }
 134}
 135
 136impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
 137    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 138        self.0 += &summary.output.len;
 139    }
 140}
 141
 142#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 143pub struct InlayPoint(pub Point);
 144
 145impl Add for InlayPoint {
 146    type Output = Self;
 147
 148    fn add(self, rhs: Self) -> Self::Output {
 149        Self(self.0 + rhs.0)
 150    }
 151}
 152
 153impl Sub for InlayPoint {
 154    type Output = Self;
 155
 156    fn sub(self, rhs: Self) -> Self::Output {
 157        Self(self.0 - rhs.0)
 158    }
 159}
 160
 161impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
 162    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 163        self.0 += &summary.output.lines;
 164    }
 165}
 166
 167impl<'a> sum_tree::Dimension<'a, TransformSummary> for usize {
 168    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 169        *self += &summary.input.len;
 170    }
 171}
 172
 173impl<'a> sum_tree::Dimension<'a, TransformSummary> for Point {
 174    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 175        *self += &summary.input.lines;
 176    }
 177}
 178
 179#[derive(Clone)]
 180pub struct InlayBufferRows<'a> {
 181    transforms: Cursor<'a, Transform, (InlayPoint, Point)>,
 182    buffer_rows: MultiBufferRows<'a>,
 183    inlay_row: u32,
 184    max_buffer_row: u32,
 185}
 186
 187#[derive(Debug, Copy, Clone, Eq, PartialEq)]
 188struct HighlightEndpoint {
 189    offset: InlayOffset,
 190    is_start: bool,
 191    tag: Option<TypeId>,
 192    style: HighlightStyle,
 193}
 194
 195impl PartialOrd for HighlightEndpoint {
 196    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
 197        Some(self.cmp(other))
 198    }
 199}
 200
 201impl Ord for HighlightEndpoint {
 202    fn cmp(&self, other: &Self) -> cmp::Ordering {
 203        self.offset
 204            .cmp(&other.offset)
 205            .then_with(|| other.is_start.cmp(&self.is_start))
 206    }
 207}
 208
 209pub struct InlayChunks<'a> {
 210    transforms: Cursor<'a, Transform, (InlayOffset, usize)>,
 211    buffer_chunks: MultiBufferChunks<'a>,
 212    buffer_chunk: Option<Chunk<'a>>,
 213    inlay_chunks: Option<text::Chunks<'a>>,
 214    inlay_chunk: Option<&'a str>,
 215    output_offset: InlayOffset,
 216    max_output_offset: InlayOffset,
 217    inlay_highlight_style: Option<HighlightStyle>,
 218    suggestion_highlight_style: Option<HighlightStyle>,
 219    highlight_endpoints: Peekable<vec::IntoIter<HighlightEndpoint>>,
 220    active_highlights: BTreeMap<Option<TypeId>, HighlightStyle>,
 221    highlights: Highlights<'a>,
 222    snapshot: &'a InlaySnapshot,
 223}
 224
 225impl<'a> InlayChunks<'a> {
 226    pub fn seek(&mut self, offset: InlayOffset) {
 227        self.transforms.seek(&offset, Bias::Right, &());
 228
 229        let buffer_offset = self.snapshot.to_buffer_offset(offset);
 230        self.buffer_chunks.seek(buffer_offset);
 231        self.inlay_chunks = None;
 232        self.buffer_chunk = None;
 233        self.output_offset = offset;
 234    }
 235
 236    pub fn offset(&self) -> InlayOffset {
 237        self.output_offset
 238    }
 239}
 240
 241impl<'a> Iterator for InlayChunks<'a> {
 242    type Item = Chunk<'a>;
 243
 244    fn next(&mut self) -> Option<Self::Item> {
 245        if self.output_offset == self.max_output_offset {
 246            return None;
 247        }
 248
 249        let mut next_highlight_endpoint = InlayOffset(usize::MAX);
 250        while let Some(endpoint) = self.highlight_endpoints.peek().copied() {
 251            if endpoint.offset <= self.output_offset {
 252                if endpoint.is_start {
 253                    self.active_highlights.insert(endpoint.tag, endpoint.style);
 254                } else {
 255                    self.active_highlights.remove(&endpoint.tag);
 256                }
 257                self.highlight_endpoints.next();
 258            } else {
 259                next_highlight_endpoint = endpoint.offset;
 260                break;
 261            }
 262        }
 263
 264        let chunk = match self.transforms.item()? {
 265            Transform::Isomorphic(_) => {
 266                let chunk = self
 267                    .buffer_chunk
 268                    .get_or_insert_with(|| self.buffer_chunks.next().unwrap());
 269                if chunk.text.is_empty() {
 270                    *chunk = self.buffer_chunks.next().unwrap();
 271                }
 272
 273                let (prefix, suffix) = chunk.text.split_at(
 274                    chunk
 275                        .text
 276                        .len()
 277                        .min(self.transforms.end(&()).0 .0 - self.output_offset.0)
 278                        .min(next_highlight_endpoint.0 - self.output_offset.0),
 279                );
 280
 281                chunk.text = suffix;
 282                self.output_offset.0 += prefix.len();
 283                let mut prefix = Chunk {
 284                    text: prefix,
 285                    ..chunk.clone()
 286                };
 287                if !self.active_highlights.is_empty() {
 288                    let mut highlight_style = HighlightStyle::default();
 289                    for active_highlight in self.active_highlights.values() {
 290                        highlight_style.highlight(*active_highlight);
 291                    }
 292                    prefix.highlight_style = Some(highlight_style);
 293                }
 294                prefix
 295            }
 296            Transform::Inlay(inlay) => {
 297                let mut inlay_style_and_highlight = None;
 298                if let Some(inlay_highlights) = self.highlights.inlay_highlights {
 299                    for (_, inlay_id_to_data) in inlay_highlights.iter() {
 300                        let style_and_highlight = inlay_id_to_data.get(&inlay.id);
 301                        if style_and_highlight.is_some() {
 302                            inlay_style_and_highlight = style_and_highlight;
 303                            break;
 304                        }
 305                    }
 306                }
 307
 308                let mut highlight_style = match inlay.id {
 309                    InlayId::Suggestion(_) => self.suggestion_highlight_style,
 310                    InlayId::Hint(_) => self.inlay_highlight_style,
 311                };
 312                let next_inlay_highlight_endpoint;
 313                let offset_in_inlay = self.output_offset - self.transforms.start().0;
 314                if let Some((style, highlight)) = inlay_style_and_highlight {
 315                    let range = &highlight.range;
 316                    if offset_in_inlay.0 < range.start {
 317                        next_inlay_highlight_endpoint = range.start - offset_in_inlay.0;
 318                    } else if offset_in_inlay.0 >= range.end {
 319                        next_inlay_highlight_endpoint = usize::MAX;
 320                    } else {
 321                        next_inlay_highlight_endpoint = range.end - offset_in_inlay.0;
 322                        highlight_style
 323                            .get_or_insert_with(|| Default::default())
 324                            .highlight(style.clone());
 325                    }
 326                } else {
 327                    next_inlay_highlight_endpoint = usize::MAX;
 328                }
 329
 330                let inlay_chunks = self.inlay_chunks.get_or_insert_with(|| {
 331                    let start = offset_in_inlay;
 332                    let end = cmp::min(self.max_output_offset, self.transforms.end(&()).0)
 333                        - self.transforms.start().0;
 334                    inlay.text.chunks_in_range(start.0..end.0)
 335                });
 336                let inlay_chunk = self
 337                    .inlay_chunk
 338                    .get_or_insert_with(|| inlay_chunks.next().unwrap());
 339                let (chunk, remainder) =
 340                    inlay_chunk.split_at(inlay_chunk.len().min(next_inlay_highlight_endpoint));
 341                *inlay_chunk = remainder;
 342                if inlay_chunk.is_empty() {
 343                    self.inlay_chunk = None;
 344                }
 345
 346                self.output_offset.0 += chunk.len();
 347
 348                if !self.active_highlights.is_empty() {
 349                    for active_highlight in self.active_highlights.values() {
 350                        highlight_style
 351                            .get_or_insert(Default::default())
 352                            .highlight(*active_highlight);
 353                    }
 354                }
 355                Chunk {
 356                    text: chunk,
 357                    highlight_style,
 358                    ..Default::default()
 359                }
 360            }
 361        };
 362
 363        if self.output_offset == self.transforms.end(&()).0 {
 364            self.inlay_chunks = None;
 365            self.transforms.next(&());
 366        }
 367
 368        Some(chunk)
 369    }
 370}
 371
 372impl<'a> InlayBufferRows<'a> {
 373    pub fn seek(&mut self, row: u32) {
 374        let inlay_point = InlayPoint::new(row, 0);
 375        self.transforms.seek(&inlay_point, Bias::Left, &());
 376
 377        let mut buffer_point = self.transforms.start().1;
 378        let buffer_row = if row == 0 {
 379            0
 380        } else {
 381            match self.transforms.item() {
 382                Some(Transform::Isomorphic(_)) => {
 383                    buffer_point += inlay_point.0 - self.transforms.start().0 .0;
 384                    buffer_point.row
 385                }
 386                _ => cmp::min(buffer_point.row + 1, self.max_buffer_row),
 387            }
 388        };
 389        self.inlay_row = inlay_point.row();
 390        self.buffer_rows.seek(buffer_row);
 391    }
 392}
 393
 394impl<'a> Iterator for InlayBufferRows<'a> {
 395    type Item = Option<u32>;
 396
 397    fn next(&mut self) -> Option<Self::Item> {
 398        let buffer_row = if self.inlay_row == 0 {
 399            self.buffer_rows.next().unwrap()
 400        } else {
 401            match self.transforms.item()? {
 402                Transform::Inlay(_) => None,
 403                Transform::Isomorphic(_) => self.buffer_rows.next().unwrap(),
 404            }
 405        };
 406
 407        self.inlay_row += 1;
 408        self.transforms
 409            .seek_forward(&InlayPoint::new(self.inlay_row, 0), Bias::Left, &());
 410
 411        Some(buffer_row)
 412    }
 413}
 414
 415impl InlayPoint {
 416    pub fn new(row: u32, column: u32) -> Self {
 417        Self(Point::new(row, column))
 418    }
 419
 420    pub fn row(self) -> u32 {
 421        self.0.row
 422    }
 423}
 424
 425impl InlayMap {
 426    pub fn new(buffer: MultiBufferSnapshot) -> (Self, InlaySnapshot) {
 427        let version = 0;
 428        let snapshot = InlaySnapshot {
 429            buffer: buffer.clone(),
 430            transforms: SumTree::from_iter(Some(Transform::Isomorphic(buffer.text_summary())), &()),
 431            inlays: Vec::new(),
 432            version,
 433        };
 434
 435        (
 436            Self {
 437                snapshot: snapshot.clone(),
 438            },
 439            snapshot,
 440        )
 441    }
 442
 443    pub fn sync(
 444        &mut self,
 445        buffer_snapshot: MultiBufferSnapshot,
 446        mut buffer_edits: Vec<text::Edit<usize>>,
 447    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 448        let snapshot = &mut self.snapshot;
 449
 450        if buffer_edits.is_empty() {
 451            if snapshot.buffer.trailing_excerpt_update_count()
 452                != buffer_snapshot.trailing_excerpt_update_count()
 453            {
 454                buffer_edits.push(Edit {
 455                    old: snapshot.buffer.len()..snapshot.buffer.len(),
 456                    new: buffer_snapshot.len()..buffer_snapshot.len(),
 457                });
 458            }
 459        }
 460
 461        if buffer_edits.is_empty() {
 462            if snapshot.buffer.edit_count() != buffer_snapshot.edit_count()
 463                || snapshot.buffer.parse_count() != buffer_snapshot.parse_count()
 464                || snapshot.buffer.diagnostics_update_count()
 465                    != buffer_snapshot.diagnostics_update_count()
 466                || snapshot.buffer.git_diff_update_count()
 467                    != buffer_snapshot.git_diff_update_count()
 468                || snapshot.buffer.trailing_excerpt_update_count()
 469                    != buffer_snapshot.trailing_excerpt_update_count()
 470            {
 471                snapshot.version += 1;
 472            }
 473
 474            snapshot.buffer = buffer_snapshot;
 475            (snapshot.clone(), Vec::new())
 476        } else {
 477            let mut inlay_edits = Patch::default();
 478            let mut new_transforms = SumTree::new();
 479            let mut cursor = snapshot.transforms.cursor::<(usize, InlayOffset)>();
 480            let mut buffer_edits_iter = buffer_edits.iter().peekable();
 481            while let Some(buffer_edit) = buffer_edits_iter.next() {
 482                new_transforms.append(cursor.slice(&buffer_edit.old.start, Bias::Left, &()), &());
 483                if let Some(Transform::Isomorphic(transform)) = cursor.item() {
 484                    if cursor.end(&()).0 == buffer_edit.old.start {
 485                        push_isomorphic(&mut new_transforms, transform.clone());
 486                        cursor.next(&());
 487                    }
 488                }
 489
 490                // Remove all the inlays and transforms contained by the edit.
 491                let old_start =
 492                    cursor.start().1 + InlayOffset(buffer_edit.old.start - cursor.start().0);
 493                cursor.seek(&buffer_edit.old.end, Bias::Right, &());
 494                let old_end =
 495                    cursor.start().1 + InlayOffset(buffer_edit.old.end - cursor.start().0);
 496
 497                // Push the unchanged prefix.
 498                let prefix_start = new_transforms.summary().input.len;
 499                let prefix_end = buffer_edit.new.start;
 500                push_isomorphic(
 501                    &mut new_transforms,
 502                    buffer_snapshot.text_summary_for_range(prefix_start..prefix_end),
 503                );
 504                let new_start = InlayOffset(new_transforms.summary().output.len);
 505
 506                let start_ix = match snapshot.inlays.binary_search_by(|probe| {
 507                    probe
 508                        .position
 509                        .to_offset(&buffer_snapshot)
 510                        .cmp(&buffer_edit.new.start)
 511                        .then(std::cmp::Ordering::Greater)
 512                }) {
 513                    Ok(ix) | Err(ix) => ix,
 514                };
 515
 516                for inlay in &snapshot.inlays[start_ix..] {
 517                    let buffer_offset = inlay.position.to_offset(&buffer_snapshot);
 518                    if buffer_offset > buffer_edit.new.end {
 519                        break;
 520                    }
 521
 522                    let prefix_start = new_transforms.summary().input.len;
 523                    let prefix_end = buffer_offset;
 524                    push_isomorphic(
 525                        &mut new_transforms,
 526                        buffer_snapshot.text_summary_for_range(prefix_start..prefix_end),
 527                    );
 528
 529                    if inlay.position.is_valid(&buffer_snapshot) {
 530                        new_transforms.push(Transform::Inlay(inlay.clone()), &());
 531                    }
 532                }
 533
 534                // Apply the rest of the edit.
 535                let transform_start = new_transforms.summary().input.len;
 536                push_isomorphic(
 537                    &mut new_transforms,
 538                    buffer_snapshot.text_summary_for_range(transform_start..buffer_edit.new.end),
 539                );
 540                let new_end = InlayOffset(new_transforms.summary().output.len);
 541                inlay_edits.push(Edit {
 542                    old: old_start..old_end,
 543                    new: new_start..new_end,
 544                });
 545
 546                // If the next edit doesn't intersect the current isomorphic transform, then
 547                // we can push its remainder.
 548                if buffer_edits_iter
 549                    .peek()
 550                    .map_or(true, |edit| edit.old.start >= cursor.end(&()).0)
 551                {
 552                    let transform_start = new_transforms.summary().input.len;
 553                    let transform_end =
 554                        buffer_edit.new.end + (cursor.end(&()).0 - buffer_edit.old.end);
 555                    push_isomorphic(
 556                        &mut new_transforms,
 557                        buffer_snapshot.text_summary_for_range(transform_start..transform_end),
 558                    );
 559                    cursor.next(&());
 560                }
 561            }
 562
 563            new_transforms.append(cursor.suffix(&()), &());
 564            if new_transforms.is_empty() {
 565                new_transforms.push(Transform::Isomorphic(Default::default()), &());
 566            }
 567
 568            drop(cursor);
 569            snapshot.transforms = new_transforms;
 570            snapshot.version += 1;
 571            snapshot.buffer = buffer_snapshot;
 572            snapshot.check_invariants();
 573
 574            (snapshot.clone(), inlay_edits.into_inner())
 575        }
 576    }
 577
 578    pub fn splice(
 579        &mut self,
 580        to_remove: Vec<InlayId>,
 581        to_insert: Vec<Inlay>,
 582    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 583        let snapshot = &mut self.snapshot;
 584        let mut edits = BTreeSet::new();
 585
 586        snapshot.inlays.retain(|inlay| {
 587            let retain = !to_remove.contains(&inlay.id);
 588            if !retain {
 589                let offset = inlay.position.to_offset(&snapshot.buffer);
 590                edits.insert(offset);
 591            }
 592            retain
 593        });
 594
 595        for inlay_to_insert in to_insert {
 596            // Avoid inserting empty inlays.
 597            if inlay_to_insert.text.is_empty() {
 598                continue;
 599            }
 600
 601            let offset = inlay_to_insert.position.to_offset(&snapshot.buffer);
 602            match snapshot.inlays.binary_search_by(|probe| {
 603                probe
 604                    .position
 605                    .cmp(&inlay_to_insert.position, &snapshot.buffer)
 606            }) {
 607                Ok(ix) | Err(ix) => {
 608                    snapshot.inlays.insert(ix, inlay_to_insert);
 609                }
 610            }
 611
 612            edits.insert(offset);
 613        }
 614
 615        let buffer_edits = edits
 616            .into_iter()
 617            .map(|offset| Edit {
 618                old: offset..offset,
 619                new: offset..offset,
 620            })
 621            .collect();
 622        let buffer_snapshot = snapshot.buffer.clone();
 623        let (snapshot, edits) = self.sync(buffer_snapshot, buffer_edits);
 624        (snapshot, edits)
 625    }
 626
 627    pub fn current_inlays(&self) -> impl Iterator<Item = &Inlay> {
 628        self.snapshot.inlays.iter()
 629    }
 630
 631    #[cfg(test)]
 632    pub(crate) fn randomly_mutate(
 633        &mut self,
 634        next_inlay_id: &mut usize,
 635        rng: &mut rand::rngs::StdRng,
 636    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 637        use rand::prelude::*;
 638        use util::post_inc;
 639
 640        let mut to_remove = Vec::new();
 641        let mut to_insert = Vec::new();
 642        let snapshot = &mut self.snapshot;
 643        for i in 0..rng.gen_range(1..=5) {
 644            if snapshot.inlays.is_empty() || rng.gen() {
 645                let position = snapshot.buffer.random_byte_range(0, rng).start;
 646                let bias = if rng.gen() { Bias::Left } else { Bias::Right };
 647                let len = if rng.gen_bool(0.01) {
 648                    0
 649                } else {
 650                    rng.gen_range(1..=5)
 651                };
 652                let text = util::RandomCharIter::new(&mut *rng)
 653                    .filter(|ch| *ch != '\r')
 654                    .take(len)
 655                    .collect::<String>();
 656
 657                let inlay_id = if i % 2 == 0 {
 658                    InlayId::Hint(post_inc(next_inlay_id))
 659                } else {
 660                    InlayId::Suggestion(post_inc(next_inlay_id))
 661                };
 662                log::info!(
 663                    "creating inlay {:?} at buffer offset {} with bias {:?} and text {:?}",
 664                    inlay_id,
 665                    position,
 666                    bias,
 667                    text
 668                );
 669
 670                to_insert.push(Inlay {
 671                    id: inlay_id,
 672                    position: snapshot.buffer.anchor_at(position, bias),
 673                    text: text.into(),
 674                });
 675            } else {
 676                to_remove.push(
 677                    snapshot
 678                        .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<'a>(&'a self, row: u32) -> InlayBufferRows<'a> {
 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 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        link_go_to_definition::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
1551                .snapshot
1552                .inlays
1553                .iter()
1554                .map(|inlay| inlay.id)
1555                .collect(),
1556            Vec::new(),
1557        );
1558        assert_eq!(inlay_snapshot.text(), "abxJKLyDzefghi");
1559    }
1560
1561    #[gpui::test]
1562    fn test_inlay_buffer_rows(cx: &mut AppContext) {
1563        let buffer = MultiBuffer::build_simple("abc\ndef\nghi", cx);
1564        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
1565        assert_eq!(inlay_snapshot.text(), "abc\ndef\nghi");
1566        let mut next_inlay_id = 0;
1567
1568        let (inlay_snapshot, _) = inlay_map.splice(
1569            Vec::new(),
1570            vec![
1571                Inlay {
1572                    id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1573                    position: buffer.read(cx).snapshot(cx).anchor_before(0),
1574                    text: "|123|\n".into(),
1575                },
1576                Inlay {
1577                    id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1578                    position: buffer.read(cx).snapshot(cx).anchor_before(4),
1579                    text: "|456|".into(),
1580                },
1581                Inlay {
1582                    id: InlayId::Suggestion(post_inc(&mut next_inlay_id)),
1583                    position: buffer.read(cx).snapshot(cx).anchor_before(7),
1584                    text: "\n|567|\n".into(),
1585                },
1586            ],
1587        );
1588        assert_eq!(inlay_snapshot.text(), "|123|\nabc\n|456|def\n|567|\n\nghi");
1589        assert_eq!(
1590            inlay_snapshot.buffer_rows(0).collect::<Vec<_>>(),
1591            vec![Some(0), None, Some(1), None, None, Some(2)]
1592        );
1593    }
1594
1595    #[gpui::test(iterations = 100)]
1596    fn test_random_inlays(cx: &mut AppContext, mut rng: StdRng) {
1597        init_test(cx);
1598
1599        let operations = env::var("OPERATIONS")
1600            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1601            .unwrap_or(10);
1602
1603        let len = rng.gen_range(0..30);
1604        let buffer = if rng.gen() {
1605            let text = util::RandomCharIter::new(&mut rng)
1606                .take(len)
1607                .collect::<String>();
1608            MultiBuffer::build_simple(&text, cx)
1609        } else {
1610            MultiBuffer::build_random(&mut rng, cx)
1611        };
1612        let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1613        let mut next_inlay_id = 0;
1614        log::info!("buffer text: {:?}", buffer_snapshot.text());
1615        let (mut inlay_map, mut inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1616        for _ in 0..operations {
1617            let mut inlay_edits = Patch::default();
1618
1619            let mut prev_inlay_text = inlay_snapshot.text();
1620            let mut buffer_edits = Vec::new();
1621            match rng.gen_range(0..=100) {
1622                0..=50 => {
1623                    let (snapshot, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1624                    log::info!("mutated text: {:?}", snapshot.text());
1625                    inlay_edits = Patch::new(edits);
1626                }
1627                _ => buffer.update(cx, |buffer, cx| {
1628                    let subscription = buffer.subscribe();
1629                    let edit_count = rng.gen_range(1..=5);
1630                    buffer.randomly_mutate(&mut rng, edit_count, cx);
1631                    buffer_snapshot = buffer.snapshot(cx);
1632                    let edits = subscription.consume().into_inner();
1633                    log::info!("editing {:?}", edits);
1634                    buffer_edits.extend(edits);
1635                }),
1636            };
1637
1638            let (new_inlay_snapshot, new_inlay_edits) =
1639                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1640            inlay_snapshot = new_inlay_snapshot;
1641            inlay_edits = inlay_edits.compose(new_inlay_edits);
1642
1643            log::info!("buffer text: {:?}", buffer_snapshot.text());
1644            log::info!("inlay text: {:?}", inlay_snapshot.text());
1645
1646            let inlays = inlay_map
1647                .snapshot
1648                .inlays
1649                .iter()
1650                .filter(|inlay| inlay.position.is_valid(&buffer_snapshot))
1651                .map(|inlay| {
1652                    let offset = inlay.position.to_offset(&buffer_snapshot);
1653                    (offset, inlay.clone())
1654                })
1655                .collect::<Vec<_>>();
1656            let mut expected_text = Rope::from(buffer_snapshot.text());
1657            for (offset, inlay) in inlays.iter().rev() {
1658                expected_text.replace(*offset..*offset, &inlay.text.to_string());
1659            }
1660            assert_eq!(inlay_snapshot.text(), expected_text.to_string());
1661
1662            let expected_buffer_rows = inlay_snapshot.buffer_rows(0).collect::<Vec<_>>();
1663            assert_eq!(
1664                expected_buffer_rows.len() as u32,
1665                expected_text.max_point().row + 1
1666            );
1667            for row_start in 0..expected_buffer_rows.len() {
1668                assert_eq!(
1669                    inlay_snapshot
1670                        .buffer_rows(row_start as u32)
1671                        .collect::<Vec<_>>(),
1672                    &expected_buffer_rows[row_start..],
1673                    "incorrect buffer rows starting at {}",
1674                    row_start
1675                );
1676            }
1677
1678            let mut text_highlights = TextHighlights::default();
1679            let mut inlay_highlights = InlayHighlights::default();
1680            let highlight_count = rng.gen_range(0_usize..10);
1681            if false && rng.gen_bool(0.5) {
1682                let mut highlight_ranges = (0..highlight_count)
1683                    .map(|_| buffer_snapshot.random_byte_range(0, &mut rng))
1684                    .collect::<Vec<_>>();
1685                highlight_ranges.sort_by_key(|range| (range.start, Reverse(range.end)));
1686                log::info!("highlighting text ranges {highlight_ranges:?}");
1687                text_highlights.insert(
1688                    Some(TypeId::of::<()>()),
1689                    Arc::new((
1690                        HighlightStyle::default(),
1691                        highlight_ranges
1692                            .into_iter()
1693                            .map(|range| {
1694                                buffer_snapshot.anchor_before(range.start)
1695                                    ..buffer_snapshot.anchor_after(range.end)
1696                            })
1697                            .collect(),
1698                    )),
1699                );
1700            } else {
1701                let mut inlay_indices = BTreeSet::default();
1702                while inlay_indices.len() < highlight_count.min(inlays.len()) {
1703                    inlay_indices.insert(rng.gen_range(0..inlays.len()));
1704                }
1705                let new_highlights = inlay_indices
1706                    .into_iter()
1707                    .filter_map(|i| {
1708                        let (_, inlay) = &inlays[i];
1709                        let inlay_text_len = inlay.text.len();
1710                        match inlay_text_len {
1711                            0 => None,
1712                            1 => Some(InlayHighlight {
1713                                inlay: inlay.id,
1714                                inlay_position: inlay.position,
1715                                range: 0..1,
1716                            }),
1717                            n => {
1718                                let inlay_text = inlay.text.to_string();
1719                                let mut highlight_end = rng.gen_range(1..n);
1720                                let mut highlight_start = rng.gen_range(0..highlight_end);
1721                                while !inlay_text.is_char_boundary(highlight_end) {
1722                                    highlight_end += 1;
1723                                }
1724                                while !inlay_text.is_char_boundary(highlight_start) {
1725                                    highlight_start -= 1;
1726                                }
1727                                Some(InlayHighlight {
1728                                    inlay: inlay.id,
1729                                    inlay_position: inlay.position,
1730                                    range: highlight_start..highlight_end,
1731                                })
1732                            }
1733                        }
1734                    })
1735                    .map(|highlight| (highlight.inlay, (HighlightStyle::default(), highlight)))
1736                    .collect();
1737                log::info!("highlighting inlay ranges {new_highlights:?}");
1738                inlay_highlights.insert(TypeId::of::<()>(), new_highlights);
1739            };
1740
1741            for _ in 0..5 {
1742                let mut end = rng.gen_range(0..=inlay_snapshot.len().0);
1743                end = expected_text.clip_offset(end, Bias::Right);
1744                let mut start = rng.gen_range(0..=end);
1745                start = expected_text.clip_offset(start, Bias::Right);
1746
1747                let range = InlayOffset(start)..InlayOffset(end);
1748                log::info!("calling inlay_snapshot.chunks({:?})", range);
1749                let actual_text = inlay_snapshot
1750                    .chunks(
1751                        range,
1752                        false,
1753                        Highlights {
1754                            text_highlights: Some(&text_highlights),
1755                            inlay_highlights: Some(&inlay_highlights),
1756                            ..Highlights::default()
1757                        },
1758                    )
1759                    .map(|chunk| chunk.text)
1760                    .collect::<String>();
1761                assert_eq!(
1762                    actual_text,
1763                    expected_text.slice(start..end).to_string(),
1764                    "incorrect text in range {:?}",
1765                    start..end
1766                );
1767
1768                assert_eq!(
1769                    inlay_snapshot.text_summary_for_range(InlayOffset(start)..InlayOffset(end)),
1770                    expected_text.slice(start..end).summary()
1771                );
1772            }
1773
1774            for edit in inlay_edits {
1775                prev_inlay_text.replace_range(
1776                    edit.new.start.0..edit.new.start.0 + edit.old_len().0,
1777                    &inlay_snapshot.text()[edit.new.start.0..edit.new.end.0],
1778                );
1779            }
1780            assert_eq!(prev_inlay_text, inlay_snapshot.text());
1781
1782            assert_eq!(expected_text.max_point(), inlay_snapshot.max_point().0);
1783            assert_eq!(expected_text.len(), inlay_snapshot.len().0);
1784
1785            let mut buffer_point = Point::default();
1786            let mut inlay_point = inlay_snapshot.to_inlay_point(buffer_point);
1787            let mut buffer_chars = buffer_snapshot.chars_at(0);
1788            loop {
1789                // Ensure conversion from buffer coordinates to inlay coordinates
1790                // is consistent.
1791                let buffer_offset = buffer_snapshot.point_to_offset(buffer_point);
1792                assert_eq!(
1793                    inlay_snapshot.to_point(inlay_snapshot.to_inlay_offset(buffer_offset)),
1794                    inlay_point
1795                );
1796
1797                // No matter which bias we clip an inlay point with, it doesn't move
1798                // because it was constructed from a buffer point.
1799                assert_eq!(
1800                    inlay_snapshot.clip_point(inlay_point, Bias::Left),
1801                    inlay_point,
1802                    "invalid inlay point for buffer point {:?} when clipped left",
1803                    buffer_point
1804                );
1805                assert_eq!(
1806                    inlay_snapshot.clip_point(inlay_point, Bias::Right),
1807                    inlay_point,
1808                    "invalid inlay point for buffer point {:?} when clipped right",
1809                    buffer_point
1810                );
1811
1812                if let Some(ch) = buffer_chars.next() {
1813                    if ch == '\n' {
1814                        buffer_point += Point::new(1, 0);
1815                    } else {
1816                        buffer_point += Point::new(0, ch.len_utf8() as u32);
1817                    }
1818
1819                    // Ensure that moving forward in the buffer always moves the inlay point forward as well.
1820                    let new_inlay_point = inlay_snapshot.to_inlay_point(buffer_point);
1821                    assert!(new_inlay_point > inlay_point);
1822                    inlay_point = new_inlay_point;
1823                } else {
1824                    break;
1825                }
1826            }
1827
1828            let mut inlay_point = InlayPoint::default();
1829            let mut inlay_offset = InlayOffset::default();
1830            for ch in expected_text.chars() {
1831                assert_eq!(
1832                    inlay_snapshot.to_offset(inlay_point),
1833                    inlay_offset,
1834                    "invalid to_offset({:?})",
1835                    inlay_point
1836                );
1837                assert_eq!(
1838                    inlay_snapshot.to_point(inlay_offset),
1839                    inlay_point,
1840                    "invalid to_point({:?})",
1841                    inlay_offset
1842                );
1843
1844                let mut bytes = [0; 4];
1845                for byte in ch.encode_utf8(&mut bytes).as_bytes() {
1846                    inlay_offset.0 += 1;
1847                    if *byte == b'\n' {
1848                        inlay_point.0 += Point::new(1, 0);
1849                    } else {
1850                        inlay_point.0 += Point::new(0, 1);
1851                    }
1852
1853                    let clipped_left_point = inlay_snapshot.clip_point(inlay_point, Bias::Left);
1854                    let clipped_right_point = inlay_snapshot.clip_point(inlay_point, Bias::Right);
1855                    assert!(
1856                        clipped_left_point <= clipped_right_point,
1857                        "inlay point {:?} when clipped left is greater than when clipped right ({:?} > {:?})",
1858                        inlay_point,
1859                        clipped_left_point,
1860                        clipped_right_point
1861                    );
1862
1863                    // Ensure the clipped points are at valid text locations.
1864                    assert_eq!(
1865                        clipped_left_point.0,
1866                        expected_text.clip_point(clipped_left_point.0, Bias::Left)
1867                    );
1868                    assert_eq!(
1869                        clipped_right_point.0,
1870                        expected_text.clip_point(clipped_right_point.0, Bias::Right)
1871                    );
1872
1873                    // Ensure the clipped points never overshoot the end of the map.
1874                    assert!(clipped_left_point <= inlay_snapshot.max_point());
1875                    assert!(clipped_right_point <= inlay_snapshot.max_point());
1876
1877                    // Ensure the clipped points are at valid buffer locations.
1878                    assert_eq!(
1879                        inlay_snapshot
1880                            .to_inlay_point(inlay_snapshot.to_buffer_point(clipped_left_point)),
1881                        clipped_left_point,
1882                        "to_buffer_point({:?}) = {:?}",
1883                        clipped_left_point,
1884                        inlay_snapshot.to_buffer_point(clipped_left_point),
1885                    );
1886                    assert_eq!(
1887                        inlay_snapshot
1888                            .to_inlay_point(inlay_snapshot.to_buffer_point(clipped_right_point)),
1889                        clipped_right_point,
1890                        "to_buffer_point({:?}) = {:?}",
1891                        clipped_right_point,
1892                        inlay_snapshot.to_buffer_point(clipped_right_point),
1893                    );
1894                }
1895            }
1896        }
1897    }
1898
1899    fn init_test(cx: &mut AppContext) {
1900        cx.set_global(SettingsStore::test(cx));
1901        theme::init((), cx);
1902    }
1903}