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