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