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