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