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::{div, font, observe, px, AppContext, BorrowAppContext, Context, Element, Hsla};
1264 use language::{
1265 language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1266 Buffer, Language, LanguageConfig, LanguageMatcher,
1267 };
1268 use project::Project;
1269 use rand::{prelude::*, Rng};
1270 use settings::SettingsStore;
1271 use smol::stream::StreamExt;
1272 use std::{env, sync::Arc};
1273 use theme::{LoadThemes, SyntaxTheme};
1274 use unindent::Unindent as _;
1275 use util::test::{marked_text_ranges, sample_text};
1276 use Bias::*;
1277
1278 #[gpui::test(iterations = 100)]
1279 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1280 cx.background_executor.set_block_on_ticks(0..=50);
1281 let operations = env::var("OPERATIONS")
1282 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1283 .unwrap_or(10);
1284
1285 let mut tab_size = rng.gen_range(1..=4);
1286 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1287 let excerpt_header_height = rng.gen_range(1..=5);
1288 let font_size = px(14.0);
1289 let max_wrap_width = 300.0;
1290 let mut wrap_width = if rng.gen_bool(0.1) {
1291 None
1292 } else {
1293 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1294 };
1295
1296 log::info!("tab size: {}", tab_size);
1297 log::info!("wrap width: {:?}", wrap_width);
1298
1299 cx.update(|cx| {
1300 init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1301 });
1302
1303 let buffer = cx.update(|cx| {
1304 if rng.gen() {
1305 let len = rng.gen_range(0..10);
1306 let text = util::RandomCharIter::new(&mut rng)
1307 .take(len)
1308 .collect::<String>();
1309 MultiBuffer::build_simple(&text, cx)
1310 } else {
1311 MultiBuffer::build_random(&mut rng, cx)
1312 }
1313 });
1314
1315 let map = cx.new_model(|cx| {
1316 DisplayMap::new(
1317 buffer.clone(),
1318 font("Helvetica"),
1319 font_size,
1320 wrap_width,
1321 true,
1322 buffer_start_excerpt_header_height,
1323 excerpt_header_height,
1324 0,
1325 FoldPlaceholder::test(),
1326 cx,
1327 )
1328 });
1329 let mut notifications = observe(&map, cx);
1330 let mut fold_count = 0;
1331 let mut blocks = Vec::new();
1332
1333 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1334 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1335 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1336 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1337 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1338 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1339 log::info!("display text: {:?}", snapshot.text());
1340
1341 for _i in 0..operations {
1342 match rng.gen_range(0..100) {
1343 0..=19 => {
1344 wrap_width = if rng.gen_bool(0.2) {
1345 None
1346 } else {
1347 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1348 };
1349 log::info!("setting wrap width to {:?}", wrap_width);
1350 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1351 }
1352 20..=29 => {
1353 let mut tab_sizes = vec![1, 2, 3, 4];
1354 tab_sizes.remove((tab_size - 1) as usize);
1355 tab_size = *tab_sizes.choose(&mut rng).unwrap();
1356 log::info!("setting tab size to {:?}", tab_size);
1357 cx.update(|cx| {
1358 cx.update_global::<SettingsStore, _>(|store, cx| {
1359 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1360 s.defaults.tab_size = NonZeroU32::new(tab_size);
1361 });
1362 });
1363 });
1364 }
1365 30..=44 => {
1366 map.update(cx, |map, cx| {
1367 if rng.gen() || blocks.is_empty() {
1368 let buffer = map.snapshot(cx).buffer_snapshot;
1369 let block_properties = (0..rng.gen_range(1..=1))
1370 .map(|_| {
1371 let position =
1372 buffer.anchor_after(buffer.clip_offset(
1373 rng.gen_range(0..=buffer.len()),
1374 Bias::Left,
1375 ));
1376
1377 let placement = if rng.gen() {
1378 BlockPlacement::Above(position)
1379 } else {
1380 BlockPlacement::Below(position)
1381 };
1382 let height = rng.gen_range(1..5);
1383 log::info!(
1384 "inserting block {:?} with height {}",
1385 placement.as_ref().map(|p| p.to_point(&buffer)),
1386 height
1387 );
1388 let priority = rng.gen_range(1..100);
1389 BlockProperties {
1390 placement,
1391 style: BlockStyle::Fixed,
1392 height,
1393 render: Box::new(|_| div().into_any()),
1394 priority,
1395 }
1396 })
1397 .collect::<Vec<_>>();
1398 blocks.extend(map.insert_blocks(block_properties, cx));
1399 } else {
1400 blocks.shuffle(&mut rng);
1401 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1402 let block_ids_to_remove = (0..remove_count)
1403 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1404 .collect();
1405 log::info!("removing block ids {:?}", block_ids_to_remove);
1406 map.remove_blocks(block_ids_to_remove, cx);
1407 }
1408 });
1409 }
1410 45..=79 => {
1411 let mut ranges = Vec::new();
1412 for _ in 0..rng.gen_range(1..=3) {
1413 buffer.read_with(cx, |buffer, cx| {
1414 let buffer = buffer.read(cx);
1415 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1416 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1417 ranges.push(start..end);
1418 });
1419 }
1420
1421 if rng.gen() && fold_count > 0 {
1422 log::info!("unfolding ranges: {:?}", ranges);
1423 map.update(cx, |map, cx| {
1424 map.unfold(ranges, true, cx);
1425 });
1426 } else {
1427 log::info!("folding ranges: {:?}", ranges);
1428 map.update(cx, |map, cx| {
1429 map.fold(
1430 ranges
1431 .into_iter()
1432 .map(|range| (range, FoldPlaceholder::test())),
1433 cx,
1434 );
1435 });
1436 }
1437 }
1438 _ => {
1439 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1440 }
1441 }
1442
1443 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1444 notifications.next().await.unwrap();
1445 }
1446
1447 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1448 fold_count = snapshot.fold_count();
1449 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1450 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1451 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1452 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1453 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1454 log::info!("display text: {:?}", snapshot.text());
1455
1456 // Line boundaries
1457 let buffer = &snapshot.buffer_snapshot;
1458 for _ in 0..5 {
1459 let row = rng.gen_range(0..=buffer.max_point().row);
1460 let column = rng.gen_range(0..=buffer.line_len(MultiBufferRow(row)));
1461 let point = buffer.clip_point(Point::new(row, column), Left);
1462
1463 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1464 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1465
1466 assert!(prev_buffer_bound <= point);
1467 assert!(next_buffer_bound >= point);
1468 assert_eq!(prev_buffer_bound.column, 0);
1469 assert_eq!(prev_display_bound.column(), 0);
1470 if next_buffer_bound < buffer.max_point() {
1471 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1472 }
1473
1474 assert_eq!(
1475 prev_display_bound,
1476 prev_buffer_bound.to_display_point(&snapshot),
1477 "row boundary before {:?}. reported buffer row boundary: {:?}",
1478 point,
1479 prev_buffer_bound
1480 );
1481 assert_eq!(
1482 next_display_bound,
1483 next_buffer_bound.to_display_point(&snapshot),
1484 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1485 point,
1486 next_buffer_bound
1487 );
1488 assert_eq!(
1489 prev_buffer_bound,
1490 prev_display_bound.to_point(&snapshot),
1491 "row boundary before {:?}. reported display row boundary: {:?}",
1492 point,
1493 prev_display_bound
1494 );
1495 assert_eq!(
1496 next_buffer_bound,
1497 next_display_bound.to_point(&snapshot),
1498 "row boundary after {:?}. reported display row boundary: {:?}",
1499 point,
1500 next_display_bound
1501 );
1502 }
1503
1504 // Movement
1505 let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1506 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1507 for _ in 0..5 {
1508 let row = rng.gen_range(0..=snapshot.max_point().row().0);
1509 let column = rng.gen_range(0..=snapshot.line_len(DisplayRow(row)));
1510 let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1511
1512 log::info!("Moving from point {:?}", point);
1513
1514 let moved_right = movement::right(&snapshot, point);
1515 log::info!("Right {:?}", moved_right);
1516 if point < max_point {
1517 assert!(moved_right > point);
1518 if point.column() == snapshot.line_len(point.row())
1519 || snapshot.soft_wrap_indent(point.row()).is_some()
1520 && point.column() == snapshot.line_len(point.row()) - 1
1521 {
1522 assert!(moved_right.row() > point.row());
1523 }
1524 } else {
1525 assert_eq!(moved_right, point);
1526 }
1527
1528 let moved_left = movement::left(&snapshot, point);
1529 log::info!("Left {:?}", moved_left);
1530 if point > min_point {
1531 assert!(moved_left < point);
1532 if point.column() == 0 {
1533 assert!(moved_left.row() < point.row());
1534 }
1535 } else {
1536 assert_eq!(moved_left, point);
1537 }
1538 }
1539 }
1540 }
1541
1542 #[cfg(target_os = "macos")]
1543 #[gpui::test(retries = 5)]
1544 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1545 cx.background_executor
1546 .set_block_on_ticks(usize::MAX..=usize::MAX);
1547 cx.update(|cx| {
1548 init_test(cx, |_| {});
1549 });
1550
1551 let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1552 let editor = cx.editor.clone();
1553 let window = cx.window;
1554
1555 _ = cx.update_window(window, |_, cx| {
1556 let text_layout_details =
1557 editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1558
1559 let font_size = px(12.0);
1560 let wrap_width = Some(px(64.));
1561
1562 let text = "one two three four five\nsix seven eight";
1563 let buffer = MultiBuffer::build_simple(text, cx);
1564 let map = cx.new_model(|cx| {
1565 DisplayMap::new(
1566 buffer.clone(),
1567 font("Helvetica"),
1568 font_size,
1569 wrap_width,
1570 true,
1571 1,
1572 1,
1573 0,
1574 FoldPlaceholder::test(),
1575 cx,
1576 )
1577 });
1578
1579 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1580 assert_eq!(
1581 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1582 "one two \nthree four \nfive\nsix seven \neight"
1583 );
1584 assert_eq!(
1585 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1586 DisplayPoint::new(DisplayRow(0), 7)
1587 );
1588 assert_eq!(
1589 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1590 DisplayPoint::new(DisplayRow(1), 0)
1591 );
1592 assert_eq!(
1593 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1594 DisplayPoint::new(DisplayRow(1), 0)
1595 );
1596 assert_eq!(
1597 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1598 DisplayPoint::new(DisplayRow(0), 7)
1599 );
1600
1601 let x = snapshot
1602 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1603 assert_eq!(
1604 movement::up(
1605 &snapshot,
1606 DisplayPoint::new(DisplayRow(1), 10),
1607 language::SelectionGoal::None,
1608 false,
1609 &text_layout_details,
1610 ),
1611 (
1612 DisplayPoint::new(DisplayRow(0), 7),
1613 language::SelectionGoal::HorizontalPosition(x.0)
1614 )
1615 );
1616 assert_eq!(
1617 movement::down(
1618 &snapshot,
1619 DisplayPoint::new(DisplayRow(0), 7),
1620 language::SelectionGoal::HorizontalPosition(x.0),
1621 false,
1622 &text_layout_details
1623 ),
1624 (
1625 DisplayPoint::new(DisplayRow(1), 10),
1626 language::SelectionGoal::HorizontalPosition(x.0)
1627 )
1628 );
1629 assert_eq!(
1630 movement::down(
1631 &snapshot,
1632 DisplayPoint::new(DisplayRow(1), 10),
1633 language::SelectionGoal::HorizontalPosition(x.0),
1634 false,
1635 &text_layout_details
1636 ),
1637 (
1638 DisplayPoint::new(DisplayRow(2), 4),
1639 language::SelectionGoal::HorizontalPosition(x.0)
1640 )
1641 );
1642
1643 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1644 buffer.update(cx, |buffer, cx| {
1645 buffer.edit([(ix..ix, "and ")], None, cx);
1646 });
1647
1648 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1649 assert_eq!(
1650 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1651 "three four \nfive\nsix and \nseven eight"
1652 );
1653
1654 // Re-wrap on font size changes
1655 map.update(cx, |map, cx| {
1656 map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1657 });
1658
1659 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1660 assert_eq!(
1661 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1662 "three \nfour five\nsix and \nseven \neight"
1663 )
1664 });
1665 }
1666
1667 #[gpui::test]
1668 fn test_text_chunks(cx: &mut gpui::AppContext) {
1669 init_test(cx, |_| {});
1670
1671 let text = sample_text(6, 6, 'a');
1672 let buffer = MultiBuffer::build_simple(&text, cx);
1673
1674 let font_size = px(14.0);
1675 let map = cx.new_model(|cx| {
1676 DisplayMap::new(
1677 buffer.clone(),
1678 font("Helvetica"),
1679 font_size,
1680 None,
1681 true,
1682 1,
1683 1,
1684 0,
1685 FoldPlaceholder::test(),
1686 cx,
1687 )
1688 });
1689
1690 buffer.update(cx, |buffer, cx| {
1691 buffer.edit(
1692 vec![
1693 (
1694 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1695 "\t",
1696 ),
1697 (
1698 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1699 "\t",
1700 ),
1701 (
1702 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1703 "\t",
1704 ),
1705 ],
1706 None,
1707 cx,
1708 )
1709 });
1710
1711 assert_eq!(
1712 map.update(cx, |map, cx| map.snapshot(cx))
1713 .text_chunks(DisplayRow(1))
1714 .collect::<String>()
1715 .lines()
1716 .next(),
1717 Some(" b bbbbb")
1718 );
1719 assert_eq!(
1720 map.update(cx, |map, cx| map.snapshot(cx))
1721 .text_chunks(DisplayRow(2))
1722 .collect::<String>()
1723 .lines()
1724 .next(),
1725 Some("c ccccc")
1726 );
1727 }
1728
1729 #[gpui::test]
1730 async fn test_chunks(cx: &mut gpui::TestAppContext) {
1731 let text = r#"
1732 fn outer() {}
1733
1734 mod module {
1735 fn inner() {}
1736 }"#
1737 .unindent();
1738
1739 let theme =
1740 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1741 let language = Arc::new(
1742 Language::new(
1743 LanguageConfig {
1744 name: "Test".into(),
1745 matcher: LanguageMatcher {
1746 path_suffixes: vec![".test".to_string()],
1747 ..Default::default()
1748 },
1749 ..Default::default()
1750 },
1751 Some(tree_sitter_rust::LANGUAGE.into()),
1752 )
1753 .with_highlights_query(
1754 r#"
1755 (mod_item name: (identifier) body: _ @mod.body)
1756 (function_item name: (identifier) @fn.name)
1757 "#,
1758 )
1759 .unwrap(),
1760 );
1761 language.set_theme(&theme);
1762
1763 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1764
1765 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1766 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1767 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1768
1769 let font_size = px(14.0);
1770
1771 let map = cx.new_model(|cx| {
1772 DisplayMap::new(
1773 buffer,
1774 font("Helvetica"),
1775 font_size,
1776 None,
1777 true,
1778 1,
1779 1,
1780 1,
1781 FoldPlaceholder::test(),
1782 cx,
1783 )
1784 });
1785 assert_eq!(
1786 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1787 vec![
1788 ("fn ".to_string(), None),
1789 ("outer".to_string(), Some(Hsla::blue())),
1790 ("() {}\n\nmod module ".to_string(), None),
1791 ("{\n fn ".to_string(), Some(Hsla::red())),
1792 ("inner".to_string(), Some(Hsla::blue())),
1793 ("() {}\n}".to_string(), Some(Hsla::red())),
1794 ]
1795 );
1796 assert_eq!(
1797 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1798 vec![
1799 (" fn ".to_string(), Some(Hsla::red())),
1800 ("inner".to_string(), Some(Hsla::blue())),
1801 ("() {}\n}".to_string(), Some(Hsla::red())),
1802 ]
1803 );
1804
1805 map.update(cx, |map, cx| {
1806 map.fold(
1807 vec![(
1808 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1809 FoldPlaceholder::test(),
1810 )],
1811 cx,
1812 )
1813 });
1814 assert_eq!(
1815 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
1816 vec![
1817 ("fn ".to_string(), None),
1818 ("out".to_string(), Some(Hsla::blue())),
1819 ("⋯".to_string(), None),
1820 (" fn ".to_string(), Some(Hsla::red())),
1821 ("inner".to_string(), Some(Hsla::blue())),
1822 ("() {}\n}".to_string(), Some(Hsla::red())),
1823 ]
1824 );
1825 }
1826
1827 #[gpui::test]
1828 async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
1829 cx.background_executor
1830 .set_block_on_ticks(usize::MAX..=usize::MAX);
1831
1832 let text = r#"
1833 const A: &str = "
1834 one
1835 two
1836 three
1837 ";
1838 const B: &str = "four";
1839 "#
1840 .unindent();
1841
1842 let theme = SyntaxTheme::new_test(vec![
1843 ("string", Hsla::red()),
1844 ("punctuation", Hsla::blue()),
1845 ("keyword", Hsla::green()),
1846 ]);
1847 let language = Arc::new(
1848 Language::new(
1849 LanguageConfig {
1850 name: "Rust".into(),
1851 ..Default::default()
1852 },
1853 Some(tree_sitter_rust::LANGUAGE.into()),
1854 )
1855 .with_highlights_query(
1856 r#"
1857 (string_literal) @string
1858 "const" @keyword
1859 [":" ";"] @punctuation
1860 "#,
1861 )
1862 .unwrap(),
1863 );
1864 language.set_theme(&theme);
1865
1866 cx.update(|cx| init_test(cx, |_| {}));
1867
1868 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1869 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1870 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1871 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1872
1873 let map = cx.new_model(|cx| {
1874 DisplayMap::new(
1875 buffer,
1876 font("Courier"),
1877 px(16.0),
1878 None,
1879 true,
1880 1,
1881 1,
1882 0,
1883 FoldPlaceholder::test(),
1884 cx,
1885 )
1886 });
1887
1888 // Insert a block in the middle of a multi-line string literal
1889 map.update(cx, |map, cx| {
1890 map.insert_blocks(
1891 [BlockProperties {
1892 placement: BlockPlacement::Below(
1893 buffer_snapshot.anchor_before(Point::new(1, 0)),
1894 ),
1895 height: 1,
1896 style: BlockStyle::Sticky,
1897 render: Box::new(|_| div().into_any()),
1898 priority: 0,
1899 }],
1900 cx,
1901 )
1902 });
1903
1904 pretty_assertions::assert_eq!(
1905 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
1906 [
1907 ("const".into(), Some(Hsla::green())),
1908 (" A".into(), None),
1909 (":".into(), Some(Hsla::blue())),
1910 (" &str = ".into(), None),
1911 ("\"\n one\n".into(), Some(Hsla::red())),
1912 ("\n".into(), None),
1913 (" two\n three\n\"".into(), Some(Hsla::red())),
1914 (";".into(), Some(Hsla::blue())),
1915 ("\n".into(), None),
1916 ("const".into(), Some(Hsla::green())),
1917 (" B".into(), None),
1918 (":".into(), Some(Hsla::blue())),
1919 (" &str = ".into(), None),
1920 ("\"four\"".into(), Some(Hsla::red())),
1921 (";".into(), Some(Hsla::blue())),
1922 ("\n".into(), None),
1923 ]
1924 );
1925 }
1926
1927 // todo(linux) fails due to pixel differences in text rendering
1928 #[cfg(target_os = "macos")]
1929 #[gpui::test]
1930 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1931 cx.background_executor
1932 .set_block_on_ticks(usize::MAX..=usize::MAX);
1933
1934 let text = r#"
1935 fn outer() {}
1936
1937 mod module {
1938 fn inner() {}
1939 }"#
1940 .unindent();
1941
1942 let theme =
1943 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1944 let language = Arc::new(
1945 Language::new(
1946 LanguageConfig {
1947 name: "Test".into(),
1948 matcher: LanguageMatcher {
1949 path_suffixes: vec![".test".to_string()],
1950 ..Default::default()
1951 },
1952 ..Default::default()
1953 },
1954 Some(tree_sitter_rust::LANGUAGE.into()),
1955 )
1956 .with_highlights_query(
1957 r#"
1958 (mod_item name: (identifier) body: _ @mod.body)
1959 (function_item name: (identifier) @fn.name)
1960 "#,
1961 )
1962 .unwrap(),
1963 );
1964 language.set_theme(&theme);
1965
1966 cx.update(|cx| init_test(cx, |_| {}));
1967
1968 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1969 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1970 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1971
1972 let font_size = px(16.0);
1973
1974 let map = cx.new_model(|cx| {
1975 DisplayMap::new(
1976 buffer,
1977 font("Courier"),
1978 font_size,
1979 Some(px(40.0)),
1980 true,
1981 1,
1982 1,
1983 0,
1984 FoldPlaceholder::test(),
1985 cx,
1986 )
1987 });
1988 assert_eq!(
1989 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1990 [
1991 ("fn \n".to_string(), None),
1992 ("oute\nr".to_string(), Some(Hsla::blue())),
1993 ("() \n{}\n\n".to_string(), None),
1994 ]
1995 );
1996 assert_eq!(
1997 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1998 [("{}\n\n".to_string(), None)]
1999 );
2000
2001 map.update(cx, |map, cx| {
2002 map.fold(
2003 vec![(
2004 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2005 FoldPlaceholder::test(),
2006 )],
2007 cx,
2008 )
2009 });
2010 assert_eq!(
2011 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
2012 [
2013 ("out".to_string(), Some(Hsla::blue())),
2014 ("⋯\n".to_string(), None),
2015 (" \nfn ".to_string(), Some(Hsla::red())),
2016 ("i\n".to_string(), Some(Hsla::blue()))
2017 ]
2018 );
2019 }
2020
2021 #[gpui::test]
2022 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
2023 cx.update(|cx| init_test(cx, |_| {}));
2024
2025 let theme =
2026 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
2027 let language = Arc::new(
2028 Language::new(
2029 LanguageConfig {
2030 name: "Test".into(),
2031 matcher: LanguageMatcher {
2032 path_suffixes: vec![".test".to_string()],
2033 ..Default::default()
2034 },
2035 ..Default::default()
2036 },
2037 Some(tree_sitter_rust::LANGUAGE.into()),
2038 )
2039 .with_highlights_query(
2040 r#"
2041 ":" @operator
2042 (string_literal) @string
2043 "#,
2044 )
2045 .unwrap(),
2046 );
2047 language.set_theme(&theme);
2048
2049 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
2050
2051 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
2052 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2053
2054 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
2055 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2056
2057 let font_size = px(16.0);
2058 let map = cx.new_model(|cx| {
2059 DisplayMap::new(
2060 buffer,
2061 font("Courier"),
2062 font_size,
2063 None,
2064 true,
2065 1,
2066 1,
2067 1,
2068 FoldPlaceholder::test(),
2069 cx,
2070 )
2071 });
2072
2073 enum MyType {}
2074
2075 let style = HighlightStyle {
2076 color: Some(Hsla::blue()),
2077 ..Default::default()
2078 };
2079
2080 map.update(cx, |map, _cx| {
2081 map.highlight_text(
2082 TypeId::of::<MyType>(),
2083 highlighted_ranges
2084 .into_iter()
2085 .map(|range| {
2086 buffer_snapshot.anchor_before(range.start)
2087 ..buffer_snapshot.anchor_before(range.end)
2088 })
2089 .collect(),
2090 style,
2091 );
2092 });
2093
2094 assert_eq!(
2095 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
2096 [
2097 ("const ".to_string(), None, None),
2098 ("a".to_string(), None, Some(Hsla::blue())),
2099 (":".to_string(), Some(Hsla::red()), None),
2100 (" B = ".to_string(), None, None),
2101 ("\"c ".to_string(), Some(Hsla::green()), None),
2102 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2103 ("\"".to_string(), Some(Hsla::green()), None),
2104 ]
2105 );
2106 }
2107
2108 #[gpui::test]
2109 fn test_clip_point(cx: &mut gpui::AppContext) {
2110 init_test(cx, |_| {});
2111
2112 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
2113 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2114
2115 match bias {
2116 Bias::Left => {
2117 if shift_right {
2118 *markers[1].column_mut() += 1;
2119 }
2120
2121 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2122 }
2123 Bias::Right => {
2124 if shift_right {
2125 *markers[0].column_mut() += 1;
2126 }
2127
2128 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2129 }
2130 };
2131 }
2132
2133 use Bias::{Left, Right};
2134 assert("ˇˇα", false, Left, cx);
2135 assert("ˇˇα", true, Left, cx);
2136 assert("ˇˇα", false, Right, cx);
2137 assert("ˇαˇ", true, Right, cx);
2138 assert("ˇˇ✋", false, Left, cx);
2139 assert("ˇˇ✋", true, Left, cx);
2140 assert("ˇˇ✋", false, Right, cx);
2141 assert("ˇ✋ˇ", true, Right, cx);
2142 assert("ˇˇ🍐", false, Left, cx);
2143 assert("ˇˇ🍐", true, Left, cx);
2144 assert("ˇˇ🍐", false, Right, cx);
2145 assert("ˇ🍐ˇ", true, Right, cx);
2146 assert("ˇˇ\t", false, Left, cx);
2147 assert("ˇˇ\t", true, Left, cx);
2148 assert("ˇˇ\t", false, Right, cx);
2149 assert("ˇ\tˇ", true, Right, cx);
2150 assert(" ˇˇ\t", false, Left, cx);
2151 assert(" ˇˇ\t", true, Left, cx);
2152 assert(" ˇˇ\t", false, Right, cx);
2153 assert(" ˇ\tˇ", true, Right, cx);
2154 assert(" ˇˇ\t", false, Left, cx);
2155 assert(" ˇˇ\t", false, Right, cx);
2156 }
2157
2158 #[gpui::test]
2159 fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
2160 init_test(cx, |_| {});
2161
2162 fn assert(text: &str, cx: &mut gpui::AppContext) {
2163 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2164 unmarked_snapshot.clip_at_line_ends = true;
2165 assert_eq!(
2166 unmarked_snapshot.clip_point(markers[1], Bias::Left),
2167 markers[0]
2168 );
2169 }
2170
2171 assert("ˇˇ", cx);
2172 assert("ˇaˇ", cx);
2173 assert("aˇbˇ", cx);
2174 assert("aˇαˇ", cx);
2175 }
2176
2177 #[gpui::test]
2178 fn test_creases(cx: &mut gpui::AppContext) {
2179 init_test(cx, |_| {});
2180
2181 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2182 let buffer = MultiBuffer::build_simple(text, cx);
2183 let font_size = px(14.0);
2184 cx.new_model(|cx| {
2185 let mut map = DisplayMap::new(
2186 buffer.clone(),
2187 font("Helvetica"),
2188 font_size,
2189 None,
2190 true,
2191 1,
2192 1,
2193 0,
2194 FoldPlaceholder::test(),
2195 cx,
2196 );
2197 let snapshot = map.buffer.read(cx).snapshot(cx);
2198 let range =
2199 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2200
2201 map.crease_map.insert(
2202 [Crease::new(
2203 range,
2204 FoldPlaceholder::test(),
2205 |_row, _status, _toggle, _cx| div(),
2206 |_row, _status, _cx| div(),
2207 )],
2208 &map.buffer.read(cx).snapshot(cx),
2209 );
2210
2211 map
2212 });
2213 }
2214
2215 #[gpui::test]
2216 fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
2217 init_test(cx, |_| {});
2218
2219 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
2220 let buffer = MultiBuffer::build_simple(text, cx);
2221 let font_size = px(14.0);
2222
2223 let map = cx.new_model(|cx| {
2224 DisplayMap::new(
2225 buffer.clone(),
2226 font("Helvetica"),
2227 font_size,
2228 None,
2229 true,
2230 1,
2231 1,
2232 0,
2233 FoldPlaceholder::test(),
2234 cx,
2235 )
2236 });
2237 let map = map.update(cx, |map, cx| map.snapshot(cx));
2238 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
2239 assert_eq!(
2240 map.text_chunks(DisplayRow(0)).collect::<String>(),
2241 "✅ α\nβ \n🏀β γ"
2242 );
2243 assert_eq!(
2244 map.text_chunks(DisplayRow(1)).collect::<String>(),
2245 "β \n🏀β γ"
2246 );
2247 assert_eq!(
2248 map.text_chunks(DisplayRow(2)).collect::<String>(),
2249 "🏀β γ"
2250 );
2251
2252 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
2253 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
2254 assert_eq!(point.to_display_point(&map), display_point);
2255 assert_eq!(display_point.to_point(&map), point);
2256
2257 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2258 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
2259 assert_eq!(point.to_display_point(&map), display_point);
2260 assert_eq!(display_point.to_point(&map), point,);
2261
2262 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2263 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
2264 assert_eq!(point.to_display_point(&map), display_point);
2265 assert_eq!(display_point.to_point(&map), point,);
2266
2267 // Display points inside of expanded tabs
2268 assert_eq!(
2269 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2270 MultiBufferPoint::new(0, "✅\t".len() as u32),
2271 );
2272 assert_eq!(
2273 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2274 MultiBufferPoint::new(0, "✅".len() as u32),
2275 );
2276
2277 // Clipping display points inside of multi-byte characters
2278 assert_eq!(
2279 map.clip_point(
2280 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2281 Left
2282 ),
2283 DisplayPoint::new(DisplayRow(0), 0)
2284 );
2285 assert_eq!(
2286 map.clip_point(
2287 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2288 Bias::Right
2289 ),
2290 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
2291 );
2292 }
2293
2294 #[gpui::test]
2295 fn test_max_point(cx: &mut gpui::AppContext) {
2296 init_test(cx, |_| {});
2297
2298 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2299 let font_size = px(14.0);
2300 let map = cx.new_model(|cx| {
2301 DisplayMap::new(
2302 buffer.clone(),
2303 font("Helvetica"),
2304 font_size,
2305 None,
2306 true,
2307 1,
2308 1,
2309 0,
2310 FoldPlaceholder::test(),
2311 cx,
2312 )
2313 });
2314 assert_eq!(
2315 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2316 DisplayPoint::new(DisplayRow(1), 11)
2317 )
2318 }
2319
2320 fn syntax_chunks(
2321 rows: Range<DisplayRow>,
2322 map: &Model<DisplayMap>,
2323 theme: &SyntaxTheme,
2324 cx: &mut AppContext,
2325 ) -> Vec<(String, Option<Hsla>)> {
2326 chunks(rows, map, theme, cx)
2327 .into_iter()
2328 .map(|(text, color, _)| (text, color))
2329 .collect()
2330 }
2331
2332 fn chunks(
2333 rows: Range<DisplayRow>,
2334 map: &Model<DisplayMap>,
2335 theme: &SyntaxTheme,
2336 cx: &mut AppContext,
2337 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2338 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2339 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2340 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2341 let syntax_color = chunk
2342 .syntax_highlight_id
2343 .and_then(|id| id.style(theme)?.color);
2344 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2345 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
2346 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2347 last_chunk.push_str(chunk.text);
2348 continue;
2349 }
2350 }
2351 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2352 }
2353 chunks
2354 }
2355
2356 fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
2357 let settings = SettingsStore::test(cx);
2358 cx.set_global(settings);
2359 language::init(cx);
2360 crate::init(cx);
2361 Project::init_settings(cx);
2362 theme::init(LoadThemes::JustBase, cx);
2363 cx.update_global::<SettingsStore, _>(|store, cx| {
2364 store.update_user_settings::<AllLanguageSettings>(cx, f);
2365 });
2366 }
2367}