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