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