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