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