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