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