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