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