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