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