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