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