inlay_map.rs

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