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 #[gpui::test(retries = 5)]
1761 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1762 cx.background_executor
1763 .set_block_on_ticks(usize::MAX..=usize::MAX);
1764 cx.update(|cx| {
1765 init_test(cx, |_| {});
1766 });
1767
1768 let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1769 let editor = cx.editor.clone();
1770 let window = cx.window;
1771
1772 _ = cx.update_window(window, |_, window, cx| {
1773 let text_layout_details =
1774 editor.update(cx, |editor, _cx| editor.text_layout_details(window));
1775
1776 let font_size = px(12.0);
1777 let wrap_width = Some(px(96.));
1778
1779 let text = "one two three four five\nsix seven eight";
1780 let buffer = MultiBuffer::build_simple(text, cx);
1781 let map = cx.new(|cx| {
1782 DisplayMap::new(
1783 buffer.clone(),
1784 font("Helvetica"),
1785 font_size,
1786 wrap_width,
1787 1,
1788 1,
1789 FoldPlaceholder::test(),
1790 cx,
1791 )
1792 });
1793
1794 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1795 assert_eq!(
1796 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1797 "one two \nthree four \nfive\nsix seven \neight"
1798 );
1799 assert_eq!(
1800 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1801 DisplayPoint::new(DisplayRow(0), 7)
1802 );
1803 assert_eq!(
1804 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1805 DisplayPoint::new(DisplayRow(1), 0)
1806 );
1807 assert_eq!(
1808 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1809 DisplayPoint::new(DisplayRow(1), 0)
1810 );
1811 assert_eq!(
1812 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1813 DisplayPoint::new(DisplayRow(0), 7)
1814 );
1815
1816 let x = snapshot
1817 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1818 assert_eq!(
1819 movement::up(
1820 &snapshot,
1821 DisplayPoint::new(DisplayRow(1), 10),
1822 language::SelectionGoal::None,
1823 false,
1824 &text_layout_details,
1825 ),
1826 (
1827 DisplayPoint::new(DisplayRow(0), 7),
1828 language::SelectionGoal::HorizontalPosition(x.0)
1829 )
1830 );
1831 assert_eq!(
1832 movement::down(
1833 &snapshot,
1834 DisplayPoint::new(DisplayRow(0), 7),
1835 language::SelectionGoal::HorizontalPosition(x.0),
1836 false,
1837 &text_layout_details
1838 ),
1839 (
1840 DisplayPoint::new(DisplayRow(1), 10),
1841 language::SelectionGoal::HorizontalPosition(x.0)
1842 )
1843 );
1844 assert_eq!(
1845 movement::down(
1846 &snapshot,
1847 DisplayPoint::new(DisplayRow(1), 10),
1848 language::SelectionGoal::HorizontalPosition(x.0),
1849 false,
1850 &text_layout_details
1851 ),
1852 (
1853 DisplayPoint::new(DisplayRow(2), 4),
1854 language::SelectionGoal::HorizontalPosition(x.0)
1855 )
1856 );
1857
1858 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1859 buffer.update(cx, |buffer, cx| {
1860 buffer.edit([(ix..ix, "and ")], None, cx);
1861 });
1862
1863 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1864 assert_eq!(
1865 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1866 "three four \nfive\nsix and \nseven eight"
1867 );
1868
1869 // Re-wrap on font size changes
1870 map.update(cx, |map, cx| {
1871 map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1872 });
1873
1874 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1875 assert_eq!(
1876 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1877 "three \nfour five\nsix and \nseven \neight"
1878 )
1879 });
1880 }
1881
1882 #[gpui::test]
1883 fn test_text_chunks(cx: &mut gpui::App) {
1884 init_test(cx, |_| {});
1885
1886 let text = sample_text(6, 6, 'a');
1887 let buffer = MultiBuffer::build_simple(&text, cx);
1888
1889 let font_size = px(14.0);
1890 let map = cx.new(|cx| {
1891 DisplayMap::new(
1892 buffer.clone(),
1893 font("Helvetica"),
1894 font_size,
1895 None,
1896 1,
1897 1,
1898 FoldPlaceholder::test(),
1899 cx,
1900 )
1901 });
1902
1903 buffer.update(cx, |buffer, cx| {
1904 buffer.edit(
1905 vec![
1906 (
1907 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1908 "\t",
1909 ),
1910 (
1911 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1912 "\t",
1913 ),
1914 (
1915 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1916 "\t",
1917 ),
1918 ],
1919 None,
1920 cx,
1921 )
1922 });
1923
1924 assert_eq!(
1925 map.update(cx, |map, cx| map.snapshot(cx))
1926 .text_chunks(DisplayRow(1))
1927 .collect::<String>()
1928 .lines()
1929 .next(),
1930 Some(" b bbbbb")
1931 );
1932 assert_eq!(
1933 map.update(cx, |map, cx| map.snapshot(cx))
1934 .text_chunks(DisplayRow(2))
1935 .collect::<String>()
1936 .lines()
1937 .next(),
1938 Some("c ccccc")
1939 );
1940 }
1941
1942 #[gpui::test]
1943 fn test_inlays_with_newlines_after_blocks(cx: &mut gpui::TestAppContext) {
1944 cx.update(|cx| init_test(cx, |_| {}));
1945
1946 let buffer = cx.new(|cx| Buffer::local("a", cx));
1947 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1948 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1949
1950 let font_size = px(14.0);
1951 let map = cx.new(|cx| {
1952 DisplayMap::new(
1953 buffer.clone(),
1954 font("Helvetica"),
1955 font_size,
1956 None,
1957 1,
1958 1,
1959 FoldPlaceholder::test(),
1960 cx,
1961 )
1962 });
1963
1964 map.update(cx, |map, cx| {
1965 map.insert_blocks(
1966 [BlockProperties {
1967 placement: BlockPlacement::Above(
1968 buffer_snapshot.anchor_before(Point::new(0, 0)),
1969 ),
1970 height: Some(2),
1971 style: BlockStyle::Sticky,
1972 render: Arc::new(|_| div().into_any()),
1973 priority: 0,
1974 }],
1975 cx,
1976 );
1977 });
1978 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\na"));
1979
1980 map.update(cx, |map, cx| {
1981 map.splice_inlays(
1982 &[],
1983 vec![Inlay {
1984 id: InlayId::InlineCompletion(0),
1985 position: buffer_snapshot.anchor_after(0),
1986 text: "\n".into(),
1987 }],
1988 cx,
1989 );
1990 });
1991 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\na"));
1992
1993 // Regression test: updating the display map does not crash when a
1994 // block is immediately followed by a multi-line inlay.
1995 buffer.update(cx, |buffer, cx| {
1996 buffer.edit([(1..1, "b")], None, cx);
1997 });
1998 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\nab"));
1999 }
2000
2001 #[gpui::test]
2002 async fn test_chunks(cx: &mut gpui::TestAppContext) {
2003 let text = r#"
2004 fn outer() {}
2005
2006 mod module {
2007 fn inner() {}
2008 }"#
2009 .unindent();
2010
2011 let theme =
2012 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2013 let language = Arc::new(
2014 Language::new(
2015 LanguageConfig {
2016 name: "Test".into(),
2017 matcher: LanguageMatcher {
2018 path_suffixes: vec![".test".to_string()],
2019 ..Default::default()
2020 },
2021 ..Default::default()
2022 },
2023 Some(tree_sitter_rust::LANGUAGE.into()),
2024 )
2025 .with_highlights_query(
2026 r#"
2027 (mod_item name: (identifier) body: _ @mod.body)
2028 (function_item name: (identifier) @fn.name)
2029 "#,
2030 )
2031 .unwrap(),
2032 );
2033 language.set_theme(&theme);
2034
2035 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
2036
2037 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2038 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2039 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2040
2041 let font_size = px(14.0);
2042
2043 let map = cx.new(|cx| {
2044 DisplayMap::new(
2045 buffer,
2046 font("Helvetica"),
2047 font_size,
2048 None,
2049 1,
2050 1,
2051 FoldPlaceholder::test(),
2052 cx,
2053 )
2054 });
2055 assert_eq!(
2056 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2057 vec![
2058 ("fn ".to_string(), None),
2059 ("outer".to_string(), Some(Hsla::blue())),
2060 ("() {}\n\nmod module ".to_string(), None),
2061 ("{\n fn ".to_string(), Some(Hsla::red())),
2062 ("inner".to_string(), Some(Hsla::blue())),
2063 ("() {}\n}".to_string(), Some(Hsla::red())),
2064 ]
2065 );
2066 assert_eq!(
2067 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2068 vec![
2069 (" fn ".to_string(), Some(Hsla::red())),
2070 ("inner".to_string(), Some(Hsla::blue())),
2071 ("() {}\n}".to_string(), Some(Hsla::red())),
2072 ]
2073 );
2074
2075 map.update(cx, |map, cx| {
2076 map.fold(
2077 vec![Crease::simple(
2078 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2079 FoldPlaceholder::test(),
2080 )],
2081 cx,
2082 )
2083 });
2084 assert_eq!(
2085 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
2086 vec![
2087 ("fn ".to_string(), None),
2088 ("out".to_string(), Some(Hsla::blue())),
2089 ("⋯".to_string(), None),
2090 (" fn ".to_string(), Some(Hsla::red())),
2091 ("inner".to_string(), Some(Hsla::blue())),
2092 ("() {}\n}".to_string(), Some(Hsla::red())),
2093 ]
2094 );
2095 }
2096
2097 #[gpui::test]
2098 async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
2099 cx.background_executor
2100 .set_block_on_ticks(usize::MAX..=usize::MAX);
2101
2102 let text = r#"
2103 const A: &str = "
2104 one
2105 two
2106 three
2107 ";
2108 const B: &str = "four";
2109 "#
2110 .unindent();
2111
2112 let theme = SyntaxTheme::new_test(vec![
2113 ("string", Hsla::red()),
2114 ("punctuation", Hsla::blue()),
2115 ("keyword", Hsla::green()),
2116 ]);
2117 let language = Arc::new(
2118 Language::new(
2119 LanguageConfig {
2120 name: "Rust".into(),
2121 ..Default::default()
2122 },
2123 Some(tree_sitter_rust::LANGUAGE.into()),
2124 )
2125 .with_highlights_query(
2126 r#"
2127 (string_literal) @string
2128 "const" @keyword
2129 [":" ";"] @punctuation
2130 "#,
2131 )
2132 .unwrap(),
2133 );
2134 language.set_theme(&theme);
2135
2136 cx.update(|cx| init_test(cx, |_| {}));
2137
2138 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2139 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2140 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2141 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2142
2143 let map = cx.new(|cx| {
2144 DisplayMap::new(
2145 buffer,
2146 font("Courier"),
2147 px(16.0),
2148 None,
2149 1,
2150 1,
2151 FoldPlaceholder::test(),
2152 cx,
2153 )
2154 });
2155
2156 // Insert two blocks in the middle of a multi-line string literal.
2157 // The second block has zero height.
2158 map.update(cx, |map, cx| {
2159 map.insert_blocks(
2160 [
2161 BlockProperties {
2162 placement: BlockPlacement::Below(
2163 buffer_snapshot.anchor_before(Point::new(1, 0)),
2164 ),
2165 height: Some(1),
2166 style: BlockStyle::Sticky,
2167 render: Arc::new(|_| div().into_any()),
2168 priority: 0,
2169 },
2170 BlockProperties {
2171 placement: BlockPlacement::Below(
2172 buffer_snapshot.anchor_before(Point::new(2, 0)),
2173 ),
2174 height: None,
2175 style: BlockStyle::Sticky,
2176 render: Arc::new(|_| div().into_any()),
2177 priority: 0,
2178 },
2179 ],
2180 cx,
2181 )
2182 });
2183
2184 pretty_assertions::assert_eq!(
2185 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
2186 [
2187 ("const".into(), Some(Hsla::green())),
2188 (" A".into(), None),
2189 (":".into(), Some(Hsla::blue())),
2190 (" &str = ".into(), None),
2191 ("\"\n one\n".into(), Some(Hsla::red())),
2192 ("\n".into(), None),
2193 (" two\n three\n\"".into(), Some(Hsla::red())),
2194 (";".into(), Some(Hsla::blue())),
2195 ("\n".into(), None),
2196 ("const".into(), Some(Hsla::green())),
2197 (" B".into(), None),
2198 (":".into(), Some(Hsla::blue())),
2199 (" &str = ".into(), None),
2200 ("\"four\"".into(), Some(Hsla::red())),
2201 (";".into(), Some(Hsla::blue())),
2202 ("\n".into(), None),
2203 ]
2204 );
2205 }
2206
2207 #[gpui::test]
2208 async fn test_chunks_with_diagnostics_across_blocks(cx: &mut gpui::TestAppContext) {
2209 cx.background_executor
2210 .set_block_on_ticks(usize::MAX..=usize::MAX);
2211
2212 let text = r#"
2213 struct A {
2214 b: usize;
2215 }
2216 const c: usize = 1;
2217 "#
2218 .unindent();
2219
2220 cx.update(|cx| init_test(cx, |_| {}));
2221
2222 let buffer = cx.new(|cx| Buffer::local(text, cx));
2223
2224 buffer.update(cx, |buffer, cx| {
2225 buffer.update_diagnostics(
2226 LanguageServerId(0),
2227 DiagnosticSet::new(
2228 [DiagnosticEntry {
2229 range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
2230 diagnostic: Diagnostic {
2231 severity: DiagnosticSeverity::ERROR,
2232 group_id: 1,
2233 message: "hi".into(),
2234 ..Default::default()
2235 },
2236 }],
2237 buffer,
2238 ),
2239 cx,
2240 )
2241 });
2242
2243 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2244 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2245
2246 let map = cx.new(|cx| {
2247 DisplayMap::new(
2248 buffer,
2249 font("Courier"),
2250 px(16.0),
2251 None,
2252 1,
2253 1,
2254 FoldPlaceholder::test(),
2255 cx,
2256 )
2257 });
2258
2259 let black = gpui::black().to_rgb();
2260 let red = gpui::red().to_rgb();
2261
2262 // Insert a block in the middle of a multi-line diagnostic.
2263 map.update(cx, |map, cx| {
2264 map.highlight_text(
2265 TypeId::of::<usize>(),
2266 vec![
2267 buffer_snapshot.anchor_before(Point::new(3, 9))
2268 ..buffer_snapshot.anchor_after(Point::new(3, 14)),
2269 buffer_snapshot.anchor_before(Point::new(3, 17))
2270 ..buffer_snapshot.anchor_after(Point::new(3, 18)),
2271 ],
2272 red.into(),
2273 );
2274 map.insert_blocks(
2275 [BlockProperties {
2276 placement: BlockPlacement::Below(
2277 buffer_snapshot.anchor_before(Point::new(1, 0)),
2278 ),
2279 height: Some(1),
2280 style: BlockStyle::Sticky,
2281 render: Arc::new(|_| div().into_any()),
2282 priority: 0,
2283 }],
2284 cx,
2285 )
2286 });
2287
2288 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2289 let mut chunks = Vec::<(String, Option<DiagnosticSeverity>, Rgba)>::new();
2290 for chunk in snapshot.chunks(DisplayRow(0)..DisplayRow(5), true, Default::default()) {
2291 let color = chunk
2292 .highlight_style
2293 .and_then(|style| style.color)
2294 .map_or(black, |color| color.to_rgb());
2295 if let Some((last_chunk, last_severity, last_color)) = chunks.last_mut() {
2296 if *last_severity == chunk.diagnostic_severity && *last_color == color {
2297 last_chunk.push_str(chunk.text);
2298 continue;
2299 }
2300 }
2301
2302 chunks.push((chunk.text.to_string(), chunk.diagnostic_severity, color));
2303 }
2304
2305 assert_eq!(
2306 chunks,
2307 [
2308 (
2309 "struct A {\n b: usize;\n".into(),
2310 Some(DiagnosticSeverity::ERROR),
2311 black
2312 ),
2313 ("\n".into(), None, black),
2314 ("}".into(), Some(DiagnosticSeverity::ERROR), black),
2315 ("\nconst c: ".into(), None, black),
2316 ("usize".into(), None, red),
2317 (" = ".into(), None, black),
2318 ("1".into(), None, red),
2319 (";\n".into(), None, black),
2320 ]
2321 );
2322 }
2323
2324 #[gpui::test]
2325 async fn test_point_translation_with_replace_blocks(cx: &mut gpui::TestAppContext) {
2326 cx.background_executor
2327 .set_block_on_ticks(usize::MAX..=usize::MAX);
2328
2329 cx.update(|cx| init_test(cx, |_| {}));
2330
2331 let buffer = cx.update(|cx| MultiBuffer::build_simple("abcde\nfghij\nklmno\npqrst", cx));
2332 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2333 let map = cx.new(|cx| {
2334 DisplayMap::new(
2335 buffer.clone(),
2336 font("Courier"),
2337 px(16.0),
2338 None,
2339 1,
2340 1,
2341 FoldPlaceholder::test(),
2342 cx,
2343 )
2344 });
2345
2346 let snapshot = map.update(cx, |map, cx| {
2347 map.insert_blocks(
2348 [BlockProperties {
2349 placement: BlockPlacement::Replace(
2350 buffer_snapshot.anchor_before(Point::new(1, 2))
2351 ..=buffer_snapshot.anchor_after(Point::new(2, 3)),
2352 ),
2353 height: Some(4),
2354 style: BlockStyle::Fixed,
2355 render: Arc::new(|_| div().into_any()),
2356 priority: 0,
2357 }],
2358 cx,
2359 );
2360 map.snapshot(cx)
2361 });
2362
2363 assert_eq!(snapshot.text(), "abcde\n\n\n\n\npqrst");
2364
2365 let point_to_display_points = [
2366 (Point::new(1, 0), DisplayPoint::new(DisplayRow(1), 0)),
2367 (Point::new(2, 0), DisplayPoint::new(DisplayRow(1), 0)),
2368 (Point::new(3, 0), DisplayPoint::new(DisplayRow(5), 0)),
2369 ];
2370 for (buffer_point, display_point) in point_to_display_points {
2371 assert_eq!(
2372 snapshot.point_to_display_point(buffer_point, Bias::Left),
2373 display_point,
2374 "point_to_display_point({:?}, Bias::Left)",
2375 buffer_point
2376 );
2377 assert_eq!(
2378 snapshot.point_to_display_point(buffer_point, Bias::Right),
2379 display_point,
2380 "point_to_display_point({:?}, Bias::Right)",
2381 buffer_point
2382 );
2383 }
2384
2385 let display_points_to_points = [
2386 (
2387 DisplayPoint::new(DisplayRow(1), 0),
2388 Point::new(1, 0),
2389 Point::new(2, 5),
2390 ),
2391 (
2392 DisplayPoint::new(DisplayRow(2), 0),
2393 Point::new(1, 0),
2394 Point::new(2, 5),
2395 ),
2396 (
2397 DisplayPoint::new(DisplayRow(3), 0),
2398 Point::new(1, 0),
2399 Point::new(2, 5),
2400 ),
2401 (
2402 DisplayPoint::new(DisplayRow(4), 0),
2403 Point::new(1, 0),
2404 Point::new(2, 5),
2405 ),
2406 (
2407 DisplayPoint::new(DisplayRow(5), 0),
2408 Point::new(3, 0),
2409 Point::new(3, 0),
2410 ),
2411 ];
2412 for (display_point, left_buffer_point, right_buffer_point) in display_points_to_points {
2413 assert_eq!(
2414 snapshot.display_point_to_point(display_point, Bias::Left),
2415 left_buffer_point,
2416 "display_point_to_point({:?}, Bias::Left)",
2417 display_point
2418 );
2419 assert_eq!(
2420 snapshot.display_point_to_point(display_point, Bias::Right),
2421 right_buffer_point,
2422 "display_point_to_point({:?}, Bias::Right)",
2423 display_point
2424 );
2425 }
2426 }
2427
2428 #[gpui::test]
2429 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
2430 cx.background_executor
2431 .set_block_on_ticks(usize::MAX..=usize::MAX);
2432
2433 let text = r#"
2434 fn outer() {}
2435
2436 mod module {
2437 fn inner() {}
2438 }"#
2439 .unindent();
2440
2441 let theme =
2442 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2443 let language = Arc::new(
2444 Language::new(
2445 LanguageConfig {
2446 name: "Test".into(),
2447 matcher: LanguageMatcher {
2448 path_suffixes: vec![".test".to_string()],
2449 ..Default::default()
2450 },
2451 ..Default::default()
2452 },
2453 Some(tree_sitter_rust::LANGUAGE.into()),
2454 )
2455 .with_highlights_query(
2456 r#"
2457 (mod_item name: (identifier) body: _ @mod.body)
2458 (function_item name: (identifier) @fn.name)
2459 "#,
2460 )
2461 .unwrap(),
2462 );
2463 language.set_theme(&theme);
2464
2465 cx.update(|cx| init_test(cx, |_| {}));
2466
2467 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2468 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2469 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2470
2471 let font_size = px(16.0);
2472
2473 let map = cx.new(|cx| {
2474 DisplayMap::new(
2475 buffer,
2476 font("Courier"),
2477 font_size,
2478 Some(px(40.0)),
2479 1,
2480 1,
2481 FoldPlaceholder::test(),
2482 cx,
2483 )
2484 });
2485 assert_eq!(
2486 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2487 [
2488 ("fn \n".to_string(), None),
2489 ("oute\nr".to_string(), Some(Hsla::blue())),
2490 ("() \n{}\n\n".to_string(), None),
2491 ]
2492 );
2493 assert_eq!(
2494 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2495 [("{}\n\n".to_string(), None)]
2496 );
2497
2498 map.update(cx, |map, cx| {
2499 map.fold(
2500 vec![Crease::simple(
2501 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2502 FoldPlaceholder::test(),
2503 )],
2504 cx,
2505 )
2506 });
2507 assert_eq!(
2508 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
2509 [
2510 ("out".to_string(), Some(Hsla::blue())),
2511 ("⋯\n".to_string(), None),
2512 (" \nfn ".to_string(), Some(Hsla::red())),
2513 ("i\n".to_string(), Some(Hsla::blue()))
2514 ]
2515 );
2516 }
2517
2518 #[gpui::test]
2519 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
2520 cx.update(|cx| init_test(cx, |_| {}));
2521
2522 let theme =
2523 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
2524 let language = Arc::new(
2525 Language::new(
2526 LanguageConfig {
2527 name: "Test".into(),
2528 matcher: LanguageMatcher {
2529 path_suffixes: vec![".test".to_string()],
2530 ..Default::default()
2531 },
2532 ..Default::default()
2533 },
2534 Some(tree_sitter_rust::LANGUAGE.into()),
2535 )
2536 .with_highlights_query(
2537 r#"
2538 ":" @operator
2539 (string_literal) @string
2540 "#,
2541 )
2542 .unwrap(),
2543 );
2544 language.set_theme(&theme);
2545
2546 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
2547
2548 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2549 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2550
2551 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2552 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2553
2554 let font_size = px(16.0);
2555 let map = cx.new(|cx| {
2556 DisplayMap::new(
2557 buffer,
2558 font("Courier"),
2559 font_size,
2560 None,
2561 1,
2562 1,
2563 FoldPlaceholder::test(),
2564 cx,
2565 )
2566 });
2567
2568 enum MyType {}
2569
2570 let style = HighlightStyle {
2571 color: Some(Hsla::blue()),
2572 ..Default::default()
2573 };
2574
2575 map.update(cx, |map, _cx| {
2576 map.highlight_text(
2577 TypeId::of::<MyType>(),
2578 highlighted_ranges
2579 .into_iter()
2580 .map(|range| {
2581 buffer_snapshot.anchor_before(range.start)
2582 ..buffer_snapshot.anchor_before(range.end)
2583 })
2584 .collect(),
2585 style,
2586 );
2587 });
2588
2589 assert_eq!(
2590 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
2591 [
2592 ("const ".to_string(), None, None),
2593 ("a".to_string(), None, Some(Hsla::blue())),
2594 (":".to_string(), Some(Hsla::red()), None),
2595 (" B = ".to_string(), None, None),
2596 ("\"c ".to_string(), Some(Hsla::green()), None),
2597 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2598 ("\"".to_string(), Some(Hsla::green()), None),
2599 ]
2600 );
2601 }
2602
2603 #[gpui::test]
2604 fn test_clip_point(cx: &mut gpui::App) {
2605 init_test(cx, |_| {});
2606
2607 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::App) {
2608 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2609
2610 match bias {
2611 Bias::Left => {
2612 if shift_right {
2613 *markers[1].column_mut() += 1;
2614 }
2615
2616 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2617 }
2618 Bias::Right => {
2619 if shift_right {
2620 *markers[0].column_mut() += 1;
2621 }
2622
2623 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2624 }
2625 };
2626 }
2627
2628 use Bias::{Left, Right};
2629 assert("ˇˇα", false, Left, cx);
2630 assert("ˇˇα", true, Left, cx);
2631 assert("ˇˇα", false, Right, cx);
2632 assert("ˇαˇ", true, Right, cx);
2633 assert("ˇˇ✋", false, Left, cx);
2634 assert("ˇˇ✋", true, Left, cx);
2635 assert("ˇˇ✋", false, Right, cx);
2636 assert("ˇ✋ˇ", true, Right, cx);
2637 assert("ˇˇ🍐", false, Left, cx);
2638 assert("ˇˇ🍐", true, Left, cx);
2639 assert("ˇˇ🍐", false, Right, cx);
2640 assert("ˇ🍐ˇ", true, Right, cx);
2641 assert("ˇˇ\t", false, Left, cx);
2642 assert("ˇˇ\t", true, Left, cx);
2643 assert("ˇˇ\t", false, Right, cx);
2644 assert("ˇ\tˇ", true, Right, cx);
2645 assert(" ˇˇ\t", false, Left, cx);
2646 assert(" ˇˇ\t", true, Left, cx);
2647 assert(" ˇˇ\t", false, Right, cx);
2648 assert(" ˇ\tˇ", true, Right, cx);
2649 assert(" ˇˇ\t", false, Left, cx);
2650 assert(" ˇˇ\t", false, Right, cx);
2651 }
2652
2653 #[gpui::test]
2654 fn test_clip_at_line_ends(cx: &mut gpui::App) {
2655 init_test(cx, |_| {});
2656
2657 fn assert(text: &str, cx: &mut gpui::App) {
2658 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2659 unmarked_snapshot.clip_at_line_ends = true;
2660 assert_eq!(
2661 unmarked_snapshot.clip_point(markers[1], Bias::Left),
2662 markers[0]
2663 );
2664 }
2665
2666 assert("ˇˇ", cx);
2667 assert("ˇaˇ", cx);
2668 assert("aˇbˇ", cx);
2669 assert("aˇαˇ", cx);
2670 }
2671
2672 #[gpui::test]
2673 fn test_creases(cx: &mut gpui::App) {
2674 init_test(cx, |_| {});
2675
2676 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2677 let buffer = MultiBuffer::build_simple(text, cx);
2678 let font_size = px(14.0);
2679 cx.new(|cx| {
2680 let mut map = DisplayMap::new(
2681 buffer.clone(),
2682 font("Helvetica"),
2683 font_size,
2684 None,
2685 1,
2686 1,
2687 FoldPlaceholder::test(),
2688 cx,
2689 );
2690 let snapshot = map.buffer.read(cx).snapshot(cx);
2691 let range =
2692 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2693
2694 map.crease_map.insert(
2695 [Crease::inline(
2696 range,
2697 FoldPlaceholder::test(),
2698 |_row, _status, _toggle, _window, _cx| div(),
2699 |_row, _status, _window, _cx| div(),
2700 )],
2701 &map.buffer.read(cx).snapshot(cx),
2702 );
2703
2704 map
2705 });
2706 }
2707
2708 #[gpui::test]
2709 fn test_tabs_with_multibyte_chars(cx: &mut gpui::App) {
2710 init_test(cx, |_| {});
2711
2712 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
2713 let buffer = MultiBuffer::build_simple(text, cx);
2714 let font_size = px(14.0);
2715
2716 let map = cx.new(|cx| {
2717 DisplayMap::new(
2718 buffer.clone(),
2719 font("Helvetica"),
2720 font_size,
2721 None,
2722 1,
2723 1,
2724 FoldPlaceholder::test(),
2725 cx,
2726 )
2727 });
2728 let map = map.update(cx, |map, cx| map.snapshot(cx));
2729 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
2730 assert_eq!(
2731 map.text_chunks(DisplayRow(0)).collect::<String>(),
2732 "✅ α\nβ \n🏀β γ"
2733 );
2734 assert_eq!(
2735 map.text_chunks(DisplayRow(1)).collect::<String>(),
2736 "β \n🏀β γ"
2737 );
2738 assert_eq!(
2739 map.text_chunks(DisplayRow(2)).collect::<String>(),
2740 "🏀β γ"
2741 );
2742
2743 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
2744 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
2745 assert_eq!(point.to_display_point(&map), display_point);
2746 assert_eq!(display_point.to_point(&map), point);
2747
2748 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2749 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
2750 assert_eq!(point.to_display_point(&map), display_point);
2751 assert_eq!(display_point.to_point(&map), point,);
2752
2753 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2754 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
2755 assert_eq!(point.to_display_point(&map), display_point);
2756 assert_eq!(display_point.to_point(&map), point,);
2757
2758 // Display points inside of expanded tabs
2759 assert_eq!(
2760 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2761 MultiBufferPoint::new(0, "✅\t".len() as u32),
2762 );
2763 assert_eq!(
2764 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2765 MultiBufferPoint::new(0, "✅".len() as u32),
2766 );
2767
2768 // Clipping display points inside of multi-byte characters
2769 assert_eq!(
2770 map.clip_point(
2771 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2772 Left
2773 ),
2774 DisplayPoint::new(DisplayRow(0), 0)
2775 );
2776 assert_eq!(
2777 map.clip_point(
2778 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2779 Bias::Right
2780 ),
2781 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
2782 );
2783 }
2784
2785 #[gpui::test]
2786 fn test_max_point(cx: &mut gpui::App) {
2787 init_test(cx, |_| {});
2788
2789 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2790 let font_size = px(14.0);
2791 let map = cx.new(|cx| {
2792 DisplayMap::new(
2793 buffer.clone(),
2794 font("Helvetica"),
2795 font_size,
2796 None,
2797 1,
2798 1,
2799 FoldPlaceholder::test(),
2800 cx,
2801 )
2802 });
2803 assert_eq!(
2804 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2805 DisplayPoint::new(DisplayRow(1), 11)
2806 )
2807 }
2808
2809 fn syntax_chunks(
2810 rows: Range<DisplayRow>,
2811 map: &Entity<DisplayMap>,
2812 theme: &SyntaxTheme,
2813 cx: &mut App,
2814 ) -> Vec<(String, Option<Hsla>)> {
2815 chunks(rows, map, theme, cx)
2816 .into_iter()
2817 .map(|(text, color, _)| (text, color))
2818 .collect()
2819 }
2820
2821 fn chunks(
2822 rows: Range<DisplayRow>,
2823 map: &Entity<DisplayMap>,
2824 theme: &SyntaxTheme,
2825 cx: &mut App,
2826 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2827 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2828 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2829 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2830 let syntax_color = chunk
2831 .syntax_highlight_id
2832 .and_then(|id| id.style(theme)?.color);
2833 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2834 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
2835 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2836 last_chunk.push_str(chunk.text);
2837 continue;
2838 }
2839 }
2840 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2841 }
2842 chunks
2843 }
2844
2845 fn init_test(cx: &mut App, f: impl Fn(&mut AllLanguageSettingsContent)) {
2846 let settings = SettingsStore::test(cx);
2847 cx.set_global(settings);
2848 workspace::init_settings(cx);
2849 language::init(cx);
2850 crate::init(cx);
2851 Project::init_settings(cx);
2852 theme::init(LoadThemes::JustBase, cx);
2853 cx.update_global::<SettingsStore, _>(|store, cx| {
2854 store.update_user_settings::<AllLanguageSettings>(cx, f);
2855 });
2856 }
2857}