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