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