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