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