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