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