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