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