tab_map.rs

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