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