tab_map.rs

  1use super::{
  2    fold_map::{self, FoldEdit, FoldPoint, FoldSnapshot},
  3    TextHighlights,
  4};
  5use crate::MultiBufferSnapshot;
  6use language::{rope, Chunk};
  7use parking_lot::Mutex;
  8use std::{cmp, mem, ops::Range};
  9use sum_tree::Bias;
 10use text::Point;
 11
 12pub struct TabMap(Mutex<TabSnapshot>);
 13
 14impl TabMap {
 15    pub fn new(input: FoldSnapshot, tab_size: u32) -> (Self, TabSnapshot) {
 16        let snapshot = TabSnapshot {
 17            fold_snapshot: input,
 18            tab_size,
 19        };
 20        (Self(Mutex::new(snapshot.clone())), snapshot)
 21    }
 22
 23    pub fn sync(
 24        &self,
 25        fold_snapshot: FoldSnapshot,
 26        mut fold_edits: Vec<FoldEdit>,
 27        tab_size: u32,
 28    ) -> (TabSnapshot, Vec<TabEdit>) {
 29        let mut old_snapshot = self.0.lock();
 30        let max_offset = old_snapshot.fold_snapshot.len();
 31        let new_snapshot = TabSnapshot {
 32            fold_snapshot,
 33            tab_size,
 34        };
 35
 36        let mut tab_edits = Vec::with_capacity(fold_edits.len());
 37        for fold_edit in &mut fold_edits {
 38            let mut delta = 0;
 39            for chunk in
 40                old_snapshot
 41                    .fold_snapshot
 42                    .chunks(fold_edit.old.end..max_offset, false, None)
 43            {
 44                let patterns: &[_] = &['\t', '\n'];
 45                if let Some(ix) = chunk.text.find(patterns) {
 46                    if &chunk.text[ix..ix + 1] == "\t" {
 47                        fold_edit.old.end.0 += delta + ix + 1;
 48                        fold_edit.new.end.0 += delta + ix + 1;
 49                    }
 50
 51                    break;
 52                }
 53
 54                delta += chunk.text.len();
 55            }
 56        }
 57
 58        let mut ix = 1;
 59        while ix < fold_edits.len() {
 60            let (prev_edits, next_edits) = fold_edits.split_at_mut(ix);
 61            let prev_edit = prev_edits.last_mut().unwrap();
 62            let edit = &next_edits[0];
 63            if prev_edit.old.end >= edit.old.start {
 64                prev_edit.old.end = edit.old.end;
 65                prev_edit.new.end = edit.new.end;
 66                fold_edits.remove(ix);
 67            } else {
 68                ix += 1;
 69            }
 70        }
 71
 72        for fold_edit in fold_edits {
 73            let old_start = fold_edit.old.start.to_point(&old_snapshot.fold_snapshot);
 74            let old_end = fold_edit.old.end.to_point(&old_snapshot.fold_snapshot);
 75            let new_start = fold_edit.new.start.to_point(&new_snapshot.fold_snapshot);
 76            let new_end = fold_edit.new.end.to_point(&new_snapshot.fold_snapshot);
 77            tab_edits.push(TabEdit {
 78                old: old_snapshot.to_tab_point(old_start)..old_snapshot.to_tab_point(old_end),
 79                new: new_snapshot.to_tab_point(new_start)..new_snapshot.to_tab_point(new_end),
 80            });
 81        }
 82
 83        *old_snapshot = new_snapshot;
 84        (old_snapshot.clone(), tab_edits)
 85    }
 86}
 87
 88#[derive(Clone)]
 89pub struct TabSnapshot {
 90    pub fold_snapshot: FoldSnapshot,
 91    pub tab_size: u32,
 92}
 93
 94impl TabSnapshot {
 95    pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
 96        self.fold_snapshot.buffer_snapshot()
 97    }
 98
 99    pub fn text_summary(&self) -> TextSummary {
100        self.text_summary_for_range(TabPoint::zero()..self.max_point())
101    }
102
103    pub fn text_summary_for_range(&self, range: Range<TabPoint>) -> TextSummary {
104        let input_start = self.to_fold_point(range.start, Bias::Left).0;
105        let input_end = self.to_fold_point(range.end, Bias::Right).0;
106        let input_summary = self
107            .fold_snapshot
108            .text_summary_for_range(input_start..input_end);
109
110        let mut first_line_chars = 0;
111        let line_end = if range.start.row() == range.end.row() {
112            range.end
113        } else {
114            self.max_point()
115        };
116        for c in self
117            .chunks(range.start..line_end, false, None)
118            .flat_map(|chunk| chunk.text.chars())
119        {
120            if c == '\n' {
121                break;
122            }
123            first_line_chars += 1;
124        }
125
126        let mut last_line_chars = 0;
127        if range.start.row() == range.end.row() {
128            last_line_chars = first_line_chars;
129        } else {
130            for _ in self
131                .chunks(TabPoint::new(range.end.row(), 0)..range.end, false, None)
132                .flat_map(|chunk| chunk.text.chars())
133            {
134                last_line_chars += 1;
135            }
136        }
137
138        TextSummary {
139            lines: range.end.0 - range.start.0,
140            first_line_chars,
141            last_line_chars,
142            longest_row: input_summary.longest_row,
143            longest_row_chars: input_summary.longest_row_chars,
144        }
145    }
146
147    pub fn version(&self) -> usize {
148        self.fold_snapshot.version
149    }
150
151    pub fn chunks<'a>(
152        &'a self,
153        range: Range<TabPoint>,
154        language_aware: bool,
155        text_highlights: Option<&'a TextHighlights>,
156    ) -> TabChunks<'a> {
157        let (input_start, expanded_char_column, to_next_stop) =
158            self.to_fold_point(range.start, Bias::Left);
159        let input_start = input_start.to_offset(&self.fold_snapshot);
160        let input_end = self
161            .to_fold_point(range.end, Bias::Right)
162            .0
163            .to_offset(&self.fold_snapshot);
164        let to_next_stop = if range.start.0 + Point::new(0, to_next_stop as u32) > range.end.0 {
165            (range.end.column() - range.start.column()) as usize
166        } else {
167            to_next_stop
168        };
169
170        TabChunks {
171            fold_chunks: self.fold_snapshot.chunks(
172                input_start..input_end,
173                language_aware,
174                text_highlights,
175            ),
176            column: expanded_char_column,
177            output_position: range.start.0,
178            max_output_position: range.end.0,
179            tab_size: self.tab_size,
180            chunk: Chunk {
181                text: &SPACES[0..to_next_stop],
182                ..Default::default()
183            },
184            skip_leading_tab: to_next_stop > 0,
185        }
186    }
187
188    pub fn buffer_rows(&self, row: u32) -> fold_map::FoldBufferRows {
189        self.fold_snapshot.buffer_rows(row)
190    }
191
192    #[cfg(test)]
193    pub fn text(&self) -> String {
194        self.chunks(TabPoint::zero()..self.max_point(), false, None)
195            .map(|chunk| chunk.text)
196            .collect()
197    }
198
199    pub fn max_point(&self) -> TabPoint {
200        self.to_tab_point(self.fold_snapshot.max_point())
201    }
202
203    pub fn clip_point(&self, point: TabPoint, bias: Bias) -> TabPoint {
204        self.to_tab_point(
205            self.fold_snapshot
206                .clip_point(self.to_fold_point(point, bias).0, bias),
207        )
208    }
209
210    pub fn to_tab_point(&self, input: FoldPoint) -> TabPoint {
211        let chars = self.fold_snapshot.chars_at(FoldPoint::new(input.row(), 0));
212        let expanded = Self::expand_tabs(chars, input.column() as usize, self.tab_size);
213        TabPoint::new(input.row(), expanded as u32)
214    }
215
216    pub fn to_fold_point(&self, output: TabPoint, bias: Bias) -> (FoldPoint, usize, usize) {
217        let chars = self.fold_snapshot.chars_at(FoldPoint::new(output.row(), 0));
218        let expanded = output.column() as usize;
219        let (collapsed, expanded_char_column, to_next_stop) =
220            Self::collapse_tabs(chars, expanded, bias, self.tab_size);
221        (
222            FoldPoint::new(output.row(), collapsed as u32),
223            expanded_char_column,
224            to_next_stop,
225        )
226    }
227
228    pub fn from_point(&self, point: Point, bias: Bias) -> TabPoint {
229        self.to_tab_point(self.fold_snapshot.to_fold_point(point, bias))
230    }
231
232    pub fn to_point(&self, point: TabPoint, bias: Bias) -> Point {
233        self.to_fold_point(point, bias)
234            .0
235            .to_buffer_point(&self.fold_snapshot)
236    }
237
238    fn expand_tabs(chars: impl Iterator<Item = char>, column: usize, tab_size: u32) -> usize {
239        let mut expanded_chars = 0;
240        let mut expanded_bytes = 0;
241        let mut collapsed_bytes = 0;
242        for c in chars {
243            if collapsed_bytes == column {
244                break;
245            }
246            if c == '\t' {
247                let tab_len = tab_size as usize - expanded_chars % tab_size as usize;
248                expanded_bytes += tab_len;
249                expanded_chars += tab_len;
250            } else {
251                expanded_bytes += c.len_utf8();
252                expanded_chars += 1;
253            }
254            collapsed_bytes += c.len_utf8();
255        }
256        expanded_bytes
257    }
258
259    fn collapse_tabs(
260        mut chars: impl Iterator<Item = char>,
261        column: usize,
262        bias: Bias,
263        tab_size: u32,
264    ) -> (usize, usize, usize) {
265        let mut expanded_bytes = 0;
266        let mut expanded_chars = 0;
267        let mut collapsed_bytes = 0;
268        while let Some(c) = chars.next() {
269            if expanded_bytes >= column {
270                break;
271            }
272
273            if c == '\t' {
274                let tab_len = tab_size as usize - (expanded_chars % tab_size as usize);
275                expanded_chars += tab_len;
276                expanded_bytes += tab_len;
277                if expanded_bytes > column {
278                    expanded_chars -= expanded_bytes - column;
279                    return match bias {
280                        Bias::Left => (collapsed_bytes, expanded_chars, expanded_bytes - column),
281                        Bias::Right => (collapsed_bytes + 1, expanded_chars, 0),
282                    };
283                }
284            } else {
285                expanded_chars += 1;
286                expanded_bytes += c.len_utf8();
287            }
288
289            if expanded_bytes > column && matches!(bias, Bias::Left) {
290                expanded_chars -= 1;
291                break;
292            }
293
294            collapsed_bytes += c.len_utf8();
295        }
296        (collapsed_bytes, expanded_chars, 0)
297    }
298}
299
300#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
301pub struct TabPoint(pub super::Point);
302
303impl TabPoint {
304    pub fn new(row: u32, column: u32) -> Self {
305        Self(super::Point::new(row, column))
306    }
307
308    pub fn zero() -> Self {
309        Self::new(0, 0)
310    }
311
312    pub fn row(self) -> u32 {
313        self.0.row
314    }
315
316    pub fn column(self) -> u32 {
317        self.0.column
318    }
319}
320
321impl From<super::Point> for TabPoint {
322    fn from(point: super::Point) -> Self {
323        Self(point)
324    }
325}
326
327pub type TabEdit = text::Edit<TabPoint>;
328
329#[derive(Clone, Debug, Default, Eq, PartialEq)]
330pub struct TextSummary {
331    pub lines: super::Point,
332    pub first_line_chars: u32,
333    pub last_line_chars: u32,
334    pub longest_row: u32,
335    pub longest_row_chars: u32,
336}
337
338impl<'a> From<&'a str> for TextSummary {
339    fn from(text: &'a str) -> Self {
340        let sum = rope::TextSummary::from(text);
341
342        TextSummary {
343            lines: sum.lines,
344            first_line_chars: sum.first_line_chars,
345            last_line_chars: sum.last_line_chars,
346            longest_row: sum.longest_row,
347            longest_row_chars: sum.longest_row_chars,
348        }
349    }
350}
351
352impl<'a> std::ops::AddAssign<&'a Self> for TextSummary {
353    fn add_assign(&mut self, other: &'a Self) {
354        let joined_chars = self.last_line_chars + other.first_line_chars;
355        if joined_chars > self.longest_row_chars {
356            self.longest_row = self.lines.row;
357            self.longest_row_chars = joined_chars;
358        }
359        if other.longest_row_chars > self.longest_row_chars {
360            self.longest_row = self.lines.row + other.longest_row;
361            self.longest_row_chars = other.longest_row_chars;
362        }
363
364        if self.lines.row == 0 {
365            self.first_line_chars += other.first_line_chars;
366        }
367
368        if other.lines.row == 0 {
369            self.last_line_chars += other.first_line_chars;
370        } else {
371            self.last_line_chars = other.last_line_chars;
372        }
373
374        self.lines += &other.lines;
375    }
376}
377
378// Handles a tab width <= 16
379const SPACES: &'static str = "                ";
380
381pub struct TabChunks<'a> {
382    fold_chunks: fold_map::FoldChunks<'a>,
383    chunk: Chunk<'a>,
384    column: usize,
385    output_position: Point,
386    max_output_position: Point,
387    tab_size: u32,
388    skip_leading_tab: bool,
389}
390
391impl<'a> Iterator for TabChunks<'a> {
392    type Item = Chunk<'a>;
393
394    fn next(&mut self) -> Option<Self::Item> {
395        if self.chunk.text.is_empty() {
396            if let Some(chunk) = self.fold_chunks.next() {
397                self.chunk = chunk;
398                if self.skip_leading_tab {
399                    self.chunk.text = &self.chunk.text[1..];
400                    self.skip_leading_tab = false;
401                }
402            } else {
403                return None;
404            }
405        }
406
407        for (ix, c) in self.chunk.text.char_indices() {
408            match c {
409                '\t' => {
410                    if ix > 0 {
411                        let (prefix, suffix) = self.chunk.text.split_at(ix);
412                        self.chunk.text = suffix;
413                        return Some(Chunk {
414                            text: prefix,
415                            ..self.chunk
416                        });
417                    } else {
418                        self.chunk.text = &self.chunk.text[1..];
419                        let mut len = self.tab_size - self.column as u32 % self.tab_size;
420                        let next_output_position = cmp::min(
421                            self.output_position + Point::new(0, len),
422                            self.max_output_position,
423                        );
424                        len = next_output_position.column - self.output_position.column;
425                        self.column += len as usize;
426                        self.output_position = next_output_position;
427                        return Some(Chunk {
428                            text: &SPACES[0..len as usize],
429                            ..self.chunk
430                        });
431                    }
432                }
433                '\n' => {
434                    self.column = 0;
435                    self.output_position += Point::new(1, 0);
436                }
437                _ => {
438                    self.column += 1;
439                    self.output_position.column += c.len_utf8() as u32;
440                }
441            }
442        }
443
444        Some(mem::take(&mut self.chunk))
445    }
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451    use crate::{display_map::fold_map::FoldMap, MultiBuffer};
452    use rand::{prelude::StdRng, Rng};
453    use text::{RandomCharIter, Rope};
454
455    #[test]
456    fn test_expand_tabs() {
457        assert_eq!(TabSnapshot::expand_tabs("\t".chars(), 0, 4), 0);
458        assert_eq!(TabSnapshot::expand_tabs("\t".chars(), 1, 4), 4);
459        assert_eq!(TabSnapshot::expand_tabs("\ta".chars(), 2, 4), 5);
460    }
461
462    #[gpui::test(iterations = 100)]
463    fn test_random_tabs(cx: &mut gpui::MutableAppContext, mut rng: StdRng) {
464        let tab_size = rng.gen_range(1..=4);
465        let len = rng.gen_range(0..30);
466        let buffer = if rng.gen() {
467            let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
468            MultiBuffer::build_simple(&text, cx)
469        } else {
470            MultiBuffer::build_random(&mut rng, cx)
471        };
472        let buffer_snapshot = buffer.read(cx).snapshot(cx);
473        log::info!("Buffer text: {:?}", buffer_snapshot.text());
474
475        let (mut fold_map, _) = FoldMap::new(buffer_snapshot.clone());
476        fold_map.randomly_mutate(&mut rng);
477        let (folds_snapshot, _) = fold_map.read(buffer_snapshot.clone(), vec![]);
478        log::info!("FoldMap text: {:?}", folds_snapshot.text());
479
480        let (_, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), tab_size);
481        let text = Rope::from(tabs_snapshot.text().as_str());
482        log::info!(
483            "TabMap text (tab size: {}): {:?}",
484            tab_size,
485            tabs_snapshot.text(),
486        );
487
488        for _ in 0..5 {
489            let end_row = rng.gen_range(0..=text.max_point().row);
490            let end_column = rng.gen_range(0..=text.line_len(end_row));
491            let mut end = TabPoint(text.clip_point(Point::new(end_row, end_column), Bias::Right));
492            let start_row = rng.gen_range(0..=text.max_point().row);
493            let start_column = rng.gen_range(0..=text.line_len(start_row));
494            let mut start =
495                TabPoint(text.clip_point(Point::new(start_row, start_column), Bias::Left));
496            if start > end {
497                mem::swap(&mut start, &mut end);
498            }
499
500            let expected_text = text
501                .chunks_in_range(text.point_to_offset(start.0)..text.point_to_offset(end.0))
502                .collect::<String>();
503            let expected_summary = TextSummary::from(expected_text.as_str());
504            assert_eq!(
505                expected_text,
506                tabs_snapshot
507                    .chunks(start..end, false, None)
508                    .map(|c| c.text)
509                    .collect::<String>(),
510                "chunks({:?}..{:?})",
511                start,
512                end
513            );
514
515            let mut actual_summary = tabs_snapshot.text_summary_for_range(start..end);
516            if tab_size > 1 && folds_snapshot.text().contains('\t') {
517                actual_summary.longest_row = expected_summary.longest_row;
518                actual_summary.longest_row_chars = expected_summary.longest_row_chars;
519            }
520
521            assert_eq!(actual_summary, expected_summary,);
522        }
523    }
524}