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 let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
645 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
646 for _ in 0..5 {
647 let row = rng.gen_range(0..=snapshot.max_point().row());
648 let column = rng.gen_range(0..=snapshot.line_len(row));
649 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
650
651 log::info!("Moving from point {:?}", point);
652
653 let moved_right = movement::right(&snapshot, point).unwrap();
654 log::info!("Right {:?}", moved_right);
655 if point < max_point {
656 assert!(moved_right > point);
657 if point.column() == snapshot.line_len(point.row())
658 || snapshot.soft_wrap_indent(point.row()).is_some()
659 && point.column() == snapshot.line_len(point.row()) - 1
660 {
661 assert!(moved_right.row() > point.row());
662 }
663 } else {
664 assert_eq!(moved_right, point);
665 }
666
667 let moved_left = movement::left(&snapshot, point).unwrap();
668 log::info!("Left {:?}", moved_left);
669 if point > min_point {
670 assert!(moved_left < point);
671 if point.column() == 0 {
672 assert!(moved_left.row() < point.row());
673 }
674 } else {
675 assert_eq!(moved_left, point);
676 }
677 }
678 }
679 }
680
681 #[gpui::test(retries = 5)]
682 fn test_soft_wraps(cx: &mut MutableAppContext) {
683 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
684 cx.foreground().forbid_parking();
685
686 let font_cache = cx.font_cache();
687
688 let tab_size = 4;
689 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
690 let font_id = font_cache
691 .select_font(family_id, &Default::default())
692 .unwrap();
693 let font_size = 12.0;
694 let wrap_width = Some(64.);
695
696 let text = "one two three four five\nsix seven eight";
697 let buffer = MultiBuffer::build_simple(text, cx);
698 let map = cx.add_model(|cx| {
699 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
700 });
701
702 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
703 assert_eq!(
704 snapshot.text_chunks(0).collect::<String>(),
705 "one two \nthree four \nfive\nsix seven \neight"
706 );
707 assert_eq!(
708 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
709 DisplayPoint::new(0, 7)
710 );
711 assert_eq!(
712 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
713 DisplayPoint::new(1, 0)
714 );
715 assert_eq!(
716 movement::right(&snapshot, DisplayPoint::new(0, 7)).unwrap(),
717 DisplayPoint::new(1, 0)
718 );
719 assert_eq!(
720 movement::left(&snapshot, DisplayPoint::new(1, 0)).unwrap(),
721 DisplayPoint::new(0, 7)
722 );
723 assert_eq!(
724 movement::up(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None).unwrap(),
725 (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
726 );
727 assert_eq!(
728 movement::down(
729 &snapshot,
730 DisplayPoint::new(0, 7),
731 SelectionGoal::Column(10)
732 )
733 .unwrap(),
734 (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
735 );
736 assert_eq!(
737 movement::down(
738 &snapshot,
739 DisplayPoint::new(1, 10),
740 SelectionGoal::Column(10)
741 )
742 .unwrap(),
743 (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
744 );
745
746 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
747 buffer.update(cx, |buffer, cx| {
748 buffer.edit(vec![ix..ix], "and ", cx);
749 });
750
751 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
752 assert_eq!(
753 snapshot.text_chunks(1).collect::<String>(),
754 "three four \nfive\nsix and \nseven eight"
755 );
756
757 // Re-wrap on font size changes
758 map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
759
760 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
761 assert_eq!(
762 snapshot.text_chunks(1).collect::<String>(),
763 "three \nfour five\nsix and \nseven \neight"
764 )
765 }
766
767 #[gpui::test]
768 fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
769 let text = sample_text(6, 6, 'a');
770 let buffer = MultiBuffer::build_simple(&text, cx);
771 let tab_size = 4;
772 let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
773 let font_id = cx
774 .font_cache()
775 .select_font(family_id, &Default::default())
776 .unwrap();
777 let font_size = 14.0;
778 let map = cx.add_model(|cx| {
779 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
780 });
781 buffer.update(cx, |buffer, cx| {
782 buffer.edit(
783 vec![
784 Point::new(1, 0)..Point::new(1, 0),
785 Point::new(1, 1)..Point::new(1, 1),
786 Point::new(2, 1)..Point::new(2, 1),
787 ],
788 "\t",
789 cx,
790 )
791 });
792
793 assert_eq!(
794 map.update(cx, |map, cx| map.snapshot(cx))
795 .text_chunks(1)
796 .collect::<String>()
797 .lines()
798 .next(),
799 Some(" b bbbbb")
800 );
801 assert_eq!(
802 map.update(cx, |map, cx| map.snapshot(cx))
803 .text_chunks(2)
804 .collect::<String>()
805 .lines()
806 .next(),
807 Some("c ccccc")
808 );
809 }
810
811 #[gpui::test]
812 async fn test_chunks(mut cx: gpui::TestAppContext) {
813 use unindent::Unindent as _;
814
815 let text = r#"
816 fn outer() {}
817
818 mod module {
819 fn inner() {}
820 }"#
821 .unindent();
822
823 let theme = SyntaxTheme::new(vec![
824 ("mod.body".to_string(), Color::red().into()),
825 ("fn.name".to_string(), Color::blue().into()),
826 ]);
827 let lang = Arc::new(
828 Language::new(
829 LanguageConfig {
830 name: "Test".to_string(),
831 path_suffixes: vec![".test".to_string()],
832 ..Default::default()
833 },
834 Some(tree_sitter_rust::language()),
835 )
836 .with_highlights_query(
837 r#"
838 (mod_item name: (identifier) body: _ @mod.body)
839 (function_item name: (identifier) @fn.name)
840 "#,
841 )
842 .unwrap(),
843 );
844 lang.set_theme(&theme);
845
846 let buffer =
847 cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
848 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
849 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
850
851 let tab_size = 2;
852 let font_cache = cx.font_cache();
853 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
854 let font_id = font_cache
855 .select_font(family_id, &Default::default())
856 .unwrap();
857 let font_size = 14.0;
858
859 let map =
860 cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
861 assert_eq!(
862 cx.update(|cx| chunks(0..5, &map, &theme, cx)),
863 vec![
864 ("fn ".to_string(), None),
865 ("outer".to_string(), Some(Color::blue())),
866 ("() {}\n\nmod module ".to_string(), None),
867 ("{\n fn ".to_string(), Some(Color::red())),
868 ("inner".to_string(), Some(Color::blue())),
869 ("() {}\n}".to_string(), Some(Color::red())),
870 ]
871 );
872 assert_eq!(
873 cx.update(|cx| chunks(3..5, &map, &theme, cx)),
874 vec![
875 (" fn ".to_string(), Some(Color::red())),
876 ("inner".to_string(), Some(Color::blue())),
877 ("() {}\n}".to_string(), Some(Color::red())),
878 ]
879 );
880
881 map.update(&mut cx, |map, cx| {
882 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
883 });
884 assert_eq!(
885 cx.update(|cx| chunks(0..2, &map, &theme, cx)),
886 vec![
887 ("fn ".to_string(), None),
888 ("out".to_string(), Some(Color::blue())),
889 ("…".to_string(), None),
890 (" fn ".to_string(), Some(Color::red())),
891 ("inner".to_string(), Some(Color::blue())),
892 ("() {}\n}".to_string(), Some(Color::red())),
893 ]
894 );
895 }
896
897 #[gpui::test]
898 async fn test_chunks_with_soft_wrapping(mut cx: gpui::TestAppContext) {
899 use unindent::Unindent as _;
900
901 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
902
903 let text = r#"
904 fn outer() {}
905
906 mod module {
907 fn inner() {}
908 }"#
909 .unindent();
910
911 let theme = SyntaxTheme::new(vec![
912 ("mod.body".to_string(), Color::red().into()),
913 ("fn.name".to_string(), Color::blue().into()),
914 ]);
915 let lang = Arc::new(
916 Language::new(
917 LanguageConfig {
918 name: "Test".to_string(),
919 path_suffixes: vec![".test".to_string()],
920 ..Default::default()
921 },
922 Some(tree_sitter_rust::language()),
923 )
924 .with_highlights_query(
925 r#"
926 (mod_item name: (identifier) body: _ @mod.body)
927 (function_item name: (identifier) @fn.name)
928 "#,
929 )
930 .unwrap(),
931 );
932 lang.set_theme(&theme);
933
934 let buffer =
935 cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
936 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
937 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
938
939 let font_cache = cx.font_cache();
940
941 let tab_size = 4;
942 let family_id = font_cache.load_family(&["Courier"]).unwrap();
943 let font_id = font_cache
944 .select_font(family_id, &Default::default())
945 .unwrap();
946 let font_size = 16.0;
947
948 let map = cx
949 .add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, Some(40.0), cx));
950 assert_eq!(
951 cx.update(|cx| chunks(0..5, &map, &theme, cx)),
952 [
953 ("fn \n".to_string(), None),
954 ("oute\nr".to_string(), Some(Color::blue())),
955 ("() \n{}\n\n".to_string(), None),
956 ]
957 );
958 assert_eq!(
959 cx.update(|cx| chunks(3..5, &map, &theme, cx)),
960 [("{}\n\n".to_string(), None)]
961 );
962
963 map.update(&mut cx, |map, cx| {
964 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
965 });
966 assert_eq!(
967 cx.update(|cx| chunks(1..4, &map, &theme, cx)),
968 [
969 ("out".to_string(), Some(Color::blue())),
970 ("…\n".to_string(), None),
971 (" \nfn ".to_string(), Some(Color::red())),
972 ("i\n".to_string(), Some(Color::blue()))
973 ]
974 );
975 }
976
977 #[gpui::test]
978 fn test_clip_point(cx: &mut gpui::MutableAppContext) {
979 use Bias::{Left, Right};
980
981 let text = "\n'a', 'α',\t'✋',\t'❎', '🍐'\n";
982 let display_text = "\n'a', 'α', '✋', '❎', '🍐'\n";
983 let buffer = MultiBuffer::build_simple(text, cx);
984
985 let tab_size = 4;
986 let font_cache = cx.font_cache();
987 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
988 let font_id = font_cache
989 .select_font(family_id, &Default::default())
990 .unwrap();
991 let font_size = 14.0;
992 let map = cx.add_model(|cx| {
993 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
994 });
995 let map = map.update(cx, |map, cx| map.snapshot(cx));
996
997 assert_eq!(map.text(), display_text);
998 for (input_column, bias, output_column) in vec![
999 ("'a', '".len(), Left, "'a', '".len()),
1000 ("'a', '".len() + 1, Left, "'a', '".len()),
1001 ("'a', '".len() + 1, Right, "'a', 'α".len()),
1002 ("'a', 'α', ".len(), Left, "'a', 'α',".len()),
1003 ("'a', 'α', ".len(), Right, "'a', 'α', ".len()),
1004 ("'a', 'α', '".len() + 1, Left, "'a', 'α', '".len()),
1005 ("'a', 'α', '".len() + 1, Right, "'a', 'α', '✋".len()),
1006 ("'a', 'α', '✋',".len(), Right, "'a', 'α', '✋',".len()),
1007 ("'a', 'α', '✋', ".len(), Left, "'a', 'α', '✋',".len()),
1008 (
1009 "'a', 'α', '✋', ".len(),
1010 Right,
1011 "'a', 'α', '✋', ".len(),
1012 ),
1013 ] {
1014 assert_eq!(
1015 map.clip_point(DisplayPoint::new(1, input_column as u32), bias),
1016 DisplayPoint::new(1, output_column as u32),
1017 "clip_point(({}, {}))",
1018 1,
1019 input_column,
1020 );
1021 }
1022 }
1023
1024 #[gpui::test]
1025 fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1026 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
1027 let buffer = MultiBuffer::build_simple(text, cx);
1028 let tab_size = 4;
1029 let font_cache = cx.font_cache();
1030 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1031 let font_id = font_cache
1032 .select_font(family_id, &Default::default())
1033 .unwrap();
1034 let font_size = 14.0;
1035
1036 let map = cx.add_model(|cx| {
1037 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1038 });
1039 let map = map.update(cx, |map, cx| map.snapshot(cx));
1040 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
1041 assert_eq!(
1042 map.text_chunks(0).collect::<String>(),
1043 "✅ α\nβ \n🏀β γ"
1044 );
1045 assert_eq!(map.text_chunks(1).collect::<String>(), "β \n🏀β γ");
1046 assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β γ");
1047
1048 let point = Point::new(0, "✅\t\t".len() as u32);
1049 let display_point = DisplayPoint::new(0, "✅ ".len() as u32);
1050 assert_eq!(point.to_display_point(&map), display_point);
1051 assert_eq!(display_point.to_point(&map), point);
1052
1053 let point = Point::new(1, "β\t".len() as u32);
1054 let display_point = DisplayPoint::new(1, "β ".len() as u32);
1055 assert_eq!(point.to_display_point(&map), display_point);
1056 assert_eq!(display_point.to_point(&map), point,);
1057
1058 let point = Point::new(2, "🏀β\t\t".len() as u32);
1059 let display_point = DisplayPoint::new(2, "🏀β ".len() as u32);
1060 assert_eq!(point.to_display_point(&map), display_point);
1061 assert_eq!(display_point.to_point(&map), point,);
1062
1063 // Display points inside of expanded tabs
1064 assert_eq!(
1065 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1066 Point::new(0, "✅\t".len() as u32),
1067 );
1068 assert_eq!(
1069 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1070 Point::new(0, "✅".len() as u32),
1071 );
1072
1073 // Clipping display points inside of multi-byte characters
1074 assert_eq!(
1075 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Left),
1076 DisplayPoint::new(0, 0)
1077 );
1078 assert_eq!(
1079 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Bias::Right),
1080 DisplayPoint::new(0, "✅".len() as u32)
1081 );
1082 }
1083
1084 #[gpui::test]
1085 fn test_max_point(cx: &mut gpui::MutableAppContext) {
1086 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1087 let tab_size = 4;
1088 let font_cache = cx.font_cache();
1089 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1090 let font_id = font_cache
1091 .select_font(family_id, &Default::default())
1092 .unwrap();
1093 let font_size = 14.0;
1094 let map = cx.add_model(|cx| {
1095 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1096 });
1097 assert_eq!(
1098 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1099 DisplayPoint::new(1, 11)
1100 )
1101 }
1102
1103 fn chunks<'a>(
1104 rows: Range<u32>,
1105 map: &ModelHandle<DisplayMap>,
1106 theme: &'a SyntaxTheme,
1107 cx: &mut MutableAppContext,
1108 ) -> Vec<(String, Option<Color>)> {
1109 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1110 let mut chunks: Vec<(String, Option<Color>)> = Vec::new();
1111 for chunk in snapshot.chunks(rows, Some(theme)) {
1112 let color = chunk.highlight_style.map(|s| s.color);
1113 if let Some((last_chunk, last_color)) = chunks.last_mut() {
1114 if color == *last_color {
1115 last_chunk.push_str(chunk.text);
1116 } else {
1117 chunks.push((chunk.text.to_string(), color));
1118 }
1119 } else {
1120 chunks.push((chunk.text.to_string(), color));
1121 }
1122 }
1123 chunks
1124 }
1125}