1mod block_map;
2mod fold_map;
3mod suggestion_map;
4mod tab_map;
5mod wrap_map;
6
7use crate::{Anchor, AnchorRangeExt, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint};
8pub use block_map::{BlockMap, BlockPoint};
9use collections::{HashMap, HashSet};
10use fold_map::FoldMap;
11use gpui::{
12 color::Color,
13 fonts::{FontId, HighlightStyle},
14 Entity, ModelContext, ModelHandle,
15};
16use language::{OffsetUtf16, Point, Subscription as BufferSubscription};
17use settings::Settings;
18use std::{any::TypeId, fmt::Debug, num::NonZeroU32, ops::Range, sync::Arc};
19pub use suggestion_map::Suggestion;
20use suggestion_map::SuggestionMap;
21use sum_tree::{Bias, TreeMap};
22use tab_map::{TabMap, TabSnapshot};
23use wrap_map::WrapMap;
24
25pub use block_map::{
26 BlockBufferRows as DisplayBufferRows, BlockChunks as DisplayChunks, BlockContext,
27 BlockDisposition, BlockId, BlockProperties, BlockStyle, RenderBlock, TransformBlock,
28};
29
30#[derive(Copy, Clone, Debug, PartialEq, Eq)]
31pub enum FoldStatus {
32 Folded,
33 Foldable,
34}
35
36pub trait ToDisplayPoint {
37 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
38}
39
40type TextHighlights = TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>;
41
42pub struct DisplayMap {
43 buffer: ModelHandle<MultiBuffer>,
44 buffer_subscription: BufferSubscription,
45 fold_map: FoldMap,
46 suggestion_map: SuggestionMap,
47 tab_map: TabMap,
48 wrap_map: ModelHandle<WrapMap>,
49 block_map: BlockMap,
50 text_highlights: TextHighlights,
51 pub clip_at_line_ends: bool,
52}
53
54impl Entity for DisplayMap {
55 type Event = ();
56}
57
58impl DisplayMap {
59 pub fn new(
60 buffer: ModelHandle<MultiBuffer>,
61 font_id: FontId,
62 font_size: f32,
63 wrap_width: Option<f32>,
64 buffer_header_height: u8,
65 excerpt_header_height: u8,
66 cx: &mut ModelContext<Self>,
67 ) -> Self {
68 let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
69
70 let tab_size = Self::tab_size(&buffer, cx);
71 let (fold_map, snapshot) = FoldMap::new(buffer.read(cx).snapshot(cx));
72 let (suggestion_map, snapshot) = SuggestionMap::new(snapshot);
73 let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
74 let (wrap_map, snapshot) = WrapMap::new(snapshot, font_id, font_size, wrap_width, cx);
75 let block_map = BlockMap::new(snapshot, buffer_header_height, excerpt_header_height);
76 cx.observe(&wrap_map, |_, _, cx| cx.notify()).detach();
77 DisplayMap {
78 buffer,
79 buffer_subscription,
80 fold_map,
81 suggestion_map,
82 tab_map,
83 wrap_map,
84 block_map,
85 text_highlights: Default::default(),
86 clip_at_line_ends: false,
87 }
88 }
89
90 pub fn snapshot(&self, cx: &mut ModelContext<Self>) -> DisplaySnapshot {
91 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
92 let edits = self.buffer_subscription.consume().into_inner();
93 let (fold_snapshot, edits) = self.fold_map.read(buffer_snapshot, edits);
94 let (suggestion_snapshot, edits) = self.suggestion_map.sync(fold_snapshot.clone(), edits);
95
96 let tab_size = Self::tab_size(&self.buffer, cx);
97 let (tab_snapshot, edits) = self
98 .tab_map
99 .sync(suggestion_snapshot.clone(), edits, tab_size);
100 let (wrap_snapshot, edits) = self
101 .wrap_map
102 .update(cx, |map, cx| map.sync(tab_snapshot.clone(), edits, cx));
103 let block_snapshot = self.block_map.read(wrap_snapshot.clone(), edits);
104
105 DisplaySnapshot {
106 buffer_snapshot: self.buffer.read(cx).snapshot(cx),
107 fold_snapshot,
108 suggestion_snapshot,
109 tab_snapshot,
110 wrap_snapshot,
111 block_snapshot,
112 text_highlights: self.text_highlights.clone(),
113 clip_at_line_ends: self.clip_at_line_ends,
114 }
115 }
116
117 pub fn set_state(&mut self, other: &DisplaySnapshot, cx: &mut ModelContext<Self>) {
118 self.fold(
119 other
120 .folds_in_range(0..other.buffer_snapshot.len())
121 .map(|fold| fold.to_offset(&other.buffer_snapshot)),
122 cx,
123 );
124 }
125
126 pub fn fold<T: ToOffset>(
127 &mut self,
128 ranges: impl IntoIterator<Item = Range<T>>,
129 cx: &mut ModelContext<Self>,
130 ) {
131 let snapshot = self.buffer.read(cx).snapshot(cx);
132 let edits = self.buffer_subscription.consume().into_inner();
133 let tab_size = Self::tab_size(&self.buffer, cx);
134 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
135 let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
136 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
137 let (snapshot, edits) = self
138 .wrap_map
139 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
140 self.block_map.read(snapshot, edits);
141 let (snapshot, edits) = fold_map.fold(ranges);
142 let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
143 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
144 let (snapshot, edits) = self
145 .wrap_map
146 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
147 self.block_map.read(snapshot, edits);
148 }
149
150 pub fn unfold<T: ToOffset>(
151 &mut self,
152 ranges: impl IntoIterator<Item = Range<T>>,
153 inclusive: bool,
154 cx: &mut ModelContext<Self>,
155 ) {
156 let snapshot = self.buffer.read(cx).snapshot(cx);
157 let edits = self.buffer_subscription.consume().into_inner();
158 let tab_size = Self::tab_size(&self.buffer, cx);
159 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
160 let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
161 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
162 let (snapshot, edits) = self
163 .wrap_map
164 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
165 self.block_map.read(snapshot, edits);
166 let (snapshot, edits) = fold_map.unfold(ranges, inclusive);
167 let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
168 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
169 let (snapshot, edits) = self
170 .wrap_map
171 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
172 self.block_map.read(snapshot, edits);
173 }
174
175 pub fn insert_blocks(
176 &mut self,
177 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
178 cx: &mut ModelContext<Self>,
179 ) -> Vec<BlockId> {
180 let snapshot = self.buffer.read(cx).snapshot(cx);
181 let edits = self.buffer_subscription.consume().into_inner();
182 let tab_size = Self::tab_size(&self.buffer, cx);
183 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
184 let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
185 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
186 let (snapshot, edits) = self
187 .wrap_map
188 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
189 let mut block_map = self.block_map.write(snapshot, edits);
190 block_map.insert(blocks)
191 }
192
193 pub fn replace_blocks(&mut self, styles: HashMap<BlockId, RenderBlock>) {
194 self.block_map.replace(styles);
195 }
196
197 pub fn remove_blocks(&mut self, ids: HashSet<BlockId>, cx: &mut ModelContext<Self>) {
198 let snapshot = self.buffer.read(cx).snapshot(cx);
199 let edits = self.buffer_subscription.consume().into_inner();
200 let tab_size = Self::tab_size(&self.buffer, cx);
201 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
202 let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
203 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
204 let (snapshot, edits) = self
205 .wrap_map
206 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
207 let mut block_map = self.block_map.write(snapshot, edits);
208 block_map.remove(ids);
209 }
210
211 pub fn highlight_text(
212 &mut self,
213 type_id: TypeId,
214 ranges: Vec<Range<Anchor>>,
215 style: HighlightStyle,
216 ) {
217 self.text_highlights
218 .insert(Some(type_id), Arc::new((style, ranges)));
219 }
220
221 pub fn text_highlights(&self, type_id: TypeId) -> Option<(HighlightStyle, &[Range<Anchor>])> {
222 let highlights = self.text_highlights.get(&Some(type_id))?;
223 Some((highlights.0, &highlights.1))
224 }
225
226 pub fn clear_text_highlights(
227 &mut self,
228 type_id: TypeId,
229 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
230 self.text_highlights.remove(&Some(type_id))
231 }
232
233 pub fn replace_suggestion<T>(
234 &self,
235 new_suggestion: Option<Suggestion<T>>,
236 cx: &mut ModelContext<Self>,
237 ) where
238 T: ToPoint,
239 {
240 let snapshot = self.buffer.read(cx).snapshot(cx);
241 let edits = self.buffer_subscription.consume().into_inner();
242 let tab_size = Self::tab_size(&self.buffer, cx);
243 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
244 let (snapshot, edits) = self.suggestion_map.replace(new_suggestion, snapshot, edits);
245 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
246 let (snapshot, edits) = self
247 .wrap_map
248 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
249 self.block_map.read(snapshot, edits);
250 }
251
252 pub fn set_font(&self, font_id: FontId, font_size: f32, cx: &mut ModelContext<Self>) -> bool {
253 self.wrap_map
254 .update(cx, |map, cx| map.set_font(font_id, font_size, cx))
255 }
256
257 pub fn set_fold_ellipses_color(&mut self, color: Color) -> bool {
258 self.fold_map.set_ellipses_color(color)
259 }
260
261 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut ModelContext<Self>) -> bool {
262 self.wrap_map
263 .update(cx, |map, cx| map.set_wrap_width(width, cx))
264 }
265
266 fn tab_size(buffer: &ModelHandle<MultiBuffer>, cx: &mut ModelContext<Self>) -> NonZeroU32 {
267 let language_name = buffer
268 .read(cx)
269 .as_singleton()
270 .and_then(|buffer| buffer.read(cx).language())
271 .map(|language| language.name());
272
273 cx.global::<Settings>().tab_size(language_name.as_deref())
274 }
275
276 #[cfg(test)]
277 pub fn is_rewrapping(&self, cx: &gpui::AppContext) -> bool {
278 self.wrap_map.read(cx).is_rewrapping()
279 }
280}
281
282pub struct DisplaySnapshot {
283 pub buffer_snapshot: MultiBufferSnapshot,
284 fold_snapshot: fold_map::FoldSnapshot,
285 suggestion_snapshot: suggestion_map::SuggestionSnapshot,
286 tab_snapshot: tab_map::TabSnapshot,
287 wrap_snapshot: wrap_map::WrapSnapshot,
288 block_snapshot: block_map::BlockSnapshot,
289 text_highlights: TextHighlights,
290 clip_at_line_ends: bool,
291}
292
293impl DisplaySnapshot {
294 #[cfg(test)]
295 pub fn fold_count(&self) -> usize {
296 self.fold_snapshot.fold_count()
297 }
298
299 pub fn is_empty(&self) -> bool {
300 self.buffer_snapshot.len() == 0
301 }
302
303 pub fn buffer_rows(&self, start_row: u32) -> DisplayBufferRows {
304 self.block_snapshot.buffer_rows(start_row)
305 }
306
307 pub fn max_buffer_row(&self) -> u32 {
308 self.buffer_snapshot.max_buffer_row()
309 }
310
311 pub fn prev_line_boundary(&self, mut point: Point) -> (Point, DisplayPoint) {
312 loop {
313 let mut fold_point = self.fold_snapshot.to_fold_point(point, Bias::Left);
314 *fold_point.column_mut() = 0;
315 point = fold_point.to_buffer_point(&self.fold_snapshot);
316
317 let mut display_point = self.point_to_display_point(point, Bias::Left);
318 *display_point.column_mut() = 0;
319 let next_point = self.display_point_to_point(display_point, Bias::Left);
320 if next_point == point {
321 return (point, display_point);
322 }
323 point = next_point;
324 }
325 }
326
327 pub fn next_line_boundary(&self, mut point: Point) -> (Point, DisplayPoint) {
328 loop {
329 let mut fold_point = self.fold_snapshot.to_fold_point(point, Bias::Right);
330 *fold_point.column_mut() = self.fold_snapshot.line_len(fold_point.row());
331 point = fold_point.to_buffer_point(&self.fold_snapshot);
332
333 let mut display_point = self.point_to_display_point(point, Bias::Right);
334 *display_point.column_mut() = self.line_len(display_point.row());
335 let next_point = self.display_point_to_point(display_point, Bias::Right);
336 if next_point == point {
337 return (point, display_point);
338 }
339 point = next_point;
340 }
341 }
342
343 pub fn expand_to_line(&self, range: Range<Point>) -> Range<Point> {
344 let mut new_start = self.prev_line_boundary(range.start).0;
345 let mut new_end = self.next_line_boundary(range.end).0;
346
347 if new_start.row == range.start.row && new_end.row == range.end.row {
348 if new_end.row < self.buffer_snapshot.max_point().row {
349 new_end.row += 1;
350 new_end.column = 0;
351 } else if new_start.row > 0 {
352 new_start.row -= 1;
353 new_start.column = self.buffer_snapshot.line_len(new_start.row);
354 }
355 }
356
357 new_start..new_end
358 }
359
360 fn point_to_display_point(&self, point: Point, bias: Bias) -> DisplayPoint {
361 let fold_point = self.fold_snapshot.to_fold_point(point, bias);
362 let suggestion_point = self.suggestion_snapshot.to_suggestion_point(fold_point);
363 let tab_point = self.tab_snapshot.to_tab_point(suggestion_point);
364 let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
365 let block_point = self.block_snapshot.to_block_point(wrap_point);
366 DisplayPoint(block_point)
367 }
368
369 fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {
370 let block_point = point.0;
371 let wrap_point = self.block_snapshot.to_wrap_point(block_point);
372 let tab_point = self.wrap_snapshot.to_tab_point(wrap_point);
373 let suggestion_point = self.tab_snapshot.to_suggestion_point(tab_point, bias).0;
374 let fold_point = self.suggestion_snapshot.to_fold_point(suggestion_point);
375 fold_point.to_buffer_point(&self.fold_snapshot)
376 }
377
378 pub fn max_point(&self) -> DisplayPoint {
379 DisplayPoint(self.block_snapshot.max_point())
380 }
381
382 /// Returns text chunks starting at the given display row until the end of the file
383 pub fn text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
384 self.block_snapshot
385 .chunks(display_row..self.max_point().row() + 1, false, None)
386 .map(|h| h.text)
387 }
388
389 /// Returns text chunks starting at the end of the given display row in reverse until the start of the file
390 pub fn reverse_text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
391 (0..=display_row).into_iter().rev().flat_map(|row| {
392 self.block_snapshot
393 .chunks(row..row + 1, false, None)
394 .map(|h| h.text)
395 .collect::<Vec<_>>()
396 .into_iter()
397 .rev()
398 })
399 }
400
401 pub fn chunks(&self, display_rows: Range<u32>, language_aware: bool) -> DisplayChunks<'_> {
402 self.block_snapshot
403 .chunks(display_rows, language_aware, Some(&self.text_highlights))
404 }
405
406 pub fn chars_at(
407 &self,
408 mut point: DisplayPoint,
409 ) -> impl Iterator<Item = (char, DisplayPoint)> + '_ {
410 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
411 self.text_chunks(point.row())
412 .flat_map(str::chars)
413 .skip_while({
414 let mut column = 0;
415 move |char| {
416 let at_point = column >= point.column();
417 column += char.len_utf8() as u32;
418 !at_point
419 }
420 })
421 .map(move |ch| {
422 let result = (ch, point);
423 if ch == '\n' {
424 *point.row_mut() += 1;
425 *point.column_mut() = 0;
426 } else {
427 *point.column_mut() += ch.len_utf8() as u32;
428 }
429 result
430 })
431 }
432
433 pub fn reverse_chars_at(
434 &self,
435 mut point: DisplayPoint,
436 ) -> impl Iterator<Item = (char, DisplayPoint)> + '_ {
437 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
438 self.reverse_text_chunks(point.row())
439 .flat_map(|chunk| chunk.chars().rev())
440 .skip_while({
441 let mut column = self.line_len(point.row());
442 if self.max_point().row() > point.row() {
443 column += 1;
444 }
445
446 move |char| {
447 let at_point = column <= point.column();
448 column = column.saturating_sub(char.len_utf8() as u32);
449 !at_point
450 }
451 })
452 .map(move |ch| {
453 if ch == '\n' {
454 *point.row_mut() -= 1;
455 *point.column_mut() = self.line_len(point.row());
456 } else {
457 *point.column_mut() = point.column().saturating_sub(ch.len_utf8() as u32);
458 }
459 (ch, point)
460 })
461 }
462
463 /// Returns an iterator of the start positions of the occurances of `target` in the `self` after `from`
464 /// Stops if `condition` returns false for any of the character position pairs observed.
465 pub fn find_while<'a>(
466 &'a self,
467 from: DisplayPoint,
468 target: &str,
469 condition: impl FnMut(char, DisplayPoint) -> bool + 'a,
470 ) -> impl Iterator<Item = DisplayPoint> + 'a {
471 Self::find_internal(self.chars_at(from), target.chars().collect(), condition)
472 }
473
474 /// Returns an iterator of the end positions of the occurances of `target` in the `self` before `from`
475 /// Stops if `condition` returns false for any of the character position pairs observed.
476 pub fn reverse_find_while<'a>(
477 &'a self,
478 from: DisplayPoint,
479 target: &str,
480 condition: impl FnMut(char, DisplayPoint) -> bool + 'a,
481 ) -> impl Iterator<Item = DisplayPoint> + 'a {
482 Self::find_internal(
483 self.reverse_chars_at(from),
484 target.chars().rev().collect(),
485 condition,
486 )
487 }
488
489 fn find_internal<'a>(
490 iterator: impl Iterator<Item = (char, DisplayPoint)> + 'a,
491 target: Vec<char>,
492 mut condition: impl FnMut(char, DisplayPoint) -> bool + 'a,
493 ) -> impl Iterator<Item = DisplayPoint> + 'a {
494 // List of partial matches with the index of the last seen character in target and the starting point of the match
495 let mut partial_matches: Vec<(usize, DisplayPoint)> = Vec::new();
496 iterator
497 .take_while(move |(ch, point)| condition(*ch, *point))
498 .filter_map(move |(ch, point)| {
499 if Some(&ch) == target.get(0) {
500 partial_matches.push((0, point));
501 }
502
503 let mut found = None;
504 // Keep partial matches that have the correct next character
505 partial_matches.retain_mut(|(match_position, match_start)| {
506 if target.get(*match_position) == Some(&ch) {
507 *match_position += 1;
508 if *match_position == target.len() {
509 found = Some(match_start.clone());
510 // This match is completed. No need to keep tracking it
511 false
512 } else {
513 true
514 }
515 } else {
516 false
517 }
518 });
519
520 found
521 })
522 }
523
524 pub fn column_to_chars(&self, display_row: u32, target: u32) -> u32 {
525 let mut count = 0;
526 let mut column = 0;
527 for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
528 if column >= target {
529 break;
530 }
531 count += 1;
532 column += c.len_utf8() as u32;
533 }
534 count
535 }
536
537 pub fn column_from_chars(&self, display_row: u32, char_count: u32) -> u32 {
538 let mut column = 0;
539
540 for (count, (c, _)) in self.chars_at(DisplayPoint::new(display_row, 0)).enumerate() {
541 if c == '\n' || count >= char_count as usize {
542 break;
543 }
544 column += c.len_utf8() as u32;
545 }
546
547 column
548 }
549
550 pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
551 let mut clipped = self.block_snapshot.clip_point(point.0, bias);
552 if self.clip_at_line_ends {
553 clipped = self.clip_at_line_end(DisplayPoint(clipped)).0
554 }
555 DisplayPoint(clipped)
556 }
557
558 pub fn clip_at_line_end(&self, point: DisplayPoint) -> DisplayPoint {
559 let mut point = point.0;
560 if point.column == self.line_len(point.row) {
561 point.column = point.column.saturating_sub(1);
562 point = self.block_snapshot.clip_point(point, Bias::Left);
563 }
564 DisplayPoint(point)
565 }
566
567 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Range<Anchor>>
568 where
569 T: ToOffset,
570 {
571 self.fold_snapshot.folds_in_range(range)
572 }
573
574 pub fn blocks_in_range(
575 &self,
576 rows: Range<u32>,
577 ) -> impl Iterator<Item = (u32, &TransformBlock)> {
578 self.block_snapshot.blocks_in_range(rows)
579 }
580
581 pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
582 self.fold_snapshot.intersects_fold(offset)
583 }
584
585 pub fn is_line_folded(&self, buffer_row: u32) -> bool {
586 self.fold_snapshot.is_line_folded(buffer_row)
587 }
588
589 pub fn is_block_line(&self, display_row: u32) -> bool {
590 self.block_snapshot.is_block_line(display_row)
591 }
592
593 pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
594 let wrap_row = self
595 .block_snapshot
596 .to_wrap_point(BlockPoint::new(display_row, 0))
597 .row();
598 self.wrap_snapshot.soft_wrap_indent(wrap_row)
599 }
600
601 pub fn text(&self) -> String {
602 self.text_chunks(0).collect()
603 }
604
605 pub fn line(&self, display_row: u32) -> String {
606 let mut result = String::new();
607 for chunk in self.text_chunks(display_row) {
608 if let Some(ix) = chunk.find('\n') {
609 result.push_str(&chunk[0..ix]);
610 break;
611 } else {
612 result.push_str(chunk);
613 }
614 }
615 result
616 }
617
618 pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
619 let mut indent = 0;
620 let mut is_blank = true;
621 for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
622 if c == ' ' {
623 indent += 1;
624 } else {
625 is_blank = c == '\n';
626 break;
627 }
628 }
629 (indent, is_blank)
630 }
631
632 pub fn line_indent_for_buffer_row(&self, buffer_row: u32) -> (u32, bool) {
633 let (buffer, range) = self
634 .buffer_snapshot
635 .buffer_line_for_row(buffer_row)
636 .unwrap();
637 let chars = buffer.chars_at(Point::new(range.start.row, 0));
638
639 let mut is_blank = false;
640 let indent_size = TabSnapshot::expand_tabs(
641 chars.take_while(|c| {
642 if *c == ' ' || *c == '\t' {
643 true
644 } else {
645 if *c == '\n' {
646 is_blank = true;
647 }
648 false
649 }
650 }),
651 buffer.line_len(buffer_row) as usize, // Never collapse
652 self.tab_snapshot.tab_size,
653 );
654
655 (indent_size as u32, is_blank)
656 }
657
658 pub fn line_len(&self, row: u32) -> u32 {
659 self.block_snapshot.line_len(row)
660 }
661
662 pub fn longest_row(&self) -> u32 {
663 self.block_snapshot.longest_row()
664 }
665
666 pub fn fold_for_line(self: &Self, buffer_row: u32) -> Option<FoldStatus> {
667 if self.is_line_folded(buffer_row) {
668 Some(FoldStatus::Folded)
669 } else if self.is_foldable(buffer_row) {
670 Some(FoldStatus::Foldable)
671 } else {
672 None
673 }
674 }
675
676 pub fn is_foldable(self: &Self, buffer_row: u32) -> bool {
677 let max_row = self.buffer_snapshot.max_buffer_row();
678 if buffer_row >= max_row {
679 return false;
680 }
681
682 let (indent_size, is_blank) = self.line_indent_for_buffer_row(buffer_row);
683 if is_blank {
684 return false;
685 }
686
687 for next_row in (buffer_row + 1)..=max_row {
688 let (next_indent_size, next_line_is_blank) = self.line_indent_for_buffer_row(next_row);
689 if next_indent_size > indent_size {
690 return true;
691 } else if !next_line_is_blank {
692 break;
693 }
694 }
695
696 false
697 }
698
699 pub fn foldable_range(self: &Self, buffer_row: u32) -> Option<Range<Point>> {
700 let start = Point::new(buffer_row, self.buffer_snapshot.line_len(buffer_row));
701 if self.is_foldable(start.row) && !self.is_line_folded(start.row) {
702 let (start_indent, _) = self.line_indent_for_buffer_row(buffer_row);
703 let max_point = self.buffer_snapshot.max_point();
704 let mut end = None;
705
706 for row in (buffer_row + 1)..=max_point.row {
707 let (indent, is_blank) = self.line_indent_for_buffer_row(row);
708 if !is_blank && indent <= start_indent {
709 let prev_row = row - 1;
710 end = Some(Point::new(
711 prev_row,
712 self.buffer_snapshot.line_len(prev_row),
713 ));
714 break;
715 }
716 }
717 let end = end.unwrap_or(max_point);
718 Some(start..end)
719 } else {
720 None
721 }
722 }
723
724 #[cfg(any(test, feature = "test-support"))]
725 pub fn highlight_ranges<Tag: ?Sized + 'static>(
726 &self,
727 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
728 let type_id = TypeId::of::<Tag>();
729 self.text_highlights.get(&Some(type_id)).cloned()
730 }
731}
732
733#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
734pub struct DisplayPoint(BlockPoint);
735
736impl Debug for DisplayPoint {
737 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
738 f.write_fmt(format_args!(
739 "DisplayPoint({}, {})",
740 self.row(),
741 self.column()
742 ))
743 }
744}
745
746impl DisplayPoint {
747 pub fn new(row: u32, column: u32) -> Self {
748 Self(BlockPoint(Point::new(row, column)))
749 }
750
751 pub fn zero() -> Self {
752 Self::new(0, 0)
753 }
754
755 pub fn is_zero(&self) -> bool {
756 self.0.is_zero()
757 }
758
759 pub fn row(self) -> u32 {
760 self.0.row
761 }
762
763 pub fn column(self) -> u32 {
764 self.0.column
765 }
766
767 pub fn row_mut(&mut self) -> &mut u32 {
768 &mut self.0.row
769 }
770
771 pub fn column_mut(&mut self) -> &mut u32 {
772 &mut self.0.column
773 }
774
775 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
776 map.display_point_to_point(self, Bias::Left)
777 }
778
779 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
780 let wrap_point = map.block_snapshot.to_wrap_point(self.0);
781 let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
782 let suggestion_point = map.tab_snapshot.to_suggestion_point(tab_point, bias).0;
783 let fold_point = map.suggestion_snapshot.to_fold_point(suggestion_point);
784 fold_point.to_buffer_offset(&map.fold_snapshot)
785 }
786}
787
788impl ToDisplayPoint for usize {
789 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
790 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
791 }
792}
793
794impl ToDisplayPoint for OffsetUtf16 {
795 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
796 self.to_offset(&map.buffer_snapshot).to_display_point(map)
797 }
798}
799
800impl ToDisplayPoint for Point {
801 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
802 map.point_to_display_point(*self, Bias::Left)
803 }
804}
805
806impl ToDisplayPoint for Anchor {
807 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
808 self.to_point(&map.buffer_snapshot).to_display_point(map)
809 }
810}
811
812pub fn next_rows(display_row: u32, display_map: &DisplaySnapshot) -> impl Iterator<Item = u32> {
813 let max_row = display_map.max_point().row();
814 let start_row = display_row + 1;
815 let mut current = None;
816 std::iter::from_fn(move || {
817 if current == None {
818 current = Some(start_row);
819 } else {
820 current = Some(current.unwrap() + 1)
821 }
822 if current.unwrap() > max_row {
823 None
824 } else {
825 current
826 }
827 })
828}
829
830#[cfg(test)]
831pub mod tests {
832 use super::*;
833 use crate::{movement, test::marked_display_snapshot};
834 use gpui::{color::Color, elements::*, test::observe, MutableAppContext};
835 use language::{Buffer, Language, LanguageConfig, SelectionGoal};
836 use rand::{prelude::*, Rng};
837 use smol::stream::StreamExt;
838 use std::{env, sync::Arc};
839 use theme::SyntaxTheme;
840 use util::test::{marked_text_offsets, marked_text_ranges, sample_text};
841 use Bias::*;
842
843 #[gpui::test(iterations = 100)]
844 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
845 cx.foreground().set_block_on_ticks(0..=50);
846 cx.foreground().forbid_parking();
847 let operations = env::var("OPERATIONS")
848 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
849 .unwrap_or(10);
850
851 let font_cache = cx.font_cache().clone();
852 let mut tab_size = rng.gen_range(1..=4);
853 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
854 let excerpt_header_height = rng.gen_range(1..=5);
855 let family_id = font_cache
856 .load_family(&["Helvetica"], &Default::default())
857 .unwrap();
858 let font_id = font_cache
859 .select_font(family_id, &Default::default())
860 .unwrap();
861 let font_size = 14.0;
862 let max_wrap_width = 300.0;
863 let mut wrap_width = if rng.gen_bool(0.1) {
864 None
865 } else {
866 Some(rng.gen_range(0.0..=max_wrap_width))
867 };
868
869 log::info!("tab size: {}", tab_size);
870 log::info!("wrap width: {:?}", wrap_width);
871
872 cx.update(|cx| {
873 let mut settings = Settings::test(cx);
874 settings.editor_overrides.tab_size = NonZeroU32::new(tab_size);
875 cx.set_global(settings)
876 });
877
878 let buffer = cx.update(|cx| {
879 if rng.gen() {
880 let len = rng.gen_range(0..10);
881 let text = util::RandomCharIter::new(&mut rng)
882 .take(len)
883 .collect::<String>();
884 MultiBuffer::build_simple(&text, cx)
885 } else {
886 MultiBuffer::build_random(&mut rng, cx)
887 }
888 });
889
890 let map = cx.add_model(|cx| {
891 DisplayMap::new(
892 buffer.clone(),
893 font_id,
894 font_size,
895 wrap_width,
896 buffer_start_excerpt_header_height,
897 excerpt_header_height,
898 cx,
899 )
900 });
901 let mut notifications = observe(&map, cx);
902 let mut fold_count = 0;
903 let mut blocks = Vec::new();
904
905 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
906 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
907 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
908 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
909 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
910 log::info!("block text: {:?}", snapshot.block_snapshot.text());
911 log::info!("display text: {:?}", snapshot.text());
912
913 for _i in 0..operations {
914 match rng.gen_range(0..100) {
915 0..=19 => {
916 wrap_width = if rng.gen_bool(0.2) {
917 None
918 } else {
919 Some(rng.gen_range(0.0..=max_wrap_width))
920 };
921 log::info!("setting wrap width to {:?}", wrap_width);
922 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
923 }
924 20..=29 => {
925 let mut tab_sizes = vec![1, 2, 3, 4];
926 tab_sizes.remove((tab_size - 1) as usize);
927 tab_size = *tab_sizes.choose(&mut rng).unwrap();
928 log::info!("setting tab size to {:?}", tab_size);
929 cx.update(|cx| {
930 let mut settings = Settings::test(cx);
931 settings.editor_overrides.tab_size = NonZeroU32::new(tab_size);
932 cx.set_global(settings)
933 });
934 }
935 30..=44 => {
936 map.update(cx, |map, cx| {
937 if rng.gen() || blocks.is_empty() {
938 let buffer = map.snapshot(cx).buffer_snapshot;
939 let block_properties = (0..rng.gen_range(1..=1))
940 .map(|_| {
941 let position =
942 buffer.anchor_after(buffer.clip_offset(
943 rng.gen_range(0..=buffer.len()),
944 Bias::Left,
945 ));
946
947 let disposition = if rng.gen() {
948 BlockDisposition::Above
949 } else {
950 BlockDisposition::Below
951 };
952 let height = rng.gen_range(1..5);
953 log::info!(
954 "inserting block {:?} {:?} with height {}",
955 disposition,
956 position.to_point(&buffer),
957 height
958 );
959 BlockProperties {
960 style: BlockStyle::Fixed,
961 position,
962 height,
963 disposition,
964 render: Arc::new(|_| Empty::new().boxed()),
965 }
966 })
967 .collect::<Vec<_>>();
968 blocks.extend(map.insert_blocks(block_properties, cx));
969 } else {
970 blocks.shuffle(&mut rng);
971 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
972 let block_ids_to_remove = (0..remove_count)
973 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
974 .collect();
975 log::info!("removing block ids {:?}", block_ids_to_remove);
976 map.remove_blocks(block_ids_to_remove, cx);
977 }
978 });
979 }
980 45..=79 => {
981 let mut ranges = Vec::new();
982 for _ in 0..rng.gen_range(1..=3) {
983 buffer.read_with(cx, |buffer, cx| {
984 let buffer = buffer.read(cx);
985 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
986 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
987 ranges.push(start..end);
988 });
989 }
990
991 if rng.gen() && fold_count > 0 {
992 log::info!("unfolding ranges: {:?}", ranges);
993 map.update(cx, |map, cx| {
994 map.unfold(ranges, true, cx);
995 });
996 } else {
997 log::info!("folding ranges: {:?}", ranges);
998 map.update(cx, |map, cx| {
999 map.fold(ranges, cx);
1000 });
1001 }
1002 }
1003 _ => {
1004 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1005 }
1006 }
1007
1008 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1009 notifications.next().await.unwrap();
1010 }
1011
1012 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1013 fold_count = snapshot.fold_count();
1014 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1015 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1016 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1017 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1018 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1019 log::info!("display text: {:?}", snapshot.text());
1020
1021 // Line boundaries
1022 let buffer = &snapshot.buffer_snapshot;
1023 for _ in 0..5 {
1024 let row = rng.gen_range(0..=buffer.max_point().row);
1025 let column = rng.gen_range(0..=buffer.line_len(row));
1026 let point = buffer.clip_point(Point::new(row, column), Left);
1027
1028 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1029 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1030
1031 assert!(prev_buffer_bound <= point);
1032 assert!(next_buffer_bound >= point);
1033 assert_eq!(prev_buffer_bound.column, 0);
1034 assert_eq!(prev_display_bound.column(), 0);
1035 if next_buffer_bound < buffer.max_point() {
1036 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1037 }
1038
1039 assert_eq!(
1040 prev_display_bound,
1041 prev_buffer_bound.to_display_point(&snapshot),
1042 "row boundary before {:?}. reported buffer row boundary: {:?}",
1043 point,
1044 prev_buffer_bound
1045 );
1046 assert_eq!(
1047 next_display_bound,
1048 next_buffer_bound.to_display_point(&snapshot),
1049 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1050 point,
1051 next_buffer_bound
1052 );
1053 assert_eq!(
1054 prev_buffer_bound,
1055 prev_display_bound.to_point(&snapshot),
1056 "row boundary before {:?}. reported display row boundary: {:?}",
1057 point,
1058 prev_display_bound
1059 );
1060 assert_eq!(
1061 next_buffer_bound,
1062 next_display_bound.to_point(&snapshot),
1063 "row boundary after {:?}. reported display row boundary: {:?}",
1064 point,
1065 next_display_bound
1066 );
1067 }
1068
1069 // Movement
1070 let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1071 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1072 for _ in 0..5 {
1073 let row = rng.gen_range(0..=snapshot.max_point().row());
1074 let column = rng.gen_range(0..=snapshot.line_len(row));
1075 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1076
1077 log::info!("Moving from point {:?}", point);
1078
1079 let moved_right = movement::right(&snapshot, point);
1080 log::info!("Right {:?}", moved_right);
1081 if point < max_point {
1082 assert!(moved_right > point);
1083 if point.column() == snapshot.line_len(point.row())
1084 || snapshot.soft_wrap_indent(point.row()).is_some()
1085 && point.column() == snapshot.line_len(point.row()) - 1
1086 {
1087 assert!(moved_right.row() > point.row());
1088 }
1089 } else {
1090 assert_eq!(moved_right, point);
1091 }
1092
1093 let moved_left = movement::left(&snapshot, point);
1094 log::info!("Left {:?}", moved_left);
1095 if point > min_point {
1096 assert!(moved_left < point);
1097 if point.column() == 0 {
1098 assert!(moved_left.row() < point.row());
1099 }
1100 } else {
1101 assert_eq!(moved_left, point);
1102 }
1103 }
1104 }
1105 }
1106
1107 #[gpui::test(retries = 5)]
1108 fn test_soft_wraps(cx: &mut MutableAppContext) {
1109 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1110 cx.foreground().forbid_parking();
1111
1112 let font_cache = cx.font_cache();
1113
1114 let family_id = font_cache
1115 .load_family(&["Helvetica"], &Default::default())
1116 .unwrap();
1117 let font_id = font_cache
1118 .select_font(family_id, &Default::default())
1119 .unwrap();
1120 let font_size = 12.0;
1121 let wrap_width = Some(64.);
1122 cx.set_global(Settings::test(cx));
1123
1124 let text = "one two three four five\nsix seven eight";
1125 let buffer = MultiBuffer::build_simple(text, cx);
1126 let map = cx.add_model(|cx| {
1127 DisplayMap::new(buffer.clone(), font_id, font_size, wrap_width, 1, 1, cx)
1128 });
1129
1130 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1131 assert_eq!(
1132 snapshot.text_chunks(0).collect::<String>(),
1133 "one two \nthree four \nfive\nsix seven \neight"
1134 );
1135 assert_eq!(
1136 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1137 DisplayPoint::new(0, 7)
1138 );
1139 assert_eq!(
1140 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1141 DisplayPoint::new(1, 0)
1142 );
1143 assert_eq!(
1144 movement::right(&snapshot, DisplayPoint::new(0, 7)),
1145 DisplayPoint::new(1, 0)
1146 );
1147 assert_eq!(
1148 movement::left(&snapshot, DisplayPoint::new(1, 0)),
1149 DisplayPoint::new(0, 7)
1150 );
1151 assert_eq!(
1152 movement::up(
1153 &snapshot,
1154 DisplayPoint::new(1, 10),
1155 SelectionGoal::None,
1156 false
1157 ),
1158 (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
1159 );
1160 assert_eq!(
1161 movement::down(
1162 &snapshot,
1163 DisplayPoint::new(0, 7),
1164 SelectionGoal::Column(10),
1165 false
1166 ),
1167 (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
1168 );
1169 assert_eq!(
1170 movement::down(
1171 &snapshot,
1172 DisplayPoint::new(1, 10),
1173 SelectionGoal::Column(10),
1174 false
1175 ),
1176 (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
1177 );
1178
1179 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1180 buffer.update(cx, |buffer, cx| {
1181 buffer.edit([(ix..ix, "and ")], None, cx);
1182 });
1183
1184 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1185 assert_eq!(
1186 snapshot.text_chunks(1).collect::<String>(),
1187 "three four \nfive\nsix and \nseven eight"
1188 );
1189
1190 // Re-wrap on font size changes
1191 map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
1192
1193 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1194 assert_eq!(
1195 snapshot.text_chunks(1).collect::<String>(),
1196 "three \nfour five\nsix and \nseven \neight"
1197 )
1198 }
1199
1200 #[gpui::test]
1201 fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
1202 cx.set_global(Settings::test(cx));
1203 let text = sample_text(6, 6, 'a');
1204 let buffer = MultiBuffer::build_simple(&text, cx);
1205 let family_id = cx
1206 .font_cache()
1207 .load_family(&["Helvetica"], &Default::default())
1208 .unwrap();
1209 let font_id = cx
1210 .font_cache()
1211 .select_font(family_id, &Default::default())
1212 .unwrap();
1213 let font_size = 14.0;
1214 let map =
1215 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1216 buffer.update(cx, |buffer, cx| {
1217 buffer.edit(
1218 vec![
1219 (Point::new(1, 0)..Point::new(1, 0), "\t"),
1220 (Point::new(1, 1)..Point::new(1, 1), "\t"),
1221 (Point::new(2, 1)..Point::new(2, 1), "\t"),
1222 ],
1223 None,
1224 cx,
1225 )
1226 });
1227
1228 assert_eq!(
1229 map.update(cx, |map, cx| map.snapshot(cx))
1230 .text_chunks(1)
1231 .collect::<String>()
1232 .lines()
1233 .next(),
1234 Some(" b bbbbb")
1235 );
1236 assert_eq!(
1237 map.update(cx, |map, cx| map.snapshot(cx))
1238 .text_chunks(2)
1239 .collect::<String>()
1240 .lines()
1241 .next(),
1242 Some("c ccccc")
1243 );
1244 }
1245
1246 #[gpui::test]
1247 async fn test_chunks(cx: &mut gpui::TestAppContext) {
1248 use unindent::Unindent as _;
1249
1250 let text = r#"
1251 fn outer() {}
1252
1253 mod module {
1254 fn inner() {}
1255 }"#
1256 .unindent();
1257
1258 let theme = SyntaxTheme::new(vec![
1259 ("mod.body".to_string(), Color::red().into()),
1260 ("fn.name".to_string(), Color::blue().into()),
1261 ]);
1262 let language = Arc::new(
1263 Language::new(
1264 LanguageConfig {
1265 name: "Test".into(),
1266 path_suffixes: vec![".test".to_string()],
1267 ..Default::default()
1268 },
1269 Some(tree_sitter_rust::language()),
1270 )
1271 .with_highlights_query(
1272 r#"
1273 (mod_item name: (identifier) body: _ @mod.body)
1274 (function_item name: (identifier) @fn.name)
1275 "#,
1276 )
1277 .unwrap(),
1278 );
1279 language.set_theme(&theme);
1280 cx.update(|cx| {
1281 let mut settings = Settings::test(cx);
1282 settings.editor_defaults.tab_size = Some(2.try_into().unwrap());
1283 cx.set_global(settings);
1284 });
1285
1286 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1287 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1288 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1289
1290 let font_cache = cx.font_cache();
1291 let family_id = font_cache
1292 .load_family(&["Helvetica"], &Default::default())
1293 .unwrap();
1294 let font_id = font_cache
1295 .select_font(family_id, &Default::default())
1296 .unwrap();
1297 let font_size = 14.0;
1298
1299 let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1300 assert_eq!(
1301 cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1302 vec![
1303 ("fn ".to_string(), None),
1304 ("outer".to_string(), Some(Color::blue())),
1305 ("() {}\n\nmod module ".to_string(), None),
1306 ("{\n fn ".to_string(), Some(Color::red())),
1307 ("inner".to_string(), Some(Color::blue())),
1308 ("() {}\n}".to_string(), Some(Color::red())),
1309 ]
1310 );
1311 assert_eq!(
1312 cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1313 vec![
1314 (" fn ".to_string(), Some(Color::red())),
1315 ("inner".to_string(), Some(Color::blue())),
1316 ("() {}\n}".to_string(), Some(Color::red())),
1317 ]
1318 );
1319
1320 map.update(cx, |map, cx| {
1321 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1322 });
1323 assert_eq!(
1324 cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1325 vec![
1326 ("fn ".to_string(), None),
1327 ("out".to_string(), Some(Color::blue())),
1328 ("β―".to_string(), None),
1329 (" fn ".to_string(), Some(Color::red())),
1330 ("inner".to_string(), Some(Color::blue())),
1331 ("() {}\n}".to_string(), Some(Color::red())),
1332 ]
1333 );
1334 }
1335
1336 #[gpui::test]
1337 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1338 use unindent::Unindent as _;
1339
1340 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1341
1342 let text = r#"
1343 fn outer() {}
1344
1345 mod module {
1346 fn inner() {}
1347 }"#
1348 .unindent();
1349
1350 let theme = SyntaxTheme::new(vec![
1351 ("mod.body".to_string(), Color::red().into()),
1352 ("fn.name".to_string(), Color::blue().into()),
1353 ]);
1354 let language = Arc::new(
1355 Language::new(
1356 LanguageConfig {
1357 name: "Test".into(),
1358 path_suffixes: vec![".test".to_string()],
1359 ..Default::default()
1360 },
1361 Some(tree_sitter_rust::language()),
1362 )
1363 .with_highlights_query(
1364 r#"
1365 (mod_item name: (identifier) body: _ @mod.body)
1366 (function_item name: (identifier) @fn.name)
1367 "#,
1368 )
1369 .unwrap(),
1370 );
1371 language.set_theme(&theme);
1372
1373 cx.update(|cx| cx.set_global(Settings::test(cx)));
1374
1375 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1376 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1377 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1378
1379 let font_cache = cx.font_cache();
1380
1381 let family_id = font_cache
1382 .load_family(&["Courier"], &Default::default())
1383 .unwrap();
1384 let font_id = font_cache
1385 .select_font(family_id, &Default::default())
1386 .unwrap();
1387 let font_size = 16.0;
1388
1389 let map =
1390 cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, Some(40.0), 1, 1, cx));
1391 assert_eq!(
1392 cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1393 [
1394 ("fn \n".to_string(), None),
1395 ("oute\nr".to_string(), Some(Color::blue())),
1396 ("() \n{}\n\n".to_string(), None),
1397 ]
1398 );
1399 assert_eq!(
1400 cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1401 [("{}\n\n".to_string(), None)]
1402 );
1403
1404 map.update(cx, |map, cx| {
1405 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1406 });
1407 assert_eq!(
1408 cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1409 [
1410 ("out".to_string(), Some(Color::blue())),
1411 ("β―\n".to_string(), None),
1412 (" \nfn ".to_string(), Some(Color::red())),
1413 ("i\n".to_string(), Some(Color::blue()))
1414 ]
1415 );
1416 }
1417
1418 #[gpui::test]
1419 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1420 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1421
1422 cx.update(|cx| cx.set_global(Settings::test(cx)));
1423 let theme = SyntaxTheme::new(vec![
1424 ("operator".to_string(), Color::red().into()),
1425 ("string".to_string(), Color::green().into()),
1426 ]);
1427 let language = Arc::new(
1428 Language::new(
1429 LanguageConfig {
1430 name: "Test".into(),
1431 path_suffixes: vec![".test".to_string()],
1432 ..Default::default()
1433 },
1434 Some(tree_sitter_rust::language()),
1435 )
1436 .with_highlights_query(
1437 r#"
1438 ":" @operator
1439 (string_literal) @string
1440 "#,
1441 )
1442 .unwrap(),
1443 );
1444 language.set_theme(&theme);
1445
1446 let (text, highlighted_ranges) = marked_text_ranges(r#"constΛ Β«aΒ»: B = "c Β«dΒ»""#, false);
1447
1448 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1449 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1450
1451 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1452 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1453
1454 let font_cache = cx.font_cache();
1455 let family_id = font_cache
1456 .load_family(&["Courier"], &Default::default())
1457 .unwrap();
1458 let font_id = font_cache
1459 .select_font(family_id, &Default::default())
1460 .unwrap();
1461 let font_size = 16.0;
1462 let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1463
1464 enum MyType {}
1465
1466 let style = HighlightStyle {
1467 color: Some(Color::blue()),
1468 ..Default::default()
1469 };
1470
1471 map.update(cx, |map, _cx| {
1472 map.highlight_text(
1473 TypeId::of::<MyType>(),
1474 highlighted_ranges
1475 .into_iter()
1476 .map(|range| {
1477 buffer_snapshot.anchor_before(range.start)
1478 ..buffer_snapshot.anchor_before(range.end)
1479 })
1480 .collect(),
1481 style,
1482 );
1483 });
1484
1485 assert_eq!(
1486 cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1487 [
1488 ("const ".to_string(), None, None),
1489 ("a".to_string(), None, Some(Color::blue())),
1490 (":".to_string(), Some(Color::red()), None),
1491 (" B = ".to_string(), None, None),
1492 ("\"c ".to_string(), Some(Color::green()), None),
1493 ("d".to_string(), Some(Color::green()), Some(Color::blue())),
1494 ("\"".to_string(), Some(Color::green()), None),
1495 ]
1496 );
1497 }
1498
1499 #[gpui::test]
1500 fn test_clip_point(cx: &mut gpui::MutableAppContext) {
1501 cx.set_global(Settings::test(cx));
1502 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::MutableAppContext) {
1503 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1504
1505 match bias {
1506 Bias::Left => {
1507 if shift_right {
1508 *markers[1].column_mut() += 1;
1509 }
1510
1511 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1512 }
1513 Bias::Right => {
1514 if shift_right {
1515 *markers[0].column_mut() += 1;
1516 }
1517
1518 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1519 }
1520 };
1521 }
1522
1523 use Bias::{Left, Right};
1524 assert("ΛΛΞ±", false, Left, cx);
1525 assert("ΛΛΞ±", true, Left, cx);
1526 assert("ΛΛΞ±", false, Right, cx);
1527 assert("ΛΞ±Λ", true, Right, cx);
1528 assert("ΛΛβ", false, Left, cx);
1529 assert("ΛΛβ", true, Left, cx);
1530 assert("ΛΛβ", false, Right, cx);
1531 assert("ΛβΛ", true, Right, cx);
1532 assert("ΛΛπ", false, Left, cx);
1533 assert("ΛΛπ", true, Left, cx);
1534 assert("ΛΛπ", false, Right, cx);
1535 assert("ΛπΛ", true, Right, cx);
1536 assert("ΛΛ\t", false, Left, cx);
1537 assert("ΛΛ\t", true, Left, cx);
1538 assert("ΛΛ\t", false, Right, cx);
1539 assert("Λ\tΛ", true, Right, cx);
1540 assert(" ΛΛ\t", false, Left, cx);
1541 assert(" ΛΛ\t", true, Left, cx);
1542 assert(" ΛΛ\t", false, Right, cx);
1543 assert(" Λ\tΛ", true, Right, cx);
1544 assert(" ΛΛ\t", false, Left, cx);
1545 assert(" ΛΛ\t", false, Right, cx);
1546 }
1547
1548 #[gpui::test]
1549 fn test_clip_at_line_ends(cx: &mut gpui::MutableAppContext) {
1550 cx.set_global(Settings::test(cx));
1551
1552 fn assert(text: &str, cx: &mut gpui::MutableAppContext) {
1553 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1554 unmarked_snapshot.clip_at_line_ends = true;
1555 assert_eq!(
1556 unmarked_snapshot.clip_point(markers[1], Bias::Left),
1557 markers[0]
1558 );
1559 }
1560
1561 assert("ΛΛ", cx);
1562 assert("ΛaΛ", cx);
1563 assert("aΛbΛ", cx);
1564 assert("aΛΞ±Λ", cx);
1565 }
1566
1567 #[gpui::test]
1568 fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1569 cx.set_global(Settings::test(cx));
1570 let text = "β
\t\tΞ±\nΞ²\t\nπΞ²\t\tΞ³";
1571 let buffer = MultiBuffer::build_simple(text, cx);
1572 let font_cache = cx.font_cache();
1573 let family_id = font_cache
1574 .load_family(&["Helvetica"], &Default::default())
1575 .unwrap();
1576 let font_id = font_cache
1577 .select_font(family_id, &Default::default())
1578 .unwrap();
1579 let font_size = 14.0;
1580
1581 let map =
1582 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1583 let map = map.update(cx, |map, cx| map.snapshot(cx));
1584 assert_eq!(map.text(), "β
Ξ±\nΞ² \nπΞ² Ξ³");
1585 assert_eq!(
1586 map.text_chunks(0).collect::<String>(),
1587 "β
Ξ±\nΞ² \nπΞ² Ξ³"
1588 );
1589 assert_eq!(map.text_chunks(1).collect::<String>(), "Ξ² \nπΞ² Ξ³");
1590 assert_eq!(map.text_chunks(2).collect::<String>(), "πΞ² Ξ³");
1591
1592 let point = Point::new(0, "β
\t\t".len() as u32);
1593 let display_point = DisplayPoint::new(0, "β
".len() as u32);
1594 assert_eq!(point.to_display_point(&map), display_point);
1595 assert_eq!(display_point.to_point(&map), point);
1596
1597 let point = Point::new(1, "Ξ²\t".len() as u32);
1598 let display_point = DisplayPoint::new(1, "Ξ² ".len() as u32);
1599 assert_eq!(point.to_display_point(&map), display_point);
1600 assert_eq!(display_point.to_point(&map), point,);
1601
1602 let point = Point::new(2, "πΞ²\t\t".len() as u32);
1603 let display_point = DisplayPoint::new(2, "πΞ² ".len() as u32);
1604 assert_eq!(point.to_display_point(&map), display_point);
1605 assert_eq!(display_point.to_point(&map), point,);
1606
1607 // Display points inside of expanded tabs
1608 assert_eq!(
1609 DisplayPoint::new(0, "β
".len() as u32).to_point(&map),
1610 Point::new(0, "β
\t".len() as u32),
1611 );
1612 assert_eq!(
1613 DisplayPoint::new(0, "β
".len() as u32).to_point(&map),
1614 Point::new(0, "β
".len() as u32),
1615 );
1616
1617 // Clipping display points inside of multi-byte characters
1618 assert_eq!(
1619 map.clip_point(DisplayPoint::new(0, "β
".len() as u32 - 1), Left),
1620 DisplayPoint::new(0, 0)
1621 );
1622 assert_eq!(
1623 map.clip_point(DisplayPoint::new(0, "β
".len() as u32 - 1), Bias::Right),
1624 DisplayPoint::new(0, "β
".len() as u32)
1625 );
1626 }
1627
1628 #[gpui::test]
1629 fn test_max_point(cx: &mut gpui::MutableAppContext) {
1630 cx.set_global(Settings::test(cx));
1631 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1632 let font_cache = cx.font_cache();
1633 let family_id = font_cache
1634 .load_family(&["Helvetica"], &Default::default())
1635 .unwrap();
1636 let font_id = font_cache
1637 .select_font(family_id, &Default::default())
1638 .unwrap();
1639 let font_size = 14.0;
1640 let map =
1641 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1642 assert_eq!(
1643 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1644 DisplayPoint::new(1, 11)
1645 )
1646 }
1647
1648 #[test]
1649 fn test_find_internal() {
1650 assert("This is a Λtest of find internal", "test");
1651 assert("Some text ΛaΛaΛaa with repeated characters", "aa");
1652
1653 fn assert(marked_text: &str, target: &str) {
1654 let (text, expected_offsets) = marked_text_offsets(marked_text);
1655
1656 let chars = text
1657 .chars()
1658 .enumerate()
1659 .map(|(index, ch)| (ch, DisplayPoint::new(0, index as u32)));
1660 let target = target.chars();
1661
1662 assert_eq!(
1663 expected_offsets
1664 .into_iter()
1665 .map(|offset| offset as u32)
1666 .collect::<Vec<_>>(),
1667 DisplaySnapshot::find_internal(chars, target.collect(), |_, _| true)
1668 .map(|point| point.column())
1669 .collect::<Vec<_>>()
1670 )
1671 }
1672 }
1673
1674 fn syntax_chunks<'a>(
1675 rows: Range<u32>,
1676 map: &ModelHandle<DisplayMap>,
1677 theme: &'a SyntaxTheme,
1678 cx: &mut MutableAppContext,
1679 ) -> Vec<(String, Option<Color>)> {
1680 chunks(rows, map, theme, cx)
1681 .into_iter()
1682 .map(|(text, color, _)| (text, color))
1683 .collect()
1684 }
1685
1686 fn chunks<'a>(
1687 rows: Range<u32>,
1688 map: &ModelHandle<DisplayMap>,
1689 theme: &'a SyntaxTheme,
1690 cx: &mut MutableAppContext,
1691 ) -> Vec<(String, Option<Color>, Option<Color>)> {
1692 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1693 let mut chunks: Vec<(String, Option<Color>, Option<Color>)> = Vec::new();
1694 for chunk in snapshot.chunks(rows, true) {
1695 let syntax_color = chunk
1696 .syntax_highlight_id
1697 .and_then(|id| id.style(theme)?.color);
1698 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1699 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1700 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1701 last_chunk.push_str(chunk.text);
1702 continue;
1703 }
1704 }
1705 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1706 }
1707 chunks
1708 }
1709}