suggestion_map.rs

  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::SettingsStore;
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        init_test(cx);
635
636        let operations = env::var("OPERATIONS")
637            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
638            .unwrap_or(10);
639
640        let len = rng.gen_range(0..30);
641        let buffer = if rng.gen() {
642            let text = util::RandomCharIter::new(&mut rng)
643                .take(len)
644                .collect::<String>();
645            MultiBuffer::build_simple(&text, cx)
646        } else {
647            MultiBuffer::build_random(&mut rng, cx)
648        };
649        let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
650        log::info!("buffer text: {:?}", buffer_snapshot.text());
651
652        let (mut fold_map, mut fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
653        let (suggestion_map, mut suggestion_snapshot) = SuggestionMap::new(fold_snapshot.clone());
654
655        for _ in 0..operations {
656            let mut suggestion_edits = Patch::default();
657
658            let mut prev_suggestion_text = suggestion_snapshot.text();
659            let mut buffer_edits = Vec::new();
660            match rng.gen_range(0..=100) {
661                0..=29 => {
662                    let (_, edits) = suggestion_map.randomly_mutate(&mut rng);
663                    suggestion_edits = suggestion_edits.compose(edits);
664                }
665                30..=59 => {
666                    for (new_fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
667                        fold_snapshot = new_fold_snapshot;
668                        let (_, edits) = suggestion_map.sync(fold_snapshot.clone(), fold_edits);
669                        suggestion_edits = suggestion_edits.compose(edits);
670                    }
671                }
672                _ => buffer.update(cx, |buffer, cx| {
673                    let subscription = buffer.subscribe();
674                    let edit_count = rng.gen_range(1..=5);
675                    buffer.randomly_mutate(&mut rng, edit_count, cx);
676                    buffer_snapshot = buffer.snapshot(cx);
677                    let edits = subscription.consume().into_inner();
678                    log::info!("editing {:?}", edits);
679                    buffer_edits.extend(edits);
680                }),
681            };
682
683            let (new_fold_snapshot, fold_edits) =
684                fold_map.read(buffer_snapshot.clone(), buffer_edits);
685            fold_snapshot = new_fold_snapshot;
686            let (new_suggestion_snapshot, edits) =
687                suggestion_map.sync(fold_snapshot.clone(), fold_edits);
688            suggestion_snapshot = new_suggestion_snapshot;
689            suggestion_edits = suggestion_edits.compose(edits);
690
691            log::info!("buffer text: {:?}", buffer_snapshot.text());
692            log::info!("folds text: {:?}", fold_snapshot.text());
693            log::info!("suggestions text: {:?}", suggestion_snapshot.text());
694
695            let mut expected_text = Rope::from(fold_snapshot.text().as_str());
696            let mut expected_buffer_rows = fold_snapshot.buffer_rows(0).collect::<Vec<_>>();
697            if let Some(suggestion) = suggestion_snapshot.suggestion.as_ref() {
698                expected_text.replace(
699                    suggestion.position.0..suggestion.position.0,
700                    &suggestion.text.to_string(),
701                );
702                let suggestion_start = suggestion.position.to_point(&fold_snapshot).0;
703                let suggestion_end = suggestion_start + suggestion.text.max_point();
704                expected_buffer_rows.splice(
705                    (suggestion_start.row + 1) as usize..(suggestion_start.row + 1) as usize,
706                    (0..suggestion_end.row - suggestion_start.row).map(|_| None),
707                );
708            }
709            assert_eq!(suggestion_snapshot.text(), expected_text.to_string());
710            for row_start in 0..expected_buffer_rows.len() {
711                assert_eq!(
712                    suggestion_snapshot
713                        .buffer_rows(row_start as u32)
714                        .collect::<Vec<_>>(),
715                    &expected_buffer_rows[row_start..],
716                    "incorrect buffer rows starting at {}",
717                    row_start
718                );
719            }
720
721            for _ in 0..5 {
722                let mut end = rng.gen_range(0..=suggestion_snapshot.len().0);
723                end = expected_text.clip_offset(end, Bias::Right);
724                let mut start = rng.gen_range(0..=end);
725                start = expected_text.clip_offset(start, Bias::Right);
726
727                let actual_text = suggestion_snapshot
728                    .chunks(
729                        SuggestionOffset(start)..SuggestionOffset(end),
730                        false,
731                        None,
732                        None,
733                    )
734                    .map(|chunk| chunk.text)
735                    .collect::<String>();
736                assert_eq!(
737                    actual_text,
738                    expected_text.slice(start..end).to_string(),
739                    "incorrect text in range {:?}",
740                    start..end
741                );
742
743                let start_point = SuggestionPoint(expected_text.offset_to_point(start));
744                let end_point = SuggestionPoint(expected_text.offset_to_point(end));
745                assert_eq!(
746                    suggestion_snapshot.text_summary_for_range(start_point..end_point),
747                    expected_text.slice(start..end).summary()
748                );
749            }
750
751            for edit in suggestion_edits.into_inner() {
752                prev_suggestion_text.replace_range(
753                    edit.new.start.0..edit.new.start.0 + edit.old_len().0,
754                    &suggestion_snapshot.text()[edit.new.start.0..edit.new.end.0],
755                );
756            }
757            assert_eq!(prev_suggestion_text, suggestion_snapshot.text());
758
759            assert_eq!(expected_text.max_point(), suggestion_snapshot.max_point().0);
760            assert_eq!(expected_text.len(), suggestion_snapshot.len().0);
761
762            let mut suggestion_point = SuggestionPoint::default();
763            let mut suggestion_offset = SuggestionOffset::default();
764            for ch in expected_text.chars() {
765                assert_eq!(
766                    suggestion_snapshot.to_offset(suggestion_point),
767                    suggestion_offset,
768                    "invalid to_offset({:?})",
769                    suggestion_point
770                );
771                assert_eq!(
772                    suggestion_snapshot.to_point(suggestion_offset),
773                    suggestion_point,
774                    "invalid to_point({:?})",
775                    suggestion_offset
776                );
777                assert_eq!(
778                    suggestion_snapshot
779                        .to_suggestion_point(suggestion_snapshot.to_fold_point(suggestion_point)),
780                    suggestion_snapshot.clip_point(suggestion_point, Bias::Left),
781                );
782
783                let mut bytes = [0; 4];
784                for byte in ch.encode_utf8(&mut bytes).as_bytes() {
785                    suggestion_offset.0 += 1;
786                    if *byte == b'\n' {
787                        suggestion_point.0 += Point::new(1, 0);
788                    } else {
789                        suggestion_point.0 += Point::new(0, 1);
790                    }
791
792                    let clipped_left_point =
793                        suggestion_snapshot.clip_point(suggestion_point, Bias::Left);
794                    let clipped_right_point =
795                        suggestion_snapshot.clip_point(suggestion_point, Bias::Right);
796                    assert!(
797                        clipped_left_point <= clipped_right_point,
798                        "clipped left point {:?} is greater than clipped right point {:?}",
799                        clipped_left_point,
800                        clipped_right_point
801                    );
802                    assert_eq!(
803                        clipped_left_point.0,
804                        expected_text.clip_point(clipped_left_point.0, Bias::Left)
805                    );
806                    assert_eq!(
807                        clipped_right_point.0,
808                        expected_text.clip_point(clipped_right_point.0, Bias::Right)
809                    );
810                    assert!(clipped_left_point <= suggestion_snapshot.max_point());
811                    assert!(clipped_right_point <= suggestion_snapshot.max_point());
812
813                    if let Some(suggestion) = suggestion_snapshot.suggestion.as_ref() {
814                        let suggestion_start = suggestion.position.to_point(&fold_snapshot).0;
815                        let suggestion_end = suggestion_start + suggestion.text.max_point();
816                        let invalid_range = (
817                            Bound::Excluded(suggestion_start),
818                            Bound::Included(suggestion_end),
819                        );
820                        assert!(
821                            !invalid_range.contains(&clipped_left_point.0),
822                            "clipped left point {:?} is inside invalid suggestion range {:?}",
823                            clipped_left_point,
824                            invalid_range
825                        );
826                        assert!(
827                            !invalid_range.contains(&clipped_right_point.0),
828                            "clipped right point {:?} is inside invalid suggestion range {:?}",
829                            clipped_right_point,
830                            invalid_range
831                        );
832                    }
833                }
834            }
835        }
836    }
837
838    fn init_test(cx: &mut AppContext) {
839        cx.set_global(SettingsStore::test(cx));
840        theme::init((), cx);
841    }
842
843    impl SuggestionMap {
844        pub fn randomly_mutate(
845            &self,
846            rng: &mut impl Rng,
847        ) -> (SuggestionSnapshot, Vec<SuggestionEdit>) {
848            let fold_snapshot = self.0.lock().fold_snapshot.clone();
849            let new_suggestion = if rng.gen_bool(0.3) {
850                None
851            } else {
852                let index = rng.gen_range(0..=fold_snapshot.buffer_snapshot().len());
853                let len = rng.gen_range(0..30);
854                Some(Suggestion {
855                    position: index,
856                    text: util::RandomCharIter::new(rng)
857                        .take(len)
858                        .filter(|ch| *ch != '\r')
859                        .collect::<String>()
860                        .as_str()
861                        .into(),
862                })
863            };
864
865            log::info!("replacing suggestion with {:?}", new_suggestion);
866            let (snapshot, edits, _) =
867                self.replace(new_suggestion, fold_snapshot, Default::default());
868            (snapshot, edits)
869        }
870    }
871}