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