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