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