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