tab_map.rs

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