tab_map.rs

  1use super::{
  2    fold_map::{self, FoldChunks, FoldEdit, FoldPoint, FoldSnapshot},
  3    TextHighlights,
  4};
  5use crate::MultiBufferSnapshot;
  6use gpui::fonts::HighlightStyle;
  7use language::{Chunk, Point};
  8use parking_lot::Mutex;
  9use std::{cmp, mem, num::NonZeroU32, ops::Range};
 10use sum_tree::Bias;
 11
 12const MAX_EXPANSION_COLUMN: u32 = 256;
 13
 14pub struct TabMap(Mutex<TabSnapshot>);
 15
 16impl TabMap {
 17    pub fn new(fold_snapshot: FoldSnapshot, tab_size: NonZeroU32) -> (Self, TabSnapshot) {
 18        let snapshot = TabSnapshot {
 19            fold_snapshot,
 20            tab_size,
 21            max_expansion_column: MAX_EXPANSION_COLUMN,
 22            version: 0,
 23        };
 24        (Self(Mutex::new(snapshot.clone())), snapshot)
 25    }
 26
 27    #[cfg(test)]
 28    pub fn set_max_expansion_column(&self, column: u32) -> TabSnapshot {
 29        self.0.lock().max_expansion_column = column;
 30        self.0.lock().clone()
 31    }
 32
 33    pub fn sync(
 34        &self,
 35        fold_snapshot: FoldSnapshot,
 36        mut fold_edits: Vec<FoldEdit>,
 37        tab_size: NonZeroU32,
 38    ) -> (TabSnapshot, Vec<TabEdit>) {
 39        let mut old_snapshot = self.0.lock();
 40        let mut new_snapshot = TabSnapshot {
 41            fold_snapshot,
 42            tab_size,
 43            max_expansion_column: old_snapshot.max_expansion_column,
 44            version: old_snapshot.version,
 45        };
 46
 47        if old_snapshot.fold_snapshot.version != new_snapshot.fold_snapshot.version {
 48            new_snapshot.version += 1;
 49        }
 50
 51        let mut tab_edits = Vec::with_capacity(fold_edits.len());
 52
 53        if old_snapshot.tab_size == new_snapshot.tab_size {
 54            // Expand each edit to include the next tab on the same line as the edit,
 55            // and any subsequent tabs on that line that moved across the tab expansion
 56            // boundary.
 57            for fold_edit in &mut fold_edits {
 58                let old_end = fold_edit.old.end.to_point(&old_snapshot.fold_snapshot);
 59                let old_end_row_successor_offset = cmp::min(
 60                    FoldPoint::new(old_end.row() + 1, 0),
 61                    old_snapshot.fold_snapshot.max_point(),
 62                )
 63                .to_offset(&old_snapshot.fold_snapshot);
 64                let new_end = fold_edit.new.end.to_point(&new_snapshot.fold_snapshot);
 65
 66                let mut offset_from_edit = 0;
 67                let mut first_tab_offset = None;
 68                let mut last_tab_with_changed_expansion_offset = None;
 69                'outer: for chunk in old_snapshot.fold_snapshot.chunks(
 70                    fold_edit.old.end..old_end_row_successor_offset,
 71                    false,
 72                    None,
 73                    None,
 74                ) {
 75                    for (ix, _) in chunk.text.match_indices('\t') {
 76                        let offset_from_edit = offset_from_edit + (ix as u32);
 77                        if first_tab_offset.is_none() {
 78                            first_tab_offset = Some(offset_from_edit);
 79                        }
 80
 81                        let old_column = old_end.column() + offset_from_edit;
 82                        let new_column = new_end.column() + offset_from_edit;
 83                        let was_expanded = old_column < old_snapshot.max_expansion_column;
 84                        let is_expanded = new_column < new_snapshot.max_expansion_column;
 85                        if was_expanded != is_expanded {
 86                            last_tab_with_changed_expansion_offset = Some(offset_from_edit);
 87                        } else if !was_expanded && !is_expanded {
 88                            break 'outer;
 89                        }
 90                    }
 91
 92                    offset_from_edit += chunk.text.len() as u32;
 93                    if old_end.column() + offset_from_edit >= old_snapshot.max_expansion_column
 94                        && new_end.column() + offset_from_edit >= new_snapshot.max_expansion_column
 95                    {
 96                        break;
 97                    }
 98                }
 99
100                if let Some(offset) = last_tab_with_changed_expansion_offset.or(first_tab_offset) {
101                    fold_edit.old.end.0 += offset as usize + 1;
102                    fold_edit.new.end.0 += offset as usize + 1;
103                }
104            }
105
106            // Combine any edits that overlap due to the expansion.
107            let mut ix = 1;
108            while ix < fold_edits.len() {
109                let (prev_edits, next_edits) = fold_edits.split_at_mut(ix);
110                let prev_edit = prev_edits.last_mut().unwrap();
111                let edit = &next_edits[0];
112                if prev_edit.old.end >= edit.old.start {
113                    prev_edit.old.end = edit.old.end;
114                    prev_edit.new.end = edit.new.end;
115                    fold_edits.remove(ix);
116                } else {
117                    ix += 1;
118                }
119            }
120
121            for fold_edit in fold_edits {
122                let old_start = fold_edit.old.start.to_point(&old_snapshot.fold_snapshot);
123                let old_end = fold_edit.old.end.to_point(&old_snapshot.fold_snapshot);
124                let new_start = fold_edit.new.start.to_point(&new_snapshot.fold_snapshot);
125                let new_end = fold_edit.new.end.to_point(&new_snapshot.fold_snapshot);
126                tab_edits.push(TabEdit {
127                    old: old_snapshot.to_tab_point(old_start)..old_snapshot.to_tab_point(old_end),
128                    new: new_snapshot.to_tab_point(new_start)..new_snapshot.to_tab_point(new_end),
129                });
130            }
131        } else {
132            new_snapshot.version += 1;
133            tab_edits.push(TabEdit {
134                old: TabPoint::zero()..old_snapshot.max_point(),
135                new: TabPoint::zero()..new_snapshot.max_point(),
136            });
137        }
138
139        *old_snapshot = new_snapshot;
140        (old_snapshot.clone(), tab_edits)
141    }
142}
143
144#[derive(Clone)]
145pub struct TabSnapshot {
146    pub fold_snapshot: FoldSnapshot,
147    pub tab_size: NonZeroU32,
148    pub max_expansion_column: u32,
149    pub version: usize,
150}
151
152impl TabSnapshot {
153    pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
154        &self.fold_snapshot.inlay_snapshot.buffer
155    }
156
157    pub fn line_len(&self, row: u32) -> u32 {
158        let max_point = self.max_point();
159        if row < max_point.row() {
160            self.to_tab_point(FoldPoint::new(row, self.fold_snapshot.line_len(row)))
161                .0
162                .column
163        } else {
164            max_point.column()
165        }
166    }
167
168    pub fn text_summary(&self) -> TextSummary {
169        self.text_summary_for_range(TabPoint::zero()..self.max_point())
170    }
171
172    pub fn text_summary_for_range(&self, range: Range<TabPoint>) -> TextSummary {
173        let input_start = self.to_fold_point(range.start, Bias::Left).0;
174        let input_end = self.to_fold_point(range.end, Bias::Right).0;
175        let input_summary = self
176            .fold_snapshot
177            .text_summary_for_range(input_start..input_end);
178
179        let mut first_line_chars = 0;
180        let line_end = if range.start.row() == range.end.row() {
181            range.end
182        } else {
183            self.max_point()
184        };
185        for c in self
186            .chunks(range.start..line_end, false, None, None)
187            .flat_map(|chunk| chunk.text.chars())
188        {
189            if c == '\n' {
190                break;
191            }
192            first_line_chars += 1;
193        }
194
195        let mut last_line_chars = 0;
196        if range.start.row() == range.end.row() {
197            last_line_chars = first_line_chars;
198        } else {
199            for _ in self
200                .chunks(
201                    TabPoint::new(range.end.row(), 0)..range.end,
202                    false,
203                    None,
204                    None,
205                )
206                .flat_map(|chunk| chunk.text.chars())
207            {
208                last_line_chars += 1;
209            }
210        }
211
212        TextSummary {
213            lines: range.end.0 - range.start.0,
214            first_line_chars,
215            last_line_chars,
216            longest_row: input_summary.longest_row,
217            longest_row_chars: input_summary.longest_row_chars,
218        }
219    }
220
221    pub fn chunks<'a>(
222        &'a self,
223        range: Range<TabPoint>,
224        language_aware: bool,
225        text_highlights: Option<&'a TextHighlights>,
226        inlay_highlights: Option<HighlightStyle>,
227    ) -> TabChunks<'a> {
228        let (input_start, expanded_char_column, to_next_stop) =
229            self.to_fold_point(range.start, Bias::Left);
230        let input_column = input_start.column();
231        let input_start = input_start.to_offset(&self.fold_snapshot);
232        let input_end = self
233            .to_fold_point(range.end, Bias::Right)
234            .0
235            .to_offset(&self.fold_snapshot);
236        let to_next_stop = if range.start.0 + Point::new(0, to_next_stop) > range.end.0 {
237            range.end.column() - range.start.column()
238        } else {
239            to_next_stop
240        };
241
242        TabChunks {
243            fold_chunks: self.fold_snapshot.chunks(
244                input_start..input_end,
245                language_aware,
246                text_highlights,
247                inlay_highlights,
248            ),
249            input_column,
250            column: expanded_char_column,
251            max_expansion_column: self.max_expansion_column,
252            output_position: range.start.0,
253            max_output_position: range.end.0,
254            tab_size: self.tab_size,
255            chunk: Chunk {
256                text: &SPACES[0..(to_next_stop as usize)],
257                is_tab: true,
258                ..Default::default()
259            },
260            inside_leading_tab: to_next_stop > 0,
261        }
262    }
263
264    pub fn buffer_rows(&self, row: u32) -> fold_map::FoldBufferRows<'_> {
265        self.fold_snapshot.buffer_rows(row)
266    }
267
268    #[cfg(test)]
269    pub fn text(&self) -> String {
270        self.chunks(TabPoint::zero()..self.max_point(), false, None, None)
271            .map(|chunk| chunk.text)
272            .collect()
273    }
274
275    pub fn max_point(&self) -> TabPoint {
276        self.to_tab_point(self.fold_snapshot.max_point())
277    }
278
279    pub fn clip_point(&self, point: TabPoint, bias: Bias) -> TabPoint {
280        self.to_tab_point(
281            self.fold_snapshot
282                .clip_point(self.to_fold_point(point, bias).0, bias),
283        )
284    }
285
286    pub fn to_tab_point(&self, input: FoldPoint) -> TabPoint {
287        let chars = self.fold_snapshot.chars_at(FoldPoint::new(input.row(), 0));
288        let expanded = self.expand_tabs(chars, input.column());
289        TabPoint::new(input.row(), expanded)
290    }
291
292    pub fn to_fold_point(&self, output: TabPoint, bias: Bias) -> (FoldPoint, u32, u32) {
293        let chars = self.fold_snapshot.chars_at(FoldPoint::new(output.row(), 0));
294        let expanded = output.column();
295        let (collapsed, expanded_char_column, to_next_stop) =
296            self.collapse_tabs(chars, expanded, bias);
297        (
298            FoldPoint::new(output.row(), collapsed as u32),
299            expanded_char_column,
300            to_next_stop,
301        )
302    }
303
304    pub fn make_tab_point(&self, point: Point, bias: Bias) -> TabPoint {
305        let inlay_point = self.fold_snapshot.inlay_snapshot.to_inlay_point(point);
306        let fold_point = self.fold_snapshot.to_fold_point(inlay_point, bias);
307        self.to_tab_point(fold_point)
308    }
309
310    pub fn to_point(&self, point: TabPoint, bias: Bias) -> Point {
311        let fold_point = self.to_fold_point(point, bias).0;
312        let inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
313        self.fold_snapshot
314            .inlay_snapshot
315            .to_buffer_point(inlay_point)
316    }
317
318    fn expand_tabs(&self, chars: impl Iterator<Item = char>, column: u32) -> u32 {
319        let tab_size = self.tab_size.get();
320
321        let mut expanded_chars = 0;
322        let mut expanded_bytes = 0;
323        let mut collapsed_bytes = 0;
324        let end_column = column.min(self.max_expansion_column);
325        for c in chars {
326            if collapsed_bytes >= end_column {
327                break;
328            }
329            if c == '\t' {
330                let tab_len = tab_size - expanded_chars % tab_size;
331                expanded_bytes += tab_len;
332                expanded_chars += tab_len;
333            } else {
334                expanded_bytes += c.len_utf8() as u32;
335                expanded_chars += 1;
336            }
337            collapsed_bytes += c.len_utf8() as u32;
338        }
339        expanded_bytes + column.saturating_sub(collapsed_bytes)
340    }
341
342    fn collapse_tabs(
343        &self,
344        chars: impl Iterator<Item = char>,
345        column: u32,
346        bias: Bias,
347    ) -> (u32, u32, u32) {
348        let tab_size = self.tab_size.get();
349
350        let mut expanded_bytes = 0;
351        let mut expanded_chars = 0;
352        let mut collapsed_bytes = 0;
353        for c in chars {
354            if expanded_bytes >= column {
355                break;
356            }
357            if collapsed_bytes >= self.max_expansion_column {
358                break;
359            }
360
361            if c == '\t' {
362                let tab_len = tab_size - (expanded_chars % tab_size);
363                expanded_chars += tab_len;
364                expanded_bytes += tab_len;
365                if expanded_bytes > column {
366                    expanded_chars -= expanded_bytes - column;
367                    return match bias {
368                        Bias::Left => (collapsed_bytes, expanded_chars, expanded_bytes - column),
369                        Bias::Right => (collapsed_bytes + 1, expanded_chars, 0),
370                    };
371                }
372            } else {
373                expanded_chars += 1;
374                expanded_bytes += c.len_utf8() as u32;
375            }
376
377            if expanded_bytes > column && matches!(bias, Bias::Left) {
378                expanded_chars -= 1;
379                break;
380            }
381
382            collapsed_bytes += c.len_utf8() as u32;
383        }
384        (
385            collapsed_bytes + column.saturating_sub(expanded_bytes),
386            expanded_chars,
387            0,
388        )
389    }
390}
391
392#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
393pub struct TabPoint(pub Point);
394
395impl TabPoint {
396    pub fn new(row: u32, column: u32) -> Self {
397        Self(Point::new(row, column))
398    }
399
400    pub fn zero() -> Self {
401        Self::new(0, 0)
402    }
403
404    pub fn row(self) -> u32 {
405        self.0.row
406    }
407
408    pub fn column(self) -> u32 {
409        self.0.column
410    }
411}
412
413impl From<Point> for TabPoint {
414    fn from(point: Point) -> Self {
415        Self(point)
416    }
417}
418
419pub type TabEdit = text::Edit<TabPoint>;
420
421#[derive(Clone, Debug, Default, Eq, PartialEq)]
422pub struct TextSummary {
423    pub lines: Point,
424    pub first_line_chars: u32,
425    pub last_line_chars: u32,
426    pub longest_row: u32,
427    pub longest_row_chars: u32,
428}
429
430impl<'a> From<&'a str> for TextSummary {
431    fn from(text: &'a str) -> Self {
432        let sum = text::TextSummary::from(text);
433
434        TextSummary {
435            lines: sum.lines,
436            first_line_chars: sum.first_line_chars,
437            last_line_chars: sum.last_line_chars,
438            longest_row: sum.longest_row,
439            longest_row_chars: sum.longest_row_chars,
440        }
441    }
442}
443
444impl<'a> std::ops::AddAssign<&'a Self> for TextSummary {
445    fn add_assign(&mut self, other: &'a Self) {
446        let joined_chars = self.last_line_chars + other.first_line_chars;
447        if joined_chars > self.longest_row_chars {
448            self.longest_row = self.lines.row;
449            self.longest_row_chars = joined_chars;
450        }
451        if other.longest_row_chars > self.longest_row_chars {
452            self.longest_row = self.lines.row + other.longest_row;
453            self.longest_row_chars = other.longest_row_chars;
454        }
455
456        if self.lines.row == 0 {
457            self.first_line_chars += other.first_line_chars;
458        }
459
460        if other.lines.row == 0 {
461            self.last_line_chars += other.first_line_chars;
462        } else {
463            self.last_line_chars = other.last_line_chars;
464        }
465
466        self.lines += &other.lines;
467    }
468}
469
470// Handles a tab width <= 16
471const SPACES: &str = "                ";
472
473pub struct TabChunks<'a> {
474    fold_chunks: FoldChunks<'a>,
475    chunk: Chunk<'a>,
476    column: u32,
477    max_expansion_column: u32,
478    output_position: Point,
479    input_column: u32,
480    max_output_position: Point,
481    tab_size: NonZeroU32,
482    inside_leading_tab: bool,
483}
484
485impl<'a> Iterator for TabChunks<'a> {
486    type Item = Chunk<'a>;
487
488    fn next(&mut self) -> Option<Self::Item> {
489        if self.chunk.text.is_empty() {
490            if let Some(chunk) = self.fold_chunks.next() {
491                self.chunk = chunk;
492                if self.inside_leading_tab {
493                    self.chunk.text = &self.chunk.text[1..];
494                    self.inside_leading_tab = false;
495                    self.input_column += 1;
496                }
497            } else {
498                return None;
499            }
500        }
501
502        for (ix, c) in self.chunk.text.char_indices() {
503            match c {
504                '\t' => {
505                    if ix > 0 {
506                        let (prefix, suffix) = self.chunk.text.split_at(ix);
507                        self.chunk.text = suffix;
508                        return Some(Chunk {
509                            text: prefix,
510                            ..self.chunk
511                        });
512                    } else {
513                        self.chunk.text = &self.chunk.text[1..];
514                        let tab_size = if self.input_column < self.max_expansion_column {
515                            self.tab_size.get() as u32
516                        } else {
517                            1
518                        };
519                        let mut len = tab_size - self.column % tab_size;
520                        let next_output_position = cmp::min(
521                            self.output_position + Point::new(0, len),
522                            self.max_output_position,
523                        );
524                        len = next_output_position.column - self.output_position.column;
525                        self.column += len;
526                        self.input_column += 1;
527                        self.output_position = next_output_position;
528                        return Some(Chunk {
529                            text: &SPACES[..len as usize],
530                            is_tab: true,
531                            ..self.chunk
532                        });
533                    }
534                }
535                '\n' => {
536                    self.column = 0;
537                    self.input_column = 0;
538                    self.output_position += Point::new(1, 0);
539                }
540                _ => {
541                    self.column += 1;
542                    if !self.inside_leading_tab {
543                        self.input_column += c.len_utf8() as u32;
544                    }
545                    self.output_position.column += c.len_utf8() as u32;
546                }
547            }
548        }
549
550        Some(mem::take(&mut self.chunk))
551    }
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557    use crate::{
558        display_map::{fold_map::FoldMap, inlay_map::InlayMap},
559        MultiBuffer,
560    };
561    use rand::{prelude::StdRng, Rng};
562
563    #[gpui::test]
564    fn test_expand_tabs(cx: &mut gpui::AppContext) {
565        let buffer = MultiBuffer::build_simple("", cx);
566        let buffer_snapshot = buffer.read(cx).snapshot(cx);
567        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
568        let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
569        let (_, tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
570
571        assert_eq!(tab_snapshot.expand_tabs("\t".chars(), 0), 0);
572        assert_eq!(tab_snapshot.expand_tabs("\t".chars(), 1), 4);
573        assert_eq!(tab_snapshot.expand_tabs("\ta".chars(), 2), 5);
574    }
575
576    #[gpui::test]
577    fn test_long_lines(cx: &mut gpui::AppContext) {
578        let max_expansion_column = 12;
579        let input = "A\tBC\tDEF\tG\tHI\tJ\tK\tL\tM";
580        let output = "A   BC  DEF G   HI J K L M";
581
582        let buffer = MultiBuffer::build_simple(input, cx);
583        let buffer_snapshot = buffer.read(cx).snapshot(cx);
584        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
585        let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
586        let (_, mut tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
587
588        tab_snapshot.max_expansion_column = max_expansion_column;
589        assert_eq!(tab_snapshot.text(), output);
590
591        for (ix, c) in input.char_indices() {
592            assert_eq!(
593                tab_snapshot
594                    .chunks(
595                        TabPoint::new(0, ix as u32)..tab_snapshot.max_point(),
596                        false,
597                        None,
598                        None,
599                    )
600                    .map(|c| c.text)
601                    .collect::<String>(),
602                &output[ix..],
603                "text from index {ix}"
604            );
605
606            if c != '\t' {
607                let input_point = Point::new(0, ix as u32);
608                let output_point = Point::new(0, output.find(c).unwrap() as u32);
609                assert_eq!(
610                    tab_snapshot.to_tab_point(FoldPoint(input_point)),
611                    TabPoint(output_point),
612                    "to_tab_point({input_point:?})"
613                );
614                assert_eq!(
615                    tab_snapshot
616                        .to_fold_point(TabPoint(output_point), Bias::Left)
617                        .0,
618                    FoldPoint(input_point),
619                    "to_fold_point({output_point:?})"
620                );
621            }
622        }
623    }
624
625    #[gpui::test]
626    fn test_long_lines_with_character_spanning_max_expansion_column(cx: &mut gpui::AppContext) {
627        let max_expansion_column = 8;
628        let input = "abcdefg⋯hij";
629
630        let buffer = MultiBuffer::build_simple(input, cx);
631        let buffer_snapshot = buffer.read(cx).snapshot(cx);
632        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
633        let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
634        let (_, mut tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
635
636        tab_snapshot.max_expansion_column = max_expansion_column;
637        assert_eq!(tab_snapshot.text(), input);
638    }
639
640    #[gpui::test]
641    fn test_marking_tabs(cx: &mut gpui::AppContext) {
642        let input = "\t \thello";
643
644        let buffer = MultiBuffer::build_simple(&input, cx);
645        let buffer_snapshot = buffer.read(cx).snapshot(cx);
646        let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
647        let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
648        let (_, tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
649
650        assert_eq!(
651            chunks(&tab_snapshot, TabPoint::zero()),
652            vec![
653                ("    ".to_string(), true),
654                (" ".to_string(), false),
655                ("   ".to_string(), true),
656                ("hello".to_string(), false),
657            ]
658        );
659        assert_eq!(
660            chunks(&tab_snapshot, TabPoint::new(0, 2)),
661            vec![
662                ("  ".to_string(), true),
663                (" ".to_string(), false),
664                ("   ".to_string(), true),
665                ("hello".to_string(), false),
666            ]
667        );
668
669        fn chunks(snapshot: &TabSnapshot, start: TabPoint) -> Vec<(String, bool)> {
670            let mut chunks = Vec::new();
671            let mut was_tab = false;
672            let mut text = String::new();
673            for chunk in snapshot.chunks(start..snapshot.max_point(), false, None, None) {
674                if chunk.is_tab != was_tab {
675                    if !text.is_empty() {
676                        chunks.push((mem::take(&mut text), was_tab));
677                    }
678                    was_tab = chunk.is_tab;
679                }
680                text.push_str(chunk.text);
681            }
682
683            if !text.is_empty() {
684                chunks.push((text, was_tab));
685            }
686            chunks
687        }
688    }
689
690    #[gpui::test(iterations = 100)]
691    fn test_random_tabs(cx: &mut gpui::AppContext, mut rng: StdRng) {
692        let tab_size = NonZeroU32::new(rng.gen_range(1..=4)).unwrap();
693        let len = rng.gen_range(0..30);
694        let buffer = if rng.gen() {
695            let text = util::RandomCharIter::new(&mut rng)
696                .take(len)
697                .collect::<String>();
698            MultiBuffer::build_simple(&text, cx)
699        } else {
700            MultiBuffer::build_random(&mut rng, cx)
701        };
702        let buffer_snapshot = buffer.read(cx).snapshot(cx);
703        log::info!("Buffer text: {:?}", buffer_snapshot.text());
704
705        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
706        log::info!("InlayMap text: {:?}", inlay_snapshot.text());
707        let (mut fold_map, _) = FoldMap::new(inlay_snapshot.clone());
708        fold_map.randomly_mutate(&mut rng);
709        let (fold_snapshot, _) = fold_map.read(inlay_snapshot, vec![]);
710        log::info!("FoldMap text: {:?}", fold_snapshot.text());
711        let (inlay_snapshot, _) = inlay_map.randomly_mutate(&mut 0, &mut rng);
712        log::info!("InlayMap text: {:?}", inlay_snapshot.text());
713
714        let (tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
715        let tabs_snapshot = tab_map.set_max_expansion_column(32);
716
717        let text = text::Rope::from(tabs_snapshot.text().as_str());
718        log::info!(
719            "TabMap text (tab size: {}): {:?}",
720            tab_size,
721            tabs_snapshot.text(),
722        );
723
724        for _ in 0..5 {
725            let end_row = rng.gen_range(0..=text.max_point().row);
726            let end_column = rng.gen_range(0..=text.line_len(end_row));
727            let mut end = TabPoint(text.clip_point(Point::new(end_row, end_column), Bias::Right));
728            let start_row = rng.gen_range(0..=text.max_point().row);
729            let start_column = rng.gen_range(0..=text.line_len(start_row));
730            let mut start =
731                TabPoint(text.clip_point(Point::new(start_row, start_column), Bias::Left));
732            if start > end {
733                mem::swap(&mut start, &mut end);
734            }
735
736            let expected_text = text
737                .chunks_in_range(text.point_to_offset(start.0)..text.point_to_offset(end.0))
738                .collect::<String>();
739            let expected_summary = TextSummary::from(expected_text.as_str());
740            assert_eq!(
741                tabs_snapshot
742                    .chunks(start..end, false, None, None)
743                    .map(|c| c.text)
744                    .collect::<String>(),
745                expected_text,
746                "chunks({:?}..{:?})",
747                start,
748                end
749            );
750
751            let mut actual_summary = tabs_snapshot.text_summary_for_range(start..end);
752            if tab_size.get() > 1 && inlay_snapshot.text().contains('\t') {
753                actual_summary.longest_row = expected_summary.longest_row;
754                actual_summary.longest_row_chars = expected_summary.longest_row_chars;
755            }
756            assert_eq!(actual_summary, expected_summary);
757        }
758
759        for row in 0..=text.max_point().row {
760            assert_eq!(
761                tabs_snapshot.line_len(row),
762                text.line_len(row),
763                "line_len({row})"
764            );
765        }
766    }
767}