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