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