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