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