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