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