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