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