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