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