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