1use crate::{
2 multi_buffer::{MultiBufferChunks, MultiBufferRows},
3 Anchor, InlayId, MultiBufferSnapshot, ToOffset,
4};
5use collections::{BTreeMap, BTreeSet};
6use gpui::fonts::HighlightStyle;
7use language::{Chunk, Edit, Point, TextSummary};
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
21pub struct InlayMap {
22 snapshot: InlaySnapshot,
23 inlays: Vec<Inlay>,
24}
25
26#[derive(Clone)]
27pub struct InlaySnapshot {
28 pub buffer: MultiBufferSnapshot,
29 transforms: SumTree<Transform>,
30 pub version: usize,
31}
32
33#[derive(Clone, Debug)]
34enum Transform {
35 Isomorphic(TextSummary),
36 Inlay(Inlay),
37}
38
39#[derive(Debug, Clone)]
40pub struct Inlay {
41 pub id: InlayId,
42 pub position: Anchor,
43 pub text: text::Rope,
44}
45
46impl Inlay {
47 pub fn hint(id: usize, position: Anchor, hint: &project::InlayHint) -> Self {
48 let mut text = hint.text();
49 if hint.padding_right && !text.ends_with(' ') {
50 text.push(' ');
51 }
52 if hint.padding_left && !text.starts_with(' ') {
53 text.insert(0, ' ');
54 }
55 Self {
56 id: InlayId::Hint(id),
57 position,
58 text: text.into(),
59 }
60 }
61
62 pub fn suggestion<T: Into<Rope>>(id: usize, position: Anchor, text: T) -> Self {
63 Self {
64 id: InlayId::Suggestion(id),
65 position,
66 text: text.into(),
67 }
68 }
69}
70
71impl sum_tree::Item for Transform {
72 type Summary = TransformSummary;
73
74 fn summary(&self) -> Self::Summary {
75 match self {
76 Transform::Isomorphic(summary) => TransformSummary {
77 input: summary.clone(),
78 output: summary.clone(),
79 },
80 Transform::Inlay(inlay) => TransformSummary {
81 input: TextSummary::default(),
82 output: inlay.text.summary(),
83 },
84 }
85 }
86}
87
88#[derive(Clone, Debug, Default)]
89struct TransformSummary {
90 input: TextSummary,
91 output: TextSummary,
92}
93
94impl sum_tree::Summary for TransformSummary {
95 type Context = ();
96
97 fn add_summary(&mut self, other: &Self, _: &()) {
98 self.input += &other.input;
99 self.output += &other.output;
100 }
101}
102
103pub type InlayEdit = Edit<InlayOffset>;
104
105#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
106pub struct InlayOffset(pub usize);
107
108impl Add for InlayOffset {
109 type Output = Self;
110
111 fn add(self, rhs: Self) -> Self::Output {
112 Self(self.0 + rhs.0)
113 }
114}
115
116impl Sub for InlayOffset {
117 type Output = Self;
118
119 fn sub(self, rhs: Self) -> Self::Output {
120 Self(self.0 - rhs.0)
121 }
122}
123
124impl AddAssign for InlayOffset {
125 fn add_assign(&mut self, rhs: Self) {
126 self.0 += rhs.0;
127 }
128}
129
130impl SubAssign for InlayOffset {
131 fn sub_assign(&mut self, rhs: Self) {
132 self.0 -= rhs.0;
133 }
134}
135
136impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayOffset {
137 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
138 self.0 += &summary.output.len;
139 }
140}
141
142#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
143pub struct InlayPoint(pub Point);
144
145impl Add for InlayPoint {
146 type Output = Self;
147
148 fn add(self, rhs: Self) -> Self::Output {
149 Self(self.0 + rhs.0)
150 }
151}
152
153impl Sub for InlayPoint {
154 type Output = Self;
155
156 fn sub(self, rhs: Self) -> Self::Output {
157 Self(self.0 - rhs.0)
158 }
159}
160
161impl<'a> sum_tree::Dimension<'a, TransformSummary> for InlayPoint {
162 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
163 self.0 += &summary.output.lines;
164 }
165}
166
167impl<'a> sum_tree::Dimension<'a, TransformSummary> for usize {
168 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
169 *self += &summary.input.len;
170 }
171}
172
173impl<'a> sum_tree::Dimension<'a, TransformSummary> for Point {
174 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
175 *self += &summary.input.lines;
176 }
177}
178
179#[derive(Clone)]
180pub struct InlayBufferRows<'a> {
181 transforms: Cursor<'a, Transform, (InlayPoint, Point)>,
182 buffer_rows: MultiBufferRows<'a>,
183 inlay_row: u32,
184 max_buffer_row: u32,
185}
186
187#[derive(Debug, Copy, Clone, Eq, PartialEq)]
188struct HighlightEndpoint {
189 offset: InlayOffset,
190 is_start: bool,
191 tag: Option<TypeId>,
192 style: HighlightStyle,
193}
194
195impl PartialOrd for HighlightEndpoint {
196 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
197 Some(self.cmp(other))
198 }
199}
200
201impl Ord for HighlightEndpoint {
202 fn cmp(&self, other: &Self) -> cmp::Ordering {
203 self.offset
204 .cmp(&other.offset)
205 .then_with(|| other.is_start.cmp(&self.is_start))
206 }
207}
208
209pub struct InlayChunks<'a> {
210 transforms: Cursor<'a, Transform, (InlayOffset, usize)>,
211 buffer_chunks: MultiBufferChunks<'a>,
212 buffer_chunk: Option<Chunk<'a>>,
213 inlay_chunks: Option<text::Chunks<'a>>,
214 inlay_chunk: Option<&'a str>,
215 output_offset: InlayOffset,
216 max_output_offset: InlayOffset,
217 inlay_highlight_style: Option<HighlightStyle>,
218 suggestion_highlight_style: Option<HighlightStyle>,
219 highlight_endpoints: Peekable<vec::IntoIter<HighlightEndpoint>>,
220 active_highlights: BTreeMap<Option<TypeId>, HighlightStyle>,
221 highlights: Highlights<'a>,
222 snapshot: &'a InlaySnapshot,
223}
224
225impl<'a> InlayChunks<'a> {
226 pub fn seek(&mut self, offset: InlayOffset) {
227 self.transforms.seek(&offset, Bias::Right, &());
228
229 let buffer_offset = self.snapshot.to_buffer_offset(offset);
230 self.buffer_chunks.seek(buffer_offset);
231 self.inlay_chunks = None;
232 self.buffer_chunk = None;
233 self.output_offset = offset;
234 }
235
236 pub fn offset(&self) -> InlayOffset {
237 self.output_offset
238 }
239}
240
241impl<'a> Iterator for InlayChunks<'a> {
242 type Item = Chunk<'a>;
243
244 fn next(&mut self) -> Option<Self::Item> {
245 if self.output_offset == self.max_output_offset {
246 return None;
247 }
248
249 let mut next_highlight_endpoint = InlayOffset(usize::MAX);
250 while let Some(endpoint) = self.highlight_endpoints.peek().copied() {
251 if endpoint.offset <= self.output_offset {
252 if endpoint.is_start {
253 self.active_highlights.insert(endpoint.tag, endpoint.style);
254 } else {
255 self.active_highlights.remove(&endpoint.tag);
256 }
257 self.highlight_endpoints.next();
258 } else {
259 next_highlight_endpoint = endpoint.offset;
260 break;
261 }
262 }
263
264 let chunk = match self.transforms.item()? {
265 Transform::Isomorphic(_) => {
266 let chunk = self
267 .buffer_chunk
268 .get_or_insert_with(|| self.buffer_chunks.next().unwrap());
269 if chunk.text.is_empty() {
270 *chunk = self.buffer_chunks.next().unwrap();
271 }
272
273 let (prefix, suffix) = chunk.text.split_at(
274 chunk
275 .text
276 .len()
277 .min(self.transforms.end(&()).0 .0 - self.output_offset.0)
278 .min(next_highlight_endpoint.0 - self.output_offset.0),
279 );
280
281 chunk.text = suffix;
282 self.output_offset.0 += prefix.len();
283 let mut prefix = Chunk {
284 text: prefix,
285 ..chunk.clone()
286 };
287 if !self.active_highlights.is_empty() {
288 let mut highlight_style = HighlightStyle::default();
289 for active_highlight in self.active_highlights.values() {
290 highlight_style.highlight(*active_highlight);
291 }
292 prefix.highlight_style = Some(highlight_style);
293 }
294 prefix
295 }
296 Transform::Inlay(inlay) => {
297 let mut inlay_style_and_highlight = None;
298 if let Some(inlay_highlights) = self.highlights.inlay_highlights {
299 for (_, inlay_id_to_data) in inlay_highlights.iter() {
300 let style_and_highlight = inlay_id_to_data.get(&inlay.id);
301 if style_and_highlight.is_some() {
302 inlay_style_and_highlight = style_and_highlight;
303 break;
304 }
305 }
306 }
307
308 let mut highlight_style = match inlay.id {
309 InlayId::Suggestion(_) => self.suggestion_highlight_style,
310 InlayId::Hint(_) => self.inlay_highlight_style,
311 };
312 let next_inlay_highlight_endpoint;
313 let offset_in_inlay = self.output_offset - self.transforms.start().0;
314 if let Some((style, highlight)) = inlay_style_and_highlight {
315 let range = &highlight.range;
316 if offset_in_inlay.0 < range.start {
317 next_inlay_highlight_endpoint = range.start - offset_in_inlay.0;
318 } else if offset_in_inlay.0 >= range.end {
319 next_inlay_highlight_endpoint = usize::MAX;
320 } else {
321 next_inlay_highlight_endpoint = range.end - offset_in_inlay.0;
322 highlight_style
323 .get_or_insert_with(|| Default::default())
324 .highlight(style.clone());
325 }
326 } else {
327 next_inlay_highlight_endpoint = usize::MAX;
328 }
329
330 let inlay_chunks = self.inlay_chunks.get_or_insert_with(|| {
331 let start = offset_in_inlay;
332 let end = cmp::min(self.max_output_offset, self.transforms.end(&()).0)
333 - self.transforms.start().0;
334 inlay.text.chunks_in_range(start.0..end.0)
335 });
336 let inlay_chunk = self
337 .inlay_chunk
338 .get_or_insert_with(|| inlay_chunks.next().unwrap());
339 let (chunk, remainder) =
340 inlay_chunk.split_at(inlay_chunk.len().min(next_inlay_highlight_endpoint));
341 *inlay_chunk = remainder;
342 if inlay_chunk.is_empty() {
343 self.inlay_chunk = None;
344 }
345
346 self.output_offset.0 += chunk.len();
347
348 if !self.active_highlights.is_empty() {
349 for active_highlight in self.active_highlights.values() {
350 highlight_style
351 .get_or_insert(Default::default())
352 .highlight(*active_highlight);
353 }
354 }
355 Chunk {
356 text: chunk,
357 highlight_style,
358 ..Default::default()
359 }
360 }
361 };
362
363 if self.output_offset == self.transforms.end(&()).0 {
364 self.inlay_chunks = None;
365 self.transforms.next(&());
366 }
367
368 Some(chunk)
369 }
370}
371
372impl<'a> InlayBufferRows<'a> {
373 pub fn seek(&mut self, row: u32) {
374 let inlay_point = InlayPoint::new(row, 0);
375 self.transforms.seek(&inlay_point, Bias::Left, &());
376
377 let mut buffer_point = self.transforms.start().1;
378 let buffer_row = if row == 0 {
379 0
380 } else {
381 match self.transforms.item() {
382 Some(Transform::Isomorphic(_)) => {
383 buffer_point += inlay_point.0 - self.transforms.start().0 .0;
384 buffer_point.row
385 }
386 _ => cmp::min(buffer_point.row + 1, self.max_buffer_row),
387 }
388 };
389 self.inlay_row = inlay_point.row();
390 self.buffer_rows.seek(buffer_row);
391 }
392}
393
394impl<'a> Iterator for InlayBufferRows<'a> {
395 type Item = Option<u32>;
396
397 fn next(&mut self) -> Option<Self::Item> {
398 let buffer_row = if self.inlay_row == 0 {
399 self.buffer_rows.next().unwrap()
400 } else {
401 match self.transforms.item()? {
402 Transform::Inlay(_) => None,
403 Transform::Isomorphic(_) => self.buffer_rows.next().unwrap(),
404 }
405 };
406
407 self.inlay_row += 1;
408 self.transforms
409 .seek_forward(&InlayPoint::new(self.inlay_row, 0), Bias::Left, &());
410
411 Some(buffer_row)
412 }
413}
414
415impl InlayPoint {
416 pub fn new(row: u32, column: u32) -> Self {
417 Self(Point::new(row, column))
418 }
419
420 pub fn row(self) -> u32 {
421 self.0.row
422 }
423}
424
425impl InlayMap {
426 pub fn new(buffer: MultiBufferSnapshot) -> (Self, InlaySnapshot) {
427 let version = 0;
428 let snapshot = InlaySnapshot {
429 buffer: buffer.clone(),
430 transforms: SumTree::from_iter(Some(Transform::Isomorphic(buffer.text_summary())), &()),
431 version,
432 };
433
434 (
435 Self {
436 snapshot: snapshot.clone(),
437 inlays: Vec::new(),
438 },
439 snapshot,
440 )
441 }
442
443 pub fn sync(
444 &mut self,
445 buffer_snapshot: MultiBufferSnapshot,
446 mut buffer_edits: Vec<text::Edit<usize>>,
447 ) -> (InlaySnapshot, Vec<InlayEdit>) {
448 let snapshot = &mut self.snapshot;
449
450 if buffer_edits.is_empty() {
451 if snapshot.buffer.trailing_excerpt_update_count()
452 != buffer_snapshot.trailing_excerpt_update_count()
453 {
454 buffer_edits.push(Edit {
455 old: snapshot.buffer.len()..snapshot.buffer.len(),
456 new: buffer_snapshot.len()..buffer_snapshot.len(),
457 });
458 }
459 }
460
461 if buffer_edits.is_empty() {
462 if snapshot.buffer.edit_count() != buffer_snapshot.edit_count()
463 || snapshot.buffer.parse_count() != buffer_snapshot.parse_count()
464 || snapshot.buffer.diagnostics_update_count()
465 != buffer_snapshot.diagnostics_update_count()
466 || snapshot.buffer.git_diff_update_count()
467 != buffer_snapshot.git_diff_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<'a>(&'a self, row: u32) -> InlayBufferRows<'a> {
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 = self.buffer.max_point().row;
990 let mut buffer_point = cursor.start().1;
991 let buffer_row = if row == 0 {
992 0
993 } else {
994 match cursor.item() {
995 Some(Transform::Isomorphic(_)) => {
996 buffer_point += inlay_point.0 - cursor.start().0 .0;
997 buffer_point.row
998 }
999 _ => cmp::min(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 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 inlay_highlight_style: highlights.inlay_highlight_style,
1055 suggestion_highlight_style: highlights.suggestion_highlight_style,
1056 highlight_endpoints: highlight_endpoints.into_iter().peekable(),
1057 active_highlights: Default::default(),
1058 highlights,
1059 snapshot: self,
1060 }
1061 }
1062
1063 fn apply_text_highlights(
1064 &self,
1065 cursor: &mut Cursor<'_, Transform, (InlayOffset, usize)>,
1066 range: &Range<InlayOffset>,
1067 text_highlights: &TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>,
1068 highlight_endpoints: &mut Vec<HighlightEndpoint>,
1069 ) {
1070 while cursor.start().0 < range.end {
1071 let transform_start = self
1072 .buffer
1073 .anchor_after(self.to_buffer_offset(cmp::max(range.start, cursor.start().0)));
1074 let transform_end =
1075 {
1076 let overshoot = InlayOffset(range.end.0 - cursor.start().0 .0);
1077 self.buffer.anchor_before(self.to_buffer_offset(cmp::min(
1078 cursor.end(&()).0,
1079 cursor.start().0 + overshoot,
1080 )))
1081 };
1082
1083 for (tag, text_highlights) in text_highlights.iter() {
1084 let style = text_highlights.0;
1085 let ranges = &text_highlights.1;
1086
1087 let start_ix = match ranges.binary_search_by(|probe| {
1088 let cmp = probe.end.cmp(&transform_start, &self.buffer);
1089 if cmp.is_gt() {
1090 cmp::Ordering::Greater
1091 } else {
1092 cmp::Ordering::Less
1093 }
1094 }) {
1095 Ok(i) | Err(i) => i,
1096 };
1097 for range in &ranges[start_ix..] {
1098 if range.start.cmp(&transform_end, &self.buffer).is_ge() {
1099 break;
1100 }
1101
1102 highlight_endpoints.push(HighlightEndpoint {
1103 offset: self.to_inlay_offset(range.start.to_offset(&self.buffer)),
1104 is_start: true,
1105 tag: *tag,
1106 style,
1107 });
1108 highlight_endpoints.push(HighlightEndpoint {
1109 offset: self.to_inlay_offset(range.end.to_offset(&self.buffer)),
1110 is_start: false,
1111 tag: *tag,
1112 style,
1113 });
1114 }
1115 }
1116
1117 cursor.next(&());
1118 }
1119 }
1120
1121 #[cfg(test)]
1122 pub fn text(&self) -> String {
1123 self.chunks(Default::default()..self.len(), false, Highlights::default())
1124 .map(|chunk| chunk.text)
1125 .collect()
1126 }
1127
1128 fn check_invariants(&self) {
1129 #[cfg(any(debug_assertions, feature = "test-support"))]
1130 {
1131 assert_eq!(self.transforms.summary().input, self.buffer.text_summary());
1132 let mut transforms = self.transforms.iter().peekable();
1133 while let Some(transform) = transforms.next() {
1134 let transform_is_isomorphic = matches!(transform, Transform::Isomorphic(_));
1135 if let Some(next_transform) = transforms.peek() {
1136 let next_transform_is_isomorphic =
1137 matches!(next_transform, Transform::Isomorphic(_));
1138 assert!(
1139 !transform_is_isomorphic || !next_transform_is_isomorphic,
1140 "two adjacent isomorphic transforms"
1141 );
1142 }
1143 }
1144 }
1145 }
1146}
1147
1148fn push_isomorphic(sum_tree: &mut SumTree<Transform>, summary: TextSummary) {
1149 if summary.len == 0 {
1150 return;
1151 }
1152
1153 let mut summary = Some(summary);
1154 sum_tree.update_last(
1155 |transform| {
1156 if let Transform::Isomorphic(transform) = transform {
1157 *transform += summary.take().unwrap();
1158 }
1159 },
1160 &(),
1161 );
1162
1163 if let Some(summary) = summary {
1164 sum_tree.push(Transform::Isomorphic(summary), &());
1165 }
1166}
1167
1168#[cfg(test)]
1169mod tests {
1170 use super::*;
1171 use crate::{
1172 display_map::{InlayHighlights, TextHighlights},
1173 link_go_to_definition::InlayHighlight,
1174 InlayId, MultiBuffer,
1175 };
1176 use gpui::AppContext;
1177 use project::{InlayHint, InlayHintLabel, ResolveState};
1178 use rand::prelude::*;
1179 use settings::SettingsStore;
1180 use std::{cmp::Reverse, env, sync::Arc};
1181 use text::Patch;
1182 use util::post_inc;
1183
1184 #[test]
1185 fn test_inlay_properties_label_padding() {
1186 assert_eq!(
1187 Inlay::hint(
1188 0,
1189 Anchor::min(),
1190 &InlayHint {
1191 label: InlayHintLabel::String("a".to_string()),
1192 position: text::Anchor::default(),
1193 padding_left: false,
1194 padding_right: false,
1195 tooltip: None,
1196 kind: None,
1197 resolve_state: ResolveState::Resolved,
1198 },
1199 )
1200 .text
1201 .to_string(),
1202 "a",
1203 "Should not pad label if not requested"
1204 );
1205
1206 assert_eq!(
1207 Inlay::hint(
1208 0,
1209 Anchor::min(),
1210 &InlayHint {
1211 label: InlayHintLabel::String("a".to_string()),
1212 position: text::Anchor::default(),
1213 padding_left: true,
1214 padding_right: true,
1215 tooltip: None,
1216 kind: None,
1217 resolve_state: ResolveState::Resolved,
1218 },
1219 )
1220 .text
1221 .to_string(),
1222 " a ",
1223 "Should pad label for every side requested"
1224 );
1225
1226 assert_eq!(
1227 Inlay::hint(
1228 0,
1229 Anchor::min(),
1230 &InlayHint {
1231 label: InlayHintLabel::String(" a ".to_string()),
1232 position: text::Anchor::default(),
1233 padding_left: false,
1234 padding_right: false,
1235 tooltip: None,
1236 kind: None,
1237 resolve_state: ResolveState::Resolved,
1238 },
1239 )
1240 .text
1241 .to_string(),
1242 " a ",
1243 "Should not change already padded label"
1244 );
1245
1246 assert_eq!(
1247 Inlay::hint(
1248 0,
1249 Anchor::min(),
1250 &InlayHint {
1251 label: InlayHintLabel::String(" a ".to_string()),
1252 position: text::Anchor::default(),
1253 padding_left: true,
1254 padding_right: true,
1255 tooltip: None,
1256 kind: None,
1257 resolve_state: ResolveState::Resolved,
1258 },
1259 )
1260 .text
1261 .to_string(),
1262 " a ",
1263 "Should not change already padded label"
1264 );
1265 }
1266
1267 #[gpui::test]
1268 fn test_basic_inlays(cx: &mut AppContext) {
1269 let buffer = MultiBuffer::build_simple("abcdefghi", cx);
1270 let buffer_edits = buffer.update(cx, |buffer, _| buffer.subscribe());
1271 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
1272 assert_eq!(inlay_snapshot.text(), "abcdefghi");
1273 let mut next_inlay_id = 0;
1274
1275 let (inlay_snapshot, _) = inlay_map.splice(
1276 Vec::new(),
1277 vec![Inlay {
1278 id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1279 position: buffer.read(cx).snapshot(cx).anchor_after(3),
1280 text: "|123|".into(),
1281 }],
1282 );
1283 assert_eq!(inlay_snapshot.text(), "abc|123|defghi");
1284 assert_eq!(
1285 inlay_snapshot.to_inlay_point(Point::new(0, 0)),
1286 InlayPoint::new(0, 0)
1287 );
1288 assert_eq!(
1289 inlay_snapshot.to_inlay_point(Point::new(0, 1)),
1290 InlayPoint::new(0, 1)
1291 );
1292 assert_eq!(
1293 inlay_snapshot.to_inlay_point(Point::new(0, 2)),
1294 InlayPoint::new(0, 2)
1295 );
1296 assert_eq!(
1297 inlay_snapshot.to_inlay_point(Point::new(0, 3)),
1298 InlayPoint::new(0, 3)
1299 );
1300 assert_eq!(
1301 inlay_snapshot.to_inlay_point(Point::new(0, 4)),
1302 InlayPoint::new(0, 9)
1303 );
1304 assert_eq!(
1305 inlay_snapshot.to_inlay_point(Point::new(0, 5)),
1306 InlayPoint::new(0, 10)
1307 );
1308 assert_eq!(
1309 inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Left),
1310 InlayPoint::new(0, 0)
1311 );
1312 assert_eq!(
1313 inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Right),
1314 InlayPoint::new(0, 0)
1315 );
1316 assert_eq!(
1317 inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Left),
1318 InlayPoint::new(0, 3)
1319 );
1320 assert_eq!(
1321 inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Right),
1322 InlayPoint::new(0, 3)
1323 );
1324 assert_eq!(
1325 inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Left),
1326 InlayPoint::new(0, 3)
1327 );
1328 assert_eq!(
1329 inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Right),
1330 InlayPoint::new(0, 9)
1331 );
1332
1333 // Edits before or after the inlay should not affect it.
1334 buffer.update(cx, |buffer, cx| {
1335 buffer.edit([(2..3, "x"), (3..3, "y"), (4..4, "z")], None, cx)
1336 });
1337 let (inlay_snapshot, _) = inlay_map.sync(
1338 buffer.read(cx).snapshot(cx),
1339 buffer_edits.consume().into_inner(),
1340 );
1341 assert_eq!(inlay_snapshot.text(), "abxy|123|dzefghi");
1342
1343 // An edit surrounding the inlay should invalidate it.
1344 buffer.update(cx, |buffer, cx| buffer.edit([(4..5, "D")], None, cx));
1345 let (inlay_snapshot, _) = inlay_map.sync(
1346 buffer.read(cx).snapshot(cx),
1347 buffer_edits.consume().into_inner(),
1348 );
1349 assert_eq!(inlay_snapshot.text(), "abxyDzefghi");
1350
1351 let (inlay_snapshot, _) = inlay_map.splice(
1352 Vec::new(),
1353 vec![
1354 Inlay {
1355 id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1356 position: buffer.read(cx).snapshot(cx).anchor_before(3),
1357 text: "|123|".into(),
1358 },
1359 Inlay {
1360 id: InlayId::Suggestion(post_inc(&mut next_inlay_id)),
1361 position: buffer.read(cx).snapshot(cx).anchor_after(3),
1362 text: "|456|".into(),
1363 },
1364 ],
1365 );
1366 assert_eq!(inlay_snapshot.text(), "abx|123||456|yDzefghi");
1367
1368 // Edits ending where the inlay starts should not move it if it has a left bias.
1369 buffer.update(cx, |buffer, cx| buffer.edit([(3..3, "JKL")], None, cx));
1370 let (inlay_snapshot, _) = inlay_map.sync(
1371 buffer.read(cx).snapshot(cx),
1372 buffer_edits.consume().into_inner(),
1373 );
1374 assert_eq!(inlay_snapshot.text(), "abx|123|JKL|456|yDzefghi");
1375
1376 assert_eq!(
1377 inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Left),
1378 InlayPoint::new(0, 0)
1379 );
1380 assert_eq!(
1381 inlay_snapshot.clip_point(InlayPoint::new(0, 0), Bias::Right),
1382 InlayPoint::new(0, 0)
1383 );
1384
1385 assert_eq!(
1386 inlay_snapshot.clip_point(InlayPoint::new(0, 1), Bias::Left),
1387 InlayPoint::new(0, 1)
1388 );
1389 assert_eq!(
1390 inlay_snapshot.clip_point(InlayPoint::new(0, 1), Bias::Right),
1391 InlayPoint::new(0, 1)
1392 );
1393
1394 assert_eq!(
1395 inlay_snapshot.clip_point(InlayPoint::new(0, 2), Bias::Left),
1396 InlayPoint::new(0, 2)
1397 );
1398 assert_eq!(
1399 inlay_snapshot.clip_point(InlayPoint::new(0, 2), Bias::Right),
1400 InlayPoint::new(0, 2)
1401 );
1402
1403 assert_eq!(
1404 inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Left),
1405 InlayPoint::new(0, 2)
1406 );
1407 assert_eq!(
1408 inlay_snapshot.clip_point(InlayPoint::new(0, 3), Bias::Right),
1409 InlayPoint::new(0, 8)
1410 );
1411
1412 assert_eq!(
1413 inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Left),
1414 InlayPoint::new(0, 2)
1415 );
1416 assert_eq!(
1417 inlay_snapshot.clip_point(InlayPoint::new(0, 4), Bias::Right),
1418 InlayPoint::new(0, 8)
1419 );
1420
1421 assert_eq!(
1422 inlay_snapshot.clip_point(InlayPoint::new(0, 5), Bias::Left),
1423 InlayPoint::new(0, 2)
1424 );
1425 assert_eq!(
1426 inlay_snapshot.clip_point(InlayPoint::new(0, 5), Bias::Right),
1427 InlayPoint::new(0, 8)
1428 );
1429
1430 assert_eq!(
1431 inlay_snapshot.clip_point(InlayPoint::new(0, 6), Bias::Left),
1432 InlayPoint::new(0, 2)
1433 );
1434 assert_eq!(
1435 inlay_snapshot.clip_point(InlayPoint::new(0, 6), Bias::Right),
1436 InlayPoint::new(0, 8)
1437 );
1438
1439 assert_eq!(
1440 inlay_snapshot.clip_point(InlayPoint::new(0, 7), Bias::Left),
1441 InlayPoint::new(0, 2)
1442 );
1443 assert_eq!(
1444 inlay_snapshot.clip_point(InlayPoint::new(0, 7), Bias::Right),
1445 InlayPoint::new(0, 8)
1446 );
1447
1448 assert_eq!(
1449 inlay_snapshot.clip_point(InlayPoint::new(0, 8), Bias::Left),
1450 InlayPoint::new(0, 8)
1451 );
1452 assert_eq!(
1453 inlay_snapshot.clip_point(InlayPoint::new(0, 8), Bias::Right),
1454 InlayPoint::new(0, 8)
1455 );
1456
1457 assert_eq!(
1458 inlay_snapshot.clip_point(InlayPoint::new(0, 9), Bias::Left),
1459 InlayPoint::new(0, 9)
1460 );
1461 assert_eq!(
1462 inlay_snapshot.clip_point(InlayPoint::new(0, 9), Bias::Right),
1463 InlayPoint::new(0, 9)
1464 );
1465
1466 assert_eq!(
1467 inlay_snapshot.clip_point(InlayPoint::new(0, 10), Bias::Left),
1468 InlayPoint::new(0, 10)
1469 );
1470 assert_eq!(
1471 inlay_snapshot.clip_point(InlayPoint::new(0, 10), Bias::Right),
1472 InlayPoint::new(0, 10)
1473 );
1474
1475 assert_eq!(
1476 inlay_snapshot.clip_point(InlayPoint::new(0, 11), Bias::Left),
1477 InlayPoint::new(0, 11)
1478 );
1479 assert_eq!(
1480 inlay_snapshot.clip_point(InlayPoint::new(0, 11), Bias::Right),
1481 InlayPoint::new(0, 11)
1482 );
1483
1484 assert_eq!(
1485 inlay_snapshot.clip_point(InlayPoint::new(0, 12), Bias::Left),
1486 InlayPoint::new(0, 11)
1487 );
1488 assert_eq!(
1489 inlay_snapshot.clip_point(InlayPoint::new(0, 12), Bias::Right),
1490 InlayPoint::new(0, 17)
1491 );
1492
1493 assert_eq!(
1494 inlay_snapshot.clip_point(InlayPoint::new(0, 13), Bias::Left),
1495 InlayPoint::new(0, 11)
1496 );
1497 assert_eq!(
1498 inlay_snapshot.clip_point(InlayPoint::new(0, 13), Bias::Right),
1499 InlayPoint::new(0, 17)
1500 );
1501
1502 assert_eq!(
1503 inlay_snapshot.clip_point(InlayPoint::new(0, 14), Bias::Left),
1504 InlayPoint::new(0, 11)
1505 );
1506 assert_eq!(
1507 inlay_snapshot.clip_point(InlayPoint::new(0, 14), Bias::Right),
1508 InlayPoint::new(0, 17)
1509 );
1510
1511 assert_eq!(
1512 inlay_snapshot.clip_point(InlayPoint::new(0, 15), Bias::Left),
1513 InlayPoint::new(0, 11)
1514 );
1515 assert_eq!(
1516 inlay_snapshot.clip_point(InlayPoint::new(0, 15), Bias::Right),
1517 InlayPoint::new(0, 17)
1518 );
1519
1520 assert_eq!(
1521 inlay_snapshot.clip_point(InlayPoint::new(0, 16), Bias::Left),
1522 InlayPoint::new(0, 11)
1523 );
1524 assert_eq!(
1525 inlay_snapshot.clip_point(InlayPoint::new(0, 16), Bias::Right),
1526 InlayPoint::new(0, 17)
1527 );
1528
1529 assert_eq!(
1530 inlay_snapshot.clip_point(InlayPoint::new(0, 17), Bias::Left),
1531 InlayPoint::new(0, 17)
1532 );
1533 assert_eq!(
1534 inlay_snapshot.clip_point(InlayPoint::new(0, 17), Bias::Right),
1535 InlayPoint::new(0, 17)
1536 );
1537
1538 assert_eq!(
1539 inlay_snapshot.clip_point(InlayPoint::new(0, 18), Bias::Left),
1540 InlayPoint::new(0, 18)
1541 );
1542 assert_eq!(
1543 inlay_snapshot.clip_point(InlayPoint::new(0, 18), Bias::Right),
1544 InlayPoint::new(0, 18)
1545 );
1546
1547 // The inlays can be manually removed.
1548 let (inlay_snapshot, _) = inlay_map.splice(
1549 inlay_map.inlays.iter().map(|inlay| inlay.id).collect(),
1550 Vec::new(),
1551 );
1552 assert_eq!(inlay_snapshot.text(), "abxJKLyDzefghi");
1553 }
1554
1555 #[gpui::test]
1556 fn test_inlay_buffer_rows(cx: &mut AppContext) {
1557 let buffer = MultiBuffer::build_simple("abc\ndef\nghi", cx);
1558 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
1559 assert_eq!(inlay_snapshot.text(), "abc\ndef\nghi");
1560 let mut next_inlay_id = 0;
1561
1562 let (inlay_snapshot, _) = inlay_map.splice(
1563 Vec::new(),
1564 vec![
1565 Inlay {
1566 id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1567 position: buffer.read(cx).snapshot(cx).anchor_before(0),
1568 text: "|123|\n".into(),
1569 },
1570 Inlay {
1571 id: InlayId::Hint(post_inc(&mut next_inlay_id)),
1572 position: buffer.read(cx).snapshot(cx).anchor_before(4),
1573 text: "|456|".into(),
1574 },
1575 Inlay {
1576 id: InlayId::Suggestion(post_inc(&mut next_inlay_id)),
1577 position: buffer.read(cx).snapshot(cx).anchor_before(7),
1578 text: "\n|567|\n".into(),
1579 },
1580 ],
1581 );
1582 assert_eq!(inlay_snapshot.text(), "|123|\nabc\n|456|def\n|567|\n\nghi");
1583 assert_eq!(
1584 inlay_snapshot.buffer_rows(0).collect::<Vec<_>>(),
1585 vec![Some(0), None, Some(1), None, None, Some(2)]
1586 );
1587 }
1588
1589 #[gpui::test(iterations = 100)]
1590 fn test_random_inlays(cx: &mut AppContext, mut rng: StdRng) {
1591 init_test(cx);
1592
1593 let operations = env::var("OPERATIONS")
1594 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1595 .unwrap_or(10);
1596
1597 let len = rng.gen_range(0..30);
1598 let buffer = if rng.gen() {
1599 let text = util::RandomCharIter::new(&mut rng)
1600 .take(len)
1601 .collect::<String>();
1602 MultiBuffer::build_simple(&text, cx)
1603 } else {
1604 MultiBuffer::build_random(&mut rng, cx)
1605 };
1606 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1607 let mut next_inlay_id = 0;
1608 log::info!("buffer text: {:?}", buffer_snapshot.text());
1609 let (mut inlay_map, mut inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1610 for _ in 0..operations {
1611 let mut inlay_edits = Patch::default();
1612
1613 let mut prev_inlay_text = inlay_snapshot.text();
1614 let mut buffer_edits = Vec::new();
1615 match rng.gen_range(0..=100) {
1616 0..=50 => {
1617 let (snapshot, edits) = inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1618 log::info!("mutated text: {:?}", snapshot.text());
1619 inlay_edits = Patch::new(edits);
1620 }
1621 _ => buffer.update(cx, |buffer, cx| {
1622 let subscription = buffer.subscribe();
1623 let edit_count = rng.gen_range(1..=5);
1624 buffer.randomly_mutate(&mut rng, edit_count, cx);
1625 buffer_snapshot = buffer.snapshot(cx);
1626 let edits = subscription.consume().into_inner();
1627 log::info!("editing {:?}", edits);
1628 buffer_edits.extend(edits);
1629 }),
1630 };
1631
1632 let (new_inlay_snapshot, new_inlay_edits) =
1633 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1634 inlay_snapshot = new_inlay_snapshot;
1635 inlay_edits = inlay_edits.compose(new_inlay_edits);
1636
1637 log::info!("buffer text: {:?}", buffer_snapshot.text());
1638 log::info!("inlay text: {:?}", inlay_snapshot.text());
1639
1640 let inlays = inlay_map
1641 .inlays
1642 .iter()
1643 .filter(|inlay| inlay.position.is_valid(&buffer_snapshot))
1644 .map(|inlay| {
1645 let offset = inlay.position.to_offset(&buffer_snapshot);
1646 (offset, inlay.clone())
1647 })
1648 .collect::<Vec<_>>();
1649 let mut expected_text = Rope::from(buffer_snapshot.text());
1650 for (offset, inlay) in inlays.iter().rev() {
1651 expected_text.replace(*offset..*offset, &inlay.text.to_string());
1652 }
1653 assert_eq!(inlay_snapshot.text(), expected_text.to_string());
1654
1655 let expected_buffer_rows = inlay_snapshot.buffer_rows(0).collect::<Vec<_>>();
1656 assert_eq!(
1657 expected_buffer_rows.len() as u32,
1658 expected_text.max_point().row + 1
1659 );
1660 for row_start in 0..expected_buffer_rows.len() {
1661 assert_eq!(
1662 inlay_snapshot
1663 .buffer_rows(row_start as u32)
1664 .collect::<Vec<_>>(),
1665 &expected_buffer_rows[row_start..],
1666 "incorrect buffer rows starting at {}",
1667 row_start
1668 );
1669 }
1670
1671 let mut text_highlights = TextHighlights::default();
1672 let text_highlight_count = rng.gen_range(0_usize..10);
1673 let mut text_highlight_ranges = (0..text_highlight_count)
1674 .map(|_| buffer_snapshot.random_byte_range(0, &mut rng))
1675 .collect::<Vec<_>>();
1676 text_highlight_ranges.sort_by_key(|range| (range.start, Reverse(range.end)));
1677 log::info!("highlighting text ranges {text_highlight_ranges:?}");
1678 text_highlights.insert(
1679 Some(TypeId::of::<()>()),
1680 Arc::new((
1681 HighlightStyle::default(),
1682 text_highlight_ranges
1683 .into_iter()
1684 .map(|range| {
1685 buffer_snapshot.anchor_before(range.start)
1686 ..buffer_snapshot.anchor_after(range.end)
1687 })
1688 .collect(),
1689 )),
1690 );
1691
1692 let mut inlay_highlights = InlayHighlights::default();
1693 if !inlays.is_empty() {
1694 let inlay_highlight_count = rng.gen_range(0..inlays.len());
1695 let mut inlay_indices = BTreeSet::default();
1696 while inlay_indices.len() < inlay_highlight_count {
1697 inlay_indices.insert(rng.gen_range(0..inlays.len()));
1698 }
1699 let new_highlights = 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 .collect();
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 cx.set_global(SettingsStore::test(cx));
1895 theme::init((), cx);
1896 }
1897}