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