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, elements::*, MutableAppContext};
497 use language::{Buffer, Language, LanguageConfig, RandomCharIter, SelectionGoal};
498 use rand::{prelude::*, 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 let mut blocks = Vec::new();
545
546 let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
547 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
548 log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
549 log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
550 log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
551 log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
552 log::info!("display text: {:?}", snapshot.text());
553
554 for _i in 0..operations {
555 match rng.gen_range(0..100) {
556 0..=19 => {
557 wrap_width = if rng.gen_bool(0.2) {
558 None
559 } else {
560 Some(rng.gen_range(0.0..=max_wrap_width))
561 };
562 log::info!("setting wrap width to {:?}", wrap_width);
563 map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
564 }
565 20..=44 => {
566 map.update(&mut cx, |map, cx| {
567 if rng.gen() || blocks.is_empty() {
568 let buffer = map.snapshot(cx).buffer_snapshot;
569 let block_properties = (0..rng.gen_range(1..=1))
570 .map(|_| {
571 let position =
572 buffer.anchor_after(buffer.clip_offset(
573 rng.gen_range(0..=buffer.len()),
574 Bias::Left,
575 ));
576
577 let disposition = if rng.gen() {
578 BlockDisposition::Above
579 } else {
580 BlockDisposition::Below
581 };
582 let height = rng.gen_range(1..5);
583 log::info!(
584 "inserting block {:?} {:?} with height {}",
585 disposition,
586 position.to_point(&buffer),
587 height
588 );
589 BlockProperties {
590 position,
591 height,
592 disposition,
593 render: Arc::new(|_| Empty::new().boxed()),
594 }
595 })
596 .collect::<Vec<_>>();
597 blocks.extend(map.insert_blocks(block_properties, cx));
598 } else {
599 blocks.shuffle(&mut rng);
600 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
601 let block_ids_to_remove = (0..remove_count)
602 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
603 .collect();
604 log::info!("removing block ids {:?}", block_ids_to_remove);
605 map.remove_blocks(block_ids_to_remove, cx);
606 }
607 });
608 }
609 45..=79 => {
610 let mut ranges = Vec::new();
611 for _ in 0..rng.gen_range(1..=3) {
612 buffer.read_with(&cx, |buffer, cx| {
613 let buffer = buffer.read(cx);
614 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
615 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
616 ranges.push(start..end);
617 });
618 }
619
620 if rng.gen() && fold_count > 0 {
621 log::info!("unfolding ranges: {:?}", ranges);
622 map.update(&mut cx, |map, cx| {
623 map.unfold(ranges, cx);
624 });
625 } else {
626 log::info!("folding ranges: {:?}", ranges);
627 map.update(&mut cx, |map, cx| {
628 map.fold(ranges, cx);
629 });
630 }
631 }
632 _ => {
633 buffer.update(&mut cx, |buffer, cx| buffer.randomly_edit(&mut rng, 5, cx));
634 }
635 }
636
637 if map.read_with(&cx, |map, cx| map.is_rewrapping(cx)) {
638 notifications.recv().await.unwrap();
639 }
640
641 let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
642 fold_count = snapshot.fold_count();
643 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
644 log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
645 log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
646 log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
647 log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
648 log::info!("display text: {:?}", snapshot.text());
649
650 // Line boundaries
651 for _ in 0..5 {
652 let row = rng.gen_range(0..=snapshot.max_point().row());
653 let column = rng.gen_range(0..=snapshot.line_len(row));
654 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
655
656 let (prev_display_bound, prev_buffer_bound) = snapshot.prev_row_boundary(point);
657 let (next_display_bound, next_buffer_bound) = snapshot.next_row_boundary(point);
658
659 assert!(prev_display_bound <= point);
660 assert!(next_display_bound >= point);
661 assert_eq!(prev_buffer_bound.column, 0);
662 assert_eq!(prev_display_bound.column(), 0);
663 if next_buffer_bound < snapshot.buffer_snapshot.max_point() {
664 assert_eq!(
665 snapshot.buffer_snapshot.chars_at(next_buffer_bound).next(),
666 Some('\n')
667 );
668 }
669
670 assert_eq!(
671 prev_display_bound,
672 prev_buffer_bound.to_display_point(&snapshot),
673 "row boundary before {:?}. reported buffer row boundary: {:?}",
674 point,
675 prev_buffer_bound
676 );
677 assert_eq!(
678 next_display_bound,
679 next_buffer_bound.to_display_point(&snapshot),
680 "display row boundary after {:?}. reported buffer row boundary: {:?}",
681 point,
682 next_buffer_bound
683 );
684 assert_eq!(
685 prev_buffer_bound,
686 prev_display_bound.to_point(&snapshot),
687 "row boundary before {:?}. reported display row boundary: {:?}",
688 point,
689 prev_display_bound
690 );
691 assert_eq!(
692 next_buffer_bound,
693 next_display_bound.to_point(&snapshot),
694 "row boundary after {:?}. reported display row boundary: {:?}",
695 point,
696 next_display_bound
697 );
698 }
699
700 // Movement
701 let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
702 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
703 for _ in 0..5 {
704 let row = rng.gen_range(0..=snapshot.max_point().row());
705 let column = rng.gen_range(0..=snapshot.line_len(row));
706 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
707
708 log::info!("Moving from point {:?}", point);
709
710 let moved_right = movement::right(&snapshot, point).unwrap();
711 log::info!("Right {:?}", moved_right);
712 if point < max_point {
713 assert!(moved_right > point);
714 if point.column() == snapshot.line_len(point.row())
715 || snapshot.soft_wrap_indent(point.row()).is_some()
716 && point.column() == snapshot.line_len(point.row()) - 1
717 {
718 assert!(moved_right.row() > point.row());
719 }
720 } else {
721 assert_eq!(moved_right, point);
722 }
723
724 let moved_left = movement::left(&snapshot, point).unwrap();
725 log::info!("Left {:?}", moved_left);
726 if point > min_point {
727 assert!(moved_left < point);
728 if point.column() == 0 {
729 assert!(moved_left.row() < point.row());
730 }
731 } else {
732 assert_eq!(moved_left, point);
733 }
734 }
735 }
736 }
737
738 #[gpui::test(retries = 5)]
739 fn test_soft_wraps(cx: &mut MutableAppContext) {
740 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
741 cx.foreground().forbid_parking();
742
743 let font_cache = cx.font_cache();
744
745 let tab_size = 4;
746 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
747 let font_id = font_cache
748 .select_font(family_id, &Default::default())
749 .unwrap();
750 let font_size = 12.0;
751 let wrap_width = Some(64.);
752
753 let text = "one two three four five\nsix seven eight";
754 let buffer = MultiBuffer::build_simple(text, cx);
755 let map = cx.add_model(|cx| {
756 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
757 });
758
759 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
760 assert_eq!(
761 snapshot.text_chunks(0).collect::<String>(),
762 "one two \nthree four \nfive\nsix seven \neight"
763 );
764 assert_eq!(
765 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
766 DisplayPoint::new(0, 7)
767 );
768 assert_eq!(
769 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
770 DisplayPoint::new(1, 0)
771 );
772 assert_eq!(
773 movement::right(&snapshot, DisplayPoint::new(0, 7)).unwrap(),
774 DisplayPoint::new(1, 0)
775 );
776 assert_eq!(
777 movement::left(&snapshot, DisplayPoint::new(1, 0)).unwrap(),
778 DisplayPoint::new(0, 7)
779 );
780 assert_eq!(
781 movement::up(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None).unwrap(),
782 (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
783 );
784 assert_eq!(
785 movement::down(
786 &snapshot,
787 DisplayPoint::new(0, 7),
788 SelectionGoal::Column(10)
789 )
790 .unwrap(),
791 (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
792 );
793 assert_eq!(
794 movement::down(
795 &snapshot,
796 DisplayPoint::new(1, 10),
797 SelectionGoal::Column(10)
798 )
799 .unwrap(),
800 (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
801 );
802
803 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
804 buffer.update(cx, |buffer, cx| {
805 buffer.edit(vec![ix..ix], "and ", cx);
806 });
807
808 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
809 assert_eq!(
810 snapshot.text_chunks(1).collect::<String>(),
811 "three four \nfive\nsix and \nseven eight"
812 );
813
814 // Re-wrap on font size changes
815 map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
816
817 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
818 assert_eq!(
819 snapshot.text_chunks(1).collect::<String>(),
820 "three \nfour five\nsix and \nseven \neight"
821 )
822 }
823
824 #[gpui::test]
825 fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
826 let text = sample_text(6, 6, 'a');
827 let buffer = MultiBuffer::build_simple(&text, cx);
828 let tab_size = 4;
829 let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
830 let font_id = cx
831 .font_cache()
832 .select_font(family_id, &Default::default())
833 .unwrap();
834 let font_size = 14.0;
835 let map = cx.add_model(|cx| {
836 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
837 });
838 buffer.update(cx, |buffer, cx| {
839 buffer.edit(
840 vec![
841 Point::new(1, 0)..Point::new(1, 0),
842 Point::new(1, 1)..Point::new(1, 1),
843 Point::new(2, 1)..Point::new(2, 1),
844 ],
845 "\t",
846 cx,
847 )
848 });
849
850 assert_eq!(
851 map.update(cx, |map, cx| map.snapshot(cx))
852 .text_chunks(1)
853 .collect::<String>()
854 .lines()
855 .next(),
856 Some(" b bbbbb")
857 );
858 assert_eq!(
859 map.update(cx, |map, cx| map.snapshot(cx))
860 .text_chunks(2)
861 .collect::<String>()
862 .lines()
863 .next(),
864 Some("c ccccc")
865 );
866 }
867
868 #[gpui::test]
869 async fn test_chunks(mut cx: gpui::TestAppContext) {
870 use unindent::Unindent as _;
871
872 let text = r#"
873 fn outer() {}
874
875 mod module {
876 fn inner() {}
877 }"#
878 .unindent();
879
880 let theme = SyntaxTheme::new(vec![
881 ("mod.body".to_string(), Color::red().into()),
882 ("fn.name".to_string(), Color::blue().into()),
883 ]);
884 let lang = Arc::new(
885 Language::new(
886 LanguageConfig {
887 name: "Test".to_string(),
888 path_suffixes: vec![".test".to_string()],
889 ..Default::default()
890 },
891 Some(tree_sitter_rust::language()),
892 )
893 .with_highlights_query(
894 r#"
895 (mod_item name: (identifier) body: _ @mod.body)
896 (function_item name: (identifier) @fn.name)
897 "#,
898 )
899 .unwrap(),
900 );
901 lang.set_theme(&theme);
902
903 let buffer =
904 cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
905 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
906 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
907
908 let tab_size = 2;
909 let font_cache = cx.font_cache();
910 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
911 let font_id = font_cache
912 .select_font(family_id, &Default::default())
913 .unwrap();
914 let font_size = 14.0;
915
916 let map =
917 cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
918 assert_eq!(
919 cx.update(|cx| chunks(0..5, &map, &theme, cx)),
920 vec![
921 ("fn ".to_string(), None),
922 ("outer".to_string(), Some(Color::blue())),
923 ("() {}\n\nmod module ".to_string(), None),
924 ("{\n fn ".to_string(), Some(Color::red())),
925 ("inner".to_string(), Some(Color::blue())),
926 ("() {}\n}".to_string(), Some(Color::red())),
927 ]
928 );
929 assert_eq!(
930 cx.update(|cx| chunks(3..5, &map, &theme, cx)),
931 vec![
932 (" fn ".to_string(), Some(Color::red())),
933 ("inner".to_string(), Some(Color::blue())),
934 ("() {}\n}".to_string(), Some(Color::red())),
935 ]
936 );
937
938 map.update(&mut cx, |map, cx| {
939 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
940 });
941 assert_eq!(
942 cx.update(|cx| chunks(0..2, &map, &theme, cx)),
943 vec![
944 ("fn ".to_string(), None),
945 ("out".to_string(), Some(Color::blue())),
946 ("…".to_string(), None),
947 (" fn ".to_string(), Some(Color::red())),
948 ("inner".to_string(), Some(Color::blue())),
949 ("() {}\n}".to_string(), Some(Color::red())),
950 ]
951 );
952 }
953
954 #[gpui::test]
955 async fn test_chunks_with_soft_wrapping(mut cx: gpui::TestAppContext) {
956 use unindent::Unindent as _;
957
958 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
959
960 let text = r#"
961 fn outer() {}
962
963 mod module {
964 fn inner() {}
965 }"#
966 .unindent();
967
968 let theme = SyntaxTheme::new(vec![
969 ("mod.body".to_string(), Color::red().into()),
970 ("fn.name".to_string(), Color::blue().into()),
971 ]);
972 let lang = Arc::new(
973 Language::new(
974 LanguageConfig {
975 name: "Test".to_string(),
976 path_suffixes: vec![".test".to_string()],
977 ..Default::default()
978 },
979 Some(tree_sitter_rust::language()),
980 )
981 .with_highlights_query(
982 r#"
983 (mod_item name: (identifier) body: _ @mod.body)
984 (function_item name: (identifier) @fn.name)
985 "#,
986 )
987 .unwrap(),
988 );
989 lang.set_theme(&theme);
990
991 let buffer =
992 cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
993 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
994 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
995
996 let font_cache = cx.font_cache();
997
998 let tab_size = 4;
999 let family_id = font_cache.load_family(&["Courier"]).unwrap();
1000 let font_id = font_cache
1001 .select_font(family_id, &Default::default())
1002 .unwrap();
1003 let font_size = 16.0;
1004
1005 let map = cx
1006 .add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, Some(40.0), cx));
1007 assert_eq!(
1008 cx.update(|cx| chunks(0..5, &map, &theme, cx)),
1009 [
1010 ("fn \n".to_string(), None),
1011 ("oute\nr".to_string(), Some(Color::blue())),
1012 ("() \n{}\n\n".to_string(), None),
1013 ]
1014 );
1015 assert_eq!(
1016 cx.update(|cx| chunks(3..5, &map, &theme, cx)),
1017 [("{}\n\n".to_string(), None)]
1018 );
1019
1020 map.update(&mut cx, |map, cx| {
1021 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1022 });
1023 assert_eq!(
1024 cx.update(|cx| chunks(1..4, &map, &theme, cx)),
1025 [
1026 ("out".to_string(), Some(Color::blue())),
1027 ("…\n".to_string(), None),
1028 (" \nfn ".to_string(), Some(Color::red())),
1029 ("i\n".to_string(), Some(Color::blue()))
1030 ]
1031 );
1032 }
1033
1034 #[gpui::test]
1035 fn test_clip_point(cx: &mut gpui::MutableAppContext) {
1036 use Bias::{Left, Right};
1037
1038 let text = "\n'a', 'α',\t'✋',\t'❎', '🍐'\n";
1039 let display_text = "\n'a', 'α', '✋', '❎', '🍐'\n";
1040 let buffer = MultiBuffer::build_simple(text, cx);
1041
1042 let tab_size = 4;
1043 let font_cache = cx.font_cache();
1044 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1045 let font_id = font_cache
1046 .select_font(family_id, &Default::default())
1047 .unwrap();
1048 let font_size = 14.0;
1049 let map = cx.add_model(|cx| {
1050 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1051 });
1052 let map = map.update(cx, |map, cx| map.snapshot(cx));
1053
1054 assert_eq!(map.text(), display_text);
1055 for (input_column, bias, output_column) in vec![
1056 ("'a', '".len(), Left, "'a', '".len()),
1057 ("'a', '".len() + 1, Left, "'a', '".len()),
1058 ("'a', '".len() + 1, Right, "'a', 'α".len()),
1059 ("'a', 'α', ".len(), Left, "'a', 'α',".len()),
1060 ("'a', 'α', ".len(), Right, "'a', 'α', ".len()),
1061 ("'a', 'α', '".len() + 1, Left, "'a', 'α', '".len()),
1062 ("'a', 'α', '".len() + 1, Right, "'a', 'α', '✋".len()),
1063 ("'a', 'α', '✋',".len(), Right, "'a', 'α', '✋',".len()),
1064 ("'a', 'α', '✋', ".len(), Left, "'a', 'α', '✋',".len()),
1065 (
1066 "'a', 'α', '✋', ".len(),
1067 Right,
1068 "'a', 'α', '✋', ".len(),
1069 ),
1070 ] {
1071 assert_eq!(
1072 map.clip_point(DisplayPoint::new(1, input_column as u32), bias),
1073 DisplayPoint::new(1, output_column as u32),
1074 "clip_point(({}, {}))",
1075 1,
1076 input_column,
1077 );
1078 }
1079 }
1080
1081 #[gpui::test]
1082 fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1083 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
1084 let buffer = MultiBuffer::build_simple(text, cx);
1085 let tab_size = 4;
1086 let font_cache = cx.font_cache();
1087 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1088 let font_id = font_cache
1089 .select_font(family_id, &Default::default())
1090 .unwrap();
1091 let font_size = 14.0;
1092
1093 let map = cx.add_model(|cx| {
1094 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1095 });
1096 let map = map.update(cx, |map, cx| map.snapshot(cx));
1097 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
1098 assert_eq!(
1099 map.text_chunks(0).collect::<String>(),
1100 "✅ α\nβ \n🏀β γ"
1101 );
1102 assert_eq!(map.text_chunks(1).collect::<String>(), "β \n🏀β γ");
1103 assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β γ");
1104
1105 let point = Point::new(0, "✅\t\t".len() as u32);
1106 let display_point = DisplayPoint::new(0, "✅ ".len() as u32);
1107 assert_eq!(point.to_display_point(&map), display_point);
1108 assert_eq!(display_point.to_point(&map), point);
1109
1110 let point = Point::new(1, "β\t".len() as u32);
1111 let display_point = DisplayPoint::new(1, "β ".len() as u32);
1112 assert_eq!(point.to_display_point(&map), display_point);
1113 assert_eq!(display_point.to_point(&map), point,);
1114
1115 let point = Point::new(2, "🏀β\t\t".len() as u32);
1116 let display_point = DisplayPoint::new(2, "🏀β ".len() as u32);
1117 assert_eq!(point.to_display_point(&map), display_point);
1118 assert_eq!(display_point.to_point(&map), point,);
1119
1120 // Display points inside of expanded tabs
1121 assert_eq!(
1122 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1123 Point::new(0, "✅\t".len() as u32),
1124 );
1125 assert_eq!(
1126 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1127 Point::new(0, "✅".len() as u32),
1128 );
1129
1130 // Clipping display points inside of multi-byte characters
1131 assert_eq!(
1132 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Left),
1133 DisplayPoint::new(0, 0)
1134 );
1135 assert_eq!(
1136 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Bias::Right),
1137 DisplayPoint::new(0, "✅".len() as u32)
1138 );
1139 }
1140
1141 #[gpui::test]
1142 fn test_max_point(cx: &mut gpui::MutableAppContext) {
1143 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1144 let tab_size = 4;
1145 let font_cache = cx.font_cache();
1146 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1147 let font_id = font_cache
1148 .select_font(family_id, &Default::default())
1149 .unwrap();
1150 let font_size = 14.0;
1151 let map = cx.add_model(|cx| {
1152 DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1153 });
1154 assert_eq!(
1155 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1156 DisplayPoint::new(1, 11)
1157 )
1158 }
1159
1160 fn chunks<'a>(
1161 rows: Range<u32>,
1162 map: &ModelHandle<DisplayMap>,
1163 theme: &'a SyntaxTheme,
1164 cx: &mut MutableAppContext,
1165 ) -> Vec<(String, Option<Color>)> {
1166 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1167 let mut chunks: Vec<(String, Option<Color>)> = Vec::new();
1168 for chunk in snapshot.chunks(rows, Some(theme)) {
1169 let color = chunk.highlight_style.map(|s| s.color);
1170 if let Some((last_chunk, last_color)) = chunks.last_mut() {
1171 if color == *last_color {
1172 last_chunk.push_str(chunk.text);
1173 } else {
1174 chunks.push((chunk.text.to_string(), color));
1175 }
1176 } else {
1177 chunks.push((chunk.text.to_string(), color));
1178 }
1179 }
1180 chunks
1181 }
1182}