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