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 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 Point {
422 fn to_display_point(&self, map: &DisplayMapSnapshot) -> DisplayPoint {
423 map.point_to_display_point(*self, Bias::Left)
424 }
425}
426
427impl ToDisplayPoint for Anchor {
428 fn to_display_point(&self, map: &DisplayMapSnapshot) -> DisplayPoint {
429 self.to_point(&map.buffer_snapshot).to_display_point(map)
430 }
431}
432
433#[derive(Clone, Copy, Debug, PartialEq, Eq)]
434pub enum DisplayRow {
435 Buffer(u32),
436 Block(BlockId, Option<BlockStyle>),
437 Wrap,
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443 use crate::{movement, test::*};
444 use gpui::{color::Color, MutableAppContext};
445 use language::{Language, LanguageConfig, RandomCharIter, SelectionGoal};
446 use rand::{prelude::StdRng, Rng};
447 use std::{env, sync::Arc};
448 use theme::SyntaxTheme;
449 use Bias::*;
450
451 #[gpui::test(iterations = 100)]
452 async fn test_random(mut cx: gpui::TestAppContext, mut rng: StdRng) {
453 cx.foreground().set_block_on_ticks(0..=50);
454 cx.foreground().forbid_parking();
455 let operations = env::var("OPERATIONS")
456 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
457 .unwrap_or(10);
458
459 let font_cache = cx.font_cache().clone();
460 let tab_size = rng.gen_range(1..=4);
461 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
462 let font_id = font_cache
463 .select_font(family_id, &Default::default())
464 .unwrap();
465 let font_size = 14.0;
466 let max_wrap_width = 300.0;
467 let mut wrap_width = if rng.gen_bool(0.1) {
468 None
469 } else {
470 Some(rng.gen_range(0.0..=max_wrap_width))
471 };
472
473 log::info!("tab size: {}", tab_size);
474 log::info!("wrap width: {:?}", wrap_width);
475
476 let buffer = cx.add_model(|cx| {
477 let len = rng.gen_range(0..10);
478 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
479 Buffer::new(0, text, cx)
480 });
481
482 let map = cx.add_model(|cx| {
483 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
484 });
485 let (_observer, notifications) = Observer::new(&map, &mut cx);
486 let mut fold_count = 0;
487
488 for _i in 0..operations {
489 match rng.gen_range(0..100) {
490 0..=19 => {
491 wrap_width = if rng.gen_bool(0.2) {
492 None
493 } else {
494 Some(rng.gen_range(0.0..=max_wrap_width))
495 };
496 log::info!("setting wrap width to {:?}", wrap_width);
497 map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
498 }
499 20..=80 => {
500 let mut ranges = Vec::new();
501 for _ in 0..rng.gen_range(1..=3) {
502 buffer.read_with(&cx, |buffer, _| {
503 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
504 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
505 ranges.push(start..end);
506 });
507 }
508
509 if rng.gen() && fold_count > 0 {
510 log::info!("unfolding ranges: {:?}", ranges);
511 map.update(&mut cx, |map, cx| {
512 map.unfold(ranges, cx);
513 });
514 } else {
515 log::info!("folding ranges: {:?}", ranges);
516 map.update(&mut cx, |map, cx| {
517 map.fold(ranges, cx);
518 });
519 }
520 }
521 _ => {
522 buffer.update(&mut cx, |buffer, _| buffer.randomly_edit(&mut rng, 5));
523 }
524 }
525
526 if map.read_with(&cx, |map, cx| map.is_rewrapping(cx)) {
527 notifications.recv().await.unwrap();
528 }
529
530 let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
531 fold_count = snapshot.fold_count();
532 log::info!("buffer text: {:?}", buffer.read_with(&cx, |b, _| b.text()));
533 log::info!("display text: {:?}", snapshot.text());
534
535 // Line boundaries
536 for _ in 0..5 {
537 let row = rng.gen_range(0..=snapshot.max_point().row());
538 let column = rng.gen_range(0..=snapshot.line_len(row));
539 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
540
541 let (prev_display_bound, prev_buffer_bound) = snapshot.prev_row_boundary(point);
542 let (next_display_bound, next_buffer_bound) = snapshot.next_row_boundary(point);
543
544 assert!(prev_display_bound <= point);
545 assert!(next_display_bound >= point);
546 assert_eq!(prev_buffer_bound.column, 0);
547 assert_eq!(prev_display_bound.column(), 0);
548 if next_display_bound < snapshot.max_point() {
549 assert_eq!(
550 buffer
551 .read_with(&cx, |buffer, _| buffer.chars_at(next_buffer_bound).next()),
552 Some('\n')
553 )
554 }
555
556 assert_eq!(
557 prev_display_bound,
558 prev_buffer_bound.to_display_point(&snapshot),
559 "row boundary before {:?}. reported buffer row boundary: {:?}",
560 point,
561 prev_buffer_bound
562 );
563 assert_eq!(
564 next_display_bound,
565 next_buffer_bound.to_display_point(&snapshot),
566 "display row boundary after {:?}. reported buffer row boundary: {:?}",
567 point,
568 next_buffer_bound
569 );
570 assert_eq!(
571 prev_buffer_bound,
572 prev_display_bound.to_point(&snapshot),
573 "row boundary before {:?}. reported display row boundary: {:?}",
574 point,
575 prev_display_bound
576 );
577 assert_eq!(
578 next_buffer_bound,
579 next_display_bound.to_point(&snapshot),
580 "row boundary after {:?}. reported display row boundary: {:?}",
581 point,
582 next_display_bound
583 );
584 }
585
586 // Movement
587 for _ in 0..5 {
588 let row = rng.gen_range(0..=snapshot.max_point().row());
589 let column = rng.gen_range(0..=snapshot.line_len(row));
590 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
591
592 log::info!("Moving from point {:?}", point);
593
594 let moved_right = movement::right(&snapshot, point).unwrap();
595 log::info!("Right {:?}", moved_right);
596 if point < snapshot.max_point() {
597 assert!(moved_right > point);
598 if point.column() == snapshot.line_len(point.row())
599 || snapshot.soft_wrap_indent(point.row()).is_some()
600 && point.column() == snapshot.line_len(point.row()) - 1
601 {
602 assert!(moved_right.row() > point.row());
603 }
604 } else {
605 assert_eq!(moved_right, point);
606 }
607
608 let moved_left = movement::left(&snapshot, point).unwrap();
609 log::info!("Left {:?}", moved_left);
610 if !point.is_zero() {
611 assert!(moved_left < point);
612 if point.column() == 0 {
613 assert!(moved_left.row() < point.row());
614 }
615 } else {
616 assert!(moved_left.is_zero());
617 }
618 }
619 }
620 }
621
622 #[gpui::test(retries = 5)]
623 fn test_soft_wraps(cx: &mut MutableAppContext) {
624 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
625 cx.foreground().forbid_parking();
626
627 let font_cache = cx.font_cache();
628
629 let tab_size = 4;
630 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
631 let font_id = font_cache
632 .select_font(family_id, &Default::default())
633 .unwrap();
634 let font_size = 12.0;
635 let wrap_width = Some(64.);
636
637 let text = "one two three four five\nsix seven eight";
638 let buffer = cx.add_model(|cx| Buffer::new(0, text.to_string(), cx));
639 let map = cx.add_model(|cx| {
640 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
641 });
642
643 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
644 assert_eq!(
645 snapshot.text_chunks(0).collect::<String>(),
646 "one two \nthree four \nfive\nsix seven \neight"
647 );
648 assert_eq!(
649 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
650 DisplayPoint::new(0, 7)
651 );
652 assert_eq!(
653 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
654 DisplayPoint::new(1, 0)
655 );
656 assert_eq!(
657 movement::right(&snapshot, DisplayPoint::new(0, 7)).unwrap(),
658 DisplayPoint::new(1, 0)
659 );
660 assert_eq!(
661 movement::left(&snapshot, DisplayPoint::new(1, 0)).unwrap(),
662 DisplayPoint::new(0, 7)
663 );
664 assert_eq!(
665 movement::up(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None).unwrap(),
666 (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
667 );
668 assert_eq!(
669 movement::down(
670 &snapshot,
671 DisplayPoint::new(0, 7),
672 SelectionGoal::Column(10)
673 )
674 .unwrap(),
675 (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
676 );
677 assert_eq!(
678 movement::down(
679 &snapshot,
680 DisplayPoint::new(1, 10),
681 SelectionGoal::Column(10)
682 )
683 .unwrap(),
684 (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
685 );
686
687 buffer.update(cx, |buffer, cx| {
688 let ix = buffer.text().find("seven").unwrap();
689 buffer.edit(vec![ix..ix], "and ", cx);
690 });
691
692 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
693 assert_eq!(
694 snapshot.text_chunks(1).collect::<String>(),
695 "three four \nfive\nsix and \nseven eight"
696 );
697
698 // Re-wrap on font size changes
699 map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
700
701 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
702 assert_eq!(
703 snapshot.text_chunks(1).collect::<String>(),
704 "three \nfour five\nsix and \nseven \neight"
705 )
706 }
707
708 #[gpui::test]
709 fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
710 let text = sample_text(6, 6);
711 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
712 let tab_size = 4;
713 let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
714 let font_id = cx
715 .font_cache()
716 .select_font(family_id, &Default::default())
717 .unwrap();
718 let font_size = 14.0;
719 let map = cx.add_model(|cx| {
720 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
721 });
722 buffer.update(cx, |buffer, cx| {
723 buffer.edit(
724 vec![
725 Point::new(1, 0)..Point::new(1, 0),
726 Point::new(1, 1)..Point::new(1, 1),
727 Point::new(2, 1)..Point::new(2, 1),
728 ],
729 "\t",
730 cx,
731 )
732 });
733
734 assert_eq!(
735 map.update(cx, |map, cx| map.snapshot(cx))
736 .text_chunks(1)
737 .collect::<String>()
738 .lines()
739 .next(),
740 Some(" b bbbbb")
741 );
742 assert_eq!(
743 map.update(cx, |map, cx| map.snapshot(cx))
744 .text_chunks(2)
745 .collect::<String>()
746 .lines()
747 .next(),
748 Some("c ccccc")
749 );
750 }
751
752 #[gpui::test]
753 async fn test_chunks(mut cx: gpui::TestAppContext) {
754 use unindent::Unindent as _;
755
756 let text = r#"
757 fn outer() {}
758
759 mod module {
760 fn inner() {}
761 }"#
762 .unindent();
763
764 let theme = SyntaxTheme::new(vec![
765 ("mod.body".to_string(), Color::red().into()),
766 ("fn.name".to_string(), Color::blue().into()),
767 ]);
768 let lang = Arc::new(
769 Language::new(
770 LanguageConfig {
771 name: "Test".to_string(),
772 path_suffixes: vec![".test".to_string()],
773 ..Default::default()
774 },
775 tree_sitter_rust::language(),
776 )
777 .with_highlights_query(
778 r#"
779 (mod_item name: (identifier) body: _ @mod.body)
780 (function_item name: (identifier) @fn.name)
781 "#,
782 )
783 .unwrap(),
784 );
785 lang.set_theme(&theme);
786
787 let buffer =
788 cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
789 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
790
791 let tab_size = 2;
792 let font_cache = cx.font_cache();
793 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
794 let font_id = font_cache
795 .select_font(family_id, &Default::default())
796 .unwrap();
797 let font_size = 14.0;
798
799 let map =
800 cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
801 assert_eq!(
802 cx.update(|cx| chunks(0..5, &map, &theme, cx)),
803 vec![
804 ("fn ".to_string(), None),
805 ("outer".to_string(), Some(Color::blue())),
806 ("() {}\n\nmod module ".to_string(), None),
807 ("{\n fn ".to_string(), Some(Color::red())),
808 ("inner".to_string(), Some(Color::blue())),
809 ("() {}\n}".to_string(), Some(Color::red())),
810 ]
811 );
812 assert_eq!(
813 cx.update(|cx| chunks(3..5, &map, &theme, cx)),
814 vec![
815 (" fn ".to_string(), Some(Color::red())),
816 ("inner".to_string(), Some(Color::blue())),
817 ("() {}\n}".to_string(), Some(Color::red())),
818 ]
819 );
820
821 map.update(&mut cx, |map, cx| {
822 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
823 });
824 assert_eq!(
825 cx.update(|cx| chunks(0..2, &map, &theme, cx)),
826 vec![
827 ("fn ".to_string(), None),
828 ("out".to_string(), Some(Color::blue())),
829 ("…".to_string(), None),
830 (" fn ".to_string(), Some(Color::red())),
831 ("inner".to_string(), Some(Color::blue())),
832 ("() {}\n}".to_string(), Some(Color::red())),
833 ]
834 );
835 }
836
837 #[gpui::test]
838 async fn test_chunks_with_soft_wrapping(mut cx: gpui::TestAppContext) {
839 use unindent::Unindent as _;
840
841 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
842
843 let text = r#"
844 fn outer() {}
845
846 mod module {
847 fn inner() {}
848 }"#
849 .unindent();
850
851 let theme = SyntaxTheme::new(vec![
852 ("mod.body".to_string(), Color::red().into()),
853 ("fn.name".to_string(), Color::blue().into()),
854 ]);
855 let lang = Arc::new(
856 Language::new(
857 LanguageConfig {
858 name: "Test".to_string(),
859 path_suffixes: vec![".test".to_string()],
860 ..Default::default()
861 },
862 tree_sitter_rust::language(),
863 )
864 .with_highlights_query(
865 r#"
866 (mod_item name: (identifier) body: _ @mod.body)
867 (function_item name: (identifier) @fn.name)
868 "#,
869 )
870 .unwrap(),
871 );
872 lang.set_theme(&theme);
873
874 let buffer =
875 cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
876 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
877
878 let font_cache = cx.font_cache();
879
880 let tab_size = 4;
881 let family_id = font_cache.load_family(&["Courier"]).unwrap();
882 let font_id = font_cache
883 .select_font(family_id, &Default::default())
884 .unwrap();
885 let font_size = 16.0;
886
887 let map = cx
888 .add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, Some(40.0), cx));
889 assert_eq!(
890 cx.update(|cx| chunks(0..5, &map, &theme, cx)),
891 [
892 ("fn \n".to_string(), None),
893 ("oute\nr".to_string(), Some(Color::blue())),
894 ("() \n{}\n\n".to_string(), None),
895 ]
896 );
897 assert_eq!(
898 cx.update(|cx| chunks(3..5, &map, &theme, cx)),
899 [("{}\n\n".to_string(), None)]
900 );
901
902 map.update(&mut cx, |map, cx| {
903 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
904 });
905 assert_eq!(
906 cx.update(|cx| chunks(1..4, &map, &theme, cx)),
907 [
908 ("out".to_string(), Some(Color::blue())),
909 ("…\n".to_string(), None),
910 (" \nfn ".to_string(), Some(Color::red())),
911 ("i\n".to_string(), Some(Color::blue()))
912 ]
913 );
914 }
915
916 #[gpui::test]
917 fn test_clip_point(cx: &mut gpui::MutableAppContext) {
918 use Bias::{Left, Right};
919
920 let text = "\n'a', 'α',\t'✋',\t'❎', '🍐'\n";
921 let display_text = "\n'a', 'α', '✋', '❎', '🍐'\n";
922 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
923
924 let tab_size = 4;
925 let font_cache = cx.font_cache();
926 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
927 let font_id = font_cache
928 .select_font(family_id, &Default::default())
929 .unwrap();
930 let font_size = 14.0;
931 let map = cx.add_model(|cx| {
932 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
933 });
934 let map = map.update(cx, |map, cx| map.snapshot(cx));
935
936 assert_eq!(map.text(), display_text);
937 for (input_column, bias, output_column) in vec![
938 ("'a', '".len(), Left, "'a', '".len()),
939 ("'a', '".len() + 1, Left, "'a', '".len()),
940 ("'a', '".len() + 1, Right, "'a', 'α".len()),
941 ("'a', 'α', ".len(), Left, "'a', 'α',".len()),
942 ("'a', 'α', ".len(), Right, "'a', 'α', ".len()),
943 ("'a', 'α', '".len() + 1, Left, "'a', 'α', '".len()),
944 ("'a', 'α', '".len() + 1, Right, "'a', 'α', '✋".len()),
945 ("'a', 'α', '✋',".len(), Right, "'a', 'α', '✋',".len()),
946 ("'a', 'α', '✋', ".len(), Left, "'a', 'α', '✋',".len()),
947 (
948 "'a', 'α', '✋', ".len(),
949 Right,
950 "'a', 'α', '✋', ".len(),
951 ),
952 ] {
953 assert_eq!(
954 map.clip_point(DisplayPoint::new(1, input_column as u32), bias),
955 DisplayPoint::new(1, output_column as u32),
956 "clip_point(({}, {}))",
957 1,
958 input_column,
959 );
960 }
961 }
962
963 #[gpui::test]
964 fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
965 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
966 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
967 let tab_size = 4;
968 let font_cache = cx.font_cache();
969 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
970 let font_id = font_cache
971 .select_font(family_id, &Default::default())
972 .unwrap();
973 let font_size = 14.0;
974
975 let map = cx.add_model(|cx| {
976 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
977 });
978 let map = map.update(cx, |map, cx| map.snapshot(cx));
979 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
980 assert_eq!(
981 map.text_chunks(0).collect::<String>(),
982 "✅ α\nβ \n🏀β γ"
983 );
984 assert_eq!(map.text_chunks(1).collect::<String>(), "β \n🏀β γ");
985 assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β γ");
986
987 let point = Point::new(0, "✅\t\t".len() as u32);
988 let display_point = DisplayPoint::new(0, "✅ ".len() as u32);
989 assert_eq!(point.to_display_point(&map), display_point);
990 assert_eq!(display_point.to_point(&map), point);
991
992 let point = Point::new(1, "β\t".len() as u32);
993 let display_point = DisplayPoint::new(1, "β ".len() as u32);
994 assert_eq!(point.to_display_point(&map), display_point);
995 assert_eq!(display_point.to_point(&map), point,);
996
997 let point = Point::new(2, "🏀β\t\t".len() as u32);
998 let display_point = DisplayPoint::new(2, "🏀β ".len() as u32);
999 assert_eq!(point.to_display_point(&map), display_point);
1000 assert_eq!(display_point.to_point(&map), point,);
1001
1002 // Display points inside of expanded tabs
1003 assert_eq!(
1004 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1005 Point::new(0, "✅\t".len() as u32),
1006 );
1007 assert_eq!(
1008 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1009 Point::new(0, "✅".len() as u32),
1010 );
1011
1012 // Clipping display points inside of multi-byte characters
1013 assert_eq!(
1014 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Left),
1015 DisplayPoint::new(0, 0)
1016 );
1017 assert_eq!(
1018 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Bias::Right),
1019 DisplayPoint::new(0, "✅".len() as u32)
1020 );
1021 }
1022
1023 #[gpui::test]
1024 fn test_max_point(cx: &mut gpui::MutableAppContext) {
1025 let buffer = cx.add_model(|cx| Buffer::new(0, "aaa\n\t\tbbb", cx));
1026 let tab_size = 4;
1027 let font_cache = cx.font_cache();
1028 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1029 let font_id = font_cache
1030 .select_font(family_id, &Default::default())
1031 .unwrap();
1032 let font_size = 14.0;
1033 let map = cx.add_model(|cx| {
1034 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1035 });
1036 assert_eq!(
1037 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1038 DisplayPoint::new(1, 11)
1039 )
1040 }
1041
1042 fn chunks<'a>(
1043 rows: Range<u32>,
1044 map: &ModelHandle<DisplayMap>,
1045 theme: &'a SyntaxTheme,
1046 cx: &mut MutableAppContext,
1047 ) -> Vec<(String, Option<Color>)> {
1048 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1049 let mut chunks: Vec<(String, Option<Color>)> = Vec::new();
1050 for chunk in snapshot.chunks(rows, Some(theme), cx) {
1051 let color = chunk.highlight_style.map(|s| s.color);
1052 if let Some((last_chunk, last_color)) = chunks.last_mut() {
1053 if color == *last_color {
1054 last_chunk.push_str(chunk.text);
1055 } else {
1056 chunks.push((chunk.text.to_string(), color));
1057 }
1058 } else {
1059 chunks.push((chunk.text.to_string(), color));
1060 }
1061 }
1062 chunks
1063 }
1064}