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