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