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