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