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