1mod block_map;
2mod fold_map;
3mod tab_map;
4mod wrap_map;
5
6use crate::{Anchor, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint};
7use block_map::{BlockMap, BlockPoint};
8use collections::{HashMap, HashSet};
9use fold_map::FoldMap;
10use gpui::{
11 fonts::{FontId, HighlightStyle},
12 Entity, ModelContext, ModelHandle,
13};
14use language::{Point, Subscription as BufferSubscription};
15use std::{any::TypeId, fmt::Debug, ops::Range, sync::Arc};
16use sum_tree::{Bias, TreeMap};
17use tab_map::TabMap;
18use wrap_map::WrapMap;
19
20pub use block_map::{
21 BlockBufferRows as DisplayBufferRows, BlockChunks as DisplayChunks, BlockContext,
22 BlockDisposition, BlockId, BlockProperties, RenderBlock, TransformBlock,
23};
24
25pub trait ToDisplayPoint {
26 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
27}
28
29type TextHighlights = TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>;
30
31pub struct DisplayMap {
32 buffer: ModelHandle<MultiBuffer>,
33 buffer_subscription: BufferSubscription,
34 fold_map: FoldMap,
35 tab_map: TabMap,
36 wrap_map: ModelHandle<WrapMap>,
37 block_map: BlockMap,
38 text_highlights: TextHighlights,
39}
40
41impl Entity for DisplayMap {
42 type Event = ();
43}
44
45impl DisplayMap {
46 pub fn new(
47 buffer: ModelHandle<MultiBuffer>,
48 tab_size: usize,
49 font_id: FontId,
50 font_size: f32,
51 wrap_width: Option<f32>,
52 buffer_header_height: u8,
53 excerpt_header_height: u8,
54 cx: &mut ModelContext<Self>,
55 ) -> Self {
56 let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
57 let (fold_map, snapshot) = FoldMap::new(buffer.read(cx).snapshot(cx));
58 let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
59 let (wrap_map, snapshot) = WrapMap::new(snapshot, font_id, font_size, wrap_width, cx);
60 let block_map = BlockMap::new(snapshot, buffer_header_height, excerpt_header_height);
61 cx.observe(&wrap_map, |_, _, cx| cx.notify()).detach();
62 DisplayMap {
63 buffer,
64 buffer_subscription,
65 fold_map,
66 tab_map,
67 wrap_map,
68 block_map,
69 text_highlights: Default::default(),
70 }
71 }
72
73 pub fn snapshot(&self, cx: &mut ModelContext<Self>) -> DisplaySnapshot {
74 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
75 let edits = self.buffer_subscription.consume().into_inner();
76 let (folds_snapshot, edits) = self.fold_map.read(buffer_snapshot, edits);
77 let (tabs_snapshot, edits) = self.tab_map.sync(folds_snapshot.clone(), edits);
78 let (wraps_snapshot, edits) = self
79 .wrap_map
80 .update(cx, |map, cx| map.sync(tabs_snapshot.clone(), edits, cx));
81 let blocks_snapshot = self.block_map.read(wraps_snapshot.clone(), edits);
82
83 DisplaySnapshot {
84 buffer_snapshot: self.buffer.read(cx).snapshot(cx),
85 folds_snapshot,
86 tabs_snapshot,
87 wraps_snapshot,
88 blocks_snapshot,
89 text_highlights: self.text_highlights.clone(),
90 }
91 }
92
93 pub fn fold<T: ToOffset>(
94 &mut self,
95 ranges: impl IntoIterator<Item = Range<T>>,
96 cx: &mut ModelContext<Self>,
97 ) {
98 let snapshot = self.buffer.read(cx).snapshot(cx);
99 let edits = self.buffer_subscription.consume().into_inner();
100 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
101 let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
102 let (snapshot, edits) = self
103 .wrap_map
104 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
105 self.block_map.read(snapshot, edits);
106 let (snapshot, edits) = fold_map.fold(ranges);
107 let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
108 let (snapshot, edits) = self
109 .wrap_map
110 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
111 self.block_map.read(snapshot, edits);
112 }
113
114 pub fn unfold<T: ToOffset>(
115 &mut self,
116 ranges: impl IntoIterator<Item = Range<T>>,
117 cx: &mut ModelContext<Self>,
118 ) {
119 let snapshot = self.buffer.read(cx).snapshot(cx);
120 let edits = self.buffer_subscription.consume().into_inner();
121 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
122 let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
123 let (snapshot, edits) = self
124 .wrap_map
125 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
126 self.block_map.read(snapshot, edits);
127 let (snapshot, edits) = fold_map.unfold(ranges);
128 let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
129 let (snapshot, edits) = self
130 .wrap_map
131 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
132 self.block_map.read(snapshot, edits);
133 }
134
135 pub fn insert_blocks(
136 &mut self,
137 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
138 cx: &mut ModelContext<Self>,
139 ) -> Vec<BlockId> {
140 let snapshot = self.buffer.read(cx).snapshot(cx);
141 let edits = self.buffer_subscription.consume().into_inner();
142 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
143 let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
144 let (snapshot, edits) = self
145 .wrap_map
146 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
147 let mut block_map = self.block_map.write(snapshot, edits);
148 block_map.insert(blocks)
149 }
150
151 pub fn replace_blocks(&mut self, styles: HashMap<BlockId, RenderBlock>) {
152 self.block_map.replace(styles);
153 }
154
155 pub fn remove_blocks(&mut self, ids: HashSet<BlockId>, cx: &mut ModelContext<Self>) {
156 let snapshot = self.buffer.read(cx).snapshot(cx);
157 let edits = self.buffer_subscription.consume().into_inner();
158 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
159 let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
160 let (snapshot, edits) = self
161 .wrap_map
162 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
163 let mut block_map = self.block_map.write(snapshot, edits);
164 block_map.remove(ids);
165 }
166
167 pub fn highlight_text(
168 &mut self,
169 type_id: TypeId,
170 ranges: Vec<Range<Anchor>>,
171 style: HighlightStyle,
172 ) {
173 self.text_highlights
174 .insert(Some(type_id), Arc::new((style, ranges)));
175 }
176
177 pub fn clear_text_highlights(
178 &mut self,
179 type_id: TypeId,
180 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
181 self.text_highlights.remove(&Some(type_id))
182 }
183
184 pub fn set_font(&self, font_id: FontId, font_size: f32, cx: &mut ModelContext<Self>) {
185 self.wrap_map
186 .update(cx, |map, cx| map.set_font(font_id, font_size, cx));
187 }
188
189 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut ModelContext<Self>) -> bool {
190 self.wrap_map
191 .update(cx, |map, cx| map.set_wrap_width(width, cx))
192 }
193
194 #[cfg(test)]
195 pub fn is_rewrapping(&self, cx: &gpui::AppContext) -> bool {
196 self.wrap_map.read(cx).is_rewrapping()
197 }
198}
199
200pub struct DisplaySnapshot {
201 pub buffer_snapshot: MultiBufferSnapshot,
202 folds_snapshot: fold_map::FoldSnapshot,
203 tabs_snapshot: tab_map::TabSnapshot,
204 wraps_snapshot: wrap_map::WrapSnapshot,
205 blocks_snapshot: block_map::BlockSnapshot,
206 text_highlights: TextHighlights,
207}
208
209impl DisplaySnapshot {
210 #[cfg(test)]
211 pub fn fold_count(&self) -> usize {
212 self.folds_snapshot.fold_count()
213 }
214
215 pub fn is_empty(&self) -> bool {
216 self.buffer_snapshot.len() == 0
217 }
218
219 pub fn buffer_rows<'a>(&'a self, start_row: u32) -> DisplayBufferRows<'a> {
220 self.blocks_snapshot.buffer_rows(start_row)
221 }
222
223 pub fn max_buffer_row(&self) -> u32 {
224 self.buffer_snapshot.max_buffer_row()
225 }
226
227 pub fn prev_line_boundary(&self, mut point: Point) -> (Point, DisplayPoint) {
228 loop {
229 let mut fold_point = self.folds_snapshot.to_fold_point(point, Bias::Left);
230 *fold_point.column_mut() = 0;
231 point = fold_point.to_buffer_point(&self.folds_snapshot);
232
233 let mut display_point = self.point_to_display_point(point, Bias::Left);
234 *display_point.column_mut() = 0;
235 let next_point = self.display_point_to_point(display_point, Bias::Left);
236 if next_point == point {
237 return (point, display_point);
238 }
239 point = next_point;
240 }
241 }
242
243 pub fn next_line_boundary(&self, mut point: Point) -> (Point, DisplayPoint) {
244 loop {
245 let mut fold_point = self.folds_snapshot.to_fold_point(point, Bias::Right);
246 *fold_point.column_mut() = self.folds_snapshot.line_len(fold_point.row());
247 point = fold_point.to_buffer_point(&self.folds_snapshot);
248
249 let mut display_point = self.point_to_display_point(point, Bias::Right);
250 *display_point.column_mut() = self.line_len(display_point.row());
251 let next_point = self.display_point_to_point(display_point, Bias::Right);
252 if next_point == point {
253 return (point, display_point);
254 }
255 point = next_point;
256 }
257 }
258
259 fn point_to_display_point(&self, point: Point, bias: Bias) -> DisplayPoint {
260 let fold_point = self.folds_snapshot.to_fold_point(point, bias);
261 let tab_point = self.tabs_snapshot.to_tab_point(fold_point);
262 let wrap_point = self.wraps_snapshot.from_tab_point(tab_point);
263 let block_point = self.blocks_snapshot.to_block_point(wrap_point);
264 DisplayPoint(block_point)
265 }
266
267 fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {
268 let block_point = point.0;
269 let wrap_point = self.blocks_snapshot.to_wrap_point(block_point);
270 let tab_point = self.wraps_snapshot.to_tab_point(wrap_point);
271 let fold_point = self.tabs_snapshot.to_fold_point(tab_point, bias).0;
272 fold_point.to_buffer_point(&self.folds_snapshot)
273 }
274
275 pub fn max_point(&self) -> DisplayPoint {
276 DisplayPoint(self.blocks_snapshot.max_point())
277 }
278
279 pub fn text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
280 self.blocks_snapshot
281 .chunks(display_row..self.max_point().row() + 1, false, None)
282 .map(|h| h.text)
283 }
284
285 pub fn chunks<'a>(
286 &'a self,
287 display_rows: Range<u32>,
288 language_aware: bool,
289 ) -> DisplayChunks<'a> {
290 self.blocks_snapshot
291 .chunks(display_rows, language_aware, Some(&self.text_highlights))
292 }
293
294 pub fn chars_at<'a>(&'a self, point: DisplayPoint) -> impl Iterator<Item = char> + 'a {
295 let mut column = 0;
296 let mut chars = self.text_chunks(point.row()).flat_map(str::chars);
297 while column < point.column() {
298 if let Some(c) = chars.next() {
299 column += c.len_utf8() as u32;
300 } else {
301 break;
302 }
303 }
304 chars
305 }
306
307 pub fn column_to_chars(&self, display_row: u32, target: u32) -> u32 {
308 let mut count = 0;
309 let mut column = 0;
310 for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
311 if column >= target {
312 break;
313 }
314 count += 1;
315 column += c.len_utf8() as u32;
316 }
317 count
318 }
319
320 pub fn column_from_chars(&self, display_row: u32, char_count: u32) -> u32 {
321 let mut count = 0;
322 let mut column = 0;
323 for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
324 if c == '\n' || count >= char_count {
325 break;
326 }
327 count += 1;
328 column += c.len_utf8() as u32;
329 }
330 column
331 }
332
333 pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
334 DisplayPoint(self.blocks_snapshot.clip_point(point.0, bias))
335 }
336
337 pub fn folds_in_range<'a, T>(
338 &'a self,
339 range: Range<T>,
340 ) -> impl Iterator<Item = &'a Range<Anchor>>
341 where
342 T: ToOffset,
343 {
344 self.folds_snapshot.folds_in_range(range)
345 }
346
347 pub fn blocks_in_range<'a>(
348 &'a self,
349 rows: Range<u32>,
350 ) -> impl Iterator<Item = (u32, &'a TransformBlock)> {
351 self.blocks_snapshot.blocks_in_range(rows)
352 }
353
354 pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
355 self.folds_snapshot.intersects_fold(offset)
356 }
357
358 pub fn is_line_folded(&self, display_row: u32) -> bool {
359 let block_point = BlockPoint(Point::new(display_row, 0));
360 let wrap_point = self.blocks_snapshot.to_wrap_point(block_point);
361 let tab_point = self.wraps_snapshot.to_tab_point(wrap_point);
362 self.folds_snapshot.is_line_folded(tab_point.row())
363 }
364
365 pub fn is_block_line(&self, display_row: u32) -> bool {
366 self.blocks_snapshot.is_block_line(display_row)
367 }
368
369 pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
370 let wrap_row = self
371 .blocks_snapshot
372 .to_wrap_point(BlockPoint::new(display_row, 0))
373 .row();
374 self.wraps_snapshot.soft_wrap_indent(wrap_row)
375 }
376
377 pub fn text(&self) -> String {
378 self.text_chunks(0).collect()
379 }
380
381 pub fn line(&self, display_row: u32) -> String {
382 let mut result = String::new();
383 for chunk in self.text_chunks(display_row) {
384 if let Some(ix) = chunk.find('\n') {
385 result.push_str(&chunk[0..ix]);
386 break;
387 } else {
388 result.push_str(chunk);
389 }
390 }
391 result
392 }
393
394 pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
395 let mut indent = 0;
396 let mut is_blank = true;
397 for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
398 if c == ' ' {
399 indent += 1;
400 } else {
401 is_blank = c == '\n';
402 break;
403 }
404 }
405 (indent, is_blank)
406 }
407
408 pub fn line_len(&self, row: u32) -> u32 {
409 self.blocks_snapshot.line_len(row)
410 }
411
412 pub fn longest_row(&self) -> u32 {
413 self.blocks_snapshot.longest_row()
414 }
415}
416
417#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
418pub struct DisplayPoint(BlockPoint);
419
420impl Debug for DisplayPoint {
421 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
422 f.write_fmt(format_args!(
423 "DisplayPoint({}, {})",
424 self.row(),
425 self.column()
426 ))
427 }
428}
429
430impl DisplayPoint {
431 pub fn new(row: u32, column: u32) -> Self {
432 Self(BlockPoint(Point::new(row, column)))
433 }
434
435 pub fn zero() -> Self {
436 Self::new(0, 0)
437 }
438
439 pub fn is_zero(&self) -> bool {
440 self.0.is_zero()
441 }
442
443 pub fn row(self) -> u32 {
444 self.0.row
445 }
446
447 pub fn column(self) -> u32 {
448 self.0.column
449 }
450
451 pub fn row_mut(&mut self) -> &mut u32 {
452 &mut self.0.row
453 }
454
455 pub fn column_mut(&mut self) -> &mut u32 {
456 &mut self.0.column
457 }
458
459 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
460 map.display_point_to_point(self, Bias::Left)
461 }
462
463 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
464 let unblocked_point = map.blocks_snapshot.to_wrap_point(self.0);
465 let unwrapped_point = map.wraps_snapshot.to_tab_point(unblocked_point);
466 let unexpanded_point = map.tabs_snapshot.to_fold_point(unwrapped_point, bias).0;
467 unexpanded_point.to_buffer_offset(&map.folds_snapshot)
468 }
469}
470
471impl ToDisplayPoint for usize {
472 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
473 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
474 }
475}
476
477impl ToDisplayPoint for Point {
478 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
479 map.point_to_display_point(*self, Bias::Left)
480 }
481}
482
483impl ToDisplayPoint for Anchor {
484 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
485 self.to_point(&map.buffer_snapshot).to_display_point(map)
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492 use crate::movement;
493 use gpui::{color::Color, elements::*, test::observe, MutableAppContext};
494 use language::{Buffer, Language, LanguageConfig, RandomCharIter, SelectionGoal};
495 use rand::{prelude::*, Rng};
496 use smol::stream::StreamExt;
497 use std::{env, sync::Arc};
498 use theme::SyntaxTheme;
499 use util::test::sample_text;
500 use Bias::*;
501
502 #[gpui::test(iterations = 100)]
503 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
504 cx.foreground().set_block_on_ticks(0..=50);
505 cx.foreground().forbid_parking();
506 let operations = env::var("OPERATIONS")
507 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
508 .unwrap_or(10);
509
510 let font_cache = cx.font_cache().clone();
511 let tab_size = rng.gen_range(1..=4);
512 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
513 let excerpt_header_height = rng.gen_range(1..=5);
514 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
515 let font_id = font_cache
516 .select_font(family_id, &Default::default())
517 .unwrap();
518 let font_size = 14.0;
519 let max_wrap_width = 300.0;
520 let mut wrap_width = if rng.gen_bool(0.1) {
521 None
522 } else {
523 Some(rng.gen_range(0.0..=max_wrap_width))
524 };
525
526 log::info!("tab size: {}", tab_size);
527 log::info!("wrap width: {:?}", wrap_width);
528
529 let buffer = cx.update(|cx| {
530 if rng.gen() {
531 let len = rng.gen_range(0..10);
532 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
533 MultiBuffer::build_simple(&text, cx)
534 } else {
535 MultiBuffer::build_random(&mut rng, cx)
536 }
537 });
538
539 let map = cx.add_model(|cx| {
540 DisplayMap::new(
541 buffer.clone(),
542 tab_size,
543 font_id,
544 font_size,
545 wrap_width,
546 buffer_start_excerpt_header_height,
547 excerpt_header_height,
548 cx,
549 )
550 });
551 let mut notifications = observe(&map, cx);
552 let mut fold_count = 0;
553 let mut blocks = Vec::new();
554
555 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
556 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
557 log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
558 log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
559 log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
560 log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
561 log::info!("display text: {:?}", snapshot.text());
562
563 for _i in 0..operations {
564 match rng.gen_range(0..100) {
565 0..=19 => {
566 wrap_width = if rng.gen_bool(0.2) {
567 None
568 } else {
569 Some(rng.gen_range(0.0..=max_wrap_width))
570 };
571 log::info!("setting wrap width to {:?}", wrap_width);
572 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
573 }
574 20..=44 => {
575 map.update(cx, |map, cx| {
576 if rng.gen() || blocks.is_empty() {
577 let buffer = map.snapshot(cx).buffer_snapshot;
578 let block_properties = (0..rng.gen_range(1..=1))
579 .map(|_| {
580 let position =
581 buffer.anchor_after(buffer.clip_offset(
582 rng.gen_range(0..=buffer.len()),
583 Bias::Left,
584 ));
585
586 let disposition = if rng.gen() {
587 BlockDisposition::Above
588 } else {
589 BlockDisposition::Below
590 };
591 let height = rng.gen_range(1..5);
592 log::info!(
593 "inserting block {:?} {:?} with height {}",
594 disposition,
595 position.to_point(&buffer),
596 height
597 );
598 BlockProperties {
599 position,
600 height,
601 disposition,
602 render: Arc::new(|_| Empty::new().boxed()),
603 }
604 })
605 .collect::<Vec<_>>();
606 blocks.extend(map.insert_blocks(block_properties, cx));
607 } else {
608 blocks.shuffle(&mut rng);
609 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
610 let block_ids_to_remove = (0..remove_count)
611 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
612 .collect();
613 log::info!("removing block ids {:?}", block_ids_to_remove);
614 map.remove_blocks(block_ids_to_remove, cx);
615 }
616 });
617 }
618 45..=79 => {
619 let mut ranges = Vec::new();
620 for _ in 0..rng.gen_range(1..=3) {
621 buffer.read_with(cx, |buffer, cx| {
622 let buffer = buffer.read(cx);
623 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
624 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
625 ranges.push(start..end);
626 });
627 }
628
629 if rng.gen() && fold_count > 0 {
630 log::info!("unfolding ranges: {:?}", ranges);
631 map.update(cx, |map, cx| {
632 map.unfold(ranges, cx);
633 });
634 } else {
635 log::info!("folding ranges: {:?}", ranges);
636 map.update(cx, |map, cx| {
637 map.fold(ranges, cx);
638 });
639 }
640 }
641 _ => {
642 buffer.update(cx, |buffer, cx| buffer.randomly_edit(&mut rng, 5, cx));
643 }
644 }
645
646 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
647 notifications.next().await.unwrap();
648 }
649
650 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
651 fold_count = snapshot.fold_count();
652 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
653 log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
654 log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
655 log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
656 log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
657 log::info!("display text: {:?}", snapshot.text());
658
659 // Line boundaries
660 let buffer = &snapshot.buffer_snapshot;
661 for _ in 0..5 {
662 let row = rng.gen_range(0..=buffer.max_point().row);
663 let column = rng.gen_range(0..=buffer.line_len(row));
664 let point = buffer.clip_point(Point::new(row, column), Left);
665
666 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
667 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
668
669 assert!(prev_buffer_bound <= point);
670 assert!(next_buffer_bound >= point);
671 assert_eq!(prev_buffer_bound.column, 0);
672 assert_eq!(prev_display_bound.column(), 0);
673 if next_buffer_bound < buffer.max_point() {
674 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
675 }
676
677 assert_eq!(
678 prev_display_bound,
679 prev_buffer_bound.to_display_point(&snapshot),
680 "row boundary before {:?}. reported buffer row boundary: {:?}",
681 point,
682 prev_buffer_bound
683 );
684 assert_eq!(
685 next_display_bound,
686 next_buffer_bound.to_display_point(&snapshot),
687 "display row boundary after {:?}. reported buffer row boundary: {:?}",
688 point,
689 next_buffer_bound
690 );
691 assert_eq!(
692 prev_buffer_bound,
693 prev_display_bound.to_point(&snapshot),
694 "row boundary before {:?}. reported display row boundary: {:?}",
695 point,
696 prev_display_bound
697 );
698 assert_eq!(
699 next_buffer_bound,
700 next_display_bound.to_point(&snapshot),
701 "row boundary after {:?}. reported display row boundary: {:?}",
702 point,
703 next_display_bound
704 );
705 }
706
707 // Movement
708 let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
709 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
710 for _ in 0..5 {
711 let row = rng.gen_range(0..=snapshot.max_point().row());
712 let column = rng.gen_range(0..=snapshot.line_len(row));
713 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
714
715 log::info!("Moving from point {:?}", point);
716
717 let moved_right = movement::right(&snapshot, point).unwrap();
718 log::info!("Right {:?}", moved_right);
719 if point < max_point {
720 assert!(moved_right > point);
721 if point.column() == snapshot.line_len(point.row())
722 || snapshot.soft_wrap_indent(point.row()).is_some()
723 && point.column() == snapshot.line_len(point.row()) - 1
724 {
725 assert!(moved_right.row() > point.row());
726 }
727 } else {
728 assert_eq!(moved_right, point);
729 }
730
731 let moved_left = movement::left(&snapshot, point).unwrap();
732 log::info!("Left {:?}", moved_left);
733 if point > min_point {
734 assert!(moved_left < point);
735 if point.column() == 0 {
736 assert!(moved_left.row() < point.row());
737 }
738 } else {
739 assert_eq!(moved_left, point);
740 }
741 }
742 }
743 }
744
745 #[gpui::test(retries = 5)]
746 fn test_soft_wraps(cx: &mut MutableAppContext) {
747 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
748 cx.foreground().forbid_parking();
749
750 let font_cache = cx.font_cache();
751
752 let tab_size = 4;
753 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
754 let font_id = font_cache
755 .select_font(family_id, &Default::default())
756 .unwrap();
757 let font_size = 12.0;
758 let wrap_width = Some(64.);
759
760 let text = "one two three four five\nsix seven eight";
761 let buffer = MultiBuffer::build_simple(text, cx);
762 let map = cx.add_model(|cx| {
763 DisplayMap::new(
764 buffer.clone(),
765 tab_size,
766 font_id,
767 font_size,
768 wrap_width,
769 1,
770 1,
771 cx,
772 )
773 });
774
775 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
776 assert_eq!(
777 snapshot.text_chunks(0).collect::<String>(),
778 "one two \nthree four \nfive\nsix seven \neight"
779 );
780 assert_eq!(
781 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
782 DisplayPoint::new(0, 7)
783 );
784 assert_eq!(
785 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
786 DisplayPoint::new(1, 0)
787 );
788 assert_eq!(
789 movement::right(&snapshot, DisplayPoint::new(0, 7)).unwrap(),
790 DisplayPoint::new(1, 0)
791 );
792 assert_eq!(
793 movement::left(&snapshot, DisplayPoint::new(1, 0)).unwrap(),
794 DisplayPoint::new(0, 7)
795 );
796 assert_eq!(
797 movement::up(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None).unwrap(),
798 (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
799 );
800 assert_eq!(
801 movement::down(
802 &snapshot,
803 DisplayPoint::new(0, 7),
804 SelectionGoal::Column(10)
805 )
806 .unwrap(),
807 (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
808 );
809 assert_eq!(
810 movement::down(
811 &snapshot,
812 DisplayPoint::new(1, 10),
813 SelectionGoal::Column(10)
814 )
815 .unwrap(),
816 (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
817 );
818
819 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
820 buffer.update(cx, |buffer, cx| {
821 buffer.edit(vec![ix..ix], "and ", cx);
822 });
823
824 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
825 assert_eq!(
826 snapshot.text_chunks(1).collect::<String>(),
827 "three four \nfive\nsix and \nseven eight"
828 );
829
830 // Re-wrap on font size changes
831 map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
832
833 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
834 assert_eq!(
835 snapshot.text_chunks(1).collect::<String>(),
836 "three \nfour five\nsix and \nseven \neight"
837 )
838 }
839
840 #[gpui::test]
841 fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
842 let text = sample_text(6, 6, 'a');
843 let buffer = MultiBuffer::build_simple(&text, cx);
844 let tab_size = 4;
845 let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
846 let font_id = cx
847 .font_cache()
848 .select_font(family_id, &Default::default())
849 .unwrap();
850 let font_size = 14.0;
851 let map = cx.add_model(|cx| {
852 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, 1, 1, cx)
853 });
854 buffer.update(cx, |buffer, cx| {
855 buffer.edit(
856 vec![
857 Point::new(1, 0)..Point::new(1, 0),
858 Point::new(1, 1)..Point::new(1, 1),
859 Point::new(2, 1)..Point::new(2, 1),
860 ],
861 "\t",
862 cx,
863 )
864 });
865
866 assert_eq!(
867 map.update(cx, |map, cx| map.snapshot(cx))
868 .text_chunks(1)
869 .collect::<String>()
870 .lines()
871 .next(),
872 Some(" b bbbbb")
873 );
874 assert_eq!(
875 map.update(cx, |map, cx| map.snapshot(cx))
876 .text_chunks(2)
877 .collect::<String>()
878 .lines()
879 .next(),
880 Some("c ccccc")
881 );
882 }
883
884 #[gpui::test]
885 async fn test_chunks(cx: &mut gpui::TestAppContext) {
886 use unindent::Unindent as _;
887
888 let text = r#"
889 fn outer() {}
890
891 mod module {
892 fn inner() {}
893 }"#
894 .unindent();
895
896 let theme = SyntaxTheme::new(vec![
897 ("mod.body".to_string(), Color::red().into()),
898 ("fn.name".to_string(), Color::blue().into()),
899 ]);
900 let language = Arc::new(
901 Language::new(
902 LanguageConfig {
903 name: "Test".into(),
904 path_suffixes: vec![".test".to_string()],
905 ..Default::default()
906 },
907 Some(tree_sitter_rust::language()),
908 )
909 .with_highlights_query(
910 r#"
911 (mod_item name: (identifier) body: _ @mod.body)
912 (function_item name: (identifier) @fn.name)
913 "#,
914 )
915 .unwrap(),
916 );
917 language.set_theme(&theme);
918
919 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
920 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
921 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
922
923 let tab_size = 2;
924 let font_cache = cx.font_cache();
925 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
926 let font_id = font_cache
927 .select_font(family_id, &Default::default())
928 .unwrap();
929 let font_size = 14.0;
930
931 let map = cx
932 .add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, 1, 1, cx));
933 assert_eq!(
934 cx.update(|cx| chunks(0..5, &map, &theme, cx)),
935 vec![
936 ("fn ".to_string(), None),
937 ("outer".to_string(), Some(Color::blue())),
938 ("() {}\n\nmod module ".to_string(), None),
939 ("{\n fn ".to_string(), Some(Color::red())),
940 ("inner".to_string(), Some(Color::blue())),
941 ("() {}\n}".to_string(), Some(Color::red())),
942 ]
943 );
944 assert_eq!(
945 cx.update(|cx| chunks(3..5, &map, &theme, cx)),
946 vec![
947 (" fn ".to_string(), Some(Color::red())),
948 ("inner".to_string(), Some(Color::blue())),
949 ("() {}\n}".to_string(), Some(Color::red())),
950 ]
951 );
952
953 map.update(cx, |map, cx| {
954 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
955 });
956 assert_eq!(
957 cx.update(|cx| chunks(0..2, &map, &theme, cx)),
958 vec![
959 ("fn ".to_string(), None),
960 ("out".to_string(), Some(Color::blue())),
961 ("…".to_string(), None),
962 (" fn ".to_string(), Some(Color::red())),
963 ("inner".to_string(), Some(Color::blue())),
964 ("() {}\n}".to_string(), Some(Color::red())),
965 ]
966 );
967 }
968
969 #[gpui::test]
970 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
971 use unindent::Unindent as _;
972
973 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
974
975 let text = r#"
976 fn outer() {}
977
978 mod module {
979 fn inner() {}
980 }"#
981 .unindent();
982
983 let theme = SyntaxTheme::new(vec![
984 ("mod.body".to_string(), Color::red().into()),
985 ("fn.name".to_string(), Color::blue().into()),
986 ]);
987 let language = Arc::new(
988 Language::new(
989 LanguageConfig {
990 name: "Test".into(),
991 path_suffixes: vec![".test".to_string()],
992 ..Default::default()
993 },
994 Some(tree_sitter_rust::language()),
995 )
996 .with_highlights_query(
997 r#"
998 (mod_item name: (identifier) body: _ @mod.body)
999 (function_item name: (identifier) @fn.name)
1000 "#,
1001 )
1002 .unwrap(),
1003 );
1004 language.set_theme(&theme);
1005
1006 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1007 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
1008 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1009
1010 let font_cache = cx.font_cache();
1011
1012 let tab_size = 4;
1013 let family_id = font_cache.load_family(&["Courier"]).unwrap();
1014 let font_id = font_cache
1015 .select_font(family_id, &Default::default())
1016 .unwrap();
1017 let font_size = 16.0;
1018
1019 let map = cx.add_model(|cx| {
1020 DisplayMap::new(buffer, tab_size, font_id, font_size, Some(40.0), 1, 1, cx)
1021 });
1022 assert_eq!(
1023 cx.update(|cx| chunks(0..5, &map, &theme, cx)),
1024 [
1025 ("fn \n".to_string(), None),
1026 ("oute\nr".to_string(), Some(Color::blue())),
1027 ("() \n{}\n\n".to_string(), None),
1028 ]
1029 );
1030 assert_eq!(
1031 cx.update(|cx| chunks(3..5, &map, &theme, cx)),
1032 [("{}\n\n".to_string(), None)]
1033 );
1034
1035 map.update(cx, |map, cx| {
1036 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1037 });
1038 assert_eq!(
1039 cx.update(|cx| chunks(1..4, &map, &theme, cx)),
1040 [
1041 ("out".to_string(), Some(Color::blue())),
1042 ("…\n".to_string(), None),
1043 (" \nfn ".to_string(), Some(Color::red())),
1044 ("i\n".to_string(), Some(Color::blue()))
1045 ]
1046 );
1047 }
1048
1049 #[gpui::test]
1050 fn test_clip_point(cx: &mut gpui::MutableAppContext) {
1051 use Bias::{Left, Right};
1052
1053 let text = "\n'a', 'α',\t'✋',\t'❎', '🍐'\n";
1054 let display_text = "\n'a', 'α', '✋', '❎', '🍐'\n";
1055 let buffer = MultiBuffer::build_simple(text, cx);
1056
1057 let tab_size = 4;
1058 let font_cache = cx.font_cache();
1059 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1060 let font_id = font_cache
1061 .select_font(family_id, &Default::default())
1062 .unwrap();
1063 let font_size = 14.0;
1064 let map = cx.add_model(|cx| {
1065 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, 1, 1, cx)
1066 });
1067 let map = map.update(cx, |map, cx| map.snapshot(cx));
1068
1069 assert_eq!(map.text(), display_text);
1070 for (input_column, bias, output_column) in vec![
1071 ("'a', '".len(), Left, "'a', '".len()),
1072 ("'a', '".len() + 1, Left, "'a', '".len()),
1073 ("'a', '".len() + 1, Right, "'a', 'α".len()),
1074 ("'a', 'α', ".len(), Left, "'a', 'α',".len()),
1075 ("'a', 'α', ".len(), Right, "'a', 'α', ".len()),
1076 ("'a', 'α', '".len() + 1, Left, "'a', 'α', '".len()),
1077 ("'a', 'α', '".len() + 1, Right, "'a', 'α', '✋".len()),
1078 ("'a', 'α', '✋',".len(), Right, "'a', 'α', '✋',".len()),
1079 ("'a', 'α', '✋', ".len(), Left, "'a', 'α', '✋',".len()),
1080 (
1081 "'a', 'α', '✋', ".len(),
1082 Right,
1083 "'a', 'α', '✋', ".len(),
1084 ),
1085 ] {
1086 assert_eq!(
1087 map.clip_point(DisplayPoint::new(1, input_column as u32), bias),
1088 DisplayPoint::new(1, output_column as u32),
1089 "clip_point(({}, {}))",
1090 1,
1091 input_column,
1092 );
1093 }
1094 }
1095
1096 #[gpui::test]
1097 fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1098 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
1099 let buffer = MultiBuffer::build_simple(text, cx);
1100 let tab_size = 4;
1101 let font_cache = cx.font_cache();
1102 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1103 let font_id = font_cache
1104 .select_font(family_id, &Default::default())
1105 .unwrap();
1106 let font_size = 14.0;
1107
1108 let map = cx.add_model(|cx| {
1109 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, 1, 1, cx)
1110 });
1111 let map = map.update(cx, |map, cx| map.snapshot(cx));
1112 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
1113 assert_eq!(
1114 map.text_chunks(0).collect::<String>(),
1115 "✅ α\nβ \n🏀β γ"
1116 );
1117 assert_eq!(map.text_chunks(1).collect::<String>(), "β \n🏀β γ");
1118 assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β γ");
1119
1120 let point = Point::new(0, "✅\t\t".len() as u32);
1121 let display_point = DisplayPoint::new(0, "✅ ".len() as u32);
1122 assert_eq!(point.to_display_point(&map), display_point);
1123 assert_eq!(display_point.to_point(&map), point);
1124
1125 let point = Point::new(1, "β\t".len() as u32);
1126 let display_point = DisplayPoint::new(1, "β ".len() as u32);
1127 assert_eq!(point.to_display_point(&map), display_point);
1128 assert_eq!(display_point.to_point(&map), point,);
1129
1130 let point = Point::new(2, "🏀β\t\t".len() as u32);
1131 let display_point = DisplayPoint::new(2, "🏀β ".len() as u32);
1132 assert_eq!(point.to_display_point(&map), display_point);
1133 assert_eq!(display_point.to_point(&map), point,);
1134
1135 // Display points inside of expanded tabs
1136 assert_eq!(
1137 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1138 Point::new(0, "✅\t".len() as u32),
1139 );
1140 assert_eq!(
1141 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1142 Point::new(0, "✅".len() as u32),
1143 );
1144
1145 // Clipping display points inside of multi-byte characters
1146 assert_eq!(
1147 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Left),
1148 DisplayPoint::new(0, 0)
1149 );
1150 assert_eq!(
1151 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Bias::Right),
1152 DisplayPoint::new(0, "✅".len() as u32)
1153 );
1154 }
1155
1156 #[gpui::test]
1157 fn test_max_point(cx: &mut gpui::MutableAppContext) {
1158 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1159 let tab_size = 4;
1160 let font_cache = cx.font_cache();
1161 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1162 let font_id = font_cache
1163 .select_font(family_id, &Default::default())
1164 .unwrap();
1165 let font_size = 14.0;
1166 let map = cx.add_model(|cx| {
1167 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, 1, 1, cx)
1168 });
1169 assert_eq!(
1170 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1171 DisplayPoint::new(1, 11)
1172 )
1173 }
1174
1175 fn chunks<'a>(
1176 rows: Range<u32>,
1177 map: &ModelHandle<DisplayMap>,
1178 theme: &'a SyntaxTheme,
1179 cx: &mut MutableAppContext,
1180 ) -> Vec<(String, Option<Color>)> {
1181 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1182 let mut chunks: Vec<(String, Option<Color>)> = Vec::new();
1183 for chunk in snapshot.chunks(rows, true) {
1184 let color = chunk
1185 .syntax_highlight_id
1186 .and_then(|id| id.style(theme)?.color);
1187 if let Some((last_chunk, last_color)) = chunks.last_mut() {
1188 if color == *last_color {
1189 last_chunk.push_str(chunk.text);
1190 } else {
1191 chunks.push((chunk.text.to_string(), color));
1192 }
1193 } else {
1194 chunks.push((chunk.text.to_string(), color));
1195 }
1196 }
1197 chunks
1198 }
1199}