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