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