inlay_map.rs

   1//! The inlay map. See the [`display_map`][super] docs for an overview of how the inlay map fits
   2//! into the rest of the [`DisplayMap`][super::DisplayMap]. Much of the documentation for this
   3//! module generalizes to other layers.
   4//!
   5//! The core of this module is the [`InlayMap`] struct, which maintains a vec of [`Inlay`]s, and
   6//! [`InlaySnapshot`], which holds a sum tree of [`Transform`]s.
   7
   8use crate::{
   9    ChunkRenderer, HighlightStyles,
  10    inlays::{Inlay, InlayContent},
  11};
  12use collections::BTreeSet;
  13use language::{Chunk, Edit, Point, TextSummary};
  14use multi_buffer::{
  15    MBTextSummary, MultiBufferOffset, MultiBufferRow, MultiBufferRows, MultiBufferSnapshot,
  16    RowInfo, ToOffset,
  17};
  18use project::InlayId;
  19use std::{
  20    cmp, iter,
  21    ops::{Add, AddAssign, Range, Sub, SubAssign},
  22    sync::Arc,
  23};
  24use sum_tree::{Bias, Cursor, Dimensions, SumTree};
  25use text::{ChunkBitmaps, Patch};
  26use ui::{ActiveTheme, IntoElement as _, ParentElement as _, Styled as _, div};
  27
  28use super::{Highlights, custom_highlights::CustomHighlightsChunks, fold_map::ChunkRendererId};
  29
  30/// Decides where the [`Inlay`]s should be displayed.
  31///
  32/// See the [`display_map` module documentation](crate::display_map) for more information.
  33pub struct InlayMap {
  34    snapshot: InlaySnapshot,
  35    inlays: Vec<Inlay>,
  36}
  37
  38#[derive(Clone)]
  39pub struct InlaySnapshot {
  40    pub buffer: MultiBufferSnapshot,
  41    transforms: SumTree<Transform>,
  42    pub version: usize,
  43}
  44
  45impl std::ops::Deref for InlaySnapshot {
  46    type Target = MultiBufferSnapshot;
  47
  48    fn deref(&self) -> &Self::Target {
  49        &self.buffer
  50    }
  51}
  52
  53#[derive(Clone, Debug)]
  54enum Transform {
  55    Isomorphic(MBTextSummary),
  56    Inlay(Inlay),
  57}
  58
  59impl sum_tree::Item for Transform {
  60    type Summary = TransformSummary;
  61
  62    #[ztracing::instrument(skip_all)]
  63    fn summary(&self, _: ()) -> Self::Summary {
  64        match self {
  65            Transform::Isomorphic(summary) => TransformSummary {
  66                input: *summary,
  67                output: *summary,
  68            },
  69            Transform::Inlay(inlay) => TransformSummary {
  70                input: MBTextSummary::default(),
  71                output: MBTextSummary::from(inlay.text().summary()),
  72            },
  73        }
  74    }
  75}
  76
  77#[derive(Clone, Debug, Default)]
  78struct TransformSummary {
  79    /// Summary of the text before inlays have been applied.
  80    input: MBTextSummary,
  81    /// Summary of the text after inlays have been applied.
  82    output: MBTextSummary,
  83}
  84
  85impl sum_tree::ContextLessSummary for TransformSummary {
  86    fn zero() -> Self {
  87        Default::default()
  88    }
  89
  90    fn add_summary(&mut self, other: &Self) {
  91        self.input += other.input;
  92        self.output += other.output;
  93    }
  94}
  95
  96pub type InlayEdit = Edit<InlayOffset>;
  97
  98#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
  99pub struct InlayOffset(pub MultiBufferOffset);
 100
 101impl Add for InlayOffset {
 102    type Output = Self;
 103
 104    fn add(self, rhs: Self) -> Self::Output {
 105        Self(self.0 + rhs.0)
 106    }
 107}
 108
 109impl Sub for InlayOffset {
 110    type Output = <MultiBufferOffset as Sub>::Output;
 111
 112    fn sub(self, rhs: Self) -> Self::Output {
 113        self.0 - rhs.0
 114    }
 115}
 116
 117impl<T> SubAssign<T> for InlayOffset
 118where
 119    MultiBufferOffset: SubAssign<T>,
 120{
 121    fn sub_assign(&mut self, rhs: T) {
 122        self.0 -= rhs;
 123    }
 124}
 125
 126impl<T> Add<T> for InlayOffset
 127where
 128    MultiBufferOffset: Add<T, Output = MultiBufferOffset>,
 129{
 130    type Output = Self;
 131
 132    fn add(self, rhs: T) -> Self::Output {
 133        Self(self.0 + rhs)
 134    }
 135}
 136
 137impl AddAssign for InlayOffset {
 138    fn add_assign(&mut self, rhs: Self) {
 139        self.0 += rhs.0;
 140    }
 141}
 142
 143impl<T> AddAssign<T> for InlayOffset
 144where
 145    MultiBufferOffset: AddAssign<T>,
 146{
 147    fn add_assign(&mut self, rhs: T) {
 148        self.0 += rhs;
 149    }
 150}
 151
 152impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
 153    fn zero(_cx: ()) -> Self {
 154        Default::default()
 155    }
 156
 157    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
 158        self.0 += summary.output.len;
 159    }
 160}
 161
 162#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 163pub struct InlayPoint(pub Point);
 164
 165impl Add for InlayPoint {
 166    type Output = Self;
 167
 168    fn add(self, rhs: Self) -> Self::Output {
 169        Self(self.0 + rhs.0)
 170    }
 171}
 172
 173impl Sub for InlayPoint {
 174    type Output = Self;
 175
 176    fn sub(self, rhs: Self) -> Self::Output {
 177        Self(self.0 - rhs.0)
 178    }
 179}
 180
 181impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
 182    fn zero(_cx: ()) -> Self {
 183        Default::default()
 184    }
 185
 186    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
 187        self.0 += &summary.output.lines;
 188    }
 189}
 190
 191impl<'a> sum_tree::Dimension<'a, TransformSummary> for MultiBufferOffset {
 192    fn zero(_cx: ()) -> Self {
 193        Default::default()
 194    }
 195
 196    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
 197        *self += summary.input.len;
 198    }
 199}
 200
 201impl<'a> sum_tree::Dimension<'a, TransformSummary> for Point {
 202    fn zero(_cx: ()) -> Self {
 203        Default::default()
 204    }
 205
 206    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
 207        *self += &summary.input.lines;
 208    }
 209}
 210
 211#[derive(Clone)]
 212pub struct InlayBufferRows<'a> {
 213    transforms: Cursor<'a, 'static, Transform, Dimensions<InlayPoint, Point>>,
 214    buffer_rows: MultiBufferRows<'a>,
 215    inlay_row: u32,
 216    max_buffer_row: MultiBufferRow,
 217}
 218
 219pub struct InlayChunks<'a> {
 220    transforms: Cursor<'a, 'static, Transform, Dimensions<InlayOffset, MultiBufferOffset>>,
 221    buffer_chunks: CustomHighlightsChunks<'a>,
 222    buffer_chunk: Option<Chunk<'a>>,
 223    inlay_chunks: Option<text::ChunkWithBitmaps<'a>>,
 224    /// text, char bitmap, tabs bitmap
 225    inlay_chunk: Option<ChunkBitmaps<'a>>,
 226    output_offset: InlayOffset,
 227    max_output_offset: InlayOffset,
 228    highlight_styles: HighlightStyles,
 229    highlights: Highlights<'a>,
 230    snapshot: &'a InlaySnapshot,
 231}
 232
 233#[derive(Clone)]
 234pub struct InlayChunk<'a> {
 235    pub chunk: Chunk<'a>,
 236    /// Whether the inlay should be customly rendered.
 237    pub renderer: Option<ChunkRenderer>,
 238}
 239
 240impl InlayChunks<'_> {
 241    #[ztracing::instrument(skip_all)]
 242    pub fn seek(&mut self, new_range: Range<InlayOffset>) {
 243        self.transforms.seek(&new_range.start, Bias::Right);
 244
 245        let buffer_range = self.snapshot.to_buffer_offset(new_range.start)
 246            ..self.snapshot.to_buffer_offset(new_range.end);
 247        self.buffer_chunks.seek(buffer_range);
 248        self.inlay_chunks = None;
 249        self.buffer_chunk = None;
 250        self.output_offset = new_range.start;
 251        self.max_output_offset = new_range.end;
 252    }
 253
 254    pub fn offset(&self) -> InlayOffset {
 255        self.output_offset
 256    }
 257}
 258
 259impl<'a> Iterator for InlayChunks<'a> {
 260    type Item = InlayChunk<'a>;
 261
 262    #[ztracing::instrument(skip_all)]
 263    fn next(&mut self) -> Option<Self::Item> {
 264        if self.output_offset == self.max_output_offset {
 265            return None;
 266        }
 267
 268        let chunk = match self.transforms.item()? {
 269            Transform::Isomorphic(_) => {
 270                let chunk = self
 271                    .buffer_chunk
 272                    .get_or_insert_with(|| self.buffer_chunks.next().unwrap());
 273                if chunk.text.is_empty() {
 274                    *chunk = self.buffer_chunks.next().unwrap();
 275                }
 276
 277                let desired_bytes = self.transforms.end().0.0 - self.output_offset.0;
 278
 279                // If we're already at the transform boundary, skip to the next transform
 280                if desired_bytes == 0 {
 281                    self.inlay_chunks = None;
 282                    self.transforms.next();
 283                    return self.next();
 284                }
 285
 286                // Determine split index handling edge cases
 287                let split_index = if desired_bytes >= chunk.text.len() {
 288                    chunk.text.len()
 289                } else {
 290                    chunk.text.ceil_char_boundary(desired_bytes)
 291                };
 292
 293                let (prefix, suffix) = chunk.text.split_at(split_index);
 294                self.output_offset.0 += prefix.len();
 295
 296                let mask = 1u128.unbounded_shl(split_index as u32).wrapping_sub(1);
 297                let chars = chunk.chars & mask;
 298                let tabs = chunk.tabs & mask;
 299                let newlines = chunk.newlines & mask;
 300
 301                chunk.chars = chunk.chars.unbounded_shr(split_index as u32);
 302                chunk.tabs = chunk.tabs.unbounded_shr(split_index as u32);
 303                chunk.newlines = chunk.newlines.unbounded_shr(split_index as u32);
 304                chunk.text = suffix;
 305
 306                InlayChunk {
 307                    chunk: Chunk {
 308                        text: prefix,
 309                        chars,
 310                        tabs,
 311                        newlines,
 312                        ..chunk.clone()
 313                    },
 314                    renderer: None,
 315                }
 316            }
 317            Transform::Inlay(inlay) => {
 318                let mut inlay_style_and_highlight = None;
 319                if let Some(inlay_highlights) = self.highlights.inlay_highlights {
 320                    for (_, inlay_id_to_data) in inlay_highlights.iter() {
 321                        let style_and_highlight = inlay_id_to_data.get(&inlay.id);
 322                        if style_and_highlight.is_some() {
 323                            inlay_style_and_highlight = style_and_highlight;
 324                            break;
 325                        }
 326                    }
 327                }
 328
 329                let mut renderer = None;
 330                let mut highlight_style = match inlay.id {
 331                    InlayId::EditPrediction(_) => self.highlight_styles.edit_prediction.map(|s| {
 332                        if inlay.text().chars().all(|c| c.is_whitespace()) {
 333                            s.whitespace
 334                        } else {
 335                            s.insertion
 336                        }
 337                    }),
 338                    InlayId::Hint(_) => self.highlight_styles.inlay_hint,
 339                    InlayId::DebuggerValue(_) => self.highlight_styles.inlay_hint,
 340                    InlayId::ReplResult(_) => {
 341                        let text = inlay.text().to_string();
 342                        renderer = Some(ChunkRenderer {
 343                            id: ChunkRendererId::Inlay(inlay.id),
 344                            render: Arc::new(move |cx| {
 345                                let colors = cx.theme().colors();
 346                                div()
 347                                    .flex()
 348                                    .flex_row()
 349                                    .items_center()
 350                                    .child(div().w_4())
 351                                    .child(
 352                                        div()
 353                                            .px_1()
 354                                            .rounded_sm()
 355                                            .bg(colors.surface_background)
 356                                            .text_color(colors.text_muted)
 357                                            .text_xs()
 358                                            .child(text.trim().to_string()),
 359                                    )
 360                                    .into_any_element()
 361                            }),
 362                            constrain_width: false,
 363                            measured_width: None,
 364                        });
 365                        self.highlight_styles.inlay_hint
 366                    }
 367                    InlayId::Color(_) => {
 368                        if let InlayContent::Color(color) = inlay.content {
 369                            renderer = Some(ChunkRenderer {
 370                                id: ChunkRendererId::Inlay(inlay.id),
 371                                render: Arc::new(move |cx| {
 372                                    div()
 373                                        .relative()
 374                                        .size_3p5()
 375                                        .child(
 376                                            div()
 377                                                .absolute()
 378                                                .right_1()
 379                                                .size_3()
 380                                                .border_1()
 381                                                .border_color(
 382                                                    if cx.theme().appearance().is_light() {
 383                                                        gpui::black().opacity(0.5)
 384                                                    } else {
 385                                                        gpui::white().opacity(0.5)
 386                                                    },
 387                                                )
 388                                                .bg(color),
 389                                        )
 390                                        .into_any_element()
 391                                }),
 392                                constrain_width: false,
 393                                measured_width: None,
 394                            });
 395                        }
 396                        self.highlight_styles.inlay_hint
 397                    }
 398                };
 399                let next_inlay_highlight_endpoint;
 400                let offset_in_inlay = self.output_offset - self.transforms.start().0;
 401                if let Some((style, highlight)) = inlay_style_and_highlight {
 402                    let range = &highlight.range;
 403                    if offset_in_inlay < range.start {
 404                        next_inlay_highlight_endpoint = range.start - offset_in_inlay;
 405                    } else if offset_in_inlay >= range.end {
 406                        next_inlay_highlight_endpoint = usize::MAX;
 407                    } else {
 408                        next_inlay_highlight_endpoint = range.end - offset_in_inlay;
 409                        highlight_style = highlight_style
 410                            .map(|highlight| highlight.highlight(*style))
 411                            .or_else(|| Some(*style));
 412                    }
 413                } else {
 414                    next_inlay_highlight_endpoint = usize::MAX;
 415                }
 416
 417                let inlay_chunks = self.inlay_chunks.get_or_insert_with(|| {
 418                    let start = offset_in_inlay;
 419                    let end = cmp::min(self.max_output_offset, self.transforms.end().0)
 420                        - self.transforms.start().0;
 421                    let chunks = inlay.text().chunks_in_range(start..end);
 422                    text::ChunkWithBitmaps(chunks)
 423                });
 424                let ChunkBitmaps {
 425                    text: inlay_chunk,
 426                    chars,
 427                    tabs,
 428                    newlines,
 429                } = self
 430                    .inlay_chunk
 431                    .get_or_insert_with(|| inlay_chunks.next().unwrap());
 432
 433                // Determine split index handling edge cases
 434                let split_index = if next_inlay_highlight_endpoint >= inlay_chunk.len() {
 435                    inlay_chunk.len()
 436                } else if next_inlay_highlight_endpoint == 0 {
 437                    // Need to take at least one character to make progress
 438                    inlay_chunk
 439                        .chars()
 440                        .next()
 441                        .map(|c| c.len_utf8())
 442                        .unwrap_or(1)
 443                } else {
 444                    inlay_chunk.ceil_char_boundary(next_inlay_highlight_endpoint)
 445                };
 446
 447                let (chunk, remainder) = inlay_chunk.split_at(split_index);
 448                *inlay_chunk = remainder;
 449
 450                let mask = 1u128.unbounded_shl(split_index as u32).wrapping_sub(1);
 451                let new_chars = *chars & mask;
 452                let new_tabs = *tabs & mask;
 453                let new_newlines = *newlines & mask;
 454
 455                *chars = chars.unbounded_shr(split_index as u32);
 456                *tabs = tabs.unbounded_shr(split_index as u32);
 457                *newlines = newlines.unbounded_shr(split_index as u32);
 458
 459                if inlay_chunk.is_empty() {
 460                    self.inlay_chunk = None;
 461                }
 462
 463                self.output_offset.0 += chunk.len();
 464
 465                InlayChunk {
 466                    chunk: Chunk {
 467                        text: chunk,
 468                        chars: new_chars,
 469                        tabs: new_tabs,
 470                        newlines: new_newlines,
 471                        highlight_style,
 472                        is_inlay: true,
 473                        ..Chunk::default()
 474                    },
 475                    renderer,
 476                }
 477            }
 478        };
 479
 480        if self.output_offset >= self.transforms.end().0 {
 481            self.inlay_chunks = None;
 482            self.transforms.next();
 483        }
 484
 485        Some(chunk)
 486    }
 487}
 488
 489impl InlayBufferRows<'_> {
 490    #[ztracing::instrument(skip_all)]
 491    pub fn seek(&mut self, row: u32) {
 492        let inlay_point = InlayPoint::new(row, 0);
 493        self.transforms.seek(&inlay_point, Bias::Left);
 494
 495        let mut buffer_point = self.transforms.start().1;
 496        let buffer_row = MultiBufferRow(if row == 0 {
 497            0
 498        } else {
 499            match self.transforms.item() {
 500                Some(Transform::Isomorphic(_)) => {
 501                    buffer_point += inlay_point.0 - self.transforms.start().0.0;
 502                    buffer_point.row
 503                }
 504                _ => cmp::min(buffer_point.row + 1, self.max_buffer_row.0),
 505            }
 506        });
 507        self.inlay_row = inlay_point.row();
 508        self.buffer_rows.seek(buffer_row);
 509    }
 510}
 511
 512impl Iterator for InlayBufferRows<'_> {
 513    type Item = RowInfo;
 514
 515    #[ztracing::instrument(skip_all)]
 516    fn next(&mut self) -> Option<Self::Item> {
 517        let buffer_row = if self.inlay_row == 0 {
 518            self.buffer_rows.next().unwrap()
 519        } else {
 520            match self.transforms.item()? {
 521                Transform::Inlay(_) => Default::default(),
 522                Transform::Isomorphic(_) => self.buffer_rows.next().unwrap(),
 523            }
 524        };
 525
 526        self.inlay_row += 1;
 527        self.transforms
 528            .seek_forward(&InlayPoint::new(self.inlay_row, 0), Bias::Left);
 529
 530        Some(buffer_row)
 531    }
 532}
 533
 534impl InlayPoint {
 535    pub fn new(row: u32, column: u32) -> Self {
 536        Self(Point::new(row, column))
 537    }
 538
 539    pub fn row(self) -> u32 {
 540        self.0.row
 541    }
 542}
 543
 544impl InlayMap {
 545    #[ztracing::instrument(skip_all)]
 546    pub fn new(buffer: MultiBufferSnapshot) -> (Self, InlaySnapshot) {
 547        let version = 0;
 548        let snapshot = InlaySnapshot {
 549            transforms: SumTree::from_iter(
 550                iter::once(Transform::Isomorphic(buffer.text_summary())),
 551                (),
 552            ),
 553            buffer,
 554            version,
 555        };
 556
 557        (
 558            Self {
 559                snapshot: snapshot.clone(),
 560                inlays: Vec::new(),
 561            },
 562            snapshot,
 563        )
 564    }
 565
 566    #[ztracing::instrument(skip_all)]
 567    pub fn sync(
 568        &mut self,
 569        buffer_snapshot: MultiBufferSnapshot,
 570        mut buffer_edits: Vec<text::Edit<MultiBufferOffset>>,
 571    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 572        let snapshot = &mut self.snapshot;
 573
 574        if buffer_edits.is_empty()
 575            && snapshot.buffer.trailing_excerpt_update_count()
 576                != buffer_snapshot.trailing_excerpt_update_count()
 577        {
 578            buffer_edits.push(Edit {
 579                old: snapshot.buffer.len()..snapshot.buffer.len(),
 580                new: buffer_snapshot.len()..buffer_snapshot.len(),
 581            });
 582        }
 583
 584        if buffer_edits.is_empty() {
 585            if snapshot.buffer.edit_count() != buffer_snapshot.edit_count()
 586                || snapshot.buffer.non_text_state_update_count()
 587                    != buffer_snapshot.non_text_state_update_count()
 588                || snapshot.buffer.trailing_excerpt_update_count()
 589                    != buffer_snapshot.trailing_excerpt_update_count()
 590            {
 591                snapshot.version += 1;
 592            }
 593
 594            snapshot.buffer = buffer_snapshot;
 595            (snapshot.clone(), Vec::new())
 596        } else {
 597            let mut inlay_edits = Patch::default();
 598            let mut new_transforms = SumTree::default();
 599            let mut cursor = snapshot
 600                .transforms
 601                .cursor::<Dimensions<MultiBufferOffset, InlayOffset>>(());
 602            let mut buffer_edits_iter = buffer_edits.iter().peekable();
 603            while let Some(buffer_edit) = buffer_edits_iter.next() {
 604                new_transforms.append(cursor.slice(&buffer_edit.old.start, Bias::Left), ());
 605                if let Some(Transform::Isomorphic(transform)) = cursor.item()
 606                    && cursor.end().0 == buffer_edit.old.start
 607                {
 608                    push_isomorphic(&mut new_transforms, *transform);
 609                    cursor.next();
 610                }
 611
 612                // Remove all the inlays and transforms contained by the edit.
 613                let old_start = cursor.start().1 + (buffer_edit.old.start - cursor.start().0);
 614                cursor.seek(&buffer_edit.old.end, Bias::Right);
 615                let old_end = cursor.start().1 + (buffer_edit.old.end - cursor.start().0);
 616
 617                // Push the unchanged prefix.
 618                let prefix_start = new_transforms.summary().input.len;
 619                let prefix_end = buffer_edit.new.start;
 620                push_isomorphic(
 621                    &mut new_transforms,
 622                    buffer_snapshot.text_summary_for_range(prefix_start..prefix_end),
 623                );
 624                let new_start = InlayOffset(new_transforms.summary().output.len);
 625
 626                let start_ix = match self.inlays.binary_search_by(|probe| {
 627                    probe
 628                        .position
 629                        .to_offset(&buffer_snapshot)
 630                        .cmp(&buffer_edit.new.start)
 631                        .then(std::cmp::Ordering::Greater)
 632                }) {
 633                    Ok(ix) | Err(ix) => ix,
 634                };
 635
 636                for inlay in &self.inlays[start_ix..] {
 637                    if !inlay.position.is_valid(&buffer_snapshot) {
 638                        continue;
 639                    }
 640                    let buffer_offset = inlay.position.to_offset(&buffer_snapshot);
 641                    if buffer_offset > buffer_edit.new.end {
 642                        break;
 643                    }
 644
 645                    let prefix_start = new_transforms.summary().input.len;
 646                    let prefix_end = buffer_offset;
 647                    push_isomorphic(
 648                        &mut new_transforms,
 649                        buffer_snapshot.text_summary_for_range(prefix_start..prefix_end),
 650                    );
 651
 652                    new_transforms.push(Transform::Inlay(inlay.clone()), ());
 653                }
 654
 655                // Apply the rest of the edit.
 656                let transform_start = new_transforms.summary().input.len;
 657                push_isomorphic(
 658                    &mut new_transforms,
 659                    buffer_snapshot.text_summary_for_range(transform_start..buffer_edit.new.end),
 660                );
 661                let new_end = InlayOffset(new_transforms.summary().output.len);
 662                inlay_edits.push(Edit {
 663                    old: old_start..old_end,
 664                    new: new_start..new_end,
 665                });
 666
 667                // If the next edit doesn't intersect the current isomorphic transform, then
 668                // we can push its remainder.
 669                if buffer_edits_iter
 670                    .peek()
 671                    .is_none_or(|edit| edit.old.start >= cursor.end().0)
 672                {
 673                    let transform_start = new_transforms.summary().input.len;
 674                    let transform_end =
 675                        buffer_edit.new.end + (cursor.end().0 - buffer_edit.old.end);
 676                    push_isomorphic(
 677                        &mut new_transforms,
 678                        buffer_snapshot.text_summary_for_range(transform_start..transform_end),
 679                    );
 680                    cursor.next();
 681                }
 682            }
 683
 684            new_transforms.append(cursor.suffix(), ());
 685            if new_transforms.is_empty() {
 686                new_transforms.push(Transform::Isomorphic(Default::default()), ());
 687            }
 688
 689            drop(cursor);
 690            snapshot.transforms = new_transforms;
 691            snapshot.version += 1;
 692            snapshot.buffer = buffer_snapshot;
 693            snapshot.check_invariants();
 694
 695            (snapshot.clone(), inlay_edits.into_inner())
 696        }
 697    }
 698
 699    #[ztracing::instrument(skip_all)]
 700    pub fn splice(
 701        &mut self,
 702        to_remove: &[InlayId],
 703        to_insert: Vec<Inlay>,
 704    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 705        let snapshot = &mut self.snapshot;
 706        let mut edits = BTreeSet::new();
 707
 708        self.inlays.retain(|inlay| {
 709            let retain = !to_remove.contains(&inlay.id);
 710            if !retain {
 711                let offset = inlay.position.to_offset(&snapshot.buffer);
 712                edits.insert(offset);
 713            }
 714            retain
 715        });
 716
 717        for inlay_to_insert in to_insert {
 718            // Avoid inserting empty inlays.
 719            if inlay_to_insert.text().is_empty() {
 720                continue;
 721            }
 722
 723            let offset = inlay_to_insert.position.to_offset(&snapshot.buffer);
 724            match self.inlays.binary_search_by(|probe| {
 725                probe
 726                    .position
 727                    .cmp(&inlay_to_insert.position, &snapshot.buffer)
 728                    .then(std::cmp::Ordering::Less)
 729            }) {
 730                Ok(ix) | Err(ix) => {
 731                    self.inlays.insert(ix, inlay_to_insert);
 732                }
 733            }
 734
 735            edits.insert(offset);
 736        }
 737
 738        let buffer_edits = edits
 739            .into_iter()
 740            .map(|offset| Edit {
 741                old: offset..offset,
 742                new: offset..offset,
 743            })
 744            .collect();
 745        let buffer_snapshot = snapshot.buffer.clone();
 746        let (snapshot, edits) = self.sync(buffer_snapshot, buffer_edits);
 747        (snapshot, edits)
 748    }
 749
 750    #[ztracing::instrument(skip_all)]
 751    pub fn current_inlays(&self) -> impl Iterator<Item = &Inlay> + Default {
 752        self.inlays.iter()
 753    }
 754
 755    #[cfg(test)]
 756    #[ztracing::instrument(skip_all)]
 757    pub(crate) fn randomly_mutate(
 758        &mut self,
 759        next_inlay_id: &mut usize,
 760        rng: &mut rand::rngs::StdRng,
 761    ) -> (InlaySnapshot, Vec<InlayEdit>) {
 762        use rand::prelude::*;
 763        use util::post_inc;
 764
 765        let mut to_remove = Vec::new();
 766        let mut to_insert = Vec::new();
 767        let snapshot = &mut self.snapshot;
 768        for i in 0..rng.random_range(1..=5) {
 769            if self.inlays.is_empty() || rng.random() {
 770                let position = snapshot
 771                    .buffer
 772                    .random_byte_range(MultiBufferOffset(0), rng)
 773                    .start;
 774                let bias = if rng.random() {
 775                    Bias::Left
 776                } else {
 777                    Bias::Right
 778                };
 779                let len = if rng.random_bool(0.01) {
 780                    0
 781                } else {
 782                    rng.random_range(1..=5)
 783                };
 784                let text = util::RandomCharIter::new(&mut *rng)
 785                    .filter(|ch| *ch != '\r')
 786                    .take(len)
 787                    .collect::<String>();
 788
 789                let next_inlay = if i % 2 == 0 {
 790                    Inlay::mock_hint(
 791                        post_inc(next_inlay_id),
 792                        snapshot.buffer.anchor_at(position, bias),
 793                        &text,
 794                    )
 795                } else {
 796                    Inlay::edit_prediction(
 797                        post_inc(next_inlay_id),
 798                        snapshot.buffer.anchor_at(position, bias),
 799                        &text,
 800                    )
 801                };
 802                let inlay_id = next_inlay.id;
 803                log::info!(
 804                    "creating inlay {inlay_id:?} at buffer offset {position} with bias {bias:?} and text {text:?}"
 805                );
 806                to_insert.push(next_inlay);
 807            } else {
 808                to_remove.push(
 809                    self.inlays
 810                        .iter()
 811                        .choose(rng)
 812                        .map(|inlay| inlay.id)
 813                        .unwrap(),
 814                );
 815            }
 816        }
 817        log::info!("removing inlays: {:?}", to_remove);
 818
 819        let (snapshot, edits) = self.splice(&to_remove, to_insert);
 820        (snapshot, edits)
 821    }
 822}
 823
 824impl InlaySnapshot {
 825    #[ztracing::instrument(skip_all)]
 826    pub fn to_point(&self, offset: InlayOffset) -> InlayPoint {
 827        let (start, _, item) = self.transforms.find::<Dimensions<
 828            InlayOffset,
 829            InlayPoint,
 830            MultiBufferOffset,
 831        >, _>((), &offset, Bias::Right);
 832        let overshoot = offset.0 - start.0.0;
 833        match item {
 834            Some(Transform::Isomorphic(_)) => {
 835                let buffer_offset_start = start.2;
 836                let buffer_offset_end = buffer_offset_start + overshoot;
 837                let buffer_start = self.buffer.offset_to_point(buffer_offset_start);
 838                let buffer_end = self.buffer.offset_to_point(buffer_offset_end);
 839                InlayPoint(start.1.0 + (buffer_end - buffer_start))
 840            }
 841            Some(Transform::Inlay(inlay)) => {
 842                let overshoot = inlay.text().offset_to_point(overshoot);
 843                InlayPoint(start.1.0 + overshoot)
 844            }
 845            None => self.max_point(),
 846        }
 847    }
 848
 849    #[ztracing::instrument(skip_all)]
 850    pub fn len(&self) -> InlayOffset {
 851        InlayOffset(self.transforms.summary().output.len)
 852    }
 853
 854    #[ztracing::instrument(skip_all)]
 855    pub fn max_point(&self) -> InlayPoint {
 856        InlayPoint(self.transforms.summary().output.lines)
 857    }
 858
 859    #[ztracing::instrument(skip_all, fields(point))]
 860    pub fn to_offset(&self, point: InlayPoint) -> InlayOffset {
 861        let (start, _, item) = self
 862            .transforms
 863            .find::<Dimensions<InlayPoint, InlayOffset, Point>, _>((), &point, Bias::Right);
 864        let overshoot = point.0 - start.0.0;
 865        match item {
 866            Some(Transform::Isomorphic(_)) => {
 867                let buffer_point_start = start.2;
 868                let buffer_point_end = buffer_point_start + overshoot;
 869                let buffer_offset_start = self.buffer.point_to_offset(buffer_point_start);
 870                let buffer_offset_end = self.buffer.point_to_offset(buffer_point_end);
 871                InlayOffset(start.1.0 + (buffer_offset_end - buffer_offset_start))
 872            }
 873            Some(Transform::Inlay(inlay)) => {
 874                let overshoot = inlay.text().point_to_offset(overshoot);
 875                InlayOffset(start.1.0 + overshoot)
 876            }
 877            None => self.len(),
 878        }
 879    }
 880    #[ztracing::instrument(skip_all)]
 881    pub fn to_buffer_point(&self, point: InlayPoint) -> Point {
 882        let (start, _, item) =
 883            self.transforms
 884                .find::<Dimensions<InlayPoint, Point>, _>((), &point, Bias::Right);
 885        match item {
 886            Some(Transform::Isomorphic(_)) => {
 887                let overshoot = point.0 - start.0.0;
 888                start.1 + overshoot
 889            }
 890            Some(Transform::Inlay(_)) => start.1,
 891            None => self.buffer.max_point(),
 892        }
 893    }
 894    #[ztracing::instrument(skip_all)]
 895    pub fn to_buffer_offset(&self, offset: InlayOffset) -> MultiBufferOffset {
 896        let (start, _, item) = self
 897            .transforms
 898            .find::<Dimensions<InlayOffset, MultiBufferOffset>, _>((), &offset, Bias::Right);
 899        match item {
 900            Some(Transform::Isomorphic(_)) => {
 901                let overshoot = offset - start.0;
 902                start.1 + overshoot
 903            }
 904            Some(Transform::Inlay(_)) => start.1,
 905            None => self.buffer.len(),
 906        }
 907    }
 908
 909    #[ztracing::instrument(skip_all)]
 910    pub fn to_inlay_offset(&self, offset: MultiBufferOffset) -> InlayOffset {
 911        let mut cursor = self
 912            .transforms
 913            .cursor::<Dimensions<MultiBufferOffset, InlayOffset>>(());
 914        cursor.seek(&offset, Bias::Left);
 915        loop {
 916            match cursor.item() {
 917                Some(Transform::Isomorphic(_)) => {
 918                    if offset == cursor.end().0 {
 919                        while let Some(Transform::Inlay(inlay)) = cursor.next_item() {
 920                            if inlay.position.bias() == Bias::Right {
 921                                break;
 922                            } else {
 923                                cursor.next();
 924                            }
 925                        }
 926                        return cursor.end().1;
 927                    } else {
 928                        let overshoot = offset - cursor.start().0;
 929                        return InlayOffset(cursor.start().1.0 + overshoot);
 930                    }
 931                }
 932                Some(Transform::Inlay(inlay)) => {
 933                    if inlay.position.bias() == Bias::Left {
 934                        cursor.next();
 935                    } else {
 936                        return cursor.start().1;
 937                    }
 938                }
 939                None => {
 940                    return self.len();
 941                }
 942            }
 943        }
 944    }
 945
 946    #[ztracing::instrument(skip_all)]
 947    pub fn to_inlay_point(&self, point: Point) -> InlayPoint {
 948        self.inlay_point_cursor().map(point, Bias::Left)
 949    }
 950
 951    /// Converts a buffer offset range into one or more `InlayOffset` ranges that
 952    /// cover only the actual buffer text, skipping any inlay hint text that falls
 953    /// within the range. When there are no inlays the returned vec contains a
 954    /// single element identical to the input mapped into inlay-offset space.
 955    pub fn buffer_offset_to_inlay_ranges(
 956        &self,
 957        range: Range<MultiBufferOffset>,
 958    ) -> impl Iterator<Item = Range<InlayOffset>> {
 959        let mut cursor = self
 960            .transforms
 961            .cursor::<Dimensions<MultiBufferOffset, InlayOffset>>(());
 962        cursor.seek(&range.start, Bias::Right);
 963
 964        std::iter::from_fn(move || {
 965            loop {
 966                match cursor.item()? {
 967                    Transform::Isomorphic(_) => {
 968                        let seg_buffer_start = cursor.start().0;
 969                        let seg_buffer_end = cursor.end().0;
 970                        let seg_inlay_start = cursor.start().1;
 971
 972                        let overlap_start = cmp::max(range.start, seg_buffer_start);
 973                        let overlap_end = cmp::min(range.end, seg_buffer_end);
 974
 975                        let past_end = seg_buffer_end >= range.end;
 976                        cursor.next();
 977
 978                        if overlap_start < overlap_end {
 979                            let inlay_start =
 980                                InlayOffset(seg_inlay_start.0 + (overlap_start - seg_buffer_start));
 981                            let inlay_end =
 982                                InlayOffset(seg_inlay_start.0 + (overlap_end - seg_buffer_start));
 983                            return Some(inlay_start..inlay_end);
 984                        }
 985
 986                        if past_end {
 987                            return None;
 988                        }
 989                    }
 990                    Transform::Inlay(_) => cursor.next(),
 991                }
 992            }
 993        })
 994    }
 995
 996    #[ztracing::instrument(skip_all)]
 997    pub fn inlay_point_cursor(&self) -> InlayPointCursor<'_> {
 998        let cursor = self.transforms.cursor::<Dimensions<Point, InlayPoint>>(());
 999        InlayPointCursor {
1000            cursor,
1001            transforms: &self.transforms,
1002        }
1003    }
1004
1005    #[ztracing::instrument(skip_all)]
1006    pub fn clip_point(&self, mut point: InlayPoint, mut bias: Bias) -> InlayPoint {
1007        let mut cursor = self.transforms.cursor::<Dimensions<InlayPoint, Point>>(());
1008        cursor.seek(&point, Bias::Left);
1009        loop {
1010            match cursor.item() {
1011                Some(Transform::Isomorphic(transform)) => {
1012                    if cursor.start().0 == point {
1013                        if let Some(Transform::Inlay(inlay)) = cursor.prev_item() {
1014                            if inlay.position.bias() == Bias::Left {
1015                                return point;
1016                            } else if bias == Bias::Left {
1017                                cursor.prev();
1018                            } else if transform.first_line_chars == 0 {
1019                                point.0 += Point::new(1, 0);
1020                            } else {
1021                                point.0 += Point::new(0, 1);
1022                            }
1023                        } else {
1024                            return point;
1025                        }
1026                    } else if cursor.end().0 == point {
1027                        if let Some(Transform::Inlay(inlay)) = cursor.next_item() {
1028                            if inlay.position.bias() == Bias::Right {
1029                                return point;
1030                            } else if bias == Bias::Right {
1031                                cursor.next();
1032                            } else if point.0.column == 0 {
1033                                point.0.row -= 1;
1034                                point.0.column = self.line_len(point.0.row);
1035                            } else {
1036                                point.0.column -= 1;
1037                            }
1038                        } else {
1039                            return point;
1040                        }
1041                    } else {
1042                        let overshoot = point.0 - cursor.start().0.0;
1043                        let buffer_point = cursor.start().1 + overshoot;
1044                        let clipped_buffer_point = self.buffer.clip_point(buffer_point, bias);
1045                        let clipped_overshoot = clipped_buffer_point - cursor.start().1;
1046                        let clipped_point = InlayPoint(cursor.start().0.0 + clipped_overshoot);
1047                        if clipped_point == point {
1048                            return clipped_point;
1049                        } else {
1050                            point = clipped_point;
1051                        }
1052                    }
1053                }
1054                Some(Transform::Inlay(inlay)) => {
1055                    if point == cursor.start().0 && inlay.position.bias() == Bias::Right {
1056                        match cursor.prev_item() {
1057                            Some(Transform::Inlay(inlay)) => {
1058                                if inlay.position.bias() == Bias::Left {
1059                                    return point;
1060                                }
1061                            }
1062                            _ => return point,
1063                        }
1064                    } else if point == cursor.end().0 && inlay.position.bias() == Bias::Left {
1065                        match cursor.next_item() {
1066                            Some(Transform::Inlay(inlay)) => {
1067                                if inlay.position.bias() == Bias::Right {
1068                                    return point;
1069                                }
1070                            }
1071                            _ => return point,
1072                        }
1073                    }
1074
1075                    if bias == Bias::Left {
1076                        point = cursor.start().0;
1077                        cursor.prev();
1078                    } else {
1079                        cursor.next();
1080                        point = cursor.start().0;
1081                    }
1082                }
1083                None => {
1084                    bias = bias.invert();
1085                    if bias == Bias::Left {
1086                        point = cursor.start().0;
1087                        cursor.prev();
1088                    } else {
1089                        cursor.next();
1090                        point = cursor.start().0;
1091                    }
1092                }
1093            }
1094        }
1095    }
1096
1097    #[ztracing::instrument(skip_all)]
1098    pub fn text_summary(&self) -> MBTextSummary {
1099        self.transforms.summary().output
1100    }
1101
1102    #[ztracing::instrument(skip_all)]
1103    pub fn text_summary_for_range(&self, range: Range<InlayOffset>) -> MBTextSummary {
1104        let mut summary = MBTextSummary::default();
1105
1106        let mut cursor = self
1107            .transforms
1108            .cursor::<Dimensions<InlayOffset, MultiBufferOffset>>(());
1109        cursor.seek(&range.start, Bias::Right);
1110
1111        let overshoot = range.start.0 - cursor.start().0.0;
1112        match cursor.item() {
1113            Some(Transform::Isomorphic(_)) => {
1114                let buffer_start = cursor.start().1;
1115                let suffix_start = buffer_start + overshoot;
1116                let suffix_end =
1117                    buffer_start + (cmp::min(cursor.end().0, range.end).0 - cursor.start().0.0);
1118                summary = self.buffer.text_summary_for_range(suffix_start..suffix_end);
1119                cursor.next();
1120            }
1121            Some(Transform::Inlay(inlay)) => {
1122                let suffix_start = overshoot;
1123                let suffix_end = cmp::min(cursor.end().0, range.end).0 - cursor.start().0.0;
1124                summary = MBTextSummary::from(
1125                    inlay
1126                        .text()
1127                        .cursor(suffix_start)
1128                        .summary::<TextSummary>(suffix_end),
1129                );
1130                cursor.next();
1131            }
1132            None => {}
1133        }
1134
1135        if range.end > cursor.start().0 {
1136            summary += cursor
1137                .summary::<_, TransformSummary>(&range.end, Bias::Right)
1138                .output;
1139
1140            let overshoot = range.end.0 - cursor.start().0.0;
1141            match cursor.item() {
1142                Some(Transform::Isomorphic(_)) => {
1143                    let prefix_start = cursor.start().1;
1144                    let prefix_end = prefix_start + overshoot;
1145                    summary += self
1146                        .buffer
1147                        .text_summary_for_range::<MBTextSummary, _>(prefix_start..prefix_end);
1148                }
1149                Some(Transform::Inlay(inlay)) => {
1150                    let prefix_end = overshoot;
1151                    summary += inlay.text().cursor(0).summary::<TextSummary>(prefix_end);
1152                }
1153                None => {}
1154            }
1155        }
1156
1157        summary
1158    }
1159
1160    #[ztracing::instrument(skip_all)]
1161    pub fn row_infos(&self, row: u32) -> InlayBufferRows<'_> {
1162        let mut cursor = self.transforms.cursor::<Dimensions<InlayPoint, Point>>(());
1163        let inlay_point = InlayPoint::new(row, 0);
1164        cursor.seek(&inlay_point, Bias::Left);
1165
1166        let max_buffer_row = self.buffer.max_row();
1167        let mut buffer_point = cursor.start().1;
1168        let buffer_row = if row == 0 {
1169            MultiBufferRow(0)
1170        } else {
1171            match cursor.item() {
1172                Some(Transform::Isomorphic(_)) => {
1173                    buffer_point += inlay_point.0 - cursor.start().0.0;
1174                    MultiBufferRow(buffer_point.row)
1175                }
1176                _ => cmp::min(MultiBufferRow(buffer_point.row + 1), max_buffer_row),
1177            }
1178        };
1179
1180        InlayBufferRows {
1181            transforms: cursor,
1182            inlay_row: inlay_point.row(),
1183            buffer_rows: self.buffer.row_infos(buffer_row),
1184            max_buffer_row,
1185        }
1186    }
1187
1188    #[ztracing::instrument(skip_all)]
1189    pub fn line_len(&self, row: u32) -> u32 {
1190        let line_start = self.to_offset(InlayPoint::new(row, 0)).0;
1191        let line_end = if row >= self.max_point().row() {
1192            self.len().0
1193        } else {
1194            self.to_offset(InlayPoint::new(row + 1, 0)).0 - 1
1195        };
1196        (line_end - line_start) as u32
1197    }
1198
1199    #[ztracing::instrument(skip_all)]
1200    pub(crate) fn chunks<'a>(
1201        &'a self,
1202        range: Range<InlayOffset>,
1203        language_aware: bool,
1204        highlights: Highlights<'a>,
1205    ) -> InlayChunks<'a> {
1206        let mut cursor = self
1207            .transforms
1208            .cursor::<Dimensions<InlayOffset, MultiBufferOffset>>(());
1209        cursor.seek(&range.start, Bias::Right);
1210
1211        let buffer_range = self.to_buffer_offset(range.start)..self.to_buffer_offset(range.end);
1212        let buffer_chunks = CustomHighlightsChunks::new(
1213            buffer_range,
1214            language_aware,
1215            highlights.text_highlights,
1216            highlights.semantic_token_highlights,
1217            &self.buffer,
1218        );
1219
1220        InlayChunks {
1221            transforms: cursor,
1222            buffer_chunks,
1223            inlay_chunks: None,
1224            inlay_chunk: None,
1225            buffer_chunk: None,
1226            output_offset: range.start,
1227            max_output_offset: range.end,
1228            highlight_styles: highlights.styles,
1229            highlights,
1230            snapshot: self,
1231        }
1232    }
1233
1234    #[cfg(test)]
1235    #[ztracing::instrument(skip_all)]
1236    pub fn text(&self) -> String {
1237        self.chunks(Default::default()..self.len(), false, Highlights::default())
1238            .map(|chunk| chunk.chunk.text)
1239            .collect()
1240    }
1241
1242    #[ztracing::instrument(skip_all)]
1243    fn check_invariants(&self) {
1244        #[cfg(any(debug_assertions, feature = "test-support"))]
1245        {
1246            assert_eq!(self.transforms.summary().input, self.buffer.text_summary());
1247            let mut transforms = self.transforms.iter().peekable();
1248            while let Some(transform) = transforms.next() {
1249                let transform_is_isomorphic = matches!(transform, Transform::Isomorphic(_));
1250                if let Some(next_transform) = transforms.peek() {
1251                    let next_transform_is_isomorphic =
1252                        matches!(next_transform, Transform::Isomorphic(_));
1253                    assert!(
1254                        !transform_is_isomorphic || !next_transform_is_isomorphic,
1255                        "two adjacent isomorphic transforms"
1256                    );
1257                }
1258            }
1259        }
1260    }
1261}
1262
1263pub struct InlayPointCursor<'transforms> {
1264    cursor: Cursor<'transforms, 'static, Transform, Dimensions<Point, InlayPoint>>,
1265    transforms: &'transforms SumTree<Transform>,
1266}
1267
1268impl InlayPointCursor<'_> {
1269    #[ztracing::instrument(skip_all)]
1270    pub fn map(&mut self, point: Point, bias: Bias) -> InlayPoint {
1271        let cursor = &mut self.cursor;
1272        if cursor.did_seek() {
1273            cursor.seek_forward(&point, Bias::Left);
1274        } else {
1275            cursor.seek(&point, Bias::Left);
1276        }
1277        loop {
1278            match cursor.item() {
1279                Some(Transform::Isomorphic(_)) => {
1280                    if point == cursor.end().0 {
1281                        while let Some(Transform::Inlay(inlay)) = cursor.next_item() {
1282                            if bias == Bias::Left && inlay.position.bias() == Bias::Right {
1283                                break;
1284                            } else {
1285                                cursor.next();
1286                            }
1287                        }
1288                        return cursor.end().1;
1289                    } else {
1290                        let overshoot = point - cursor.start().0;
1291                        return InlayPoint(cursor.start().1.0 + overshoot);
1292                    }
1293                }
1294                Some(Transform::Inlay(inlay)) => {
1295                    if inlay.position.bias() == Bias::Left || bias == Bias::Right {
1296                        cursor.next();
1297                    } else {
1298                        return cursor.start().1;
1299                    }
1300                }
1301                None => {
1302                    return InlayPoint(self.transforms.summary().output.lines);
1303                }
1304            }
1305        }
1306    }
1307}
1308
1309fn push_isomorphic(sum_tree: &mut SumTree<Transform>, summary: MBTextSummary) {
1310    if summary.len == MultiBufferOffset(0) {
1311        return;
1312    }
1313
1314    let mut summary = Some(summary);
1315    sum_tree.update_last(
1316        |transform| {
1317            if let Transform::Isomorphic(transform) = transform {
1318                *transform += summary.take().unwrap();
1319            }
1320        },
1321        (),
1322    );
1323
1324    if let Some(summary) = summary {
1325        sum_tree.push(Transform::Isomorphic(summary), ());
1326    }
1327}
1328
1329#[cfg(test)]
1330mod tests {
1331    use super::*;
1332    use crate::{
1333        MultiBuffer,
1334        display_map::{HighlightKey, InlayHighlights},
1335        hover_links::InlayHighlight,
1336    };
1337    use collections::HashMap;
1338    use gpui::{App, HighlightStyle};
1339    use multi_buffer::Anchor;
1340    use project::{InlayHint, InlayHintLabel, ResolveState};
1341    use rand::prelude::*;
1342    use settings::SettingsStore;
1343    use std::{cmp::Reverse, env, sync::Arc};
1344    use sum_tree::TreeMap;
1345    use text::{Patch, Rope};
1346    use util::RandomCharIter;
1347    use util::post_inc;
1348
1349    #[test]
1350    fn test_inlay_properties_label_padding() {
1351        assert_eq!(
1352            Inlay::hint(
1353                InlayId::Hint(0),
1354                Anchor::min(),
1355                &InlayHint {
1356                    label: InlayHintLabel::String("a".to_string()),
1357                    position: text::Anchor::MIN,
1358                    padding_left: false,
1359                    padding_right: false,
1360                    tooltip: None,
1361                    kind: None,
1362                    resolve_state: ResolveState::Resolved,
1363                },
1364            )
1365            .text()
1366            .to_string(),
1367            "a",
1368            "Should not pad label if not requested"
1369        );
1370
1371        assert_eq!(
1372            Inlay::hint(
1373                InlayId::Hint(0),
1374                Anchor::min(),
1375                &InlayHint {
1376                    label: InlayHintLabel::String("a".to_string()),
1377                    position: text::Anchor::MIN,
1378                    padding_left: true,
1379                    padding_right: true,
1380                    tooltip: None,
1381                    kind: None,
1382                    resolve_state: ResolveState::Resolved,
1383                },
1384            )
1385            .text()
1386            .to_string(),
1387            " a ",
1388            "Should pad label for every side requested"
1389        );
1390
1391        assert_eq!(
1392            Inlay::hint(
1393                InlayId::Hint(0),
1394                Anchor::min(),
1395                &InlayHint {
1396                    label: InlayHintLabel::String(" a ".to_string()),
1397                    position: text::Anchor::MIN,
1398                    padding_left: false,
1399                    padding_right: false,
1400                    tooltip: None,
1401                    kind: None,
1402                    resolve_state: ResolveState::Resolved,
1403                },
1404            )
1405            .text()
1406            .to_string(),
1407            " a ",
1408            "Should not change already padded label"
1409        );
1410
1411        assert_eq!(
1412            Inlay::hint(
1413                InlayId::Hint(0),
1414                Anchor::min(),
1415                &InlayHint {
1416                    label: InlayHintLabel::String(" a ".to_string()),
1417                    position: text::Anchor::MIN,
1418                    padding_left: true,
1419                    padding_right: true,
1420                    tooltip: None,
1421                    kind: None,
1422                    resolve_state: ResolveState::Resolved,
1423                },
1424            )
1425            .text()
1426            .to_string(),
1427            " a ",
1428            "Should not change already padded label"
1429        );
1430    }
1431
1432    #[gpui::test]
1433    fn test_inlay_hint_padding_with_multibyte_chars() {
1434        assert_eq!(
1435            Inlay::hint(
1436                InlayId::Hint(0),
1437                Anchor::min(),
1438                &InlayHint {
1439                    label: InlayHintLabel::String("🎨".to_string()),
1440                    position: text::Anchor::MIN,
1441                    padding_left: true,
1442                    padding_right: true,
1443                    tooltip: None,
1444                    kind: None,
1445                    resolve_state: ResolveState::Resolved,
1446                },
1447            )
1448            .text()
1449            .to_string(),
1450            " 🎨 ",
1451            "Should pad single emoji correctly"
1452        );
1453    }
1454
1455    #[gpui::test]
1456    fn test_basic_inlays(cx: &mut App) {
1457        let buffer = MultiBuffer::build_simple("abcdefghi", cx);
1458        let buffer_edits = buffer.update(cx, |buffer, _| buffer.subscribe());
1459        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
1460        assert_eq!(inlay_snapshot.text(), "abcdefghi");
1461        let mut next_inlay_id = 0;
1462
1463        let (inlay_snapshot, _) = inlay_map.splice(
1464            &[],
1465            vec![Inlay::mock_hint(
1466                post_inc(&mut next_inlay_id),
1467                buffer
1468                    .read(cx)
1469                    .snapshot(cx)
1470                    .anchor_after(MultiBufferOffset(3)),
1471                "|123|",
1472            )],
1473        );
1474        assert_eq!(inlay_snapshot.text(), "abc|123|defghi");
1475        assert_eq!(
1476            inlay_snapshot.to_inlay_point(Point::new(0, 0)),
1477            InlayPoint::new(0, 0)
1478        );
1479        assert_eq!(
1480            inlay_snapshot.to_inlay_point(Point::new(0, 1)),
1481            InlayPoint::new(0, 1)
1482        );
1483        assert_eq!(
1484            inlay_snapshot.to_inlay_point(Point::new(0, 2)),
1485            InlayPoint::new(0, 2)
1486        );
1487        assert_eq!(
1488            inlay_snapshot.to_inlay_point(Point::new(0, 3)),
1489            InlayPoint::new(0, 3)
1490        );
1491        assert_eq!(
1492            inlay_snapshot.to_inlay_point(Point::new(0, 4)),
1493            InlayPoint::new(0, 9)
1494        );
1495        assert_eq!(
1496            inlay_snapshot.to_inlay_point(Point::new(0, 5)),
1497            InlayPoint::new(0, 10)
1498        );
1499        assert_eq!(
1500            inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Left),
1501            InlayPoint::new(0, 0)
1502        );
1503        assert_eq!(
1504            inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Right),
1505            InlayPoint::new(0, 0)
1506        );
1507        assert_eq!(
1508            inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Left),
1509            InlayPoint::new(0, 3)
1510        );
1511        assert_eq!(
1512            inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Right),
1513            InlayPoint::new(0, 3)
1514        );
1515        assert_eq!(
1516            inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Left),
1517            InlayPoint::new(0, 3)
1518        );
1519        assert_eq!(
1520            inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Right),
1521            InlayPoint::new(0, 9)
1522        );
1523
1524        // Edits before or after the inlay should not affect it.
1525        buffer.update(cx, |buffer, cx| {
1526            buffer.edit(
1527                [
1528                    (MultiBufferOffset(2)..MultiBufferOffset(3), "x"),
1529                    (MultiBufferOffset(3)..MultiBufferOffset(3), "y"),
1530                    (MultiBufferOffset(4)..MultiBufferOffset(4), "z"),
1531                ],
1532                None,
1533                cx,
1534            )
1535        });
1536        let (inlay_snapshot, _) = inlay_map.sync(
1537            buffer.read(cx).snapshot(cx),
1538            buffer_edits.consume().into_inner(),
1539        );
1540        assert_eq!(inlay_snapshot.text(), "abxy|123|dzefghi");
1541
1542        // An edit surrounding the inlay should invalidate it.
1543        buffer.update(cx, |buffer, cx| {
1544            buffer.edit(
1545                [(MultiBufferOffset(4)..MultiBufferOffset(5), "D")],
1546                None,
1547                cx,
1548            )
1549        });
1550        let (inlay_snapshot, _) = inlay_map.sync(
1551            buffer.read(cx).snapshot(cx),
1552            buffer_edits.consume().into_inner(),
1553        );
1554        assert_eq!(inlay_snapshot.text(), "abxyDzefghi");
1555
1556        let (inlay_snapshot, _) = inlay_map.splice(
1557            &[],
1558            vec![
1559                Inlay::mock_hint(
1560                    post_inc(&mut next_inlay_id),
1561                    buffer
1562                        .read(cx)
1563                        .snapshot(cx)
1564                        .anchor_before(MultiBufferOffset(3)),
1565                    "|123|",
1566                ),
1567                Inlay::edit_prediction(
1568                    post_inc(&mut next_inlay_id),
1569                    buffer
1570                        .read(cx)
1571                        .snapshot(cx)
1572                        .anchor_after(MultiBufferOffset(3)),
1573                    "|456|",
1574                ),
1575            ],
1576        );
1577        assert_eq!(inlay_snapshot.text(), "abx|123||456|yDzefghi");
1578
1579        // Edits ending where the inlay starts should not move it if it has a left bias.
1580        buffer.update(cx, |buffer, cx| {
1581            buffer.edit(
1582                [(MultiBufferOffset(3)..MultiBufferOffset(3), "JKL")],
1583                None,
1584                cx,
1585            )
1586        });
1587        let (inlay_snapshot, _) = inlay_map.sync(
1588            buffer.read(cx).snapshot(cx),
1589            buffer_edits.consume().into_inner(),
1590        );
1591        assert_eq!(inlay_snapshot.text(), "abx|123|JKL|456|yDzefghi");
1592
1593        assert_eq!(
1594            inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Left),
1595            InlayPoint::new(0, 0)
1596        );
1597        assert_eq!(
1598            inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Right),
1599            InlayPoint::new(0, 0)
1600        );
1601
1602        assert_eq!(
1603            inlay_snapshot.clip_point(InlayPoint::new(0, 1), Bias::Left),
1604            InlayPoint::new(0, 1)
1605        );
1606        assert_eq!(
1607            inlay_snapshot.clip_point(InlayPoint::new(0, 1), Bias::Right),
1608            InlayPoint::new(0, 1)
1609        );
1610
1611        assert_eq!(
1612            inlay_snapshot.clip_point(InlayPoint::new(0, 2), Bias::Left),
1613            InlayPoint::new(0, 2)
1614        );
1615        assert_eq!(
1616            inlay_snapshot.clip_point(InlayPoint::new(0, 2), Bias::Right),
1617            InlayPoint::new(0, 2)
1618        );
1619
1620        assert_eq!(
1621            inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Left),
1622            InlayPoint::new(0, 2)
1623        );
1624        assert_eq!(
1625            inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Right),
1626            InlayPoint::new(0, 8)
1627        );
1628
1629        assert_eq!(
1630            inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Left),
1631            InlayPoint::new(0, 2)
1632        );
1633        assert_eq!(
1634            inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Right),
1635            InlayPoint::new(0, 8)
1636        );
1637
1638        assert_eq!(
1639            inlay_snapshot.clip_point(InlayPoint::new(0, 5), Bias::Left),
1640            InlayPoint::new(0, 2)
1641        );
1642        assert_eq!(
1643            inlay_snapshot.clip_point(InlayPoint::new(0, 5), Bias::Right),
1644            InlayPoint::new(0, 8)
1645        );
1646
1647        assert_eq!(
1648            inlay_snapshot.clip_point(InlayPoint::new(0, 6), Bias::Left),
1649            InlayPoint::new(0, 2)
1650        );
1651        assert_eq!(
1652            inlay_snapshot.clip_point(InlayPoint::new(0, 6), Bias::Right),
1653            InlayPoint::new(0, 8)
1654        );
1655
1656        assert_eq!(
1657            inlay_snapshot.clip_point(InlayPoint::new(0, 7), Bias::Left),
1658            InlayPoint::new(0, 2)
1659        );
1660        assert_eq!(
1661            inlay_snapshot.clip_point(InlayPoint::new(0, 7), Bias::Right),
1662            InlayPoint::new(0, 8)
1663        );
1664
1665        assert_eq!(
1666            inlay_snapshot.clip_point(InlayPoint::new(0, 8), Bias::Left),
1667            InlayPoint::new(0, 8)
1668        );
1669        assert_eq!(
1670            inlay_snapshot.clip_point(InlayPoint::new(0, 8), Bias::Right),
1671            InlayPoint::new(0, 8)
1672        );
1673
1674        assert_eq!(
1675            inlay_snapshot.clip_point(InlayPoint::new(0, 9), Bias::Left),
1676            InlayPoint::new(0, 9)
1677        );
1678        assert_eq!(
1679            inlay_snapshot.clip_point(InlayPoint::new(0, 9), Bias::Right),
1680            InlayPoint::new(0, 9)
1681        );
1682
1683        assert_eq!(
1684            inlay_snapshot.clip_point(InlayPoint::new(0, 10), Bias::Left),
1685            InlayPoint::new(0, 10)
1686        );
1687        assert_eq!(
1688            inlay_snapshot.clip_point(InlayPoint::new(0, 10), Bias::Right),
1689            InlayPoint::new(0, 10)
1690        );
1691
1692        assert_eq!(
1693            inlay_snapshot.clip_point(InlayPoint::new(0, 11), Bias::Left),
1694            InlayPoint::new(0, 11)
1695        );
1696        assert_eq!(
1697            inlay_snapshot.clip_point(InlayPoint::new(0, 11), Bias::Right),
1698            InlayPoint::new(0, 11)
1699        );
1700
1701        assert_eq!(
1702            inlay_snapshot.clip_point(InlayPoint::new(0, 12), Bias::Left),
1703            InlayPoint::new(0, 11)
1704        );
1705        assert_eq!(
1706            inlay_snapshot.clip_point(InlayPoint::new(0, 12), Bias::Right),
1707            InlayPoint::new(0, 17)
1708        );
1709
1710        assert_eq!(
1711            inlay_snapshot.clip_point(InlayPoint::new(0, 13), Bias::Left),
1712            InlayPoint::new(0, 11)
1713        );
1714        assert_eq!(
1715            inlay_snapshot.clip_point(InlayPoint::new(0, 13), Bias::Right),
1716            InlayPoint::new(0, 17)
1717        );
1718
1719        assert_eq!(
1720            inlay_snapshot.clip_point(InlayPoint::new(0, 14), Bias::Left),
1721            InlayPoint::new(0, 11)
1722        );
1723        assert_eq!(
1724            inlay_snapshot.clip_point(InlayPoint::new(0, 14), Bias::Right),
1725            InlayPoint::new(0, 17)
1726        );
1727
1728        assert_eq!(
1729            inlay_snapshot.clip_point(InlayPoint::new(0, 15), Bias::Left),
1730            InlayPoint::new(0, 11)
1731        );
1732        assert_eq!(
1733            inlay_snapshot.clip_point(InlayPoint::new(0, 15), Bias::Right),
1734            InlayPoint::new(0, 17)
1735        );
1736
1737        assert_eq!(
1738            inlay_snapshot.clip_point(InlayPoint::new(0, 16), Bias::Left),
1739            InlayPoint::new(0, 11)
1740        );
1741        assert_eq!(
1742            inlay_snapshot.clip_point(InlayPoint::new(0, 16), Bias::Right),
1743            InlayPoint::new(0, 17)
1744        );
1745
1746        assert_eq!(
1747            inlay_snapshot.clip_point(InlayPoint::new(0, 17), Bias::Left),
1748            InlayPoint::new(0, 17)
1749        );
1750        assert_eq!(
1751            inlay_snapshot.clip_point(InlayPoint::new(0, 17), Bias::Right),
1752            InlayPoint::new(0, 17)
1753        );
1754
1755        assert_eq!(
1756            inlay_snapshot.clip_point(InlayPoint::new(0, 18), Bias::Left),
1757            InlayPoint::new(0, 18)
1758        );
1759        assert_eq!(
1760            inlay_snapshot.clip_point(InlayPoint::new(0, 18), Bias::Right),
1761            InlayPoint::new(0, 18)
1762        );
1763
1764        // The inlays can be manually removed.
1765        let (inlay_snapshot, _) = inlay_map.splice(
1766            &inlay_map
1767                .inlays
1768                .iter()
1769                .map(|inlay| inlay.id)
1770                .collect::<Vec<InlayId>>(),
1771            Vec::new(),
1772        );
1773        assert_eq!(inlay_snapshot.text(), "abxJKLyDzefghi");
1774    }
1775
1776    #[gpui::test]
1777    fn test_inlay_buffer_rows(cx: &mut App) {
1778        let buffer = MultiBuffer::build_simple("abc\ndef\nghi", cx);
1779        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
1780        assert_eq!(inlay_snapshot.text(), "abc\ndef\nghi");
1781        let mut next_inlay_id = 0;
1782
1783        let (inlay_snapshot, _) = inlay_map.splice(
1784            &[],
1785            vec![
1786                Inlay::mock_hint(
1787                    post_inc(&mut next_inlay_id),
1788                    buffer
1789                        .read(cx)
1790                        .snapshot(cx)
1791                        .anchor_before(MultiBufferOffset(0)),
1792                    "|123|\n",
1793                ),
1794                Inlay::mock_hint(
1795                    post_inc(&mut next_inlay_id),
1796                    buffer
1797                        .read(cx)
1798                        .snapshot(cx)
1799                        .anchor_before(MultiBufferOffset(4)),
1800                    "|456|",
1801                ),
1802                Inlay::edit_prediction(
1803                    post_inc(&mut next_inlay_id),
1804                    buffer
1805                        .read(cx)
1806                        .snapshot(cx)
1807                        .anchor_before(MultiBufferOffset(7)),
1808                    "\n|567|\n",
1809                ),
1810            ],
1811        );
1812        assert_eq!(inlay_snapshot.text(), "|123|\nabc\n|456|def\n|567|\n\nghi");
1813        assert_eq!(
1814            inlay_snapshot
1815                .row_infos(0)
1816                .map(|info| info.buffer_row)
1817                .collect::<Vec<_>>(),
1818            vec![Some(0), None, Some(1), None, None, Some(2)]
1819        );
1820    }
1821
1822    #[gpui::test(iterations = 100)]
1823    fn test_random_inlays(cx: &mut App, mut rng: StdRng) {
1824        init_test(cx);
1825
1826        let operations = env::var("OPERATIONS")
1827            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1828            .unwrap_or(10);
1829
1830        let len = rng.random_range(0..30);
1831        let buffer = if rng.random() {
1832            let text = util::RandomCharIter::new(&mut rng)
1833                .take(len)
1834                .collect::<String>();
1835            MultiBuffer::build_simple(&text, cx)
1836        } else {
1837            MultiBuffer::build_random(&mut rng, cx)
1838        };
1839        let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1840        let mut next_inlay_id = 0;
1841        log::info!("buffer text: {:?}", buffer_snapshot.text());
1842        let (mut inlay_map, mut inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1843        for _ in 0..operations {
1844            let mut inlay_edits = Patch::default();
1845
1846            let mut prev_inlay_text = inlay_snapshot.text();
1847            let mut buffer_edits = Vec::new();
1848            match rng.random_range(0..=100) {
1849                0..=50 => {
1850                    let (snapshot, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1851                    log::info!("mutated text: {:?}", snapshot.text());
1852                    inlay_edits = Patch::new(edits);
1853                }
1854                _ => buffer.update(cx, |buffer, cx| {
1855                    let subscription = buffer.subscribe();
1856                    let edit_count = rng.random_range(1..=5);
1857                    buffer.randomly_mutate(&mut rng, edit_count, cx);
1858                    buffer_snapshot = buffer.snapshot(cx);
1859                    let edits = subscription.consume().into_inner();
1860                    log::info!("editing {:?}", edits);
1861                    buffer_edits.extend(edits);
1862                }),
1863            };
1864
1865            let (new_inlay_snapshot, new_inlay_edits) =
1866                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1867            inlay_snapshot = new_inlay_snapshot;
1868            inlay_edits = inlay_edits.compose(new_inlay_edits);
1869
1870            log::info!("buffer text: {:?}", buffer_snapshot.text());
1871            log::info!("inlay text: {:?}", inlay_snapshot.text());
1872
1873            let inlays = inlay_map
1874                .inlays
1875                .iter()
1876                .filter(|inlay| inlay.position.is_valid(&buffer_snapshot))
1877                .map(|inlay| {
1878                    let offset = inlay.position.to_offset(&buffer_snapshot);
1879                    (offset, inlay.clone())
1880                })
1881                .collect::<Vec<_>>();
1882            let mut expected_text = Rope::from(&buffer_snapshot.text());
1883            for (offset, inlay) in inlays.iter().rev() {
1884                expected_text.replace(offset.0..offset.0, &inlay.text().to_string());
1885            }
1886            assert_eq!(inlay_snapshot.text(), expected_text.to_string());
1887
1888            let expected_buffer_rows = inlay_snapshot.row_infos(0).collect::<Vec<_>>();
1889            assert_eq!(
1890                expected_buffer_rows.len() as u32,
1891                expected_text.max_point().row + 1
1892            );
1893            for row_start in 0..expected_buffer_rows.len() {
1894                assert_eq!(
1895                    inlay_snapshot
1896                        .row_infos(row_start as u32)
1897                        .collect::<Vec<_>>(),
1898                    &expected_buffer_rows[row_start..],
1899                    "incorrect buffer rows starting at {}",
1900                    row_start
1901                );
1902            }
1903
1904            let mut text_highlights = HashMap::default();
1905            let text_highlight_count = rng.random_range(0_usize..10);
1906            let mut text_highlight_ranges = (0..text_highlight_count)
1907                .map(|_| buffer_snapshot.random_byte_range(MultiBufferOffset(0), &mut rng))
1908                .collect::<Vec<_>>();
1909            text_highlight_ranges.sort_by_key(|range| (range.start, Reverse(range.end)));
1910            log::info!("highlighting text ranges {text_highlight_ranges:?}");
1911            text_highlights.insert(
1912                HighlightKey::ColorizeBracket(0),
1913                Arc::new((
1914                    HighlightStyle::default(),
1915                    text_highlight_ranges
1916                        .into_iter()
1917                        .map(|range| {
1918                            buffer_snapshot.anchor_before(range.start)
1919                                ..buffer_snapshot.anchor_after(range.end)
1920                        })
1921                        .collect(),
1922                )),
1923            );
1924            let text_highlights = Arc::new(text_highlights);
1925
1926            let mut inlay_highlights = InlayHighlights::default();
1927            if !inlays.is_empty() {
1928                let inlay_highlight_count = rng.random_range(0..inlays.len());
1929                let mut inlay_indices = BTreeSet::default();
1930                while inlay_indices.len() < inlay_highlight_count {
1931                    inlay_indices.insert(rng.random_range(0..inlays.len()));
1932                }
1933                let new_highlights = TreeMap::from_ordered_entries(
1934                    inlay_indices
1935                        .into_iter()
1936                        .filter_map(|i| {
1937                            let (_, inlay) = &inlays[i];
1938                            let inlay_text_len = inlay.text().len();
1939                            match inlay_text_len {
1940                                0 => None,
1941                                1 => Some(InlayHighlight {
1942                                    inlay: inlay.id,
1943                                    inlay_position: inlay.position,
1944                                    range: 0..1,
1945                                }),
1946                                n => {
1947                                    let inlay_text = inlay.text().to_string();
1948                                    let mut highlight_end = rng.random_range(1..n);
1949                                    let mut highlight_start = rng.random_range(0..highlight_end);
1950                                    while !inlay_text.is_char_boundary(highlight_end) {
1951                                        highlight_end += 1;
1952                                    }
1953                                    while !inlay_text.is_char_boundary(highlight_start) {
1954                                        highlight_start -= 1;
1955                                    }
1956                                    Some(InlayHighlight {
1957                                        inlay: inlay.id,
1958                                        inlay_position: inlay.position,
1959                                        range: highlight_start..highlight_end,
1960                                    })
1961                                }
1962                            }
1963                        })
1964                        .map(|highlight| (highlight.inlay, (HighlightStyle::default(), highlight))),
1965                );
1966                log::info!("highlighting inlay ranges {new_highlights:?}");
1967                inlay_highlights.insert(HighlightKey::Editor, new_highlights);
1968            }
1969
1970            for _ in 0..5 {
1971                let mut end = rng.random_range(0..=inlay_snapshot.len().0.0);
1972                end = expected_text.clip_offset(end, Bias::Right);
1973                let mut start = rng.random_range(0..=end);
1974                start = expected_text.clip_offset(start, Bias::Right);
1975
1976                let range =
1977                    InlayOffset(MultiBufferOffset(start))..InlayOffset(MultiBufferOffset(end));
1978                log::info!("calling inlay_snapshot.chunks({range:?})");
1979                let actual_text = inlay_snapshot
1980                    .chunks(
1981                        range,
1982                        false,
1983                        Highlights {
1984                            text_highlights: Some(&text_highlights),
1985                            inlay_highlights: Some(&inlay_highlights),
1986                            ..Highlights::default()
1987                        },
1988                    )
1989                    .map(|chunk| chunk.chunk.text)
1990                    .collect::<String>();
1991                assert_eq!(
1992                    actual_text,
1993                    expected_text.slice(start..end).to_string(),
1994                    "incorrect text in range {:?}",
1995                    start..end
1996                );
1997
1998                assert_eq!(
1999                    inlay_snapshot.text_summary_for_range(
2000                        InlayOffset(MultiBufferOffset(start))..InlayOffset(MultiBufferOffset(end))
2001                    ),
2002                    MBTextSummary::from(expected_text.slice(start..end).summary())
2003                );
2004            }
2005
2006            for edit in inlay_edits {
2007                prev_inlay_text.replace_range(
2008                    edit.new.start.0.0..edit.new.start.0.0 + edit.old_len(),
2009                    &inlay_snapshot.text()[edit.new.start.0.0..edit.new.end.0.0],
2010                );
2011            }
2012            assert_eq!(prev_inlay_text, inlay_snapshot.text());
2013
2014            assert_eq!(expected_text.max_point(), inlay_snapshot.max_point().0);
2015            assert_eq!(expected_text.len(), inlay_snapshot.len().0.0);
2016
2017            let mut buffer_point = Point::default();
2018            let mut inlay_point = inlay_snapshot.to_inlay_point(buffer_point);
2019            let mut buffer_chars = buffer_snapshot.chars_at(MultiBufferOffset(0));
2020            loop {
2021                // Ensure conversion from buffer coordinates to inlay coordinates
2022                // is consistent.
2023                let buffer_offset = buffer_snapshot.point_to_offset(buffer_point);
2024                assert_eq!(
2025                    inlay_snapshot.to_point(inlay_snapshot.to_inlay_offset(buffer_offset)),
2026                    inlay_point
2027                );
2028
2029                // No matter which bias we clip an inlay point with, it doesn't move
2030                // because it was constructed from a buffer point.
2031                assert_eq!(
2032                    inlay_snapshot.clip_point(inlay_point, Bias::Left),
2033                    inlay_point,
2034                    "invalid inlay point for buffer point {:?} when clipped left",
2035                    buffer_point
2036                );
2037                assert_eq!(
2038                    inlay_snapshot.clip_point(inlay_point, Bias::Right),
2039                    inlay_point,
2040                    "invalid inlay point for buffer point {:?} when clipped right",
2041                    buffer_point
2042                );
2043
2044                if let Some(ch) = buffer_chars.next() {
2045                    if ch == '\n' {
2046                        buffer_point += Point::new(1, 0);
2047                    } else {
2048                        buffer_point += Point::new(0, ch.len_utf8() as u32);
2049                    }
2050
2051                    // Ensure that moving forward in the buffer always moves the inlay point forward as well.
2052                    let new_inlay_point = inlay_snapshot.to_inlay_point(buffer_point);
2053                    assert!(new_inlay_point > inlay_point);
2054                    inlay_point = new_inlay_point;
2055                } else {
2056                    break;
2057                }
2058            }
2059
2060            let mut inlay_point = InlayPoint::default();
2061            let mut inlay_offset = InlayOffset::default();
2062            for ch in expected_text.chars() {
2063                assert_eq!(
2064                    inlay_snapshot.to_offset(inlay_point),
2065                    inlay_offset,
2066                    "invalid to_offset({:?})",
2067                    inlay_point
2068                );
2069                assert_eq!(
2070                    inlay_snapshot.to_point(inlay_offset),
2071                    inlay_point,
2072                    "invalid to_point({:?})",
2073                    inlay_offset
2074                );
2075
2076                let mut bytes = [0; 4];
2077                for byte in ch.encode_utf8(&mut bytes).as_bytes() {
2078                    inlay_offset.0 += 1;
2079                    if *byte == b'\n' {
2080                        inlay_point.0 += Point::new(1, 0);
2081                    } else {
2082                        inlay_point.0 += Point::new(0, 1);
2083                    }
2084
2085                    let clipped_left_point = inlay_snapshot.clip_point(inlay_point, Bias::Left);
2086                    let clipped_right_point = inlay_snapshot.clip_point(inlay_point, Bias::Right);
2087                    assert!(
2088                        clipped_left_point <= clipped_right_point,
2089                        "inlay point {:?} when clipped left is greater than when clipped right ({:?} > {:?})",
2090                        inlay_point,
2091                        clipped_left_point,
2092                        clipped_right_point
2093                    );
2094
2095                    // Ensure the clipped points are at valid text locations.
2096                    assert_eq!(
2097                        clipped_left_point.0,
2098                        expected_text.clip_point(clipped_left_point.0, Bias::Left)
2099                    );
2100                    assert_eq!(
2101                        clipped_right_point.0,
2102                        expected_text.clip_point(clipped_right_point.0, Bias::Right)
2103                    );
2104
2105                    // Ensure the clipped points never overshoot the end of the map.
2106                    assert!(clipped_left_point <= inlay_snapshot.max_point());
2107                    assert!(clipped_right_point <= inlay_snapshot.max_point());
2108
2109                    // Ensure the clipped points are at valid buffer locations.
2110                    assert_eq!(
2111                        inlay_snapshot
2112                            .to_inlay_point(inlay_snapshot.to_buffer_point(clipped_left_point)),
2113                        clipped_left_point,
2114                        "to_buffer_point({:?}) = {:?}",
2115                        clipped_left_point,
2116                        inlay_snapshot.to_buffer_point(clipped_left_point),
2117                    );
2118                    assert_eq!(
2119                        inlay_snapshot
2120                            .to_inlay_point(inlay_snapshot.to_buffer_point(clipped_right_point)),
2121                        clipped_right_point,
2122                        "to_buffer_point({:?}) = {:?}",
2123                        clipped_right_point,
2124                        inlay_snapshot.to_buffer_point(clipped_right_point),
2125                    );
2126                }
2127            }
2128        }
2129    }
2130
2131    #[gpui::test(iterations = 100)]
2132    fn test_random_chunk_bitmaps(cx: &mut gpui::App, mut rng: StdRng) {
2133        init_test(cx);
2134
2135        // Generate random buffer using existing test infrastructure
2136        let text_len = rng.random_range(0..10000);
2137        let buffer = if rng.random() {
2138            let text = RandomCharIter::new(&mut rng)
2139                .take(text_len)
2140                .collect::<String>();
2141            MultiBuffer::build_simple(&text, cx)
2142        } else {
2143            MultiBuffer::build_random(&mut rng, cx)
2144        };
2145
2146        let buffer_snapshot = buffer.read(cx).snapshot(cx);
2147        let (mut inlay_map, _) = InlayMap::new(buffer_snapshot.clone());
2148
2149        // Perform random mutations to add inlays
2150        let mut next_inlay_id = 0;
2151        let mutation_count = rng.random_range(1..10);
2152        for _ in 0..mutation_count {
2153            inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
2154        }
2155
2156        let (snapshot, _) = inlay_map.sync(buffer_snapshot, vec![]);
2157
2158        // Get all chunks and verify their bitmaps
2159        let chunks = snapshot.chunks(
2160            InlayOffset(MultiBufferOffset(0))..snapshot.len(),
2161            false,
2162            Highlights::default(),
2163        );
2164
2165        for chunk in chunks.into_iter().map(|inlay_chunk| inlay_chunk.chunk) {
2166            let chunk_text = chunk.text;
2167            let chars_bitmap = chunk.chars;
2168            let tabs_bitmap = chunk.tabs;
2169
2170            // Check empty chunks have empty bitmaps
2171            if chunk_text.is_empty() {
2172                assert_eq!(
2173                    chars_bitmap, 0,
2174                    "Empty chunk should have empty chars bitmap"
2175                );
2176                assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
2177                continue;
2178            }
2179
2180            // Verify that chunk text doesn't exceed 128 bytes
2181            assert!(
2182                chunk_text.len() <= 128,
2183                "Chunk text length {} exceeds 128 bytes",
2184                chunk_text.len()
2185            );
2186
2187            // Verify chars bitmap
2188            let char_indices = chunk_text
2189                .char_indices()
2190                .map(|(i, _)| i)
2191                .collect::<Vec<_>>();
2192
2193            for byte_idx in 0..chunk_text.len() {
2194                let should_have_bit = char_indices.contains(&byte_idx);
2195                let has_bit = chars_bitmap & (1 << byte_idx) != 0;
2196
2197                if has_bit != should_have_bit {
2198                    eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
2199                    eprintln!("Char indices: {:?}", char_indices);
2200                    eprintln!("Chars bitmap: {:#b}", chars_bitmap);
2201                    assert_eq!(
2202                        has_bit, should_have_bit,
2203                        "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
2204                        byte_idx, chunk_text, should_have_bit, has_bit
2205                    );
2206                }
2207            }
2208
2209            // Verify tabs bitmap
2210            for (byte_idx, byte) in chunk_text.bytes().enumerate() {
2211                let is_tab = byte == b'\t';
2212                let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
2213
2214                if has_bit != is_tab {
2215                    eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
2216                    eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
2217                    assert_eq!(
2218                        has_bit, is_tab,
2219                        "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
2220                        byte_idx, chunk_text, byte as char, is_tab, has_bit
2221                    );
2222                }
2223            }
2224        }
2225    }
2226
2227    fn init_test(cx: &mut App) {
2228        let store = SettingsStore::test(cx);
2229        cx.set_global(store);
2230        theme::init(theme::LoadThemes::JustBase, cx);
2231    }
2232
2233    /// Helper to create test highlights for an inlay
2234    fn create_inlay_highlights(
2235        inlay_id: InlayId,
2236        highlight_range: Range<usize>,
2237        position: Anchor,
2238    ) -> TreeMap<HighlightKey, TreeMap<InlayId, (HighlightStyle, InlayHighlight)>> {
2239        let mut inlay_highlights = TreeMap::default();
2240        let mut type_highlights = TreeMap::default();
2241        type_highlights.insert(
2242            inlay_id,
2243            (
2244                HighlightStyle::default(),
2245                InlayHighlight {
2246                    inlay: inlay_id,
2247                    range: highlight_range,
2248                    inlay_position: position,
2249                },
2250            ),
2251        );
2252        inlay_highlights.insert(HighlightKey::Editor, type_highlights);
2253        inlay_highlights
2254    }
2255
2256    #[gpui::test]
2257    fn test_inlay_utf8_boundary_panic_fix(cx: &mut App) {
2258        init_test(cx);
2259
2260        // This test verifies that we handle UTF-8 character boundaries correctly
2261        // when splitting inlay text for highlighting. Previously, this would panic
2262        // when trying to split at byte 13, which is in the middle of the '…' character.
2263        //
2264        // See https://github.com/zed-industries/zed/issues/33641
2265        let buffer = MultiBuffer::build_simple("fn main() {}\n", cx);
2266        let (mut inlay_map, _) = InlayMap::new(buffer.read(cx).snapshot(cx));
2267
2268        // Create an inlay with text that contains a multi-byte character
2269        // The string "SortingDirec…" contains an ellipsis character '…' which is 3 bytes (E2 80 A6)
2270        let inlay_text = "SortingDirec…";
2271        let position = buffer.read(cx).snapshot(cx).anchor_before(Point::new(0, 5));
2272
2273        let inlay = Inlay {
2274            id: InlayId::Hint(0),
2275            position,
2276            content: InlayContent::Text(text::Rope::from(inlay_text)),
2277        };
2278
2279        let (inlay_snapshot, _) = inlay_map.splice(&[], vec![inlay]);
2280
2281        // Create highlights that request a split at byte 13, which is in the middle
2282        // of the '…' character (bytes 12..15). We include the full character.
2283        let inlay_highlights = create_inlay_highlights(InlayId::Hint(0), 0..13, position);
2284
2285        let highlights = crate::display_map::Highlights {
2286            text_highlights: None,
2287            inlay_highlights: Some(&inlay_highlights),
2288            semantic_token_highlights: None,
2289            styles: crate::display_map::HighlightStyles::default(),
2290        };
2291
2292        // Collect chunks - this previously would panic
2293        let chunks: Vec<_> = inlay_snapshot
2294            .chunks(
2295                InlayOffset(MultiBufferOffset(0))..inlay_snapshot.len(),
2296                false,
2297                highlights,
2298            )
2299            .collect();
2300
2301        // Verify the chunks are correct
2302        let full_text: String = chunks.iter().map(|c| c.chunk.text).collect();
2303        assert_eq!(full_text, "fn maSortingDirec…in() {}\n");
2304
2305        // Verify the highlighted portion includes the complete ellipsis character
2306        let highlighted_chunks: Vec<_> = chunks
2307            .iter()
2308            .filter(|c| c.chunk.highlight_style.is_some() && c.chunk.is_inlay)
2309            .collect();
2310
2311        assert_eq!(highlighted_chunks.len(), 1);
2312        assert_eq!(highlighted_chunks[0].chunk.text, "SortingDirec…");
2313    }
2314
2315    #[gpui::test]
2316    fn test_inlay_utf8_boundaries(cx: &mut App) {
2317        init_test(cx);
2318
2319        struct TestCase {
2320            inlay_text: &'static str,
2321            highlight_range: Range<usize>,
2322            expected_highlighted: &'static str,
2323            description: &'static str,
2324        }
2325
2326        let test_cases = vec![
2327            TestCase {
2328                inlay_text: "Hello👋World",
2329                highlight_range: 0..7,
2330                expected_highlighted: "Hello👋",
2331                description: "Emoji boundary - rounds up to include full emoji",
2332            },
2333            TestCase {
2334                inlay_text: "Test→End",
2335                highlight_range: 0..5,
2336                expected_highlighted: "Test→",
2337                description: "Arrow boundary - rounds up to include full arrow",
2338            },
2339            TestCase {
2340                inlay_text: "café",
2341                highlight_range: 0..4,
2342                expected_highlighted: "café",
2343                description: "Accented char boundary - rounds up to include full é",
2344            },
2345            TestCase {
2346                inlay_text: "🎨🎭🎪",
2347                highlight_range: 0..5,
2348                expected_highlighted: "🎨🎭",
2349                description: "Multiple emojis - partial highlight",
2350            },
2351            TestCase {
2352                inlay_text: "普通话",
2353                highlight_range: 0..4,
2354                expected_highlighted: "普通",
2355                description: "Chinese characters - partial highlight",
2356            },
2357            TestCase {
2358                inlay_text: "Hello",
2359                highlight_range: 0..2,
2360                expected_highlighted: "He",
2361                description: "ASCII only - no adjustment needed",
2362            },
2363            TestCase {
2364                inlay_text: "👋",
2365                highlight_range: 0..1,
2366                expected_highlighted: "👋",
2367                description: "Single emoji - partial byte range includes whole char",
2368            },
2369            TestCase {
2370                inlay_text: "Test",
2371                highlight_range: 0..0,
2372                expected_highlighted: "",
2373                description: "Empty range",
2374            },
2375            TestCase {
2376                inlay_text: "🎨ABC",
2377                highlight_range: 2..5,
2378                expected_highlighted: "A",
2379                description: "Range starting mid-emoji skips the emoji",
2380            },
2381        ];
2382
2383        for test_case in test_cases {
2384            let buffer = MultiBuffer::build_simple("test", cx);
2385            let (mut inlay_map, _) = InlayMap::new(buffer.read(cx).snapshot(cx));
2386            let position = buffer.read(cx).snapshot(cx).anchor_before(Point::new(0, 2));
2387
2388            let inlay = Inlay {
2389                id: InlayId::Hint(0),
2390                position,
2391                content: InlayContent::Text(text::Rope::from(test_case.inlay_text)),
2392            };
2393
2394            let (inlay_snapshot, _) = inlay_map.splice(&[], vec![inlay]);
2395            let inlay_highlights = create_inlay_highlights(
2396                InlayId::Hint(0),
2397                test_case.highlight_range.clone(),
2398                position,
2399            );
2400
2401            let highlights = crate::display_map::Highlights {
2402                text_highlights: None,
2403                inlay_highlights: Some(&inlay_highlights),
2404                semantic_token_highlights: None,
2405                styles: crate::display_map::HighlightStyles::default(),
2406            };
2407
2408            let chunks: Vec<_> = inlay_snapshot
2409                .chunks(
2410                    InlayOffset(MultiBufferOffset(0))..inlay_snapshot.len(),
2411                    false,
2412                    highlights,
2413                )
2414                .collect();
2415
2416            // Verify we got chunks and they total to the expected text
2417            let full_text: String = chunks.iter().map(|c| c.chunk.text).collect();
2418            assert_eq!(
2419                full_text,
2420                format!("te{}st", test_case.inlay_text),
2421                "Full text mismatch for case: {}",
2422                test_case.description
2423            );
2424
2425            // Verify that the highlighted portion matches expectations
2426            let highlighted_text: String = chunks
2427                .iter()
2428                .filter(|c| c.chunk.highlight_style.is_some() && c.chunk.is_inlay)
2429                .map(|c| c.chunk.text)
2430                .collect();
2431            assert_eq!(
2432                highlighted_text, test_case.expected_highlighted,
2433                "Highlighted text mismatch for case: {} (text: '{}', range: {:?})",
2434                test_case.description, test_case.inlay_text, test_case.highlight_range
2435            );
2436        }
2437    }
2438}