inlay_map.rs

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