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