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