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