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