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