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