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