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