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