1use super::{
2 fold_map::{FoldBufferRows, FoldChunks, FoldEdit, FoldOffset, FoldPoint, FoldSnapshot},
3 TextHighlights,
4};
5use crate::{MultiBufferSnapshot, ToPoint};
6use gpui::fonts::HighlightStyle;
7use language::{Bias, Chunk, Edit, Patch, Point, Rope, TextSummary};
8use parking_lot::Mutex;
9use std::{
10 cmp,
11 ops::{Add, AddAssign, Range, Sub},
12};
13use util::post_inc;
14
15pub type SuggestionEdit = Edit<SuggestionOffset>;
16
17#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
18pub struct SuggestionOffset(pub usize);
19
20impl Add for SuggestionOffset {
21 type Output = Self;
22
23 fn add(self, rhs: Self) -> Self::Output {
24 Self(self.0 + rhs.0)
25 }
26}
27
28impl Sub for SuggestionOffset {
29 type Output = Self;
30
31 fn sub(self, rhs: Self) -> Self::Output {
32 Self(self.0 - rhs.0)
33 }
34}
35
36impl AddAssign for SuggestionOffset {
37 fn add_assign(&mut self, rhs: Self) {
38 self.0 += rhs.0;
39 }
40}
41
42#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
43pub struct SuggestionPoint(pub Point);
44
45impl SuggestionPoint {
46 pub fn new(row: u32, column: u32) -> Self {
47 Self(Point::new(row, column))
48 }
49
50 pub fn row(self) -> u32 {
51 self.0.row
52 }
53
54 pub fn column(self) -> u32 {
55 self.0.column
56 }
57}
58
59#[derive(Clone, Debug)]
60pub struct Suggestion<T> {
61 pub position: T,
62 pub text: Rope,
63}
64
65pub struct SuggestionMap(Mutex<SuggestionSnapshot>);
66
67impl SuggestionMap {
68 pub fn new(fold_snapshot: FoldSnapshot) -> (Self, SuggestionSnapshot) {
69 let snapshot = SuggestionSnapshot {
70 fold_snapshot,
71 suggestion: None,
72 version: 0,
73 };
74 (Self(Mutex::new(snapshot.clone())), snapshot)
75 }
76
77 pub fn replace<T>(
78 &self,
79 new_suggestion: Option<Suggestion<T>>,
80 fold_snapshot: FoldSnapshot,
81 fold_edits: Vec<FoldEdit>,
82 ) -> (
83 SuggestionSnapshot,
84 Vec<SuggestionEdit>,
85 Option<Suggestion<FoldOffset>>,
86 )
87 where
88 T: ToPoint,
89 {
90 let new_suggestion = new_suggestion.map(|new_suggestion| {
91 let buffer_point = new_suggestion
92 .position
93 .to_point(fold_snapshot.buffer_snapshot());
94 let fold_point = fold_snapshot.to_fold_point(buffer_point, Bias::Left);
95 let fold_offset = fold_point.to_offset(&fold_snapshot);
96 Suggestion {
97 position: fold_offset,
98 text: new_suggestion.text,
99 }
100 });
101
102 let (_, edits) = self.sync(fold_snapshot, fold_edits);
103 let mut snapshot = self.0.lock();
104
105 let mut patch = Patch::new(edits);
106 let old_suggestion = snapshot.suggestion.take();
107 if let Some(suggestion) = &old_suggestion {
108 patch = patch.compose([SuggestionEdit {
109 old: SuggestionOffset(suggestion.position.0)
110 ..SuggestionOffset(suggestion.position.0 + suggestion.text.len()),
111 new: SuggestionOffset(suggestion.position.0)
112 ..SuggestionOffset(suggestion.position.0),
113 }]);
114 }
115
116 if let Some(suggestion) = new_suggestion.as_ref() {
117 patch = patch.compose([SuggestionEdit {
118 old: SuggestionOffset(suggestion.position.0)
119 ..SuggestionOffset(suggestion.position.0),
120 new: SuggestionOffset(suggestion.position.0)
121 ..SuggestionOffset(suggestion.position.0 + suggestion.text.len()),
122 }]);
123 }
124
125 snapshot.suggestion = new_suggestion;
126 snapshot.version += 1;
127 (snapshot.clone(), patch.into_inner(), old_suggestion)
128 }
129
130 pub fn sync(
131 &self,
132 fold_snapshot: FoldSnapshot,
133 fold_edits: Vec<FoldEdit>,
134 ) -> (SuggestionSnapshot, Vec<SuggestionEdit>) {
135 let mut snapshot = self.0.lock();
136
137 if snapshot.fold_snapshot.version != fold_snapshot.version {
138 snapshot.version += 1;
139 }
140
141 let mut suggestion_edits = Vec::new();
142
143 let mut suggestion_old_len = 0;
144 let mut suggestion_new_len = 0;
145 for fold_edit in fold_edits {
146 let start = fold_edit.new.start;
147 let end = FoldOffset(start.0 + fold_edit.old_len().0);
148 if let Some(suggestion) = snapshot.suggestion.as_mut() {
149 if end <= suggestion.position {
150 suggestion.position.0 += fold_edit.new_len().0;
151 suggestion.position.0 -= fold_edit.old_len().0;
152 } else if start > suggestion.position {
153 suggestion_old_len = suggestion.text.len();
154 suggestion_new_len = suggestion_old_len;
155 } else {
156 suggestion_old_len = suggestion.text.len();
157 snapshot.suggestion.take();
158 suggestion_edits.push(SuggestionEdit {
159 old: SuggestionOffset(fold_edit.old.start.0)
160 ..SuggestionOffset(fold_edit.old.end.0 + suggestion_old_len),
161 new: SuggestionOffset(fold_edit.new.start.0)
162 ..SuggestionOffset(fold_edit.new.end.0),
163 });
164 continue;
165 }
166 }
167
168 suggestion_edits.push(SuggestionEdit {
169 old: SuggestionOffset(fold_edit.old.start.0 + suggestion_old_len)
170 ..SuggestionOffset(fold_edit.old.end.0 + suggestion_old_len),
171 new: SuggestionOffset(fold_edit.new.start.0 + suggestion_new_len)
172 ..SuggestionOffset(fold_edit.new.end.0 + suggestion_new_len),
173 });
174 }
175 snapshot.fold_snapshot = fold_snapshot;
176
177 (snapshot.clone(), suggestion_edits)
178 }
179
180 pub fn has_suggestion(&self) -> bool {
181 let snapshot = self.0.lock();
182 snapshot.suggestion.is_some()
183 }
184}
185
186#[derive(Clone)]
187pub struct SuggestionSnapshot {
188 pub fold_snapshot: FoldSnapshot,
189 pub suggestion: Option<Suggestion<FoldOffset>>,
190 pub version: usize,
191}
192
193impl SuggestionSnapshot {
194 pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
195 self.fold_snapshot.buffer_snapshot()
196 }
197
198 pub fn max_point(&self) -> SuggestionPoint {
199 if let Some(suggestion) = self.suggestion.as_ref() {
200 let suggestion_point = suggestion.position.to_point(&self.fold_snapshot);
201 let mut max_point = suggestion_point.0;
202 max_point += suggestion.text.max_point();
203 max_point += self.fold_snapshot.max_point().0 - suggestion_point.0;
204 SuggestionPoint(max_point)
205 } else {
206 SuggestionPoint(self.fold_snapshot.max_point().0)
207 }
208 }
209
210 pub fn len(&self) -> SuggestionOffset {
211 if let Some(suggestion) = self.suggestion.as_ref() {
212 let mut len = suggestion.position.0;
213 len += suggestion.text.len();
214 len += self.fold_snapshot.len().0 - suggestion.position.0;
215 SuggestionOffset(len)
216 } else {
217 SuggestionOffset(self.fold_snapshot.len().0)
218 }
219 }
220
221 pub fn line_len(&self, row: u32) -> u32 {
222 if let Some(suggestion) = &self.suggestion {
223 let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
224 let suggestion_end = suggestion_start + suggestion.text.max_point();
225
226 if row < suggestion_start.row {
227 self.fold_snapshot.line_len(row)
228 } else if row > suggestion_end.row {
229 self.fold_snapshot
230 .line_len(suggestion_start.row + (row - suggestion_end.row))
231 } else {
232 let mut result = suggestion.text.line_len(row - suggestion_start.row);
233 if row == suggestion_start.row {
234 result += suggestion_start.column;
235 }
236 if row == suggestion_end.row {
237 result +=
238 self.fold_snapshot.line_len(suggestion_start.row) - suggestion_start.column;
239 }
240 result
241 }
242 } else {
243 self.fold_snapshot.line_len(row)
244 }
245 }
246
247 pub fn clip_point(&self, point: SuggestionPoint, bias: Bias) -> SuggestionPoint {
248 if let Some(suggestion) = self.suggestion.as_ref() {
249 let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
250 let suggestion_end = suggestion_start + suggestion.text.max_point();
251 if point.0 <= suggestion_start {
252 SuggestionPoint(self.fold_snapshot.clip_point(FoldPoint(point.0), bias).0)
253 } else if point.0 > suggestion_end {
254 let fold_point = self.fold_snapshot.clip_point(
255 FoldPoint(suggestion_start + (point.0 - suggestion_end)),
256 bias,
257 );
258 let suggestion_point = suggestion_end + (fold_point.0 - suggestion_start);
259 if bias == Bias::Left && suggestion_point == suggestion_end {
260 SuggestionPoint(suggestion_start)
261 } else {
262 SuggestionPoint(suggestion_point)
263 }
264 } else if bias == Bias::Left || suggestion_start == self.fold_snapshot.max_point().0 {
265 SuggestionPoint(suggestion_start)
266 } else {
267 let fold_point = if self.fold_snapshot.line_len(suggestion_start.row)
268 > suggestion_start.column
269 {
270 FoldPoint(suggestion_start + Point::new(0, 1))
271 } else {
272 FoldPoint(suggestion_start + Point::new(1, 0))
273 };
274 let clipped_fold_point = self.fold_snapshot.clip_point(fold_point, bias);
275 SuggestionPoint(suggestion_end + (clipped_fold_point.0 - suggestion_start))
276 }
277 } else {
278 SuggestionPoint(self.fold_snapshot.clip_point(FoldPoint(point.0), bias).0)
279 }
280 }
281
282 pub fn to_offset(&self, point: SuggestionPoint) -> SuggestionOffset {
283 if let Some(suggestion) = self.suggestion.as_ref() {
284 let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
285 let suggestion_end = suggestion_start + suggestion.text.max_point();
286
287 if point.0 <= suggestion_start {
288 SuggestionOffset(FoldPoint(point.0).to_offset(&self.fold_snapshot).0)
289 } else if point.0 > suggestion_end {
290 let fold_offset = FoldPoint(suggestion_start + (point.0 - suggestion_end))
291 .to_offset(&self.fold_snapshot);
292 SuggestionOffset(fold_offset.0 + suggestion.text.len())
293 } else {
294 let offset_in_suggestion =
295 suggestion.text.point_to_offset(point.0 - suggestion_start);
296 SuggestionOffset(suggestion.position.0 + offset_in_suggestion)
297 }
298 } else {
299 SuggestionOffset(FoldPoint(point.0).to_offset(&self.fold_snapshot).0)
300 }
301 }
302
303 pub fn to_point(&self, offset: SuggestionOffset) -> SuggestionPoint {
304 if let Some(suggestion) = self.suggestion.as_ref() {
305 let suggestion_point_start = suggestion.position.to_point(&self.fold_snapshot).0;
306 if offset.0 <= suggestion.position.0 {
307 SuggestionPoint(FoldOffset(offset.0).to_point(&self.fold_snapshot).0)
308 } else if offset.0 > (suggestion.position.0 + suggestion.text.len()) {
309 let fold_point = FoldOffset(offset.0 - suggestion.text.len())
310 .to_point(&self.fold_snapshot)
311 .0;
312
313 SuggestionPoint(
314 suggestion_point_start
315 + suggestion.text.max_point()
316 + (fold_point - suggestion_point_start),
317 )
318 } else {
319 let point_in_suggestion = suggestion
320 .text
321 .offset_to_point(offset.0 - suggestion.position.0);
322 SuggestionPoint(suggestion_point_start + point_in_suggestion)
323 }
324 } else {
325 SuggestionPoint(FoldOffset(offset.0).to_point(&self.fold_snapshot).0)
326 }
327 }
328
329 pub fn to_fold_point(&self, point: SuggestionPoint) -> FoldPoint {
330 if let Some(suggestion) = self.suggestion.as_ref() {
331 let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
332 let suggestion_end = suggestion_start + suggestion.text.max_point();
333
334 if point.0 <= suggestion_start {
335 FoldPoint(point.0)
336 } else if point.0 > suggestion_end {
337 FoldPoint(suggestion_start + (point.0 - suggestion_end))
338 } else {
339 FoldPoint(suggestion_start)
340 }
341 } else {
342 FoldPoint(point.0)
343 }
344 }
345
346 pub fn to_suggestion_point(&self, point: FoldPoint) -> SuggestionPoint {
347 if let Some(suggestion) = self.suggestion.as_ref() {
348 let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
349
350 if point.0 <= suggestion_start {
351 SuggestionPoint(point.0)
352 } else {
353 let suggestion_end = suggestion_start + suggestion.text.max_point();
354 SuggestionPoint(suggestion_end + (point.0 - suggestion_start))
355 }
356 } else {
357 SuggestionPoint(point.0)
358 }
359 }
360
361 pub fn text_summary_for_range(&self, range: Range<SuggestionPoint>) -> TextSummary {
362 if let Some(suggestion) = self.suggestion.as_ref() {
363 let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
364 let suggestion_end = suggestion_start + suggestion.text.max_point();
365 let mut summary = TextSummary::default();
366
367 let prefix_range =
368 cmp::min(range.start.0, suggestion_start)..cmp::min(range.end.0, suggestion_start);
369 if prefix_range.start < prefix_range.end {
370 summary += self.fold_snapshot.text_summary_for_range(
371 FoldPoint(prefix_range.start)..FoldPoint(prefix_range.end),
372 );
373 }
374
375 let suggestion_range =
376 cmp::max(range.start.0, suggestion_start)..cmp::min(range.end.0, suggestion_end);
377 if suggestion_range.start < suggestion_range.end {
378 let point_range = suggestion_range.start - suggestion_start
379 ..suggestion_range.end - suggestion_start;
380 let offset_range = suggestion.text.point_to_offset(point_range.start)
381 ..suggestion.text.point_to_offset(point_range.end);
382 summary += suggestion
383 .text
384 .cursor(offset_range.start)
385 .summary::<TextSummary>(offset_range.end);
386 }
387
388 let suffix_range = cmp::max(range.start.0, suggestion_end)..range.end.0;
389 if suffix_range.start < suffix_range.end {
390 let start = suggestion_start + (suffix_range.start - suggestion_end);
391 let end = suggestion_start + (suffix_range.end - suggestion_end);
392 summary += self
393 .fold_snapshot
394 .text_summary_for_range(FoldPoint(start)..FoldPoint(end));
395 }
396
397 summary
398 } else {
399 self.fold_snapshot
400 .text_summary_for_range(FoldPoint(range.start.0)..FoldPoint(range.end.0))
401 }
402 }
403
404 pub fn chars_at(&self, start: SuggestionPoint) -> impl '_ + Iterator<Item = char> {
405 let start = self.to_offset(start);
406 self.chunks(start..self.len(), false, None, None)
407 .flat_map(|chunk| chunk.text.chars())
408 }
409
410 pub fn chunks<'a>(
411 &'a self,
412 range: Range<SuggestionOffset>,
413 language_aware: bool,
414 text_highlights: Option<&'a TextHighlights>,
415 suggestion_highlight: Option<HighlightStyle>,
416 ) -> SuggestionChunks<'a> {
417 if let Some(suggestion) = self.suggestion.as_ref() {
418 let suggestion_range =
419 suggestion.position.0..suggestion.position.0 + suggestion.text.len();
420
421 let prefix_chunks = if range.start.0 < suggestion_range.start {
422 Some(self.fold_snapshot.chunks(
423 FoldOffset(range.start.0)
424 ..cmp::min(FoldOffset(suggestion_range.start), FoldOffset(range.end.0)),
425 language_aware,
426 text_highlights,
427 ))
428 } else {
429 None
430 };
431
432 let clipped_suggestion_range = cmp::max(range.start.0, suggestion_range.start)
433 ..cmp::min(range.end.0, suggestion_range.end);
434 let suggestion_chunks = if clipped_suggestion_range.start < clipped_suggestion_range.end
435 {
436 let start = clipped_suggestion_range.start - suggestion_range.start;
437 let end = clipped_suggestion_range.end - suggestion_range.start;
438 Some(suggestion.text.chunks_in_range(start..end))
439 } else {
440 None
441 };
442
443 let suffix_chunks = if range.end.0 > suggestion_range.end {
444 let start = cmp::max(suggestion_range.end, range.start.0) - suggestion_range.len();
445 let end = range.end.0 - suggestion_range.len();
446 Some(self.fold_snapshot.chunks(
447 FoldOffset(start)..FoldOffset(end),
448 language_aware,
449 text_highlights,
450 ))
451 } else {
452 None
453 };
454
455 SuggestionChunks {
456 prefix_chunks,
457 suggestion_chunks,
458 suffix_chunks,
459 highlight_style: suggestion_highlight,
460 }
461 } else {
462 SuggestionChunks {
463 prefix_chunks: Some(self.fold_snapshot.chunks(
464 FoldOffset(range.start.0)..FoldOffset(range.end.0),
465 language_aware,
466 text_highlights,
467 )),
468 suggestion_chunks: None,
469 suffix_chunks: None,
470 highlight_style: None,
471 }
472 }
473 }
474
475 pub fn buffer_rows<'a>(&'a self, row: u32) -> SuggestionBufferRows<'a> {
476 let suggestion_range = if let Some(suggestion) = self.suggestion.as_ref() {
477 let start = suggestion.position.to_point(&self.fold_snapshot).0;
478 let end = start + suggestion.text.max_point();
479 start.row..end.row
480 } else {
481 u32::MAX..u32::MAX
482 };
483
484 let fold_buffer_rows = if row <= suggestion_range.start {
485 self.fold_snapshot.buffer_rows(row)
486 } else if row > suggestion_range.end {
487 self.fold_snapshot
488 .buffer_rows(row - (suggestion_range.end - suggestion_range.start))
489 } else {
490 let mut rows = self.fold_snapshot.buffer_rows(suggestion_range.start);
491 rows.next();
492 rows
493 };
494
495 SuggestionBufferRows {
496 current_row: row,
497 suggestion_row_start: suggestion_range.start,
498 suggestion_row_end: suggestion_range.end,
499 fold_buffer_rows,
500 }
501 }
502
503 #[cfg(test)]
504 pub fn text(&self) -> String {
505 self.chunks(Default::default()..self.len(), false, None, None)
506 .map(|chunk| chunk.text)
507 .collect()
508 }
509}
510
511pub struct SuggestionChunks<'a> {
512 prefix_chunks: Option<FoldChunks<'a>>,
513 suggestion_chunks: Option<text::Chunks<'a>>,
514 suffix_chunks: Option<FoldChunks<'a>>,
515 highlight_style: Option<HighlightStyle>,
516}
517
518impl<'a> Iterator for SuggestionChunks<'a> {
519 type Item = Chunk<'a>;
520
521 fn next(&mut self) -> Option<Self::Item> {
522 if let Some(chunks) = self.prefix_chunks.as_mut() {
523 if let Some(chunk) = chunks.next() {
524 return Some(chunk);
525 } else {
526 self.prefix_chunks = None;
527 }
528 }
529
530 if let Some(chunks) = self.suggestion_chunks.as_mut() {
531 if let Some(chunk) = chunks.next() {
532 return Some(Chunk {
533 text: chunk,
534 highlight_style: self.highlight_style,
535 ..Default::default()
536 });
537 } else {
538 self.suggestion_chunks = None;
539 }
540 }
541
542 if let Some(chunks) = self.suffix_chunks.as_mut() {
543 if let Some(chunk) = chunks.next() {
544 return Some(chunk);
545 } else {
546 self.suffix_chunks = None;
547 }
548 }
549
550 None
551 }
552}
553
554#[derive(Clone)]
555pub struct SuggestionBufferRows<'a> {
556 current_row: u32,
557 suggestion_row_start: u32,
558 suggestion_row_end: u32,
559 fold_buffer_rows: FoldBufferRows<'a>,
560}
561
562impl<'a> Iterator for SuggestionBufferRows<'a> {
563 type Item = Option<u32>;
564
565 fn next(&mut self) -> Option<Self::Item> {
566 let row = post_inc(&mut self.current_row);
567 if row <= self.suggestion_row_start || row > self.suggestion_row_end {
568 self.fold_buffer_rows.next()
569 } else {
570 Some(None)
571 }
572 }
573}
574
575#[cfg(test)]
576mod tests {
577 use super::*;
578 use crate::{display_map::fold_map::FoldMap, MultiBuffer};
579 use gpui::AppContext;
580 use rand::{prelude::StdRng, Rng};
581 use settings::Settings;
582 use std::{
583 env,
584 ops::{Bound, RangeBounds},
585 };
586
587 #[gpui::test]
588 fn test_basic(cx: &mut AppContext) {
589 let buffer = MultiBuffer::build_simple("abcdefghi", cx);
590 let buffer_edits = buffer.update(cx, |buffer, _| buffer.subscribe());
591 let (mut fold_map, fold_snapshot) = FoldMap::new(buffer.read(cx).snapshot(cx));
592 let (suggestion_map, suggestion_snapshot) = SuggestionMap::new(fold_snapshot.clone());
593 assert_eq!(suggestion_snapshot.text(), "abcdefghi");
594
595 let (suggestion_snapshot, _, _) = suggestion_map.replace(
596 Some(Suggestion {
597 position: 3,
598 text: "123\n456".into(),
599 }),
600 fold_snapshot,
601 Default::default(),
602 );
603 assert_eq!(suggestion_snapshot.text(), "abc123\n456defghi");
604
605 buffer.update(cx, |buffer, cx| {
606 buffer.edit(
607 [(0..0, "ABC"), (3..3, "DEF"), (4..4, "GHI"), (9..9, "JKL")],
608 None,
609 cx,
610 )
611 });
612 let (fold_snapshot, fold_edits) = fold_map.read(
613 buffer.read(cx).snapshot(cx),
614 buffer_edits.consume().into_inner(),
615 );
616 let (suggestion_snapshot, _) = suggestion_map.sync(fold_snapshot.clone(), fold_edits);
617 assert_eq!(suggestion_snapshot.text(), "ABCabcDEF123\n456dGHIefghiJKL");
618
619 let (mut fold_map_writer, _, _) =
620 fold_map.write(buffer.read(cx).snapshot(cx), Default::default());
621 let (fold_snapshot, fold_edits) = fold_map_writer.fold([0..3]);
622 let (suggestion_snapshot, _) = suggestion_map.sync(fold_snapshot, fold_edits);
623 assert_eq!(suggestion_snapshot.text(), "⋯abcDEF123\n456dGHIefghiJKL");
624
625 let (mut fold_map_writer, _, _) =
626 fold_map.write(buffer.read(cx).snapshot(cx), Default::default());
627 let (fold_snapshot, fold_edits) = fold_map_writer.fold([6..10]);
628 let (suggestion_snapshot, _) = suggestion_map.sync(fold_snapshot, fold_edits);
629 assert_eq!(suggestion_snapshot.text(), "⋯abc⋯GHIefghiJKL");
630 }
631
632 #[gpui::test(iterations = 100)]
633 fn test_random_suggestions(cx: &mut AppContext, mut rng: StdRng) {
634 cx.set_global(Settings::test(cx));
635 let operations = env::var("OPERATIONS")
636 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
637 .unwrap_or(10);
638
639 let len = rng.gen_range(0..30);
640 let buffer = if rng.gen() {
641 let text = util::RandomCharIter::new(&mut rng)
642 .take(len)
643 .collect::<String>();
644 MultiBuffer::build_simple(&text, cx)
645 } else {
646 MultiBuffer::build_random(&mut rng, cx)
647 };
648 let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
649 log::info!("buffer text: {:?}", buffer_snapshot.text());
650
651 let (mut fold_map, mut fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
652 let (suggestion_map, mut suggestion_snapshot) = SuggestionMap::new(fold_snapshot.clone());
653
654 for _ in 0..operations {
655 let mut suggestion_edits = Patch::default();
656
657 let mut prev_suggestion_text = suggestion_snapshot.text();
658 let mut buffer_edits = Vec::new();
659 match rng.gen_range(0..=100) {
660 0..=29 => {
661 let (_, edits) = suggestion_map.randomly_mutate(&mut rng);
662 suggestion_edits = suggestion_edits.compose(edits);
663 }
664 30..=59 => {
665 for (new_fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
666 fold_snapshot = new_fold_snapshot;
667 let (_, edits) = suggestion_map.sync(fold_snapshot.clone(), fold_edits);
668 suggestion_edits = suggestion_edits.compose(edits);
669 }
670 }
671 _ => buffer.update(cx, |buffer, cx| {
672 let subscription = buffer.subscribe();
673 let edit_count = rng.gen_range(1..=5);
674 buffer.randomly_mutate(&mut rng, edit_count, cx);
675 buffer_snapshot = buffer.snapshot(cx);
676 let edits = subscription.consume().into_inner();
677 log::info!("editing {:?}", edits);
678 buffer_edits.extend(edits);
679 }),
680 };
681
682 let (new_fold_snapshot, fold_edits) =
683 fold_map.read(buffer_snapshot.clone(), buffer_edits);
684 fold_snapshot = new_fold_snapshot;
685 let (new_suggestion_snapshot, edits) =
686 suggestion_map.sync(fold_snapshot.clone(), fold_edits);
687 suggestion_snapshot = new_suggestion_snapshot;
688 suggestion_edits = suggestion_edits.compose(edits);
689
690 log::info!("buffer text: {:?}", buffer_snapshot.text());
691 log::info!("folds text: {:?}", fold_snapshot.text());
692 log::info!("suggestions text: {:?}", suggestion_snapshot.text());
693
694 let mut expected_text = Rope::from(fold_snapshot.text().as_str());
695 let mut expected_buffer_rows = fold_snapshot.buffer_rows(0).collect::<Vec<_>>();
696 if let Some(suggestion) = suggestion_snapshot.suggestion.as_ref() {
697 expected_text.replace(
698 suggestion.position.0..suggestion.position.0,
699 &suggestion.text.to_string(),
700 );
701 let suggestion_start = suggestion.position.to_point(&fold_snapshot).0;
702 let suggestion_end = suggestion_start + suggestion.text.max_point();
703 expected_buffer_rows.splice(
704 (suggestion_start.row + 1) as usize..(suggestion_start.row + 1) as usize,
705 (0..suggestion_end.row - suggestion_start.row).map(|_| None),
706 );
707 }
708 assert_eq!(suggestion_snapshot.text(), expected_text.to_string());
709 for row_start in 0..expected_buffer_rows.len() {
710 assert_eq!(
711 suggestion_snapshot
712 .buffer_rows(row_start as u32)
713 .collect::<Vec<_>>(),
714 &expected_buffer_rows[row_start..],
715 "incorrect buffer rows starting at {}",
716 row_start
717 );
718 }
719
720 for _ in 0..5 {
721 let mut end = rng.gen_range(0..=suggestion_snapshot.len().0);
722 end = expected_text.clip_offset(end, Bias::Right);
723 let mut start = rng.gen_range(0..=end);
724 start = expected_text.clip_offset(start, Bias::Right);
725
726 let actual_text = suggestion_snapshot
727 .chunks(
728 SuggestionOffset(start)..SuggestionOffset(end),
729 false,
730 None,
731 None,
732 )
733 .map(|chunk| chunk.text)
734 .collect::<String>();
735 assert_eq!(
736 actual_text,
737 expected_text.slice(start..end).to_string(),
738 "incorrect text in range {:?}",
739 start..end
740 );
741
742 let start_point = SuggestionPoint(expected_text.offset_to_point(start));
743 let end_point = SuggestionPoint(expected_text.offset_to_point(end));
744 assert_eq!(
745 suggestion_snapshot.text_summary_for_range(start_point..end_point),
746 expected_text.slice(start..end).summary()
747 );
748 }
749
750 for edit in suggestion_edits.into_inner() {
751 prev_suggestion_text.replace_range(
752 edit.new.start.0..edit.new.start.0 + edit.old_len().0,
753 &suggestion_snapshot.text()[edit.new.start.0..edit.new.end.0],
754 );
755 }
756 assert_eq!(prev_suggestion_text, suggestion_snapshot.text());
757
758 assert_eq!(expected_text.max_point(), suggestion_snapshot.max_point().0);
759 assert_eq!(expected_text.len(), suggestion_snapshot.len().0);
760
761 let mut suggestion_point = SuggestionPoint::default();
762 let mut suggestion_offset = SuggestionOffset::default();
763 for ch in expected_text.chars() {
764 assert_eq!(
765 suggestion_snapshot.to_offset(suggestion_point),
766 suggestion_offset,
767 "invalid to_offset({:?})",
768 suggestion_point
769 );
770 assert_eq!(
771 suggestion_snapshot.to_point(suggestion_offset),
772 suggestion_point,
773 "invalid to_point({:?})",
774 suggestion_offset
775 );
776 assert_eq!(
777 suggestion_snapshot
778 .to_suggestion_point(suggestion_snapshot.to_fold_point(suggestion_point)),
779 suggestion_snapshot.clip_point(suggestion_point, Bias::Left),
780 );
781
782 let mut bytes = [0; 4];
783 for byte in ch.encode_utf8(&mut bytes).as_bytes() {
784 suggestion_offset.0 += 1;
785 if *byte == b'\n' {
786 suggestion_point.0 += Point::new(1, 0);
787 } else {
788 suggestion_point.0 += Point::new(0, 1);
789 }
790
791 let clipped_left_point =
792 suggestion_snapshot.clip_point(suggestion_point, Bias::Left);
793 let clipped_right_point =
794 suggestion_snapshot.clip_point(suggestion_point, Bias::Right);
795 assert!(
796 clipped_left_point <= clipped_right_point,
797 "clipped left point {:?} is greater than clipped right point {:?}",
798 clipped_left_point,
799 clipped_right_point
800 );
801 assert_eq!(
802 clipped_left_point.0,
803 expected_text.clip_point(clipped_left_point.0, Bias::Left)
804 );
805 assert_eq!(
806 clipped_right_point.0,
807 expected_text.clip_point(clipped_right_point.0, Bias::Right)
808 );
809 assert!(clipped_left_point <= suggestion_snapshot.max_point());
810 assert!(clipped_right_point <= suggestion_snapshot.max_point());
811
812 if let Some(suggestion) = suggestion_snapshot.suggestion.as_ref() {
813 let suggestion_start = suggestion.position.to_point(&fold_snapshot).0;
814 let suggestion_end = suggestion_start + suggestion.text.max_point();
815 let invalid_range = (
816 Bound::Excluded(suggestion_start),
817 Bound::Included(suggestion_end),
818 );
819 assert!(
820 !invalid_range.contains(&clipped_left_point.0),
821 "clipped left point {:?} is inside invalid suggestion range {:?}",
822 clipped_left_point,
823 invalid_range
824 );
825 assert!(
826 !invalid_range.contains(&clipped_right_point.0),
827 "clipped right point {:?} is inside invalid suggestion range {:?}",
828 clipped_right_point,
829 invalid_range
830 );
831 }
832 }
833 }
834 }
835 }
836
837 impl SuggestionMap {
838 pub fn randomly_mutate(
839 &self,
840 rng: &mut impl Rng,
841 ) -> (SuggestionSnapshot, Vec<SuggestionEdit>) {
842 let fold_snapshot = self.0.lock().fold_snapshot.clone();
843 let new_suggestion = if rng.gen_bool(0.3) {
844 None
845 } else {
846 let index = rng.gen_range(0..=fold_snapshot.buffer_snapshot().len());
847 let len = rng.gen_range(0..30);
848 Some(Suggestion {
849 position: index,
850 text: util::RandomCharIter::new(rng)
851 .take(len)
852 .filter(|ch| *ch != '\r')
853 .collect::<String>()
854 .as_str()
855 .into(),
856 })
857 };
858
859 log::info!("replacing suggestion with {:?}", new_suggestion);
860 let (snapshot, edits, _) =
861 self.replace(new_suggestion, fold_snapshot, Default::default());
862 (snapshot, edits)
863 }
864 }
865}