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
766#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
767pub struct DisplayPoint(BlockPoint);
768
769impl Debug for DisplayPoint {
770 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
771 f.write_fmt(format_args!(
772 "DisplayPoint({}, {})",
773 self.row(),
774 self.column()
775 ))
776 }
777}
778
779impl DisplayPoint {
780 pub fn new(row: u32, column: u32) -> Self {
781 Self(BlockPoint(Point::new(row, column)))
782 }
783
784 pub fn zero() -> Self {
785 Self::new(0, 0)
786 }
787
788 pub fn is_zero(&self) -> bool {
789 self.0.is_zero()
790 }
791
792 pub fn row(self) -> u32 {
793 self.0.row
794 }
795
796 pub fn column(self) -> u32 {
797 self.0.column
798 }
799
800 pub fn row_mut(&mut self) -> &mut u32 {
801 &mut self.0.row
802 }
803
804 pub fn column_mut(&mut self) -> &mut u32 {
805 &mut self.0.column
806 }
807
808 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
809 map.display_point_to_point(self, Bias::Left)
810 }
811
812 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
813 let wrap_point = map.block_snapshot.to_wrap_point(self.0);
814 let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
815 let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
816 let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
817 map.inlay_snapshot
818 .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
819 }
820}
821
822impl ToDisplayPoint for usize {
823 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
824 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
825 }
826}
827
828impl ToDisplayPoint for OffsetUtf16 {
829 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
830 self.to_offset(&map.buffer_snapshot).to_display_point(map)
831 }
832}
833
834impl ToDisplayPoint for Point {
835 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
836 map.point_to_display_point(*self, Bias::Left)
837 }
838}
839
840impl ToDisplayPoint for Anchor {
841 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
842 self.to_point(&map.buffer_snapshot).to_display_point(map)
843 }
844}
845
846pub fn next_rows(display_row: u32, display_map: &DisplaySnapshot) -> impl Iterator<Item = u32> {
847 let max_row = display_map.max_point().row();
848 let start_row = display_row + 1;
849 let mut current = None;
850 std::iter::from_fn(move || {
851 if current == None {
852 current = Some(start_row);
853 } else {
854 current = Some(current.unwrap() + 1)
855 }
856 if current.unwrap() > max_row {
857 None
858 } else {
859 current
860 }
861 })
862}
863
864#[cfg(test)]
865pub mod tests {
866 use super::*;
867 use crate::{movement, test::marked_display_snapshot};
868 use gpui::{color::Color, elements::*, test::observe, AppContext};
869 use language::{
870 language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
871 Buffer, Language, LanguageConfig, SelectionGoal,
872 };
873 use rand::{prelude::*, Rng};
874 use settings::SettingsStore;
875 use smol::stream::StreamExt;
876 use std::{env, sync::Arc};
877 use theme::SyntaxTheme;
878 use util::test::{marked_text_ranges, sample_text};
879 use Bias::*;
880
881 #[gpui::test(iterations = 100)]
882 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
883 cx.foreground().set_block_on_ticks(0..=50);
884 cx.foreground().forbid_parking();
885 let operations = env::var("OPERATIONS")
886 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
887 .unwrap_or(10);
888
889 let font_cache = cx.font_cache().clone();
890 let mut tab_size = rng.gen_range(1..=4);
891 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
892 let excerpt_header_height = rng.gen_range(1..=5);
893 let family_id = font_cache
894 .load_family(&["Helvetica"], &Default::default())
895 .unwrap();
896 let font_id = font_cache
897 .select_font(family_id, &Default::default())
898 .unwrap();
899 let font_size = 14.0;
900 let max_wrap_width = 300.0;
901 let mut wrap_width = if rng.gen_bool(0.1) {
902 None
903 } else {
904 Some(rng.gen_range(0.0..=max_wrap_width))
905 };
906
907 log::info!("tab size: {}", tab_size);
908 log::info!("wrap width: {:?}", wrap_width);
909
910 cx.update(|cx| {
911 init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
912 });
913
914 let buffer = cx.update(|cx| {
915 if rng.gen() {
916 let len = rng.gen_range(0..10);
917 let text = util::RandomCharIter::new(&mut rng)
918 .take(len)
919 .collect::<String>();
920 MultiBuffer::build_simple(&text, cx)
921 } else {
922 MultiBuffer::build_random(&mut rng, cx)
923 }
924 });
925
926 let map = cx.add_model(|cx| {
927 DisplayMap::new(
928 buffer.clone(),
929 font_id,
930 font_size,
931 wrap_width,
932 buffer_start_excerpt_header_height,
933 excerpt_header_height,
934 cx,
935 )
936 });
937 let mut notifications = observe(&map, cx);
938 let mut fold_count = 0;
939 let mut blocks = Vec::new();
940
941 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
942 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
943 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
944 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
945 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
946 log::info!("block text: {:?}", snapshot.block_snapshot.text());
947 log::info!("display text: {:?}", snapshot.text());
948
949 for _i in 0..operations {
950 match rng.gen_range(0..100) {
951 0..=19 => {
952 wrap_width = if rng.gen_bool(0.2) {
953 None
954 } else {
955 Some(rng.gen_range(0.0..=max_wrap_width))
956 };
957 log::info!("setting wrap width to {:?}", wrap_width);
958 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
959 }
960 20..=29 => {
961 let mut tab_sizes = vec![1, 2, 3, 4];
962 tab_sizes.remove((tab_size - 1) as usize);
963 tab_size = *tab_sizes.choose(&mut rng).unwrap();
964 log::info!("setting tab size to {:?}", tab_size);
965 cx.update(|cx| {
966 cx.update_global::<SettingsStore, _, _>(|store, cx| {
967 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
968 s.defaults.tab_size = NonZeroU32::new(tab_size);
969 });
970 });
971 });
972 }
973 30..=44 => {
974 map.update(cx, |map, cx| {
975 if rng.gen() || blocks.is_empty() {
976 let buffer = map.snapshot(cx).buffer_snapshot;
977 let block_properties = (0..rng.gen_range(1..=1))
978 .map(|_| {
979 let position =
980 buffer.anchor_after(buffer.clip_offset(
981 rng.gen_range(0..=buffer.len()),
982 Bias::Left,
983 ));
984
985 let disposition = if rng.gen() {
986 BlockDisposition::Above
987 } else {
988 BlockDisposition::Below
989 };
990 let height = rng.gen_range(1..5);
991 log::info!(
992 "inserting block {:?} {:?} with height {}",
993 disposition,
994 position.to_point(&buffer),
995 height
996 );
997 BlockProperties {
998 style: BlockStyle::Fixed,
999 position,
1000 height,
1001 disposition,
1002 render: Arc::new(|_| Empty::new().into_any()),
1003 }
1004 })
1005 .collect::<Vec<_>>();
1006 blocks.extend(map.insert_blocks(block_properties, cx));
1007 } else {
1008 blocks.shuffle(&mut rng);
1009 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1010 let block_ids_to_remove = (0..remove_count)
1011 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1012 .collect();
1013 log::info!("removing block ids {:?}", block_ids_to_remove);
1014 map.remove_blocks(block_ids_to_remove, cx);
1015 }
1016 });
1017 }
1018 45..=79 => {
1019 let mut ranges = Vec::new();
1020 for _ in 0..rng.gen_range(1..=3) {
1021 buffer.read_with(cx, |buffer, cx| {
1022 let buffer = buffer.read(cx);
1023 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1024 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1025 ranges.push(start..end);
1026 });
1027 }
1028
1029 if rng.gen() && fold_count > 0 {
1030 log::info!("unfolding ranges: {:?}", ranges);
1031 map.update(cx, |map, cx| {
1032 map.unfold(ranges, true, cx);
1033 });
1034 } else {
1035 log::info!("folding ranges: {:?}", ranges);
1036 map.update(cx, |map, cx| {
1037 map.fold(ranges, cx);
1038 });
1039 }
1040 }
1041 _ => {
1042 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1043 }
1044 }
1045
1046 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1047 notifications.next().await.unwrap();
1048 }
1049
1050 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1051 fold_count = snapshot.fold_count();
1052 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1053 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1054 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1055 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1056 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1057 log::info!("display text: {:?}", snapshot.text());
1058
1059 // Line boundaries
1060 let buffer = &snapshot.buffer_snapshot;
1061 for _ in 0..5 {
1062 let row = rng.gen_range(0..=buffer.max_point().row);
1063 let column = rng.gen_range(0..=buffer.line_len(row));
1064 let point = buffer.clip_point(Point::new(row, column), Left);
1065
1066 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1067 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1068
1069 assert!(prev_buffer_bound <= point);
1070 assert!(next_buffer_bound >= point);
1071 assert_eq!(prev_buffer_bound.column, 0);
1072 assert_eq!(prev_display_bound.column(), 0);
1073 if next_buffer_bound < buffer.max_point() {
1074 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1075 }
1076
1077 assert_eq!(
1078 prev_display_bound,
1079 prev_buffer_bound.to_display_point(&snapshot),
1080 "row boundary before {:?}. reported buffer row boundary: {:?}",
1081 point,
1082 prev_buffer_bound
1083 );
1084 assert_eq!(
1085 next_display_bound,
1086 next_buffer_bound.to_display_point(&snapshot),
1087 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1088 point,
1089 next_buffer_bound
1090 );
1091 assert_eq!(
1092 prev_buffer_bound,
1093 prev_display_bound.to_point(&snapshot),
1094 "row boundary before {:?}. reported display row boundary: {:?}",
1095 point,
1096 prev_display_bound
1097 );
1098 assert_eq!(
1099 next_buffer_bound,
1100 next_display_bound.to_point(&snapshot),
1101 "row boundary after {:?}. reported display row boundary: {:?}",
1102 point,
1103 next_display_bound
1104 );
1105 }
1106
1107 // Movement
1108 let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1109 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1110 for _ in 0..5 {
1111 let row = rng.gen_range(0..=snapshot.max_point().row());
1112 let column = rng.gen_range(0..=snapshot.line_len(row));
1113 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1114
1115 log::info!("Moving from point {:?}", point);
1116
1117 let moved_right = movement::right(&snapshot, point);
1118 log::info!("Right {:?}", moved_right);
1119 if point < max_point {
1120 assert!(moved_right > point);
1121 if point.column() == snapshot.line_len(point.row())
1122 || snapshot.soft_wrap_indent(point.row()).is_some()
1123 && point.column() == snapshot.line_len(point.row()) - 1
1124 {
1125 assert!(moved_right.row() > point.row());
1126 }
1127 } else {
1128 assert_eq!(moved_right, point);
1129 }
1130
1131 let moved_left = movement::left(&snapshot, point);
1132 log::info!("Left {:?}", moved_left);
1133 if point > min_point {
1134 assert!(moved_left < point);
1135 if point.column() == 0 {
1136 assert!(moved_left.row() < point.row());
1137 }
1138 } else {
1139 assert_eq!(moved_left, point);
1140 }
1141 }
1142 }
1143 }
1144
1145 #[gpui::test(retries = 5)]
1146 fn test_soft_wraps(cx: &mut AppContext) {
1147 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1148 init_test(cx, |_| {});
1149
1150 let font_cache = cx.font_cache();
1151
1152 let family_id = font_cache
1153 .load_family(&["Helvetica"], &Default::default())
1154 .unwrap();
1155 let font_id = font_cache
1156 .select_font(family_id, &Default::default())
1157 .unwrap();
1158 let font_size = 12.0;
1159 let wrap_width = Some(64.);
1160
1161 let text = "one two three four five\nsix seven eight";
1162 let buffer = MultiBuffer::build_simple(text, cx);
1163 let map = cx.add_model(|cx| {
1164 DisplayMap::new(buffer.clone(), font_id, font_size, wrap_width, 1, 1, cx)
1165 });
1166
1167 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1168 assert_eq!(
1169 snapshot.text_chunks(0).collect::<String>(),
1170 "one two \nthree four \nfive\nsix seven \neight"
1171 );
1172 assert_eq!(
1173 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1174 DisplayPoint::new(0, 7)
1175 );
1176 assert_eq!(
1177 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1178 DisplayPoint::new(1, 0)
1179 );
1180 assert_eq!(
1181 movement::right(&snapshot, DisplayPoint::new(0, 7)),
1182 DisplayPoint::new(1, 0)
1183 );
1184 assert_eq!(
1185 movement::left(&snapshot, DisplayPoint::new(1, 0)),
1186 DisplayPoint::new(0, 7)
1187 );
1188 assert_eq!(
1189 movement::up(
1190 &snapshot,
1191 DisplayPoint::new(1, 10),
1192 SelectionGoal::None,
1193 false
1194 ),
1195 (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
1196 );
1197 assert_eq!(
1198 movement::down(
1199 &snapshot,
1200 DisplayPoint::new(0, 7),
1201 SelectionGoal::Column(10),
1202 false
1203 ),
1204 (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
1205 );
1206 assert_eq!(
1207 movement::down(
1208 &snapshot,
1209 DisplayPoint::new(1, 10),
1210 SelectionGoal::Column(10),
1211 false
1212 ),
1213 (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
1214 );
1215
1216 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1217 buffer.update(cx, |buffer, cx| {
1218 buffer.edit([(ix..ix, "and ")], None, cx);
1219 });
1220
1221 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1222 assert_eq!(
1223 snapshot.text_chunks(1).collect::<String>(),
1224 "three four \nfive\nsix and \nseven eight"
1225 );
1226
1227 // Re-wrap on font size changes
1228 map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
1229
1230 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1231 assert_eq!(
1232 snapshot.text_chunks(1).collect::<String>(),
1233 "three \nfour five\nsix and \nseven \neight"
1234 )
1235 }
1236
1237 #[gpui::test]
1238 fn test_text_chunks(cx: &mut gpui::AppContext) {
1239 init_test(cx, |_| {});
1240
1241 let text = sample_text(6, 6, 'a');
1242 let buffer = MultiBuffer::build_simple(&text, cx);
1243 let family_id = cx
1244 .font_cache()
1245 .load_family(&["Helvetica"], &Default::default())
1246 .unwrap();
1247 let font_id = cx
1248 .font_cache()
1249 .select_font(family_id, &Default::default())
1250 .unwrap();
1251 let font_size = 14.0;
1252 let map =
1253 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1254
1255 buffer.update(cx, |buffer, cx| {
1256 buffer.edit(
1257 vec![
1258 (Point::new(1, 0)..Point::new(1, 0), "\t"),
1259 (Point::new(1, 1)..Point::new(1, 1), "\t"),
1260 (Point::new(2, 1)..Point::new(2, 1), "\t"),
1261 ],
1262 None,
1263 cx,
1264 )
1265 });
1266
1267 assert_eq!(
1268 map.update(cx, |map, cx| map.snapshot(cx))
1269 .text_chunks(1)
1270 .collect::<String>()
1271 .lines()
1272 .next(),
1273 Some(" b bbbbb")
1274 );
1275 assert_eq!(
1276 map.update(cx, |map, cx| map.snapshot(cx))
1277 .text_chunks(2)
1278 .collect::<String>()
1279 .lines()
1280 .next(),
1281 Some("c ccccc")
1282 );
1283 }
1284
1285 #[gpui::test]
1286 async fn test_chunks(cx: &mut gpui::TestAppContext) {
1287 use unindent::Unindent as _;
1288
1289 let text = r#"
1290 fn outer() {}
1291
1292 mod module {
1293 fn inner() {}
1294 }"#
1295 .unindent();
1296
1297 let theme = SyntaxTheme::new(vec![
1298 ("mod.body".to_string(), Color::red().into()),
1299 ("fn.name".to_string(), Color::blue().into()),
1300 ]);
1301 let language = Arc::new(
1302 Language::new(
1303 LanguageConfig {
1304 name: "Test".into(),
1305 path_suffixes: vec![".test".to_string()],
1306 ..Default::default()
1307 },
1308 Some(tree_sitter_rust::language()),
1309 )
1310 .with_highlights_query(
1311 r#"
1312 (mod_item name: (identifier) body: _ @mod.body)
1313 (function_item name: (identifier) @fn.name)
1314 "#,
1315 )
1316 .unwrap(),
1317 );
1318 language.set_theme(&theme);
1319
1320 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1321
1322 let buffer = cx
1323 .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1324 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1325 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1326
1327 let font_cache = cx.font_cache();
1328 let family_id = font_cache
1329 .load_family(&["Helvetica"], &Default::default())
1330 .unwrap();
1331 let font_id = font_cache
1332 .select_font(family_id, &Default::default())
1333 .unwrap();
1334 let font_size = 14.0;
1335
1336 let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1337 assert_eq!(
1338 cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1339 vec![
1340 ("fn ".to_string(), None),
1341 ("outer".to_string(), Some(Color::blue())),
1342 ("() {}\n\nmod module ".to_string(), None),
1343 ("{\n fn ".to_string(), Some(Color::red())),
1344 ("inner".to_string(), Some(Color::blue())),
1345 ("() {}\n}".to_string(), Some(Color::red())),
1346 ]
1347 );
1348 assert_eq!(
1349 cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1350 vec![
1351 (" fn ".to_string(), Some(Color::red())),
1352 ("inner".to_string(), Some(Color::blue())),
1353 ("() {}\n}".to_string(), Some(Color::red())),
1354 ]
1355 );
1356
1357 map.update(cx, |map, cx| {
1358 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1359 });
1360 assert_eq!(
1361 cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1362 vec![
1363 ("fn ".to_string(), None),
1364 ("out".to_string(), Some(Color::blue())),
1365 ("āÆ".to_string(), None),
1366 (" fn ".to_string(), Some(Color::red())),
1367 ("inner".to_string(), Some(Color::blue())),
1368 ("() {}\n}".to_string(), Some(Color::red())),
1369 ]
1370 );
1371 }
1372
1373 #[gpui::test]
1374 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1375 use unindent::Unindent as _;
1376
1377 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1378
1379 let text = r#"
1380 fn outer() {}
1381
1382 mod module {
1383 fn inner() {}
1384 }"#
1385 .unindent();
1386
1387 let theme = SyntaxTheme::new(vec![
1388 ("mod.body".to_string(), Color::red().into()),
1389 ("fn.name".to_string(), Color::blue().into()),
1390 ]);
1391 let language = Arc::new(
1392 Language::new(
1393 LanguageConfig {
1394 name: "Test".into(),
1395 path_suffixes: vec![".test".to_string()],
1396 ..Default::default()
1397 },
1398 Some(tree_sitter_rust::language()),
1399 )
1400 .with_highlights_query(
1401 r#"
1402 (mod_item name: (identifier) body: _ @mod.body)
1403 (function_item name: (identifier) @fn.name)
1404 "#,
1405 )
1406 .unwrap(),
1407 );
1408 language.set_theme(&theme);
1409
1410 cx.update(|cx| init_test(cx, |_| {}));
1411
1412 let buffer = cx
1413 .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1414 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1415 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1416
1417 let font_cache = cx.font_cache();
1418
1419 let family_id = font_cache
1420 .load_family(&["Courier"], &Default::default())
1421 .unwrap();
1422 let font_id = font_cache
1423 .select_font(family_id, &Default::default())
1424 .unwrap();
1425 let font_size = 16.0;
1426
1427 let map =
1428 cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, Some(40.0), 1, 1, cx));
1429 assert_eq!(
1430 cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1431 [
1432 ("fn \n".to_string(), None),
1433 ("oute\nr".to_string(), Some(Color::blue())),
1434 ("() \n{}\n\n".to_string(), None),
1435 ]
1436 );
1437 assert_eq!(
1438 cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1439 [("{}\n\n".to_string(), None)]
1440 );
1441
1442 map.update(cx, |map, cx| {
1443 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1444 });
1445 assert_eq!(
1446 cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1447 [
1448 ("out".to_string(), Some(Color::blue())),
1449 ("āÆ\n".to_string(), None),
1450 (" \nfn ".to_string(), Some(Color::red())),
1451 ("i\n".to_string(), Some(Color::blue()))
1452 ]
1453 );
1454 }
1455
1456 #[gpui::test]
1457 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1458 cx.update(|cx| init_test(cx, |_| {}));
1459
1460 let theme = SyntaxTheme::new(vec![
1461 ("operator".to_string(), Color::red().into()),
1462 ("string".to_string(), Color::green().into()),
1463 ]);
1464 let language = Arc::new(
1465 Language::new(
1466 LanguageConfig {
1467 name: "Test".into(),
1468 path_suffixes: vec![".test".to_string()],
1469 ..Default::default()
1470 },
1471 Some(tree_sitter_rust::language()),
1472 )
1473 .with_highlights_query(
1474 r#"
1475 ":" @operator
1476 (string_literal) @string
1477 "#,
1478 )
1479 .unwrap(),
1480 );
1481 language.set_theme(&theme);
1482
1483 let (text, highlighted_ranges) = marked_text_ranges(r#"constĖ Ā«aĀ»: B = "c Ā«dĀ»""#, false);
1484
1485 let buffer = cx
1486 .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1487 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1488
1489 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1490 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1491
1492 let font_cache = cx.font_cache();
1493 let family_id = font_cache
1494 .load_family(&["Courier"], &Default::default())
1495 .unwrap();
1496 let font_id = font_cache
1497 .select_font(family_id, &Default::default())
1498 .unwrap();
1499 let font_size = 16.0;
1500 let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1501
1502 enum MyType {}
1503
1504 let style = HighlightStyle {
1505 color: Some(Color::blue()),
1506 ..Default::default()
1507 };
1508
1509 map.update(cx, |map, _cx| {
1510 map.highlight_text(
1511 TypeId::of::<MyType>(),
1512 highlighted_ranges
1513 .into_iter()
1514 .map(|range| {
1515 buffer_snapshot.anchor_before(range.start)
1516 ..buffer_snapshot.anchor_before(range.end)
1517 })
1518 .collect(),
1519 style,
1520 );
1521 });
1522
1523 assert_eq!(
1524 cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1525 [
1526 ("const ".to_string(), None, None),
1527 ("a".to_string(), None, Some(Color::blue())),
1528 (":".to_string(), Some(Color::red()), None),
1529 (" B = ".to_string(), None, None),
1530 ("\"c ".to_string(), Some(Color::green()), None),
1531 ("d".to_string(), Some(Color::green()), Some(Color::blue())),
1532 ("\"".to_string(), Some(Color::green()), None),
1533 ]
1534 );
1535 }
1536
1537 #[gpui::test]
1538 fn test_clip_point(cx: &mut gpui::AppContext) {
1539 init_test(cx, |_| {});
1540
1541 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1542 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1543
1544 match bias {
1545 Bias::Left => {
1546 if shift_right {
1547 *markers[1].column_mut() += 1;
1548 }
1549
1550 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1551 }
1552 Bias::Right => {
1553 if shift_right {
1554 *markers[0].column_mut() += 1;
1555 }
1556
1557 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1558 }
1559 };
1560 }
1561
1562 use Bias::{Left, Right};
1563 assert("ĖĖα", false, Left, cx);
1564 assert("ĖĖα", true, Left, cx);
1565 assert("ĖĖα", false, Right, cx);
1566 assert("ĖαĖ", true, Right, cx);
1567 assert("ĖĖā", false, Left, cx);
1568 assert("ĖĖā", true, Left, cx);
1569 assert("ĖĖā", false, Right, cx);
1570 assert("ĖāĖ", true, Right, cx);
1571 assert("ĖĖš", false, Left, cx);
1572 assert("ĖĖš", true, Left, cx);
1573 assert("ĖĖš", false, Right, cx);
1574 assert("ĖšĖ", true, Right, cx);
1575 assert("ĖĖ\t", false, Left, cx);
1576 assert("ĖĖ\t", true, Left, cx);
1577 assert("ĖĖ\t", false, Right, cx);
1578 assert("Ė\tĖ", true, Right, cx);
1579 assert(" ĖĖ\t", false, Left, cx);
1580 assert(" ĖĖ\t", true, Left, cx);
1581 assert(" ĖĖ\t", false, Right, cx);
1582 assert(" Ė\tĖ", true, Right, cx);
1583 assert(" ĖĖ\t", false, Left, cx);
1584 assert(" ĖĖ\t", false, Right, cx);
1585 }
1586
1587 #[gpui::test]
1588 fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1589 init_test(cx, |_| {});
1590
1591 fn assert(text: &str, cx: &mut gpui::AppContext) {
1592 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1593 unmarked_snapshot.clip_at_line_ends = true;
1594 assert_eq!(
1595 unmarked_snapshot.clip_point(markers[1], Bias::Left),
1596 markers[0]
1597 );
1598 }
1599
1600 assert("ĖĖ", cx);
1601 assert("ĖaĖ", cx);
1602 assert("aĖbĖ", cx);
1603 assert("aĖαĖ", cx);
1604 }
1605
1606 #[gpui::test]
1607 fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1608 init_test(cx, |_| {});
1609
1610 let text = "ā
\t\tα\nβ\t\nšĪ²\t\tγ";
1611 let buffer = MultiBuffer::build_simple(text, cx);
1612 let font_cache = cx.font_cache();
1613 let family_id = font_cache
1614 .load_family(&["Helvetica"], &Default::default())
1615 .unwrap();
1616 let font_id = font_cache
1617 .select_font(family_id, &Default::default())
1618 .unwrap();
1619 let font_size = 14.0;
1620
1621 let map =
1622 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1623 let map = map.update(cx, |map, cx| map.snapshot(cx));
1624 assert_eq!(map.text(), "ā
α\nβ \nšĪ² γ");
1625 assert_eq!(
1626 map.text_chunks(0).collect::<String>(),
1627 "ā
α\nβ \nšĪ² γ"
1628 );
1629 assert_eq!(map.text_chunks(1).collect::<String>(), "β \nšĪ² γ");
1630 assert_eq!(map.text_chunks(2).collect::<String>(), "šĪ² γ");
1631
1632 let point = Point::new(0, "ā
\t\t".len() as u32);
1633 let display_point = DisplayPoint::new(0, "ā
".len() as u32);
1634 assert_eq!(point.to_display_point(&map), display_point);
1635 assert_eq!(display_point.to_point(&map), point);
1636
1637 let point = Point::new(1, "β\t".len() as u32);
1638 let display_point = DisplayPoint::new(1, "β ".len() as u32);
1639 assert_eq!(point.to_display_point(&map), display_point);
1640 assert_eq!(display_point.to_point(&map), point,);
1641
1642 let point = Point::new(2, "šĪ²\t\t".len() as u32);
1643 let display_point = DisplayPoint::new(2, "šĪ² ".len() as u32);
1644 assert_eq!(point.to_display_point(&map), display_point);
1645 assert_eq!(display_point.to_point(&map), point,);
1646
1647 // Display points inside of expanded tabs
1648 assert_eq!(
1649 DisplayPoint::new(0, "ā
".len() as u32).to_point(&map),
1650 Point::new(0, "ā
\t".len() as u32),
1651 );
1652 assert_eq!(
1653 DisplayPoint::new(0, "ā
".len() as u32).to_point(&map),
1654 Point::new(0, "ā
".len() as u32),
1655 );
1656
1657 // Clipping display points inside of multi-byte characters
1658 assert_eq!(
1659 map.clip_point(DisplayPoint::new(0, "ā
".len() as u32 - 1), Left),
1660 DisplayPoint::new(0, 0)
1661 );
1662 assert_eq!(
1663 map.clip_point(DisplayPoint::new(0, "ā
".len() as u32 - 1), Bias::Right),
1664 DisplayPoint::new(0, "ā
".len() as u32)
1665 );
1666 }
1667
1668 #[gpui::test]
1669 fn test_max_point(cx: &mut gpui::AppContext) {
1670 init_test(cx, |_| {});
1671
1672 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1673 let font_cache = cx.font_cache();
1674 let family_id = font_cache
1675 .load_family(&["Helvetica"], &Default::default())
1676 .unwrap();
1677 let font_id = font_cache
1678 .select_font(family_id, &Default::default())
1679 .unwrap();
1680 let font_size = 14.0;
1681 let map =
1682 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1683 assert_eq!(
1684 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1685 DisplayPoint::new(1, 11)
1686 )
1687 }
1688
1689 fn syntax_chunks<'a>(
1690 rows: Range<u32>,
1691 map: &ModelHandle<DisplayMap>,
1692 theme: &'a SyntaxTheme,
1693 cx: &mut AppContext,
1694 ) -> Vec<(String, Option<Color>)> {
1695 chunks(rows, map, theme, cx)
1696 .into_iter()
1697 .map(|(text, color, _)| (text, color))
1698 .collect()
1699 }
1700
1701 fn chunks<'a>(
1702 rows: Range<u32>,
1703 map: &ModelHandle<DisplayMap>,
1704 theme: &'a SyntaxTheme,
1705 cx: &mut AppContext,
1706 ) -> Vec<(String, Option<Color>, Option<Color>)> {
1707 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1708 let mut chunks: Vec<(String, Option<Color>, Option<Color>)> = Vec::new();
1709 for chunk in snapshot.chunks(rows, true, None, None, None) {
1710 let syntax_color = chunk
1711 .syntax_highlight_id
1712 .and_then(|id| id.style(theme)?.color);
1713 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1714 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1715 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1716 last_chunk.push_str(chunk.text);
1717 continue;
1718 }
1719 }
1720 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1721 }
1722 chunks
1723 }
1724
1725 fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
1726 cx.foreground().forbid_parking();
1727 cx.set_global(SettingsStore::test(cx));
1728 language::init(cx);
1729 cx.update_global::<SettingsStore, _, _>(|store, cx| {
1730 store.update_user_settings::<AllLanguageSettings>(cx, f);
1731 });
1732 }
1733}