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