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