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(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None),
818 (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
819 );
820 assert_eq!(
821 movement::down(
822 &snapshot,
823 DisplayPoint::new(0, 7),
824 SelectionGoal::Column(10)
825 ),
826 (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
827 );
828 assert_eq!(
829 movement::down(
830 &snapshot,
831 DisplayPoint::new(1, 10),
832 SelectionGoal::Column(10)
833 ),
834 (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
835 );
836
837 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
838 buffer.update(cx, |buffer, cx| {
839 buffer.edit(vec![ix..ix], "and ", cx);
840 });
841
842 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
843 assert_eq!(
844 snapshot.text_chunks(1).collect::<String>(),
845 "three four \nfive\nsix and \nseven eight"
846 );
847
848 // Re-wrap on font size changes
849 map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
850
851 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
852 assert_eq!(
853 snapshot.text_chunks(1).collect::<String>(),
854 "three \nfour five\nsix and \nseven \neight"
855 )
856 }
857
858 #[gpui::test]
859 fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
860 cx.set_global(Settings::test(cx));
861 let text = sample_text(6, 6, 'a');
862 let buffer = MultiBuffer::build_simple(&text, cx);
863 let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
864 let font_id = cx
865 .font_cache()
866 .select_font(family_id, &Default::default())
867 .unwrap();
868 let font_size = 14.0;
869 let map =
870 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
871 buffer.update(cx, |buffer, cx| {
872 buffer.edit(
873 vec![
874 Point::new(1, 0)..Point::new(1, 0),
875 Point::new(1, 1)..Point::new(1, 1),
876 Point::new(2, 1)..Point::new(2, 1),
877 ],
878 "\t",
879 cx,
880 )
881 });
882
883 assert_eq!(
884 map.update(cx, |map, cx| map.snapshot(cx))
885 .text_chunks(1)
886 .collect::<String>()
887 .lines()
888 .next(),
889 Some(" b bbbbb")
890 );
891 assert_eq!(
892 map.update(cx, |map, cx| map.snapshot(cx))
893 .text_chunks(2)
894 .collect::<String>()
895 .lines()
896 .next(),
897 Some("c ccccc")
898 );
899 }
900
901 #[gpui::test]
902 async fn test_chunks(cx: &mut gpui::TestAppContext) {
903 use unindent::Unindent as _;
904
905 let text = r#"
906 fn outer() {}
907
908 mod module {
909 fn inner() {}
910 }"#
911 .unindent();
912
913 let theme = SyntaxTheme::new(vec![
914 ("mod.body".to_string(), Color::red().into()),
915 ("fn.name".to_string(), Color::blue().into()),
916 ]);
917 let language = Arc::new(
918 Language::new(
919 LanguageConfig {
920 name: "Test".into(),
921 path_suffixes: vec![".test".to_string()],
922 ..Default::default()
923 },
924 Some(tree_sitter_rust::language()),
925 )
926 .with_highlights_query(
927 r#"
928 (mod_item name: (identifier) body: _ @mod.body)
929 (function_item name: (identifier) @fn.name)
930 "#,
931 )
932 .unwrap(),
933 );
934 language.set_theme(&theme);
935 cx.update(|cx| {
936 cx.set_global(Settings {
937 tab_size: 2,
938 ..Settings::test(cx)
939 })
940 });
941
942 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
943 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
944 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
945
946 let font_cache = cx.font_cache();
947 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
948 let font_id = font_cache
949 .select_font(family_id, &Default::default())
950 .unwrap();
951 let font_size = 14.0;
952
953 let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
954 assert_eq!(
955 cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
956 vec![
957 ("fn ".to_string(), None),
958 ("outer".to_string(), Some(Color::blue())),
959 ("() {}\n\nmod module ".to_string(), None),
960 ("{\n fn ".to_string(), Some(Color::red())),
961 ("inner".to_string(), Some(Color::blue())),
962 ("() {}\n}".to_string(), Some(Color::red())),
963 ]
964 );
965 assert_eq!(
966 cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
967 vec![
968 (" fn ".to_string(), Some(Color::red())),
969 ("inner".to_string(), Some(Color::blue())),
970 ("() {}\n}".to_string(), Some(Color::red())),
971 ]
972 );
973
974 map.update(cx, |map, cx| {
975 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
976 });
977 assert_eq!(
978 cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
979 vec![
980 ("fn ".to_string(), None),
981 ("out".to_string(), Some(Color::blue())),
982 ("…".to_string(), None),
983 (" fn ".to_string(), Some(Color::red())),
984 ("inner".to_string(), Some(Color::blue())),
985 ("() {}\n}".to_string(), Some(Color::red())),
986 ]
987 );
988 }
989
990 #[gpui::test]
991 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
992 use unindent::Unindent as _;
993
994 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
995
996 let text = r#"
997 fn outer() {}
998
999 mod module {
1000 fn inner() {}
1001 }"#
1002 .unindent();
1003
1004 let theme = SyntaxTheme::new(vec![
1005 ("mod.body".to_string(), Color::red().into()),
1006 ("fn.name".to_string(), Color::blue().into()),
1007 ]);
1008 let language = Arc::new(
1009 Language::new(
1010 LanguageConfig {
1011 name: "Test".into(),
1012 path_suffixes: vec![".test".to_string()],
1013 ..Default::default()
1014 },
1015 Some(tree_sitter_rust::language()),
1016 )
1017 .with_highlights_query(
1018 r#"
1019 (mod_item name: (identifier) body: _ @mod.body)
1020 (function_item name: (identifier) @fn.name)
1021 "#,
1022 )
1023 .unwrap(),
1024 );
1025 language.set_theme(&theme);
1026
1027 cx.update(|cx| cx.set_global(Settings::test(cx)));
1028
1029 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1030 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
1031 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1032
1033 let font_cache = cx.font_cache();
1034
1035 let family_id = font_cache.load_family(&["Courier"]).unwrap();
1036 let font_id = font_cache
1037 .select_font(family_id, &Default::default())
1038 .unwrap();
1039 let font_size = 16.0;
1040
1041 let map =
1042 cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, Some(40.0), 1, 1, cx));
1043 assert_eq!(
1044 cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1045 [
1046 ("fn \n".to_string(), None),
1047 ("oute\nr".to_string(), Some(Color::blue())),
1048 ("() \n{}\n\n".to_string(), None),
1049 ]
1050 );
1051 assert_eq!(
1052 cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1053 [("{}\n\n".to_string(), None)]
1054 );
1055
1056 map.update(cx, |map, cx| {
1057 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1058 });
1059 assert_eq!(
1060 cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1061 [
1062 ("out".to_string(), Some(Color::blue())),
1063 ("…\n".to_string(), None),
1064 (" \nfn ".to_string(), Some(Color::red())),
1065 ("i\n".to_string(), Some(Color::blue()))
1066 ]
1067 );
1068 }
1069
1070 #[gpui::test]
1071 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1072 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1073
1074 cx.update(|cx| cx.set_global(Settings::test(cx)));
1075 let theme = SyntaxTheme::new(vec![
1076 ("operator".to_string(), Color::red().into()),
1077 ("string".to_string(), Color::green().into()),
1078 ]);
1079 let language = Arc::new(
1080 Language::new(
1081 LanguageConfig {
1082 name: "Test".into(),
1083 path_suffixes: vec![".test".to_string()],
1084 ..Default::default()
1085 },
1086 Some(tree_sitter_rust::language()),
1087 )
1088 .with_highlights_query(
1089 r#"
1090 ":" @operator
1091 (string_literal) @string
1092 "#,
1093 )
1094 .unwrap(),
1095 );
1096 language.set_theme(&theme);
1097
1098 let (text, highlighted_ranges) = marked_text_ranges(r#"const[] [a]: B = "c [d]""#);
1099
1100 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1101 buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
1102
1103 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1104 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1105
1106 let font_cache = cx.font_cache();
1107 let family_id = font_cache.load_family(&["Courier"]).unwrap();
1108 let font_id = font_cache
1109 .select_font(family_id, &Default::default())
1110 .unwrap();
1111 let font_size = 16.0;
1112 let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1113
1114 enum MyType {}
1115
1116 let style = HighlightStyle {
1117 color: Some(Color::blue()),
1118 ..Default::default()
1119 };
1120
1121 map.update(cx, |map, _cx| {
1122 map.highlight_text(
1123 TypeId::of::<MyType>(),
1124 highlighted_ranges
1125 .into_iter()
1126 .map(|range| {
1127 buffer_snapshot.anchor_before(range.start)
1128 ..buffer_snapshot.anchor_before(range.end)
1129 })
1130 .collect(),
1131 style,
1132 );
1133 });
1134
1135 assert_eq!(
1136 cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1137 [
1138 ("const ".to_string(), None, None),
1139 ("a".to_string(), None, Some(Color::blue())),
1140 (":".to_string(), Some(Color::red()), None),
1141 (" B = ".to_string(), None, None),
1142 ("\"c ".to_string(), Some(Color::green()), None),
1143 ("d".to_string(), Some(Color::green()), Some(Color::blue())),
1144 ("\"".to_string(), Some(Color::green()), None),
1145 ]
1146 );
1147 }
1148
1149 #[gpui::test]
1150 fn test_clip_point(cx: &mut gpui::MutableAppContext) {
1151 cx.set_global(Settings::test(cx));
1152 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::MutableAppContext) {
1153 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1154
1155 match bias {
1156 Bias::Left => {
1157 if shift_right {
1158 *markers[1].column_mut() += 1;
1159 }
1160
1161 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1162 }
1163 Bias::Right => {
1164 if shift_right {
1165 *markers[0].column_mut() += 1;
1166 }
1167
1168 assert_eq!(
1169 unmarked_snapshot.clip_point(dbg!(markers[0]), bias),
1170 markers[1]
1171 )
1172 }
1173 };
1174 }
1175
1176 use Bias::{Left, Right};
1177 assert("||α", false, Left, cx);
1178 assert("||α", true, Left, cx);
1179 assert("||α", false, Right, cx);
1180 assert("|α|", true, Right, cx);
1181 assert("||✋", false, Left, cx);
1182 assert("||✋", true, Left, cx);
1183 assert("||✋", false, Right, cx);
1184 assert("|✋|", true, Right, cx);
1185 assert("||🍐", false, Left, cx);
1186 assert("||🍐", true, Left, cx);
1187 assert("||🍐", false, Right, cx);
1188 assert("|🍐|", true, Right, cx);
1189 assert("||\t", false, Left, cx);
1190 assert("||\t", true, Left, cx);
1191 assert("||\t", false, Right, cx);
1192 assert("|\t|", true, Right, cx);
1193 assert(" ||\t", false, Left, cx);
1194 assert(" ||\t", true, Left, cx);
1195 assert(" ||\t", false, Right, cx);
1196 assert(" |\t|", true, Right, cx);
1197 assert(" ||\t", false, Left, cx);
1198 assert(" ||\t", false, Right, cx);
1199 }
1200
1201 #[gpui::test]
1202 fn test_clip_at_line_ends(cx: &mut gpui::MutableAppContext) {
1203 cx.set_global(Settings::test(cx));
1204
1205 fn assert(text: &str, cx: &mut gpui::MutableAppContext) {
1206 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1207 unmarked_snapshot.clip_at_line_ends = true;
1208 assert_eq!(
1209 unmarked_snapshot.clip_point(markers[1], Bias::Left),
1210 markers[0]
1211 );
1212 }
1213
1214 assert("||", cx);
1215 assert("|a|", cx);
1216 assert("a|b|", cx);
1217 assert("a|α|", cx);
1218 }
1219
1220 #[gpui::test]
1221 fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1222 cx.set_global(Settings::test(cx));
1223 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
1224 let buffer = MultiBuffer::build_simple(text, cx);
1225 let font_cache = cx.font_cache();
1226 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1227 let font_id = font_cache
1228 .select_font(family_id, &Default::default())
1229 .unwrap();
1230 let font_size = 14.0;
1231
1232 let map =
1233 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1234 let map = map.update(cx, |map, cx| map.snapshot(cx));
1235 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
1236 assert_eq!(
1237 map.text_chunks(0).collect::<String>(),
1238 "✅ α\nβ \n🏀β γ"
1239 );
1240 assert_eq!(map.text_chunks(1).collect::<String>(), "β \n🏀β γ");
1241 assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β γ");
1242
1243 let point = Point::new(0, "✅\t\t".len() as u32);
1244 let display_point = DisplayPoint::new(0, "✅ ".len() as u32);
1245 assert_eq!(point.to_display_point(&map), display_point);
1246 assert_eq!(display_point.to_point(&map), point);
1247
1248 let point = Point::new(1, "β\t".len() as u32);
1249 let display_point = DisplayPoint::new(1, "β ".len() as u32);
1250 assert_eq!(point.to_display_point(&map), display_point);
1251 assert_eq!(display_point.to_point(&map), point,);
1252
1253 let point = Point::new(2, "🏀β\t\t".len() as u32);
1254 let display_point = DisplayPoint::new(2, "🏀β ".len() as u32);
1255 assert_eq!(point.to_display_point(&map), display_point);
1256 assert_eq!(display_point.to_point(&map), point,);
1257
1258 // Display points inside of expanded tabs
1259 assert_eq!(
1260 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1261 Point::new(0, "✅\t".len() as u32),
1262 );
1263 assert_eq!(
1264 DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1265 Point::new(0, "✅".len() as u32),
1266 );
1267
1268 // Clipping display points inside of multi-byte characters
1269 assert_eq!(
1270 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Left),
1271 DisplayPoint::new(0, 0)
1272 );
1273 assert_eq!(
1274 map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Bias::Right),
1275 DisplayPoint::new(0, "✅".len() as u32)
1276 );
1277 }
1278
1279 #[gpui::test]
1280 fn test_max_point(cx: &mut gpui::MutableAppContext) {
1281 cx.set_global(Settings::test(cx));
1282 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1283 let font_cache = cx.font_cache();
1284 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1285 let font_id = font_cache
1286 .select_font(family_id, &Default::default())
1287 .unwrap();
1288 let font_size = 14.0;
1289 let map =
1290 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1291 assert_eq!(
1292 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1293 DisplayPoint::new(1, 11)
1294 )
1295 }
1296
1297 fn syntax_chunks<'a>(
1298 rows: Range<u32>,
1299 map: &ModelHandle<DisplayMap>,
1300 theme: &'a SyntaxTheme,
1301 cx: &mut MutableAppContext,
1302 ) -> Vec<(String, Option<Color>)> {
1303 chunks(rows, map, theme, cx)
1304 .into_iter()
1305 .map(|(text, color, _)| (text, color))
1306 .collect()
1307 }
1308
1309 fn chunks<'a>(
1310 rows: Range<u32>,
1311 map: &ModelHandle<DisplayMap>,
1312 theme: &'a SyntaxTheme,
1313 cx: &mut MutableAppContext,
1314 ) -> Vec<(String, Option<Color>, Option<Color>)> {
1315 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1316 let mut chunks: Vec<(String, Option<Color>, Option<Color>)> = Vec::new();
1317 for chunk in snapshot.chunks(rows, true) {
1318 let syntax_color = chunk
1319 .syntax_highlight_id
1320 .and_then(|id| id.style(theme)?.color);
1321 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1322 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1323 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1324 last_chunk.push_str(chunk.text);
1325 continue;
1326 }
1327 }
1328 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1329 }
1330 chunks
1331 }
1332}