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 crease_map;
22mod fold_map;
23mod inlay_map;
24pub(crate) mod invisibles;
25mod tab_map;
26mod wrap_map;
27
28use crate::{
29 hover_links::InlayHighlight, movement::TextLayoutDetails, EditorStyle, InlayId, RowExt,
30};
31pub use block_map::{
32 Block, BlockBufferRows, BlockChunks as DisplayChunks, BlockContext, BlockId, BlockMap,
33 BlockPlacement, BlockPoint, BlockProperties, BlockStyle, CustomBlockId, RenderBlock,
34};
35use block_map::{BlockRow, BlockSnapshot};
36use collections::{HashMap, HashSet};
37pub use crease_map::*;
38pub use fold_map::{Fold, FoldId, FoldPlaceholder, FoldPoint};
39use fold_map::{FoldMap, FoldSnapshot};
40use gpui::{
41 AnyElement, Font, HighlightStyle, LineLayout, Model, ModelContext, Pixels, UnderlineStyle,
42};
43pub(crate) use inlay_map::Inlay;
44use inlay_map::{InlayMap, InlaySnapshot};
45pub use inlay_map::{InlayOffset, InlayPoint};
46use invisibles::{is_invisible, replacement};
47use language::{
48 language_settings::language_settings, ChunkRenderer, OffsetUtf16, Point,
49 Subscription as BufferSubscription,
50};
51use lsp::DiagnosticSeverity;
52use multi_buffer::{
53 Anchor, AnchorRangeExt, MultiBuffer, MultiBufferPoint, MultiBufferRow, MultiBufferSnapshot,
54 ToOffset, ToPoint,
55};
56use serde::Deserialize;
57use std::{
58 any::TypeId,
59 borrow::Cow,
60 fmt::Debug,
61 iter,
62 num::NonZeroU32,
63 ops::{Add, Range, Sub},
64 sync::Arc,
65};
66use sum_tree::{Bias, TreeMap};
67use tab_map::{TabMap, TabSnapshot};
68use text::LineIndent;
69use ui::{div, px, IntoElement, ParentElement, SharedString, Styled, WindowContext};
70use unicode_segmentation::UnicodeSegmentation;
71use wrap_map::{WrapMap, WrapSnapshot};
72
73#[derive(Copy, Clone, Debug, PartialEq, Eq)]
74pub enum FoldStatus {
75 Folded,
76 Foldable,
77}
78
79pub type RenderFoldToggle = Arc<dyn Fn(FoldStatus, &mut WindowContext) -> AnyElement>;
80
81pub trait ToDisplayPoint {
82 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
83}
84
85type TextHighlights = TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>;
86type InlayHighlights = TreeMap<TypeId, TreeMap<InlayId, (HighlightStyle, InlayHighlight)>>;
87
88/// Decides how text in a [`MultiBuffer`] should be displayed in a buffer, handling inlay hints,
89/// folding, hard tabs, soft wrapping, custom blocks (like diagnostics), and highlighting.
90///
91/// See the [module level documentation](self) for more information.
92pub struct DisplayMap {
93 /// The buffer that we are displaying.
94 buffer: Model<MultiBuffer>,
95 buffer_subscription: BufferSubscription,
96 /// Decides where the [`Inlay`]s should be displayed.
97 inlay_map: InlayMap,
98 /// Decides where the fold indicators should be and tracks parts of a source file that are currently folded.
99 fold_map: FoldMap,
100 /// Keeps track of hard tabs in a buffer.
101 tab_map: TabMap,
102 /// Handles soft wrapping.
103 wrap_map: Model<WrapMap>,
104 /// Tracks custom blocks such as diagnostics that should be displayed within buffer.
105 block_map: BlockMap,
106 /// Regions of text that should be highlighted.
107 text_highlights: TextHighlights,
108 /// Regions of inlays that should be highlighted.
109 inlay_highlights: InlayHighlights,
110 /// A container for explicitly foldable ranges, which supersede indentation based fold range suggestions.
111 crease_map: CreaseMap,
112 pub(crate) fold_placeholder: FoldPlaceholder,
113 pub clip_at_line_ends: bool,
114 pub(crate) masked: bool,
115}
116
117impl DisplayMap {
118 #[allow(clippy::too_many_arguments)]
119 pub fn new(
120 buffer: Model<MultiBuffer>,
121 font: Font,
122 font_size: Pixels,
123 wrap_width: Option<Pixels>,
124 show_excerpt_controls: bool,
125 buffer_header_height: u32,
126 excerpt_header_height: u32,
127 excerpt_footer_height: u32,
128 fold_placeholder: FoldPlaceholder,
129 cx: &mut ModelContext<Self>,
130 ) -> Self {
131 let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
132
133 let tab_size = Self::tab_size(&buffer, cx);
134 let buffer_snapshot = buffer.read(cx).snapshot(cx);
135 let crease_map = CreaseMap::new(&buffer_snapshot);
136 let (inlay_map, snapshot) = InlayMap::new(buffer_snapshot);
137 let (fold_map, snapshot) = FoldMap::new(snapshot);
138 let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
139 let (wrap_map, snapshot) = WrapMap::new(snapshot, font, font_size, wrap_width, cx);
140 let block_map = BlockMap::new(
141 snapshot,
142 show_excerpt_controls,
143 buffer_header_height,
144 excerpt_header_height,
145 excerpt_footer_height,
146 );
147
148 cx.observe(&wrap_map, |_, _, cx| cx.notify()).detach();
149
150 DisplayMap {
151 buffer,
152 buffer_subscription,
153 fold_map,
154 inlay_map,
155 tab_map,
156 wrap_map,
157 block_map,
158 crease_map,
159 fold_placeholder,
160 text_highlights: Default::default(),
161 inlay_highlights: Default::default(),
162 clip_at_line_ends: false,
163 masked: false,
164 }
165 }
166
167 pub fn snapshot(&mut self, cx: &mut ModelContext<Self>) -> DisplaySnapshot {
168 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
169 let edits = self.buffer_subscription.consume().into_inner();
170 let (inlay_snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
171 let (fold_snapshot, edits) = self.fold_map.read(inlay_snapshot.clone(), edits);
172 let tab_size = Self::tab_size(&self.buffer, cx);
173 let (tab_snapshot, edits) = self.tab_map.sync(fold_snapshot.clone(), edits, tab_size);
174 let (wrap_snapshot, edits) = self
175 .wrap_map
176 .update(cx, |map, cx| map.sync(tab_snapshot.clone(), edits, cx));
177 let block_snapshot = self.block_map.read(wrap_snapshot.clone(), edits).snapshot;
178
179 DisplaySnapshot {
180 buffer_snapshot: self.buffer.read(cx).snapshot(cx),
181 fold_snapshot,
182 inlay_snapshot,
183 tab_snapshot,
184 wrap_snapshot,
185 block_snapshot,
186 crease_snapshot: self.crease_map.snapshot(),
187 text_highlights: self.text_highlights.clone(),
188 inlay_highlights: self.inlay_highlights.clone(),
189 clip_at_line_ends: self.clip_at_line_ends,
190 masked: self.masked,
191 fold_placeholder: self.fold_placeholder.clone(),
192 }
193 }
194
195 pub fn set_state(&mut self, other: &DisplaySnapshot, cx: &mut ModelContext<Self>) {
196 self.fold(
197 other
198 .folds_in_range(0..other.buffer_snapshot.len())
199 .map(|fold| {
200 (
201 fold.range.to_offset(&other.buffer_snapshot),
202 fold.placeholder.clone(),
203 )
204 }),
205 cx,
206 );
207 }
208
209 pub fn fold<T: ToOffset>(
210 &mut self,
211 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
212 cx: &mut ModelContext<Self>,
213 ) {
214 let snapshot = self.buffer.read(cx).snapshot(cx);
215 let edits = self.buffer_subscription.consume().into_inner();
216 let tab_size = Self::tab_size(&self.buffer, cx);
217 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
218 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
219 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
220 let (snapshot, edits) = self
221 .wrap_map
222 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
223 self.block_map.read(snapshot, edits);
224 let (snapshot, edits) = fold_map.fold(ranges);
225 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
226 let (snapshot, edits) = self
227 .wrap_map
228 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
229 self.block_map.read(snapshot, edits);
230 }
231
232 pub fn unfold<T: ToOffset>(
233 &mut self,
234 ranges: impl IntoIterator<Item = Range<T>>,
235 inclusive: bool,
236 cx: &mut ModelContext<Self>,
237 ) {
238 let snapshot = self.buffer.read(cx).snapshot(cx);
239 let edits = self.buffer_subscription.consume().into_inner();
240 let tab_size = Self::tab_size(&self.buffer, cx);
241 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
242 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
243 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
244 let (snapshot, edits) = self
245 .wrap_map
246 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
247 self.block_map.read(snapshot, edits);
248 let (snapshot, edits) = fold_map.unfold(ranges, inclusive);
249 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
250 let (snapshot, edits) = self
251 .wrap_map
252 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
253 self.block_map.read(snapshot, edits);
254 }
255
256 pub fn insert_creases(
257 &mut self,
258 creases: impl IntoIterator<Item = Crease>,
259 cx: &mut ModelContext<Self>,
260 ) -> Vec<CreaseId> {
261 let snapshot = self.buffer.read(cx).snapshot(cx);
262 self.crease_map.insert(creases, &snapshot)
263 }
264
265 pub fn remove_creases(
266 &mut self,
267 crease_ids: impl IntoIterator<Item = CreaseId>,
268 cx: &mut ModelContext<Self>,
269 ) {
270 let snapshot = self.buffer.read(cx).snapshot(cx);
271 self.crease_map.remove(crease_ids, &snapshot)
272 }
273
274 pub fn insert_blocks(
275 &mut self,
276 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
277 cx: &mut ModelContext<Self>,
278 ) -> Vec<CustomBlockId> {
279 let snapshot = self.buffer.read(cx).snapshot(cx);
280 let edits = self.buffer_subscription.consume().into_inner();
281 let tab_size = Self::tab_size(&self.buffer, cx);
282 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
283 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
284 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
285 let (snapshot, edits) = self
286 .wrap_map
287 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
288 let mut block_map = self.block_map.write(snapshot, edits);
289 block_map.insert(blocks)
290 }
291
292 pub fn resize_blocks(
293 &mut self,
294 heights: HashMap<CustomBlockId, u32>,
295 cx: &mut ModelContext<Self>,
296 ) {
297 let snapshot = self.buffer.read(cx).snapshot(cx);
298 let edits = self.buffer_subscription.consume().into_inner();
299 let tab_size = Self::tab_size(&self.buffer, cx);
300 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
301 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
302 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
303 let (snapshot, edits) = self
304 .wrap_map
305 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
306 let mut block_map = self.block_map.write(snapshot, edits);
307 block_map.resize(heights);
308 }
309
310 pub fn replace_blocks(&mut self, renderers: HashMap<CustomBlockId, RenderBlock>) {
311 self.block_map.replace_blocks(renderers);
312 }
313
314 pub fn remove_blocks(&mut self, ids: HashSet<CustomBlockId>, cx: &mut ModelContext<Self>) {
315 let snapshot = self.buffer.read(cx).snapshot(cx);
316 let edits = self.buffer_subscription.consume().into_inner();
317 let tab_size = Self::tab_size(&self.buffer, cx);
318 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
319 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
320 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
321 let (snapshot, edits) = self
322 .wrap_map
323 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
324 let mut block_map = self.block_map.write(snapshot, edits);
325 block_map.remove(ids);
326 }
327
328 pub fn row_for_block(
329 &mut self,
330 block_id: CustomBlockId,
331 cx: &mut ModelContext<Self>,
332 ) -> Option<DisplayRow> {
333 let snapshot = self.buffer.read(cx).snapshot(cx);
334 let edits = self.buffer_subscription.consume().into_inner();
335 let tab_size = Self::tab_size(&self.buffer, cx);
336 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
337 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
338 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
339 let (snapshot, edits) = self
340 .wrap_map
341 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
342 let block_map = self.block_map.read(snapshot, edits);
343 let block_row = block_map.row_for_block(block_id)?;
344 Some(DisplayRow(block_row.0))
345 }
346
347 pub fn highlight_text(
348 &mut self,
349 type_id: TypeId,
350 ranges: Vec<Range<Anchor>>,
351 style: HighlightStyle,
352 ) {
353 self.text_highlights
354 .insert(Some(type_id), Arc::new((style, ranges)));
355 }
356
357 pub(crate) fn highlight_inlays(
358 &mut self,
359 type_id: TypeId,
360 highlights: Vec<InlayHighlight>,
361 style: HighlightStyle,
362 ) {
363 for highlight in highlights {
364 let update = self.inlay_highlights.update(&type_id, |highlights| {
365 highlights.insert(highlight.inlay, (style, highlight.clone()))
366 });
367 if update.is_none() {
368 self.inlay_highlights.insert(
369 type_id,
370 TreeMap::from_ordered_entries([(highlight.inlay, (style, highlight))]),
371 );
372 }
373 }
374 }
375
376 pub fn text_highlights(&self, type_id: TypeId) -> Option<(HighlightStyle, &[Range<Anchor>])> {
377 let highlights = self.text_highlights.get(&Some(type_id))?;
378 Some((highlights.0, &highlights.1))
379 }
380 pub fn clear_highlights(&mut self, type_id: TypeId) -> bool {
381 let mut cleared = self.text_highlights.remove(&Some(type_id)).is_some();
382 cleared |= self.inlay_highlights.remove(&type_id).is_some();
383 cleared
384 }
385
386 pub fn set_font(&self, font: Font, font_size: Pixels, cx: &mut ModelContext<Self>) -> bool {
387 self.wrap_map
388 .update(cx, |map, cx| map.set_font_with_size(font, font_size, cx))
389 }
390
391 pub fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut ModelContext<Self>) -> bool {
392 self.wrap_map
393 .update(cx, |map, cx| map.set_wrap_width(width, cx))
394 }
395
396 pub(crate) fn current_inlays(&self) -> impl Iterator<Item = &Inlay> {
397 self.inlay_map.current_inlays()
398 }
399
400 pub(crate) fn splice_inlays(
401 &mut self,
402 to_remove: Vec<InlayId>,
403 to_insert: Vec<Inlay>,
404 cx: &mut ModelContext<Self>,
405 ) {
406 if to_remove.is_empty() && to_insert.is_empty() {
407 return;
408 }
409 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
410 let edits = self.buffer_subscription.consume().into_inner();
411 let (snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
412 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
413 let tab_size = Self::tab_size(&self.buffer, cx);
414 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
415 let (snapshot, edits) = self
416 .wrap_map
417 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
418 self.block_map.read(snapshot, edits);
419
420 let (snapshot, edits) = self.inlay_map.splice(to_remove, to_insert);
421 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
422 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
423 let (snapshot, edits) = self
424 .wrap_map
425 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
426 self.block_map.read(snapshot, edits);
427 }
428
429 fn tab_size(buffer: &Model<MultiBuffer>, cx: &mut ModelContext<Self>) -> NonZeroU32 {
430 let buffer = buffer.read(cx).as_singleton().map(|buffer| buffer.read(cx));
431 let language = buffer
432 .and_then(|buffer| buffer.language())
433 .map(|l| l.name());
434 let file = buffer.and_then(|buffer| buffer.file());
435 language_settings(language, file, cx).tab_size
436 }
437
438 #[cfg(test)]
439 pub fn is_rewrapping(&self, cx: &gpui::AppContext) -> bool {
440 self.wrap_map.read(cx).is_rewrapping()
441 }
442
443 pub fn show_excerpt_controls(&self) -> bool {
444 self.block_map.show_excerpt_controls()
445 }
446}
447
448#[derive(Debug, Default)]
449pub(crate) struct Highlights<'a> {
450 pub text_highlights: Option<&'a TextHighlights>,
451 pub inlay_highlights: Option<&'a InlayHighlights>,
452 pub styles: HighlightStyles,
453}
454
455#[derive(Default, Debug, Clone, Copy)]
456pub struct HighlightStyles {
457 pub inlay_hint: Option<HighlightStyle>,
458 pub suggestion: Option<HighlightStyle>,
459}
460
461pub struct HighlightedChunk<'a> {
462 pub text: &'a str,
463 pub style: Option<HighlightStyle>,
464 pub is_tab: bool,
465 pub renderer: Option<ChunkRenderer>,
466}
467
468impl<'a> HighlightedChunk<'a> {
469 fn highlight_invisibles(
470 self,
471 editor_style: &'a EditorStyle,
472 ) -> impl Iterator<Item = Self> + 'a {
473 let mut chars = self.text.chars().peekable();
474 let mut text = self.text;
475 let style = self.style;
476 let is_tab = self.is_tab;
477 let renderer = self.renderer;
478 iter::from_fn(move || {
479 let mut prefix_len = 0;
480 while let Some(&ch) = chars.peek() {
481 if !is_invisible(ch) {
482 prefix_len += ch.len_utf8();
483 chars.next();
484 continue;
485 }
486 if prefix_len > 0 {
487 let (prefix, suffix) = text.split_at(prefix_len);
488 text = suffix;
489 return Some(HighlightedChunk {
490 text: prefix,
491 style,
492 is_tab,
493 renderer: renderer.clone(),
494 });
495 }
496 chars.next();
497 let (prefix, suffix) = text.split_at(ch.len_utf8());
498 text = suffix;
499 if let Some(replacement) = replacement(ch) {
500 let background = editor_style.status.hint_background;
501 let underline = editor_style.status.hint;
502 return Some(HighlightedChunk {
503 text: prefix,
504 style: None,
505 is_tab: false,
506 renderer: Some(ChunkRenderer {
507 render: Arc::new(move |_| {
508 div()
509 .child(replacement)
510 .bg(background)
511 .text_decoration_1()
512 .text_decoration_color(underline)
513 .into_any_element()
514 }),
515 constrain_width: false,
516 }),
517 });
518 } else {
519 let invisible_highlight = HighlightStyle {
520 background_color: Some(editor_style.status.hint_background),
521 underline: Some(UnderlineStyle {
522 color: Some(editor_style.status.hint),
523 thickness: px(1.),
524 wavy: false,
525 }),
526 ..Default::default()
527 };
528 let invisible_style = if let Some(mut style) = style {
529 style.highlight(invisible_highlight);
530 style
531 } else {
532 invisible_highlight
533 };
534
535 return Some(HighlightedChunk {
536 text: prefix,
537 style: Some(invisible_style),
538 is_tab: false,
539 renderer: renderer.clone(),
540 });
541 }
542 }
543
544 if !text.is_empty() {
545 let remainder = text;
546 text = "";
547 Some(HighlightedChunk {
548 text: remainder,
549 style,
550 is_tab,
551 renderer: renderer.clone(),
552 })
553 } else {
554 None
555 }
556 })
557 }
558}
559
560#[derive(Clone)]
561pub struct DisplaySnapshot {
562 pub buffer_snapshot: MultiBufferSnapshot,
563 pub fold_snapshot: FoldSnapshot,
564 pub crease_snapshot: CreaseSnapshot,
565 inlay_snapshot: InlaySnapshot,
566 tab_snapshot: TabSnapshot,
567 wrap_snapshot: WrapSnapshot,
568 block_snapshot: BlockSnapshot,
569 text_highlights: TextHighlights,
570 inlay_highlights: InlayHighlights,
571 clip_at_line_ends: bool,
572 masked: bool,
573 pub(crate) fold_placeholder: FoldPlaceholder,
574}
575
576impl DisplaySnapshot {
577 #[cfg(test)]
578 pub fn fold_count(&self) -> usize {
579 self.fold_snapshot.fold_count()
580 }
581
582 pub fn is_empty(&self) -> bool {
583 self.buffer_snapshot.len() == 0
584 }
585
586 pub fn buffer_rows(
587 &self,
588 start_row: DisplayRow,
589 ) -> impl Iterator<Item = Option<MultiBufferRow>> + '_ {
590 self.block_snapshot
591 .buffer_rows(BlockRow(start_row.0))
592 .map(|row| row.map(|row| MultiBufferRow(row.0)))
593 }
594
595 pub fn max_buffer_row(&self) -> MultiBufferRow {
596 self.buffer_snapshot.max_buffer_row()
597 }
598
599 pub fn prev_line_boundary(&self, mut point: MultiBufferPoint) -> (Point, DisplayPoint) {
600 loop {
601 let mut inlay_point = self.inlay_snapshot.to_inlay_point(point);
602 let mut fold_point = self.fold_snapshot.to_fold_point(inlay_point, Bias::Left);
603 fold_point.0.column = 0;
604 inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
605 point = self.inlay_snapshot.to_buffer_point(inlay_point);
606
607 let mut display_point = self.point_to_display_point(point, Bias::Left);
608 *display_point.column_mut() = 0;
609 let next_point = self.display_point_to_point(display_point, Bias::Left);
610 if next_point == point {
611 return (point, display_point);
612 }
613 point = next_point;
614 }
615 }
616
617 pub fn next_line_boundary(&self, mut point: MultiBufferPoint) -> (Point, DisplayPoint) {
618 loop {
619 let mut inlay_point = self.inlay_snapshot.to_inlay_point(point);
620 let mut fold_point = self.fold_snapshot.to_fold_point(inlay_point, Bias::Right);
621 fold_point.0.column = self.fold_snapshot.line_len(fold_point.row());
622 inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
623 point = self.inlay_snapshot.to_buffer_point(inlay_point);
624
625 let mut display_point = self.point_to_display_point(point, Bias::Right);
626 *display_point.column_mut() = self.line_len(display_point.row());
627 let next_point = self.display_point_to_point(display_point, Bias::Right);
628 if next_point == point {
629 return (point, display_point);
630 }
631 point = next_point;
632 }
633 }
634
635 // used by line_mode selections and tries to match vim behavior
636 pub fn expand_to_line(&self, range: Range<Point>) -> Range<Point> {
637 let new_start = if range.start.row == 0 {
638 MultiBufferPoint::new(0, 0)
639 } else if range.start.row == self.max_buffer_row().0
640 || (range.end.column > 0 && range.end.row == self.max_buffer_row().0)
641 {
642 MultiBufferPoint::new(
643 range.start.row - 1,
644 self.buffer_snapshot
645 .line_len(MultiBufferRow(range.start.row - 1)),
646 )
647 } else {
648 self.prev_line_boundary(range.start).0
649 };
650
651 let new_end = if range.end.column == 0 {
652 range.end
653 } else if range.end.row < self.max_buffer_row().0 {
654 self.buffer_snapshot
655 .clip_point(MultiBufferPoint::new(range.end.row + 1, 0), Bias::Left)
656 } else {
657 self.buffer_snapshot.max_point()
658 };
659
660 new_start..new_end
661 }
662
663 fn point_to_display_point(&self, point: MultiBufferPoint, bias: Bias) -> DisplayPoint {
664 let inlay_point = self.inlay_snapshot.to_inlay_point(point);
665 let fold_point = self.fold_snapshot.to_fold_point(inlay_point, bias);
666 let tab_point = self.tab_snapshot.to_tab_point(fold_point);
667 let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
668 let block_point = self.block_snapshot.to_block_point(wrap_point);
669 DisplayPoint(block_point)
670 }
671
672 fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {
673 self.inlay_snapshot
674 .to_buffer_point(self.display_point_to_inlay_point(point, bias))
675 }
676
677 pub fn display_point_to_inlay_offset(&self, point: DisplayPoint, bias: Bias) -> InlayOffset {
678 self.inlay_snapshot
679 .to_offset(self.display_point_to_inlay_point(point, bias))
680 }
681
682 pub fn anchor_to_inlay_offset(&self, anchor: Anchor) -> InlayOffset {
683 self.inlay_snapshot
684 .to_inlay_offset(anchor.to_offset(&self.buffer_snapshot))
685 }
686
687 pub fn display_point_to_anchor(&self, point: DisplayPoint, bias: Bias) -> Anchor {
688 self.buffer_snapshot
689 .anchor_at(point.to_offset(self, bias), bias)
690 }
691
692 fn display_point_to_inlay_point(&self, point: DisplayPoint, bias: Bias) -> InlayPoint {
693 let block_point = point.0;
694 let wrap_point = self.block_snapshot.to_wrap_point(block_point);
695 let tab_point = self.wrap_snapshot.to_tab_point(wrap_point);
696 let fold_point = self.tab_snapshot.to_fold_point(tab_point, bias).0;
697 fold_point.to_inlay_point(&self.fold_snapshot)
698 }
699
700 pub fn display_point_to_fold_point(&self, point: DisplayPoint, bias: Bias) -> FoldPoint {
701 let block_point = point.0;
702 let wrap_point = self.block_snapshot.to_wrap_point(block_point);
703 let tab_point = self.wrap_snapshot.to_tab_point(wrap_point);
704 self.tab_snapshot.to_fold_point(tab_point, bias).0
705 }
706
707 pub fn fold_point_to_display_point(&self, fold_point: FoldPoint) -> DisplayPoint {
708 let tab_point = self.tab_snapshot.to_tab_point(fold_point);
709 let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
710 let block_point = self.block_snapshot.to_block_point(wrap_point);
711 DisplayPoint(block_point)
712 }
713
714 pub fn max_point(&self) -> DisplayPoint {
715 DisplayPoint(self.block_snapshot.max_point())
716 }
717
718 /// Returns text chunks starting at the given display row until the end of the file
719 pub fn text_chunks(&self, display_row: DisplayRow) -> impl Iterator<Item = &str> {
720 self.block_snapshot
721 .chunks(
722 display_row.0..self.max_point().row().next_row().0,
723 false,
724 self.masked,
725 Highlights::default(),
726 )
727 .map(|h| h.text)
728 }
729
730 /// Returns text chunks starting at the end of the given display row in reverse until the start of the file
731 pub fn reverse_text_chunks(&self, display_row: DisplayRow) -> impl Iterator<Item = &str> {
732 (0..=display_row.0).rev().flat_map(move |row| {
733 self.block_snapshot
734 .chunks(row..row + 1, false, self.masked, Highlights::default())
735 .map(|h| h.text)
736 .collect::<Vec<_>>()
737 .into_iter()
738 .rev()
739 })
740 }
741
742 pub fn chunks(
743 &self,
744 display_rows: Range<DisplayRow>,
745 language_aware: bool,
746 highlight_styles: HighlightStyles,
747 ) -> DisplayChunks<'_> {
748 self.block_snapshot.chunks(
749 display_rows.start.0..display_rows.end.0,
750 language_aware,
751 self.masked,
752 Highlights {
753 text_highlights: Some(&self.text_highlights),
754 inlay_highlights: Some(&self.inlay_highlights),
755 styles: highlight_styles,
756 },
757 )
758 }
759
760 pub fn highlighted_chunks<'a>(
761 &'a self,
762 display_rows: Range<DisplayRow>,
763 language_aware: bool,
764 editor_style: &'a EditorStyle,
765 ) -> impl Iterator<Item = HighlightedChunk<'a>> {
766 self.chunks(
767 display_rows,
768 language_aware,
769 HighlightStyles {
770 inlay_hint: Some(editor_style.inlay_hints_style),
771 suggestion: Some(editor_style.suggestions_style),
772 },
773 )
774 .flat_map(|chunk| {
775 let mut highlight_style = chunk
776 .syntax_highlight_id
777 .and_then(|id| id.style(&editor_style.syntax));
778
779 if let Some(chunk_highlight) = chunk.highlight_style {
780 if let Some(highlight_style) = highlight_style.as_mut() {
781 highlight_style.highlight(chunk_highlight);
782 } else {
783 highlight_style = Some(chunk_highlight);
784 }
785 }
786
787 let mut diagnostic_highlight = HighlightStyle::default();
788
789 if chunk.is_unnecessary {
790 diagnostic_highlight.fade_out = Some(editor_style.unnecessary_code_fade);
791 }
792
793 if let Some(severity) = chunk.diagnostic_severity {
794 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
795 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
796 let diagnostic_color = super::diagnostic_style(severity, &editor_style.status);
797 diagnostic_highlight.underline = Some(UnderlineStyle {
798 color: Some(diagnostic_color),
799 thickness: 1.0.into(),
800 wavy: true,
801 });
802 }
803 }
804
805 if let Some(highlight_style) = highlight_style.as_mut() {
806 highlight_style.highlight(diagnostic_highlight);
807 } else {
808 highlight_style = Some(diagnostic_highlight);
809 }
810
811 HighlightedChunk {
812 text: chunk.text,
813 style: highlight_style,
814 is_tab: chunk.is_tab,
815 renderer: chunk.renderer,
816 }
817 .highlight_invisibles(editor_style)
818 })
819 }
820
821 pub fn layout_row(
822 &self,
823 display_row: DisplayRow,
824 TextLayoutDetails {
825 text_system,
826 editor_style,
827 rem_size,
828 scroll_anchor: _,
829 visible_rows: _,
830 vertical_scroll_margin: _,
831 }: &TextLayoutDetails,
832 ) -> Arc<LineLayout> {
833 let mut runs = Vec::new();
834 let mut line = String::new();
835
836 let range = display_row..display_row.next_row();
837 for chunk in self.highlighted_chunks(range, false, editor_style) {
838 line.push_str(chunk.text);
839
840 let text_style = if let Some(style) = chunk.style {
841 Cow::Owned(editor_style.text.clone().highlight(style))
842 } else {
843 Cow::Borrowed(&editor_style.text)
844 };
845
846 runs.push(text_style.to_run(chunk.text.len()))
847 }
848
849 if line.ends_with('\n') {
850 line.pop();
851 if let Some(last_run) = runs.last_mut() {
852 last_run.len -= 1;
853 if last_run.len == 0 {
854 runs.pop();
855 }
856 }
857 }
858
859 let font_size = editor_style.text.font_size.to_pixels(*rem_size);
860 text_system
861 .layout_line(&line, font_size, &runs)
862 .expect("we expect the font to be loaded because it's rendered by the editor")
863 }
864
865 pub fn x_for_display_point(
866 &self,
867 display_point: DisplayPoint,
868 text_layout_details: &TextLayoutDetails,
869 ) -> Pixels {
870 let line = self.layout_row(display_point.row(), text_layout_details);
871 line.x_for_index(display_point.column() as usize)
872 }
873
874 pub fn display_column_for_x(
875 &self,
876 display_row: DisplayRow,
877 x: Pixels,
878 details: &TextLayoutDetails,
879 ) -> u32 {
880 let layout_line = self.layout_row(display_row, details);
881 layout_line.closest_index_for_x(x) as u32
882 }
883
884 pub fn grapheme_at(&self, mut point: DisplayPoint) -> Option<SharedString> {
885 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
886 let chars = self
887 .text_chunks(point.row())
888 .flat_map(str::chars)
889 .skip_while({
890 let mut column = 0;
891 move |char| {
892 let at_point = column >= point.column();
893 column += char.len_utf8() as u32;
894 !at_point
895 }
896 })
897 .take_while({
898 let mut prev = false;
899 move |char| {
900 let now = char.is_ascii();
901 let end = char.is_ascii() && (char.is_ascii_whitespace() || prev);
902 prev = now;
903 !end
904 }
905 });
906 chars.collect::<String>().graphemes(true).next().map(|s| {
907 if let Some(invisible) = s.chars().next().filter(|&c| is_invisible(c)) {
908 replacement(invisible).unwrap_or(s).to_owned().into()
909 } else if s == "\n" {
910 " ".into()
911 } else {
912 s.to_owned().into()
913 }
914 })
915 }
916
917 pub fn buffer_chars_at(&self, mut offset: usize) -> impl Iterator<Item = (char, usize)> + '_ {
918 self.buffer_snapshot.chars_at(offset).map(move |ch| {
919 let ret = (ch, offset);
920 offset += ch.len_utf8();
921 ret
922 })
923 }
924
925 pub fn reverse_buffer_chars_at(
926 &self,
927 mut offset: usize,
928 ) -> impl Iterator<Item = (char, usize)> + '_ {
929 self.buffer_snapshot
930 .reversed_chars_at(offset)
931 .map(move |ch| {
932 offset -= ch.len_utf8();
933 (ch, offset)
934 })
935 }
936
937 pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
938 let mut clipped = self.block_snapshot.clip_point(point.0, bias);
939 if self.clip_at_line_ends {
940 clipped = self.clip_at_line_end(DisplayPoint(clipped)).0
941 }
942 DisplayPoint(clipped)
943 }
944
945 pub fn clip_ignoring_line_ends(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
946 DisplayPoint(self.block_snapshot.clip_point(point.0, bias))
947 }
948
949 pub fn clip_at_line_end(&self, point: DisplayPoint) -> DisplayPoint {
950 let mut point = point.0;
951 if point.column == self.line_len(DisplayRow(point.row)) {
952 point.column = point.column.saturating_sub(1);
953 point = self.block_snapshot.clip_point(point, Bias::Left);
954 }
955 DisplayPoint(point)
956 }
957
958 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Fold>
959 where
960 T: ToOffset,
961 {
962 self.fold_snapshot.folds_in_range(range)
963 }
964
965 pub fn blocks_in_range(
966 &self,
967 rows: Range<DisplayRow>,
968 ) -> impl Iterator<Item = (DisplayRow, &Block)> {
969 self.block_snapshot
970 .blocks_in_range(rows.start.0..rows.end.0)
971 .map(|(row, block)| (DisplayRow(row), block))
972 }
973
974 pub fn block_for_id(&self, id: BlockId) -> Option<Block> {
975 self.block_snapshot.block_for_id(id)
976 }
977
978 pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
979 self.fold_snapshot.intersects_fold(offset)
980 }
981
982 pub fn is_line_folded(&self, buffer_row: MultiBufferRow) -> bool {
983 self.fold_snapshot.is_line_folded(buffer_row)
984 }
985
986 pub fn is_block_line(&self, display_row: DisplayRow) -> bool {
987 self.block_snapshot.is_block_line(BlockRow(display_row.0))
988 }
989
990 pub fn soft_wrap_indent(&self, display_row: DisplayRow) -> Option<u32> {
991 let wrap_row = self
992 .block_snapshot
993 .to_wrap_point(BlockPoint::new(display_row.0, 0))
994 .row();
995 self.wrap_snapshot.soft_wrap_indent(wrap_row)
996 }
997
998 pub fn text(&self) -> String {
999 self.text_chunks(DisplayRow(0)).collect()
1000 }
1001
1002 pub fn line(&self, display_row: DisplayRow) -> String {
1003 let mut result = String::new();
1004 for chunk in self.text_chunks(display_row) {
1005 if let Some(ix) = chunk.find('\n') {
1006 result.push_str(&chunk[0..ix]);
1007 break;
1008 } else {
1009 result.push_str(chunk);
1010 }
1011 }
1012 result
1013 }
1014
1015 pub fn line_indent_for_buffer_row(&self, buffer_row: MultiBufferRow) -> LineIndent {
1016 let (buffer, range) = self
1017 .buffer_snapshot
1018 .buffer_line_for_row(buffer_row)
1019 .unwrap();
1020
1021 buffer.line_indent_for_row(range.start.row)
1022 }
1023
1024 pub fn line_len(&self, row: DisplayRow) -> u32 {
1025 self.block_snapshot.line_len(BlockRow(row.0))
1026 }
1027
1028 pub fn longest_row(&self) -> DisplayRow {
1029 DisplayRow(self.block_snapshot.longest_row())
1030 }
1031
1032 pub fn starts_indent(&self, buffer_row: MultiBufferRow) -> bool {
1033 let max_row = self.buffer_snapshot.max_buffer_row();
1034 if buffer_row >= max_row {
1035 return false;
1036 }
1037
1038 let line_indent = self.line_indent_for_buffer_row(buffer_row);
1039 if line_indent.is_line_blank() {
1040 return false;
1041 }
1042
1043 (buffer_row.0 + 1..=max_row.0)
1044 .find_map(|next_row| {
1045 let next_line_indent = self.line_indent_for_buffer_row(MultiBufferRow(next_row));
1046 if next_line_indent.raw_len() > line_indent.raw_len() {
1047 Some(true)
1048 } else if !next_line_indent.is_line_blank() {
1049 Some(false)
1050 } else {
1051 None
1052 }
1053 })
1054 .unwrap_or(false)
1055 }
1056
1057 pub fn foldable_range(
1058 &self,
1059 buffer_row: MultiBufferRow,
1060 ) -> Option<(Range<Point>, FoldPlaceholder)> {
1061 let start = MultiBufferPoint::new(buffer_row.0, self.buffer_snapshot.line_len(buffer_row));
1062 if let Some(crease) = self
1063 .crease_snapshot
1064 .query_row(buffer_row, &self.buffer_snapshot)
1065 {
1066 Some((
1067 crease.range.to_point(&self.buffer_snapshot),
1068 crease.placeholder.clone(),
1069 ))
1070 } else if self.starts_indent(MultiBufferRow(start.row))
1071 && !self.is_line_folded(MultiBufferRow(start.row))
1072 {
1073 let start_line_indent = self.line_indent_for_buffer_row(buffer_row);
1074 let max_point = self.buffer_snapshot.max_point();
1075 let mut end = None;
1076
1077 for row in (buffer_row.0 + 1)..=max_point.row {
1078 let line_indent = self.line_indent_for_buffer_row(MultiBufferRow(row));
1079 if !line_indent.is_line_blank()
1080 && line_indent.raw_len() <= start_line_indent.raw_len()
1081 {
1082 let prev_row = row - 1;
1083 end = Some(Point::new(
1084 prev_row,
1085 self.buffer_snapshot.line_len(MultiBufferRow(prev_row)),
1086 ));
1087 break;
1088 }
1089 }
1090
1091 let mut row_before_line_breaks = end.unwrap_or(max_point);
1092 while row_before_line_breaks.row > start.row
1093 && self
1094 .buffer_snapshot
1095 .is_line_blank(MultiBufferRow(row_before_line_breaks.row))
1096 {
1097 row_before_line_breaks.row -= 1;
1098 }
1099
1100 row_before_line_breaks = Point::new(
1101 row_before_line_breaks.row,
1102 self.buffer_snapshot
1103 .line_len(MultiBufferRow(row_before_line_breaks.row)),
1104 );
1105
1106 Some((start..row_before_line_breaks, self.fold_placeholder.clone()))
1107 } else {
1108 None
1109 }
1110 }
1111
1112 #[cfg(any(test, feature = "test-support"))]
1113 pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
1114 &self,
1115 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
1116 let type_id = TypeId::of::<Tag>();
1117 self.text_highlights.get(&Some(type_id)).cloned()
1118 }
1119
1120 #[allow(unused)]
1121 #[cfg(any(test, feature = "test-support"))]
1122 pub(crate) fn inlay_highlights<Tag: ?Sized + 'static>(
1123 &self,
1124 ) -> Option<&TreeMap<InlayId, (HighlightStyle, InlayHighlight)>> {
1125 let type_id = TypeId::of::<Tag>();
1126 self.inlay_highlights.get(&type_id)
1127 }
1128
1129 pub fn buffer_header_height(&self) -> u32 {
1130 self.block_snapshot.buffer_header_height
1131 }
1132
1133 pub fn excerpt_footer_height(&self) -> u32 {
1134 self.block_snapshot.excerpt_footer_height
1135 }
1136
1137 pub fn excerpt_header_height(&self) -> u32 {
1138 self.block_snapshot.excerpt_header_height
1139 }
1140}
1141
1142#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
1143pub struct DisplayPoint(BlockPoint);
1144
1145impl Debug for DisplayPoint {
1146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1147 f.write_fmt(format_args!(
1148 "DisplayPoint({}, {})",
1149 self.row().0,
1150 self.column()
1151 ))
1152 }
1153}
1154
1155impl Add for DisplayPoint {
1156 type Output = Self;
1157
1158 fn add(self, other: Self) -> Self::Output {
1159 DisplayPoint(BlockPoint(self.0 .0 + other.0 .0))
1160 }
1161}
1162
1163impl Sub for DisplayPoint {
1164 type Output = Self;
1165
1166 fn sub(self, other: Self) -> Self::Output {
1167 DisplayPoint(BlockPoint(self.0 .0 - other.0 .0))
1168 }
1169}
1170
1171#[derive(Debug, Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq, Deserialize, Hash)]
1172#[serde(transparent)]
1173pub struct DisplayRow(pub u32);
1174
1175impl Add for DisplayRow {
1176 type Output = Self;
1177
1178 fn add(self, other: Self) -> Self::Output {
1179 DisplayRow(self.0 + other.0)
1180 }
1181}
1182
1183impl Sub for DisplayRow {
1184 type Output = Self;
1185
1186 fn sub(self, other: Self) -> Self::Output {
1187 DisplayRow(self.0 - other.0)
1188 }
1189}
1190
1191impl DisplayPoint {
1192 pub fn new(row: DisplayRow, column: u32) -> Self {
1193 Self(BlockPoint(Point::new(row.0, column)))
1194 }
1195
1196 pub fn zero() -> Self {
1197 Self::new(DisplayRow(0), 0)
1198 }
1199
1200 pub fn is_zero(&self) -> bool {
1201 self.0.is_zero()
1202 }
1203
1204 pub fn row(self) -> DisplayRow {
1205 DisplayRow(self.0.row)
1206 }
1207
1208 pub fn column(self) -> u32 {
1209 self.0.column
1210 }
1211
1212 pub fn row_mut(&mut self) -> &mut u32 {
1213 &mut self.0.row
1214 }
1215
1216 pub fn column_mut(&mut self) -> &mut u32 {
1217 &mut self.0.column
1218 }
1219
1220 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
1221 map.display_point_to_point(self, Bias::Left)
1222 }
1223
1224 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
1225 let wrap_point = map.block_snapshot.to_wrap_point(self.0);
1226 let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
1227 let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
1228 let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
1229 map.inlay_snapshot
1230 .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
1231 }
1232}
1233
1234impl ToDisplayPoint for usize {
1235 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1236 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
1237 }
1238}
1239
1240impl ToDisplayPoint for OffsetUtf16 {
1241 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1242 self.to_offset(&map.buffer_snapshot).to_display_point(map)
1243 }
1244}
1245
1246impl ToDisplayPoint for Point {
1247 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1248 map.point_to_display_point(*self, Bias::Left)
1249 }
1250}
1251
1252impl ToDisplayPoint for Anchor {
1253 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1254 self.to_point(&map.buffer_snapshot).to_display_point(map)
1255 }
1256}
1257
1258#[cfg(test)]
1259pub mod tests {
1260 use super::*;
1261 use crate::{movement, test::marked_display_snapshot};
1262 use block_map::BlockPlacement;
1263 use gpui::{
1264 div, font, observe, px, AppContext, BorrowAppContext, Context, Element, Hsla, Rgba,
1265 };
1266 use language::{
1267 language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1268 Buffer, Diagnostic, DiagnosticEntry, DiagnosticSet, Language, LanguageConfig,
1269 LanguageMatcher,
1270 };
1271 use lsp::LanguageServerId;
1272 use project::Project;
1273 use rand::{prelude::*, Rng};
1274 use settings::SettingsStore;
1275 use smol::stream::StreamExt;
1276 use std::{env, sync::Arc};
1277 use text::PointUtf16;
1278 use theme::{LoadThemes, SyntaxTheme};
1279 use unindent::Unindent as _;
1280 use util::test::{marked_text_ranges, sample_text};
1281 use Bias::*;
1282
1283 #[gpui::test(iterations = 100)]
1284 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1285 cx.background_executor.set_block_on_ticks(0..=50);
1286 let operations = env::var("OPERATIONS")
1287 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1288 .unwrap_or(10);
1289
1290 let mut tab_size = rng.gen_range(1..=4);
1291 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1292 let excerpt_header_height = rng.gen_range(1..=5);
1293 let font_size = px(14.0);
1294 let max_wrap_width = 300.0;
1295 let mut wrap_width = if rng.gen_bool(0.1) {
1296 None
1297 } else {
1298 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1299 };
1300
1301 log::info!("tab size: {}", tab_size);
1302 log::info!("wrap width: {:?}", wrap_width);
1303
1304 cx.update(|cx| {
1305 init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1306 });
1307
1308 let buffer = cx.update(|cx| {
1309 if rng.gen() {
1310 let len = rng.gen_range(0..10);
1311 let text = util::RandomCharIter::new(&mut rng)
1312 .take(len)
1313 .collect::<String>();
1314 MultiBuffer::build_simple(&text, cx)
1315 } else {
1316 MultiBuffer::build_random(&mut rng, cx)
1317 }
1318 });
1319
1320 let map = cx.new_model(|cx| {
1321 DisplayMap::new(
1322 buffer.clone(),
1323 font("Helvetica"),
1324 font_size,
1325 wrap_width,
1326 true,
1327 buffer_start_excerpt_header_height,
1328 excerpt_header_height,
1329 0,
1330 FoldPlaceholder::test(),
1331 cx,
1332 )
1333 });
1334 let mut notifications = observe(&map, cx);
1335 let mut fold_count = 0;
1336 let mut blocks = Vec::new();
1337
1338 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1339 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1340 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1341 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1342 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1343 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1344 log::info!("display text: {:?}", snapshot.text());
1345
1346 for _i in 0..operations {
1347 match rng.gen_range(0..100) {
1348 0..=19 => {
1349 wrap_width = if rng.gen_bool(0.2) {
1350 None
1351 } else {
1352 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1353 };
1354 log::info!("setting wrap width to {:?}", wrap_width);
1355 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1356 }
1357 20..=29 => {
1358 let mut tab_sizes = vec![1, 2, 3, 4];
1359 tab_sizes.remove((tab_size - 1) as usize);
1360 tab_size = *tab_sizes.choose(&mut rng).unwrap();
1361 log::info!("setting tab size to {:?}", tab_size);
1362 cx.update(|cx| {
1363 cx.update_global::<SettingsStore, _>(|store, cx| {
1364 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1365 s.defaults.tab_size = NonZeroU32::new(tab_size);
1366 });
1367 });
1368 });
1369 }
1370 30..=44 => {
1371 map.update(cx, |map, cx| {
1372 if rng.gen() || blocks.is_empty() {
1373 let buffer = map.snapshot(cx).buffer_snapshot;
1374 let block_properties = (0..rng.gen_range(1..=1))
1375 .map(|_| {
1376 let position =
1377 buffer.anchor_after(buffer.clip_offset(
1378 rng.gen_range(0..=buffer.len()),
1379 Bias::Left,
1380 ));
1381
1382 let placement = if rng.gen() {
1383 BlockPlacement::Above(position)
1384 } else {
1385 BlockPlacement::Below(position)
1386 };
1387 let height = rng.gen_range(1..5);
1388 log::info!(
1389 "inserting block {:?} with height {}",
1390 placement.as_ref().map(|p| p.to_point(&buffer)),
1391 height
1392 );
1393 let priority = rng.gen_range(1..100);
1394 BlockProperties {
1395 placement,
1396 style: BlockStyle::Fixed,
1397 height,
1398 render: Box::new(|_| div().into_any()),
1399 priority,
1400 }
1401 })
1402 .collect::<Vec<_>>();
1403 blocks.extend(map.insert_blocks(block_properties, cx));
1404 } else {
1405 blocks.shuffle(&mut rng);
1406 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1407 let block_ids_to_remove = (0..remove_count)
1408 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1409 .collect();
1410 log::info!("removing block ids {:?}", block_ids_to_remove);
1411 map.remove_blocks(block_ids_to_remove, cx);
1412 }
1413 });
1414 }
1415 45..=79 => {
1416 let mut ranges = Vec::new();
1417 for _ in 0..rng.gen_range(1..=3) {
1418 buffer.read_with(cx, |buffer, cx| {
1419 let buffer = buffer.read(cx);
1420 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1421 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1422 ranges.push(start..end);
1423 });
1424 }
1425
1426 if rng.gen() && fold_count > 0 {
1427 log::info!("unfolding ranges: {:?}", ranges);
1428 map.update(cx, |map, cx| {
1429 map.unfold(ranges, true, cx);
1430 });
1431 } else {
1432 log::info!("folding ranges: {:?}", ranges);
1433 map.update(cx, |map, cx| {
1434 map.fold(
1435 ranges
1436 .into_iter()
1437 .map(|range| (range, FoldPlaceholder::test())),
1438 cx,
1439 );
1440 });
1441 }
1442 }
1443 _ => {
1444 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1445 }
1446 }
1447
1448 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1449 notifications.next().await.unwrap();
1450 }
1451
1452 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1453 fold_count = snapshot.fold_count();
1454 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1455 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1456 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1457 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1458 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1459 log::info!("display text: {:?}", snapshot.text());
1460
1461 // Line boundaries
1462 let buffer = &snapshot.buffer_snapshot;
1463 for _ in 0..5 {
1464 let row = rng.gen_range(0..=buffer.max_point().row);
1465 let column = rng.gen_range(0..=buffer.line_len(MultiBufferRow(row)));
1466 let point = buffer.clip_point(Point::new(row, column), Left);
1467
1468 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1469 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1470
1471 assert!(prev_buffer_bound <= point);
1472 assert!(next_buffer_bound >= point);
1473 assert_eq!(prev_buffer_bound.column, 0);
1474 assert_eq!(prev_display_bound.column(), 0);
1475 if next_buffer_bound < buffer.max_point() {
1476 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1477 }
1478
1479 assert_eq!(
1480 prev_display_bound,
1481 prev_buffer_bound.to_display_point(&snapshot),
1482 "row boundary before {:?}. reported buffer row boundary: {:?}",
1483 point,
1484 prev_buffer_bound
1485 );
1486 assert_eq!(
1487 next_display_bound,
1488 next_buffer_bound.to_display_point(&snapshot),
1489 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1490 point,
1491 next_buffer_bound
1492 );
1493 assert_eq!(
1494 prev_buffer_bound,
1495 prev_display_bound.to_point(&snapshot),
1496 "row boundary before {:?}. reported display row boundary: {:?}",
1497 point,
1498 prev_display_bound
1499 );
1500 assert_eq!(
1501 next_buffer_bound,
1502 next_display_bound.to_point(&snapshot),
1503 "row boundary after {:?}. reported display row boundary: {:?}",
1504 point,
1505 next_display_bound
1506 );
1507 }
1508
1509 // Movement
1510 let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1511 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1512 for _ in 0..5 {
1513 let row = rng.gen_range(0..=snapshot.max_point().row().0);
1514 let column = rng.gen_range(0..=snapshot.line_len(DisplayRow(row)));
1515 let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1516
1517 log::info!("Moving from point {:?}", point);
1518
1519 let moved_right = movement::right(&snapshot, point);
1520 log::info!("Right {:?}", moved_right);
1521 if point < max_point {
1522 assert!(moved_right > point);
1523 if point.column() == snapshot.line_len(point.row())
1524 || snapshot.soft_wrap_indent(point.row()).is_some()
1525 && point.column() == snapshot.line_len(point.row()) - 1
1526 {
1527 assert!(moved_right.row() > point.row());
1528 }
1529 } else {
1530 assert_eq!(moved_right, point);
1531 }
1532
1533 let moved_left = movement::left(&snapshot, point);
1534 log::info!("Left {:?}", moved_left);
1535 if point > min_point {
1536 assert!(moved_left < point);
1537 if point.column() == 0 {
1538 assert!(moved_left.row() < point.row());
1539 }
1540 } else {
1541 assert_eq!(moved_left, point);
1542 }
1543 }
1544 }
1545 }
1546
1547 #[cfg(target_os = "macos")]
1548 #[gpui::test(retries = 5)]
1549 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1550 cx.background_executor
1551 .set_block_on_ticks(usize::MAX..=usize::MAX);
1552 cx.update(|cx| {
1553 init_test(cx, |_| {});
1554 });
1555
1556 let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1557 let editor = cx.editor.clone();
1558 let window = cx.window;
1559
1560 _ = cx.update_window(window, |_, cx| {
1561 let text_layout_details =
1562 editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1563
1564 let font_size = px(12.0);
1565 let wrap_width = Some(px(64.));
1566
1567 let text = "one two three four five\nsix seven eight";
1568 let buffer = MultiBuffer::build_simple(text, cx);
1569 let map = cx.new_model(|cx| {
1570 DisplayMap::new(
1571 buffer.clone(),
1572 font("Helvetica"),
1573 font_size,
1574 wrap_width,
1575 true,
1576 1,
1577 1,
1578 0,
1579 FoldPlaceholder::test(),
1580 cx,
1581 )
1582 });
1583
1584 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1585 assert_eq!(
1586 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1587 "one two \nthree four \nfive\nsix seven \neight"
1588 );
1589 assert_eq!(
1590 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1591 DisplayPoint::new(DisplayRow(0), 7)
1592 );
1593 assert_eq!(
1594 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1595 DisplayPoint::new(DisplayRow(1), 0)
1596 );
1597 assert_eq!(
1598 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1599 DisplayPoint::new(DisplayRow(1), 0)
1600 );
1601 assert_eq!(
1602 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1603 DisplayPoint::new(DisplayRow(0), 7)
1604 );
1605
1606 let x = snapshot
1607 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1608 assert_eq!(
1609 movement::up(
1610 &snapshot,
1611 DisplayPoint::new(DisplayRow(1), 10),
1612 language::SelectionGoal::None,
1613 false,
1614 &text_layout_details,
1615 ),
1616 (
1617 DisplayPoint::new(DisplayRow(0), 7),
1618 language::SelectionGoal::HorizontalPosition(x.0)
1619 )
1620 );
1621 assert_eq!(
1622 movement::down(
1623 &snapshot,
1624 DisplayPoint::new(DisplayRow(0), 7),
1625 language::SelectionGoal::HorizontalPosition(x.0),
1626 false,
1627 &text_layout_details
1628 ),
1629 (
1630 DisplayPoint::new(DisplayRow(1), 10),
1631 language::SelectionGoal::HorizontalPosition(x.0)
1632 )
1633 );
1634 assert_eq!(
1635 movement::down(
1636 &snapshot,
1637 DisplayPoint::new(DisplayRow(1), 10),
1638 language::SelectionGoal::HorizontalPosition(x.0),
1639 false,
1640 &text_layout_details
1641 ),
1642 (
1643 DisplayPoint::new(DisplayRow(2), 4),
1644 language::SelectionGoal::HorizontalPosition(x.0)
1645 )
1646 );
1647
1648 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1649 buffer.update(cx, |buffer, cx| {
1650 buffer.edit([(ix..ix, "and ")], None, cx);
1651 });
1652
1653 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1654 assert_eq!(
1655 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1656 "three four \nfive\nsix and \nseven eight"
1657 );
1658
1659 // Re-wrap on font size changes
1660 map.update(cx, |map, cx| {
1661 map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1662 });
1663
1664 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1665 assert_eq!(
1666 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1667 "three \nfour five\nsix and \nseven \neight"
1668 )
1669 });
1670 }
1671
1672 #[gpui::test]
1673 fn test_text_chunks(cx: &mut gpui::AppContext) {
1674 init_test(cx, |_| {});
1675
1676 let text = sample_text(6, 6, 'a');
1677 let buffer = MultiBuffer::build_simple(&text, cx);
1678
1679 let font_size = px(14.0);
1680 let map = cx.new_model(|cx| {
1681 DisplayMap::new(
1682 buffer.clone(),
1683 font("Helvetica"),
1684 font_size,
1685 None,
1686 true,
1687 1,
1688 1,
1689 0,
1690 FoldPlaceholder::test(),
1691 cx,
1692 )
1693 });
1694
1695 buffer.update(cx, |buffer, cx| {
1696 buffer.edit(
1697 vec![
1698 (
1699 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1700 "\t",
1701 ),
1702 (
1703 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1704 "\t",
1705 ),
1706 (
1707 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1708 "\t",
1709 ),
1710 ],
1711 None,
1712 cx,
1713 )
1714 });
1715
1716 assert_eq!(
1717 map.update(cx, |map, cx| map.snapshot(cx))
1718 .text_chunks(DisplayRow(1))
1719 .collect::<String>()
1720 .lines()
1721 .next(),
1722 Some(" b bbbbb")
1723 );
1724 assert_eq!(
1725 map.update(cx, |map, cx| map.snapshot(cx))
1726 .text_chunks(DisplayRow(2))
1727 .collect::<String>()
1728 .lines()
1729 .next(),
1730 Some("c ccccc")
1731 );
1732 }
1733
1734 #[gpui::test]
1735 async fn test_chunks(cx: &mut gpui::TestAppContext) {
1736 let text = r#"
1737 fn outer() {}
1738
1739 mod module {
1740 fn inner() {}
1741 }"#
1742 .unindent();
1743
1744 let theme =
1745 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1746 let language = Arc::new(
1747 Language::new(
1748 LanguageConfig {
1749 name: "Test".into(),
1750 matcher: LanguageMatcher {
1751 path_suffixes: vec![".test".to_string()],
1752 ..Default::default()
1753 },
1754 ..Default::default()
1755 },
1756 Some(tree_sitter_rust::LANGUAGE.into()),
1757 )
1758 .with_highlights_query(
1759 r#"
1760 (mod_item name: (identifier) body: _ @mod.body)
1761 (function_item name: (identifier) @fn.name)
1762 "#,
1763 )
1764 .unwrap(),
1765 );
1766 language.set_theme(&theme);
1767
1768 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1769
1770 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1771 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1772 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1773
1774 let font_size = px(14.0);
1775
1776 let map = cx.new_model(|cx| {
1777 DisplayMap::new(
1778 buffer,
1779 font("Helvetica"),
1780 font_size,
1781 None,
1782 true,
1783 1,
1784 1,
1785 1,
1786 FoldPlaceholder::test(),
1787 cx,
1788 )
1789 });
1790 assert_eq!(
1791 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1792 vec![
1793 ("fn ".to_string(), None),
1794 ("outer".to_string(), Some(Hsla::blue())),
1795 ("() {}\n\nmod module ".to_string(), None),
1796 ("{\n fn ".to_string(), Some(Hsla::red())),
1797 ("inner".to_string(), Some(Hsla::blue())),
1798 ("() {}\n}".to_string(), Some(Hsla::red())),
1799 ]
1800 );
1801 assert_eq!(
1802 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1803 vec![
1804 (" fn ".to_string(), Some(Hsla::red())),
1805 ("inner".to_string(), Some(Hsla::blue())),
1806 ("() {}\n}".to_string(), Some(Hsla::red())),
1807 ]
1808 );
1809
1810 map.update(cx, |map, cx| {
1811 map.fold(
1812 vec![(
1813 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1814 FoldPlaceholder::test(),
1815 )],
1816 cx,
1817 )
1818 });
1819 assert_eq!(
1820 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
1821 vec![
1822 ("fn ".to_string(), None),
1823 ("out".to_string(), Some(Hsla::blue())),
1824 ("⋯".to_string(), None),
1825 (" fn ".to_string(), Some(Hsla::red())),
1826 ("inner".to_string(), Some(Hsla::blue())),
1827 ("() {}\n}".to_string(), Some(Hsla::red())),
1828 ]
1829 );
1830 }
1831
1832 #[gpui::test]
1833 async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
1834 cx.background_executor
1835 .set_block_on_ticks(usize::MAX..=usize::MAX);
1836
1837 let text = r#"
1838 const A: &str = "
1839 one
1840 two
1841 three
1842 ";
1843 const B: &str = "four";
1844 "#
1845 .unindent();
1846
1847 let theme = SyntaxTheme::new_test(vec![
1848 ("string", Hsla::red()),
1849 ("punctuation", Hsla::blue()),
1850 ("keyword", Hsla::green()),
1851 ]);
1852 let language = Arc::new(
1853 Language::new(
1854 LanguageConfig {
1855 name: "Rust".into(),
1856 ..Default::default()
1857 },
1858 Some(tree_sitter_rust::LANGUAGE.into()),
1859 )
1860 .with_highlights_query(
1861 r#"
1862 (string_literal) @string
1863 "const" @keyword
1864 [":" ";"] @punctuation
1865 "#,
1866 )
1867 .unwrap(),
1868 );
1869 language.set_theme(&theme);
1870
1871 cx.update(|cx| init_test(cx, |_| {}));
1872
1873 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1874 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1875 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1876 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1877
1878 let map = cx.new_model(|cx| {
1879 DisplayMap::new(
1880 buffer,
1881 font("Courier"),
1882 px(16.0),
1883 None,
1884 true,
1885 1,
1886 1,
1887 0,
1888 FoldPlaceholder::test(),
1889 cx,
1890 )
1891 });
1892
1893 // Insert a block in the middle of a multi-line string literal
1894 map.update(cx, |map, cx| {
1895 map.insert_blocks(
1896 [BlockProperties {
1897 placement: BlockPlacement::Below(
1898 buffer_snapshot.anchor_before(Point::new(1, 0)),
1899 ),
1900 height: 1,
1901 style: BlockStyle::Sticky,
1902 render: Box::new(|_| div().into_any()),
1903 priority: 0,
1904 }],
1905 cx,
1906 )
1907 });
1908
1909 pretty_assertions::assert_eq!(
1910 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
1911 [
1912 ("const".into(), Some(Hsla::green())),
1913 (" A".into(), None),
1914 (":".into(), Some(Hsla::blue())),
1915 (" &str = ".into(), None),
1916 ("\"\n one\n".into(), Some(Hsla::red())),
1917 ("\n".into(), None),
1918 (" two\n three\n\"".into(), Some(Hsla::red())),
1919 (";".into(), Some(Hsla::blue())),
1920 ("\n".into(), None),
1921 ("const".into(), Some(Hsla::green())),
1922 (" B".into(), None),
1923 (":".into(), Some(Hsla::blue())),
1924 (" &str = ".into(), None),
1925 ("\"four\"".into(), Some(Hsla::red())),
1926 (";".into(), Some(Hsla::blue())),
1927 ("\n".into(), None),
1928 ]
1929 );
1930 }
1931
1932 #[gpui::test]
1933 async fn test_chunks_with_diagnostics_across_blocks(cx: &mut gpui::TestAppContext) {
1934 cx.background_executor
1935 .set_block_on_ticks(usize::MAX..=usize::MAX);
1936
1937 let text = r#"
1938 struct A {
1939 b: usize;
1940 }
1941 const c: usize = 1;
1942 "#
1943 .unindent();
1944
1945 cx.update(|cx| init_test(cx, |_| {}));
1946
1947 let buffer = cx.new_model(|cx| Buffer::local(text, cx));
1948
1949 buffer.update(cx, |buffer, cx| {
1950 buffer.update_diagnostics(
1951 LanguageServerId(0),
1952 DiagnosticSet::new(
1953 [DiagnosticEntry {
1954 range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
1955 diagnostic: Diagnostic {
1956 severity: DiagnosticSeverity::ERROR,
1957 group_id: 1,
1958 message: "hi".into(),
1959 ..Default::default()
1960 },
1961 }],
1962 buffer,
1963 ),
1964 cx,
1965 )
1966 });
1967
1968 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1969 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1970
1971 let map = cx.new_model(|cx| {
1972 DisplayMap::new(
1973 buffer,
1974 font("Courier"),
1975 px(16.0),
1976 None,
1977 true,
1978 1,
1979 1,
1980 0,
1981 FoldPlaceholder::test(),
1982 cx,
1983 )
1984 });
1985
1986 let black = gpui::black().to_rgb();
1987 let red = gpui::red().to_rgb();
1988
1989 // Insert a block in the middle of a multi-line diagnostic.
1990 map.update(cx, |map, cx| {
1991 map.highlight_text(
1992 TypeId::of::<usize>(),
1993 vec![
1994 buffer_snapshot.anchor_before(Point::new(3, 9))
1995 ..buffer_snapshot.anchor_after(Point::new(3, 14)),
1996 buffer_snapshot.anchor_before(Point::new(3, 17))
1997 ..buffer_snapshot.anchor_after(Point::new(3, 18)),
1998 ],
1999 red.into(),
2000 );
2001 map.insert_blocks(
2002 [BlockProperties {
2003 placement: BlockPlacement::Below(
2004 buffer_snapshot.anchor_before(Point::new(1, 0)),
2005 ),
2006 height: 1,
2007 style: BlockStyle::Sticky,
2008 render: Box::new(|_| div().into_any()),
2009 priority: 0,
2010 }],
2011 cx,
2012 )
2013 });
2014
2015 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2016 let mut chunks = Vec::<(String, Option<DiagnosticSeverity>, Rgba)>::new();
2017 for chunk in snapshot.chunks(DisplayRow(0)..DisplayRow(5), true, Default::default()) {
2018 let color = chunk
2019 .highlight_style
2020 .and_then(|style| style.color)
2021 .map_or(black, |color| color.to_rgb());
2022 if let Some((last_chunk, last_severity, last_color)) = chunks.last_mut() {
2023 if *last_severity == chunk.diagnostic_severity && *last_color == color {
2024 last_chunk.push_str(chunk.text);
2025 continue;
2026 }
2027 }
2028
2029 chunks.push((chunk.text.to_string(), chunk.diagnostic_severity, color));
2030 }
2031
2032 assert_eq!(
2033 chunks,
2034 [
2035 (
2036 "struct A {\n b: usize;\n".into(),
2037 Some(DiagnosticSeverity::ERROR),
2038 black
2039 ),
2040 ("\n".into(), None, black),
2041 ("}".into(), Some(DiagnosticSeverity::ERROR), black),
2042 ("\nconst c: ".into(), None, black),
2043 ("usize".into(), None, red),
2044 (" = ".into(), None, black),
2045 ("1".into(), None, red),
2046 (";\n".into(), None, black),
2047 ]
2048 );
2049 }
2050
2051 // todo(linux) fails due to pixel differences in text rendering
2052 #[cfg(target_os = "macos")]
2053 #[gpui::test]
2054 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
2055 cx.background_executor
2056 .set_block_on_ticks(usize::MAX..=usize::MAX);
2057
2058 let text = r#"
2059 fn outer() {}
2060
2061 mod module {
2062 fn inner() {}
2063 }"#
2064 .unindent();
2065
2066 let theme =
2067 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2068 let language = Arc::new(
2069 Language::new(
2070 LanguageConfig {
2071 name: "Test".into(),
2072 matcher: LanguageMatcher {
2073 path_suffixes: vec![".test".to_string()],
2074 ..Default::default()
2075 },
2076 ..Default::default()
2077 },
2078 Some(tree_sitter_rust::LANGUAGE.into()),
2079 )
2080 .with_highlights_query(
2081 r#"
2082 (mod_item name: (identifier) body: _ @mod.body)
2083 (function_item name: (identifier) @fn.name)
2084 "#,
2085 )
2086 .unwrap(),
2087 );
2088 language.set_theme(&theme);
2089
2090 cx.update(|cx| init_test(cx, |_| {}));
2091
2092 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
2093 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2094 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
2095
2096 let font_size = px(16.0);
2097
2098 let map = cx.new_model(|cx| {
2099 DisplayMap::new(
2100 buffer,
2101 font("Courier"),
2102 font_size,
2103 Some(px(40.0)),
2104 true,
2105 1,
2106 1,
2107 0,
2108 FoldPlaceholder::test(),
2109 cx,
2110 )
2111 });
2112 assert_eq!(
2113 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2114 [
2115 ("fn \n".to_string(), None),
2116 ("oute\nr".to_string(), Some(Hsla::blue())),
2117 ("() \n{}\n\n".to_string(), None),
2118 ]
2119 );
2120 assert_eq!(
2121 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2122 [("{}\n\n".to_string(), None)]
2123 );
2124
2125 map.update(cx, |map, cx| {
2126 map.fold(
2127 vec![(
2128 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2129 FoldPlaceholder::test(),
2130 )],
2131 cx,
2132 )
2133 });
2134 assert_eq!(
2135 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
2136 [
2137 ("out".to_string(), Some(Hsla::blue())),
2138 ("⋯\n".to_string(), None),
2139 (" \nfn ".to_string(), Some(Hsla::red())),
2140 ("i\n".to_string(), Some(Hsla::blue()))
2141 ]
2142 );
2143 }
2144
2145 #[gpui::test]
2146 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
2147 cx.update(|cx| init_test(cx, |_| {}));
2148
2149 let theme =
2150 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
2151 let language = Arc::new(
2152 Language::new(
2153 LanguageConfig {
2154 name: "Test".into(),
2155 matcher: LanguageMatcher {
2156 path_suffixes: vec![".test".to_string()],
2157 ..Default::default()
2158 },
2159 ..Default::default()
2160 },
2161 Some(tree_sitter_rust::LANGUAGE.into()),
2162 )
2163 .with_highlights_query(
2164 r#"
2165 ":" @operator
2166 (string_literal) @string
2167 "#,
2168 )
2169 .unwrap(),
2170 );
2171 language.set_theme(&theme);
2172
2173 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
2174
2175 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
2176 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2177
2178 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
2179 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2180
2181 let font_size = px(16.0);
2182 let map = cx.new_model(|cx| {
2183 DisplayMap::new(
2184 buffer,
2185 font("Courier"),
2186 font_size,
2187 None,
2188 true,
2189 1,
2190 1,
2191 1,
2192 FoldPlaceholder::test(),
2193 cx,
2194 )
2195 });
2196
2197 enum MyType {}
2198
2199 let style = HighlightStyle {
2200 color: Some(Hsla::blue()),
2201 ..Default::default()
2202 };
2203
2204 map.update(cx, |map, _cx| {
2205 map.highlight_text(
2206 TypeId::of::<MyType>(),
2207 highlighted_ranges
2208 .into_iter()
2209 .map(|range| {
2210 buffer_snapshot.anchor_before(range.start)
2211 ..buffer_snapshot.anchor_before(range.end)
2212 })
2213 .collect(),
2214 style,
2215 );
2216 });
2217
2218 assert_eq!(
2219 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
2220 [
2221 ("const ".to_string(), None, None),
2222 ("a".to_string(), None, Some(Hsla::blue())),
2223 (":".to_string(), Some(Hsla::red()), None),
2224 (" B = ".to_string(), None, None),
2225 ("\"c ".to_string(), Some(Hsla::green()), None),
2226 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2227 ("\"".to_string(), Some(Hsla::green()), None),
2228 ]
2229 );
2230 }
2231
2232 #[gpui::test]
2233 fn test_clip_point(cx: &mut gpui::AppContext) {
2234 init_test(cx, |_| {});
2235
2236 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
2237 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2238
2239 match bias {
2240 Bias::Left => {
2241 if shift_right {
2242 *markers[1].column_mut() += 1;
2243 }
2244
2245 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2246 }
2247 Bias::Right => {
2248 if shift_right {
2249 *markers[0].column_mut() += 1;
2250 }
2251
2252 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2253 }
2254 };
2255 }
2256
2257 use Bias::{Left, Right};
2258 assert("ˇˇα", false, Left, cx);
2259 assert("ˇˇα", true, Left, cx);
2260 assert("ˇˇα", false, Right, cx);
2261 assert("ˇαˇ", true, Right, cx);
2262 assert("ˇˇ✋", false, Left, cx);
2263 assert("ˇˇ✋", true, Left, cx);
2264 assert("ˇˇ✋", false, Right, cx);
2265 assert("ˇ✋ˇ", true, Right, cx);
2266 assert("ˇˇ🍐", false, Left, cx);
2267 assert("ˇˇ🍐", true, Left, cx);
2268 assert("ˇˇ🍐", false, Right, cx);
2269 assert("ˇ🍐ˇ", true, Right, cx);
2270 assert("ˇˇ\t", false, Left, cx);
2271 assert("ˇˇ\t", true, Left, cx);
2272 assert("ˇˇ\t", false, Right, cx);
2273 assert("ˇ\tˇ", true, Right, cx);
2274 assert(" ˇˇ\t", false, Left, cx);
2275 assert(" ˇˇ\t", true, Left, cx);
2276 assert(" ˇˇ\t", false, Right, cx);
2277 assert(" ˇ\tˇ", true, Right, cx);
2278 assert(" ˇˇ\t", false, Left, cx);
2279 assert(" ˇˇ\t", false, Right, cx);
2280 }
2281
2282 #[gpui::test]
2283 fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
2284 init_test(cx, |_| {});
2285
2286 fn assert(text: &str, cx: &mut gpui::AppContext) {
2287 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2288 unmarked_snapshot.clip_at_line_ends = true;
2289 assert_eq!(
2290 unmarked_snapshot.clip_point(markers[1], Bias::Left),
2291 markers[0]
2292 );
2293 }
2294
2295 assert("ˇˇ", cx);
2296 assert("ˇaˇ", cx);
2297 assert("aˇbˇ", cx);
2298 assert("aˇαˇ", cx);
2299 }
2300
2301 #[gpui::test]
2302 fn test_creases(cx: &mut gpui::AppContext) {
2303 init_test(cx, |_| {});
2304
2305 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2306 let buffer = MultiBuffer::build_simple(text, cx);
2307 let font_size = px(14.0);
2308 cx.new_model(|cx| {
2309 let mut map = DisplayMap::new(
2310 buffer.clone(),
2311 font("Helvetica"),
2312 font_size,
2313 None,
2314 true,
2315 1,
2316 1,
2317 0,
2318 FoldPlaceholder::test(),
2319 cx,
2320 );
2321 let snapshot = map.buffer.read(cx).snapshot(cx);
2322 let range =
2323 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2324
2325 map.crease_map.insert(
2326 [Crease::new(
2327 range,
2328 FoldPlaceholder::test(),
2329 |_row, _status, _toggle, _cx| div(),
2330 |_row, _status, _cx| div(),
2331 )],
2332 &map.buffer.read(cx).snapshot(cx),
2333 );
2334
2335 map
2336 });
2337 }
2338
2339 #[gpui::test]
2340 fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
2341 init_test(cx, |_| {});
2342
2343 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
2344 let buffer = MultiBuffer::build_simple(text, cx);
2345 let font_size = px(14.0);
2346
2347 let map = cx.new_model(|cx| {
2348 DisplayMap::new(
2349 buffer.clone(),
2350 font("Helvetica"),
2351 font_size,
2352 None,
2353 true,
2354 1,
2355 1,
2356 0,
2357 FoldPlaceholder::test(),
2358 cx,
2359 )
2360 });
2361 let map = map.update(cx, |map, cx| map.snapshot(cx));
2362 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
2363 assert_eq!(
2364 map.text_chunks(DisplayRow(0)).collect::<String>(),
2365 "✅ α\nβ \n🏀β γ"
2366 );
2367 assert_eq!(
2368 map.text_chunks(DisplayRow(1)).collect::<String>(),
2369 "β \n🏀β γ"
2370 );
2371 assert_eq!(
2372 map.text_chunks(DisplayRow(2)).collect::<String>(),
2373 "🏀β γ"
2374 );
2375
2376 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
2377 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
2378 assert_eq!(point.to_display_point(&map), display_point);
2379 assert_eq!(display_point.to_point(&map), point);
2380
2381 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2382 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
2383 assert_eq!(point.to_display_point(&map), display_point);
2384 assert_eq!(display_point.to_point(&map), point,);
2385
2386 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2387 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
2388 assert_eq!(point.to_display_point(&map), display_point);
2389 assert_eq!(display_point.to_point(&map), point,);
2390
2391 // Display points inside of expanded tabs
2392 assert_eq!(
2393 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2394 MultiBufferPoint::new(0, "✅\t".len() as u32),
2395 );
2396 assert_eq!(
2397 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2398 MultiBufferPoint::new(0, "✅".len() as u32),
2399 );
2400
2401 // Clipping display points inside of multi-byte characters
2402 assert_eq!(
2403 map.clip_point(
2404 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2405 Left
2406 ),
2407 DisplayPoint::new(DisplayRow(0), 0)
2408 );
2409 assert_eq!(
2410 map.clip_point(
2411 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2412 Bias::Right
2413 ),
2414 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
2415 );
2416 }
2417
2418 #[gpui::test]
2419 fn test_max_point(cx: &mut gpui::AppContext) {
2420 init_test(cx, |_| {});
2421
2422 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2423 let font_size = px(14.0);
2424 let map = cx.new_model(|cx| {
2425 DisplayMap::new(
2426 buffer.clone(),
2427 font("Helvetica"),
2428 font_size,
2429 None,
2430 true,
2431 1,
2432 1,
2433 0,
2434 FoldPlaceholder::test(),
2435 cx,
2436 )
2437 });
2438 assert_eq!(
2439 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2440 DisplayPoint::new(DisplayRow(1), 11)
2441 )
2442 }
2443
2444 fn syntax_chunks(
2445 rows: Range<DisplayRow>,
2446 map: &Model<DisplayMap>,
2447 theme: &SyntaxTheme,
2448 cx: &mut AppContext,
2449 ) -> Vec<(String, Option<Hsla>)> {
2450 chunks(rows, map, theme, cx)
2451 .into_iter()
2452 .map(|(text, color, _)| (text, color))
2453 .collect()
2454 }
2455
2456 fn chunks(
2457 rows: Range<DisplayRow>,
2458 map: &Model<DisplayMap>,
2459 theme: &SyntaxTheme,
2460 cx: &mut AppContext,
2461 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2462 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2463 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2464 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2465 let syntax_color = chunk
2466 .syntax_highlight_id
2467 .and_then(|id| id.style(theme)?.color);
2468 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2469 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
2470 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2471 last_chunk.push_str(chunk.text);
2472 continue;
2473 }
2474 }
2475 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2476 }
2477 chunks
2478 }
2479
2480 fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
2481 let settings = SettingsStore::test(cx);
2482 cx.set_global(settings);
2483 language::init(cx);
2484 crate::init(cx);
2485 Project::init_settings(cx);
2486 theme::init(LoadThemes::JustBase, cx);
2487 cx.update_global::<SettingsStore, _>(|store, cx| {
2488 store.update_user_settings::<AllLanguageSettings>(cx, f);
2489 });
2490 }
2491}