1//! This module defines where the text should be displayed in an [`Editor`][Editor].
2//!
3//! Not literally though - rendering, layout and all that jazz is a responsibility of [`EditorElement`][EditorElement].
4//! Instead, [`DisplayMap`] decides where Inlays/Inlay hints are displayed, when
5//! to apply a soft wrap, where to add fold indicators, whether there are any tabs in the buffer that
6//! we display as spaces and where to display custom blocks (like diagnostics).
7//! Seems like a lot? That's because it is. [`DisplayMap`] is conceptually made up
8//! of several smaller structures that form a hierarchy (starting at the bottom):
9//! - [`InlayMap`] that decides where the [`Inlay`]s should be displayed.
10//! - [`FoldMap`] that decides where the fold indicators should be; it also tracks parts of a source file that are currently folded.
11//! - [`TabMap`] that keeps track of hard tabs in a buffer.
12//! - [`WrapMap`] that handles soft wrapping.
13//! - [`BlockMap`] that tracks custom blocks such as diagnostics that should be displayed within buffer.
14//! - [`DisplayMap`] that adds background highlights to the regions of text.
15//! Each one of those builds on top of preceding map.
16//!
17//! [Editor]: crate::Editor
18//! [EditorElement]: crate::element::EditorElement
19
20mod block_map;
21mod crease_map;
22mod custom_highlights;
23mod fold_map;
24mod inlay_map;
25pub(crate) mod invisibles;
26mod tab_map;
27mod wrap_map;
28
29use crate::{
30 EditorStyle, InlayId, RowExt, hover_links::InlayHighlight, movement::TextLayoutDetails,
31};
32pub use block_map::{
33 Block, BlockChunks as DisplayChunks, BlockContext, BlockId, BlockMap, BlockPlacement,
34 BlockPoint, BlockProperties, BlockRows, BlockStyle, CustomBlockId, EditorMargins, RenderBlock,
35 StickyHeaderExcerpt,
36};
37use block_map::{BlockRow, BlockSnapshot};
38use collections::{HashMap, HashSet};
39pub use crease_map::*;
40pub use fold_map::{
41 ChunkRenderer, ChunkRendererContext, ChunkRendererId, Fold, FoldId, FoldPlaceholder, FoldPoint,
42};
43use fold_map::{FoldMap, FoldSnapshot};
44use gpui::{App, Context, Entity, Font, HighlightStyle, LineLayout, Pixels, UnderlineStyle};
45pub use inlay_map::Inlay;
46use inlay_map::{InlayMap, InlaySnapshot};
47pub use inlay_map::{InlayOffset, InlayPoint};
48pub use invisibles::{is_invisible, replacement};
49use language::{
50 OffsetUtf16, Point, Subscription as BufferSubscription, language_settings::language_settings,
51};
52use multi_buffer::{
53 Anchor, AnchorRangeExt, ExcerptId, MultiBuffer, MultiBufferPoint, MultiBufferRow,
54 MultiBufferSnapshot, RowInfo, ToOffset, ToPoint,
55};
56use project::project_settings::DiagnosticSeverity;
57use serde::Deserialize;
58
59use std::{
60 any::TypeId,
61 borrow::Cow,
62 fmt::Debug,
63 iter,
64 num::NonZeroU32,
65 ops::{Add, Range, Sub},
66 sync::Arc,
67};
68use sum_tree::{Bias, TreeMap};
69use tab_map::{TabMap, TabSnapshot};
70use text::{BufferId, LineIndent};
71use ui::{SharedString, px};
72use unicode_segmentation::UnicodeSegmentation;
73use wrap_map::{WrapMap, WrapSnapshot};
74
75#[derive(Copy, Clone, Debug, PartialEq, Eq)]
76pub enum FoldStatus {
77 Folded,
78 Foldable,
79}
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
82pub enum HighlightKey {
83 Type(TypeId),
84 TypePlus(TypeId, usize),
85}
86
87pub trait ToDisplayPoint {
88 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
89}
90
91type TextHighlights = TreeMap<HighlightKey, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>;
92type InlayHighlights = TreeMap<TypeId, TreeMap<InlayId, (HighlightStyle, InlayHighlight)>>;
93
94/// Decides how text in a [`MultiBuffer`] should be displayed in a buffer, handling inlay hints,
95/// folding, hard tabs, soft wrapping, custom blocks (like diagnostics), and highlighting.
96///
97/// See the [module level documentation](self) for more information.
98pub struct DisplayMap {
99 /// The buffer that we are displaying.
100 buffer: Entity<MultiBuffer>,
101 buffer_subscription: BufferSubscription,
102 /// Decides where the [`Inlay`]s should be displayed.
103 inlay_map: InlayMap,
104 /// Decides where the fold indicators should be and tracks parts of a source file that are currently folded.
105 fold_map: FoldMap,
106 /// Keeps track of hard tabs in a buffer.
107 tab_map: TabMap,
108 /// Handles soft wrapping.
109 wrap_map: Entity<WrapMap>,
110 /// Tracks custom blocks such as diagnostics that should be displayed within buffer.
111 block_map: BlockMap,
112 /// Regions of text that should be highlighted.
113 text_highlights: TextHighlights,
114 /// Regions of inlays that should be highlighted.
115 inlay_highlights: InlayHighlights,
116 /// A container for explicitly foldable ranges, which supersede indentation based fold range suggestions.
117 crease_map: CreaseMap,
118 pub(crate) fold_placeholder: FoldPlaceholder,
119 pub clip_at_line_ends: bool,
120 pub(crate) masked: bool,
121 pub(crate) diagnostics_max_severity: DiagnosticSeverity,
122}
123
124impl DisplayMap {
125 pub fn new(
126 buffer: Entity<MultiBuffer>,
127 font: Font,
128 font_size: Pixels,
129 wrap_width: Option<Pixels>,
130 buffer_header_height: u32,
131 excerpt_header_height: u32,
132 fold_placeholder: FoldPlaceholder,
133 diagnostics_max_severity: DiagnosticSeverity,
134 cx: &mut Context<Self>,
135 ) -> Self {
136 let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
137
138 let tab_size = Self::tab_size(&buffer, cx);
139 let buffer_snapshot = buffer.read(cx).snapshot(cx);
140 let crease_map = CreaseMap::new(&buffer_snapshot);
141 let (inlay_map, snapshot) = InlayMap::new(buffer_snapshot);
142 let (fold_map, snapshot) = FoldMap::new(snapshot);
143 let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
144 let (wrap_map, snapshot) = WrapMap::new(snapshot, font, font_size, wrap_width, cx);
145 let block_map = BlockMap::new(snapshot, buffer_header_height, excerpt_header_height);
146
147 cx.observe(&wrap_map, |_, _, cx| cx.notify()).detach();
148
149 DisplayMap {
150 buffer,
151 buffer_subscription,
152 fold_map,
153 inlay_map,
154 tab_map,
155 wrap_map,
156 block_map,
157 crease_map,
158 fold_placeholder,
159 diagnostics_max_severity,
160 text_highlights: Default::default(),
161 inlay_highlights: Default::default(),
162 clip_at_line_ends: false,
163 masked: false,
164 }
165 }
166
167 pub fn snapshot(&mut self, cx: &mut Context<Self>) -> DisplaySnapshot {
168 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
169 let edits = self.buffer_subscription.consume().into_inner();
170 let (inlay_snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
171 let (fold_snapshot, edits) = self.fold_map.read(inlay_snapshot.clone(), edits);
172 let tab_size = Self::tab_size(&self.buffer, cx);
173 let (tab_snapshot, edits) = self.tab_map.sync(fold_snapshot.clone(), edits, tab_size);
174 let (wrap_snapshot, edits) = self
175 .wrap_map
176 .update(cx, |map, cx| map.sync(tab_snapshot.clone(), edits, cx));
177 let block_snapshot = self.block_map.read(wrap_snapshot.clone(), edits).snapshot;
178
179 DisplaySnapshot {
180 buffer_snapshot: self.buffer.read(cx).snapshot(cx),
181 fold_snapshot,
182 inlay_snapshot,
183 tab_snapshot,
184 wrap_snapshot,
185 block_snapshot,
186 diagnostics_max_severity: self.diagnostics_max_severity,
187 crease_snapshot: self.crease_map.snapshot(),
188 text_highlights: self.text_highlights.clone(),
189 inlay_highlights: self.inlay_highlights.clone(),
190 clip_at_line_ends: self.clip_at_line_ends,
191 masked: self.masked,
192 fold_placeholder: self.fold_placeholder.clone(),
193 }
194 }
195
196 pub fn set_state(&mut self, other: &DisplaySnapshot, cx: &mut Context<Self>) {
197 self.fold(
198 other
199 .folds_in_range(0..other.buffer_snapshot.len())
200 .map(|fold| {
201 Crease::simple(
202 fold.range.to_offset(&other.buffer_snapshot),
203 fold.placeholder.clone(),
204 )
205 })
206 .collect(),
207 cx,
208 );
209 }
210
211 /// Creates folds for the given creases.
212 pub fn fold<T: Clone + ToOffset>(&mut self, creases: Vec<Crease<T>>, cx: &mut Context<Self>) {
213 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
214 let edits = self.buffer_subscription.consume().into_inner();
215 let tab_size = Self::tab_size(&self.buffer, cx);
216 let (snapshot, edits) = self.inlay_map.sync(buffer_snapshot.clone(), edits);
217 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
218 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
219 let (snapshot, edits) = self
220 .wrap_map
221 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
222 self.block_map.read(snapshot, edits);
223
224 let inline = creases.iter().filter_map(|crease| {
225 if let Crease::Inline {
226 range, placeholder, ..
227 } = crease
228 {
229 Some((range.clone(), placeholder.clone()))
230 } else {
231 None
232 }
233 });
234 let (snapshot, edits) = fold_map.fold(inline);
235
236 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
237 let (snapshot, edits) = self
238 .wrap_map
239 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
240 let mut block_map = self.block_map.write(snapshot, edits);
241 let blocks = creases.into_iter().filter_map(|crease| {
242 if let Crease::Block {
243 range,
244 block_height,
245 render_block,
246 block_style,
247 block_priority,
248 ..
249 } = crease
250 {
251 Some((
252 range,
253 render_block,
254 block_height,
255 block_style,
256 block_priority,
257 ))
258 } else {
259 None
260 }
261 });
262 block_map.insert(
263 blocks
264 .into_iter()
265 .map(|(range, render, height, style, priority)| {
266 let start = buffer_snapshot.anchor_before(range.start);
267 let end = buffer_snapshot.anchor_after(range.end);
268 BlockProperties {
269 placement: BlockPlacement::Replace(start..=end),
270 render,
271 height: Some(height),
272 style,
273 priority,
274 }
275 }),
276 );
277 }
278
279 /// Removes any folds with the given ranges.
280 pub fn remove_folds_with_type<T: ToOffset>(
281 &mut self,
282 ranges: impl IntoIterator<Item = Range<T>>,
283 type_id: TypeId,
284 cx: &mut Context<Self>,
285 ) {
286 let snapshot = self.buffer.read(cx).snapshot(cx);
287 let edits = self.buffer_subscription.consume().into_inner();
288 let tab_size = Self::tab_size(&self.buffer, cx);
289 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
290 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
291 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
292 let (snapshot, edits) = self
293 .wrap_map
294 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
295 self.block_map.read(snapshot, edits);
296 let (snapshot, edits) = fold_map.remove_folds(ranges, type_id);
297 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
298 let (snapshot, edits) = self
299 .wrap_map
300 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
301 self.block_map.write(snapshot, edits);
302 }
303
304 /// Removes any folds whose ranges intersect any of the given ranges.
305 pub fn unfold_intersecting<T: ToOffset>(
306 &mut self,
307 ranges: impl IntoIterator<Item = Range<T>>,
308 inclusive: bool,
309 cx: &mut Context<Self>,
310 ) {
311 let snapshot = self.buffer.read(cx).snapshot(cx);
312 let offset_ranges = ranges
313 .into_iter()
314 .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot))
315 .collect::<Vec<_>>();
316 let edits = self.buffer_subscription.consume().into_inner();
317 let tab_size = Self::tab_size(&self.buffer, cx);
318 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
319 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
320 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
321 let (snapshot, edits) = self
322 .wrap_map
323 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
324 self.block_map.read(snapshot, edits);
325
326 let (snapshot, edits) =
327 fold_map.unfold_intersecting(offset_ranges.iter().cloned(), inclusive);
328 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
329 let (snapshot, edits) = self
330 .wrap_map
331 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
332 let mut block_map = self.block_map.write(snapshot, edits);
333 block_map.remove_intersecting_replace_blocks(offset_ranges, inclusive);
334 }
335
336 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
337 let snapshot = self.buffer.read(cx).snapshot(cx);
338 let edits = self.buffer_subscription.consume().into_inner();
339 let tab_size = Self::tab_size(&self.buffer, cx);
340 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
341 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
342 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
343 let (snapshot, edits) = self
344 .wrap_map
345 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
346 let mut block_map = self.block_map.write(snapshot, edits);
347 block_map.disable_header_for_buffer(buffer_id)
348 }
349
350 pub fn fold_buffers(
351 &mut self,
352 buffer_ids: impl IntoIterator<Item = language::BufferId>,
353 cx: &mut Context<Self>,
354 ) {
355 let snapshot = self.buffer.read(cx).snapshot(cx);
356 let edits = self.buffer_subscription.consume().into_inner();
357 let tab_size = Self::tab_size(&self.buffer, cx);
358 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
359 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
360 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
361 let (snapshot, edits) = self
362 .wrap_map
363 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
364 let mut block_map = self.block_map.write(snapshot, edits);
365 block_map.fold_buffers(buffer_ids, self.buffer.read(cx), cx)
366 }
367
368 pub fn unfold_buffers(
369 &mut self,
370 buffer_ids: impl IntoIterator<Item = language::BufferId>,
371 cx: &mut Context<Self>,
372 ) {
373 let snapshot = self.buffer.read(cx).snapshot(cx);
374 let edits = self.buffer_subscription.consume().into_inner();
375 let tab_size = Self::tab_size(&self.buffer, cx);
376 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
377 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
378 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
379 let (snapshot, edits) = self
380 .wrap_map
381 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
382 let mut block_map = self.block_map.write(snapshot, edits);
383 block_map.unfold_buffers(buffer_ids, self.buffer.read(cx), cx)
384 }
385
386 pub(crate) fn is_buffer_folded(&self, buffer_id: language::BufferId) -> bool {
387 self.block_map.folded_buffers.contains(&buffer_id)
388 }
389
390 pub(crate) fn folded_buffers(&self) -> &HashSet<BufferId> {
391 &self.block_map.folded_buffers
392 }
393
394 pub fn insert_creases(
395 &mut self,
396 creases: impl IntoIterator<Item = Crease<Anchor>>,
397 cx: &mut Context<Self>,
398 ) -> Vec<CreaseId> {
399 let snapshot = self.buffer.read(cx).snapshot(cx);
400 self.crease_map.insert(creases, &snapshot)
401 }
402
403 pub fn remove_creases(
404 &mut self,
405 crease_ids: impl IntoIterator<Item = CreaseId>,
406 cx: &mut Context<Self>,
407 ) -> Vec<(CreaseId, Range<Anchor>)> {
408 let snapshot = self.buffer.read(cx).snapshot(cx);
409 self.crease_map.remove(crease_ids, &snapshot)
410 }
411
412 pub fn insert_blocks(
413 &mut self,
414 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
415 cx: &mut Context<Self>,
416 ) -> Vec<CustomBlockId> {
417 let snapshot = self.buffer.read(cx).snapshot(cx);
418 let edits = self.buffer_subscription.consume().into_inner();
419 let tab_size = Self::tab_size(&self.buffer, cx);
420 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
421 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
422 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
423 let (snapshot, edits) = self
424 .wrap_map
425 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
426 let mut block_map = self.block_map.write(snapshot, edits);
427 block_map.insert(blocks)
428 }
429
430 pub fn resize_blocks(&mut self, heights: HashMap<CustomBlockId, u32>, cx: &mut Context<Self>) {
431 let snapshot = self.buffer.read(cx).snapshot(cx);
432 let edits = self.buffer_subscription.consume().into_inner();
433 let tab_size = Self::tab_size(&self.buffer, cx);
434 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
435 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
436 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
437 let (snapshot, edits) = self
438 .wrap_map
439 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
440 let mut block_map = self.block_map.write(snapshot, edits);
441 block_map.resize(heights);
442 }
443
444 pub fn replace_blocks(&mut self, renderers: HashMap<CustomBlockId, RenderBlock>) {
445 self.block_map.replace_blocks(renderers);
446 }
447
448 pub fn remove_blocks(&mut self, ids: HashSet<CustomBlockId>, cx: &mut Context<Self>) {
449 let snapshot = self.buffer.read(cx).snapshot(cx);
450 let edits = self.buffer_subscription.consume().into_inner();
451 let tab_size = Self::tab_size(&self.buffer, cx);
452 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
453 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
454 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
455 let (snapshot, edits) = self
456 .wrap_map
457 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
458 let mut block_map = self.block_map.write(snapshot, edits);
459 block_map.remove(ids);
460 }
461
462 pub fn row_for_block(
463 &mut self,
464 block_id: CustomBlockId,
465 cx: &mut Context<Self>,
466 ) -> Option<DisplayRow> {
467 let snapshot = self.buffer.read(cx).snapshot(cx);
468 let edits = self.buffer_subscription.consume().into_inner();
469 let tab_size = Self::tab_size(&self.buffer, cx);
470 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
471 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
472 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
473 let (snapshot, edits) = self
474 .wrap_map
475 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
476 let block_map = self.block_map.read(snapshot, edits);
477 let block_row = block_map.row_for_block(block_id)?;
478 Some(DisplayRow(block_row.0))
479 }
480
481 pub fn highlight_text(
482 &mut self,
483 key: HighlightKey,
484 ranges: Vec<Range<Anchor>>,
485 style: HighlightStyle,
486 ) {
487 self.text_highlights.insert(key, Arc::new((style, ranges)));
488 }
489
490 pub(crate) fn highlight_inlays(
491 &mut self,
492 type_id: TypeId,
493 highlights: Vec<InlayHighlight>,
494 style: HighlightStyle,
495 ) {
496 for highlight in highlights {
497 let update = self.inlay_highlights.update(&type_id, |highlights| {
498 highlights.insert(highlight.inlay, (style, highlight.clone()))
499 });
500 if update.is_none() {
501 self.inlay_highlights.insert(
502 type_id,
503 TreeMap::from_ordered_entries([(highlight.inlay, (style, highlight))]),
504 );
505 }
506 }
507 }
508
509 pub fn text_highlights(&self, type_id: TypeId) -> Option<(HighlightStyle, &[Range<Anchor>])> {
510 let highlights = self.text_highlights.get(&HighlightKey::Type(type_id))?;
511 Some((highlights.0, &highlights.1))
512 }
513
514 #[cfg(feature = "test-support")]
515 pub fn all_text_highlights(
516 &self,
517 ) -> impl Iterator<Item = &Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
518 self.text_highlights.values()
519 }
520
521 pub fn clear_highlights(&mut self, type_id: TypeId) -> bool {
522 let mut cleared = self
523 .text_highlights
524 .remove(&HighlightKey::Type(type_id))
525 .is_some();
526 cleared |= self.inlay_highlights.remove(&type_id).is_some();
527 cleared
528 }
529
530 pub fn set_font(&self, font: Font, font_size: Pixels, cx: &mut Context<Self>) -> bool {
531 self.wrap_map
532 .update(cx, |map, cx| map.set_font_with_size(font, font_size, cx))
533 }
534
535 pub fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut Context<Self>) -> bool {
536 self.wrap_map
537 .update(cx, |map, cx| map.set_wrap_width(width, cx))
538 }
539
540 pub fn update_fold_widths(
541 &mut self,
542 widths: impl IntoIterator<Item = (ChunkRendererId, Pixels)>,
543 cx: &mut Context<Self>,
544 ) -> bool {
545 let snapshot = self.buffer.read(cx).snapshot(cx);
546 let edits = self.buffer_subscription.consume().into_inner();
547 let tab_size = Self::tab_size(&self.buffer, cx);
548 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
549 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
550 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
551 let (snapshot, edits) = self
552 .wrap_map
553 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
554 self.block_map.read(snapshot, edits);
555
556 let (snapshot, edits) = fold_map.update_fold_widths(widths);
557 let widths_changed = !edits.is_empty();
558 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
559 let (snapshot, edits) = self
560 .wrap_map
561 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
562 self.block_map.read(snapshot, edits);
563
564 widths_changed
565 }
566
567 pub(crate) fn current_inlays(&self) -> impl Iterator<Item = &Inlay> {
568 self.inlay_map.current_inlays()
569 }
570
571 pub(crate) fn splice_inlays(
572 &mut self,
573 to_remove: &[InlayId],
574 to_insert: Vec<Inlay>,
575 cx: &mut Context<Self>,
576 ) {
577 if to_remove.is_empty() && to_insert.is_empty() {
578 return;
579 }
580 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
581 let edits = self.buffer_subscription.consume().into_inner();
582 let (snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
583 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
584 let tab_size = Self::tab_size(&self.buffer, cx);
585 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
586 let (snapshot, edits) = self
587 .wrap_map
588 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
589 self.block_map.read(snapshot, edits);
590
591 let (snapshot, edits) = self.inlay_map.splice(to_remove, to_insert);
592 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
593 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
594 let (snapshot, edits) = self
595 .wrap_map
596 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
597 self.block_map.read(snapshot, edits);
598 }
599
600 pub fn remove_inlays_for_excerpts(&mut self, excerpts_removed: &[ExcerptId]) {
601 let to_remove = self
602 .inlay_map
603 .current_inlays()
604 .filter_map(|inlay| {
605 if excerpts_removed.contains(&inlay.position.excerpt_id) {
606 Some(inlay.id)
607 } else {
608 None
609 }
610 })
611 .collect::<Vec<_>>();
612 self.inlay_map.splice(&to_remove, Vec::new());
613 }
614
615 fn tab_size(buffer: &Entity<MultiBuffer>, cx: &App) -> NonZeroU32 {
616 let buffer = buffer.read(cx).as_singleton().map(|buffer| buffer.read(cx));
617 let language = buffer
618 .and_then(|buffer| buffer.language())
619 .map(|l| l.name());
620 let file = buffer.and_then(|buffer| buffer.file());
621 language_settings(language, file, cx).tab_size
622 }
623
624 #[cfg(test)]
625 pub fn is_rewrapping(&self, cx: &gpui::App) -> bool {
626 self.wrap_map.read(cx).is_rewrapping()
627 }
628}
629
630#[derive(Debug, Default)]
631pub(crate) struct Highlights<'a> {
632 pub text_highlights: Option<&'a TextHighlights>,
633 pub inlay_highlights: Option<&'a InlayHighlights>,
634 pub styles: HighlightStyles,
635}
636
637#[derive(Clone, Copy, Debug)]
638pub struct EditPredictionStyles {
639 pub insertion: HighlightStyle,
640 pub whitespace: HighlightStyle,
641}
642
643#[derive(Default, Debug, Clone, Copy)]
644pub struct HighlightStyles {
645 pub inlay_hint: Option<HighlightStyle>,
646 pub edit_prediction: Option<EditPredictionStyles>,
647}
648
649#[derive(Clone)]
650pub enum ChunkReplacement {
651 Renderer(ChunkRenderer),
652 Str(SharedString),
653}
654
655pub struct HighlightedChunk<'a> {
656 pub text: &'a str,
657 pub style: Option<HighlightStyle>,
658 pub is_tab: bool,
659 pub is_inlay: bool,
660 pub replacement: Option<ChunkReplacement>,
661}
662
663impl<'a> HighlightedChunk<'a> {
664 fn highlight_invisibles(
665 self,
666 editor_style: &'a EditorStyle,
667 ) -> impl Iterator<Item = Self> + 'a {
668 let mut chars = self.text.chars().peekable();
669 let mut text = self.text;
670 let style = self.style;
671 let is_tab = self.is_tab;
672 let renderer = self.replacement;
673 let is_inlay = self.is_inlay;
674 iter::from_fn(move || {
675 let mut prefix_len = 0;
676 while let Some(&ch) = chars.peek() {
677 if !is_invisible(ch) {
678 prefix_len += ch.len_utf8();
679 chars.next();
680 continue;
681 }
682 if prefix_len > 0 {
683 let (prefix, suffix) = text.split_at(prefix_len);
684 text = suffix;
685 return Some(HighlightedChunk {
686 text: prefix,
687 style,
688 is_tab,
689 is_inlay,
690 replacement: renderer.clone(),
691 });
692 }
693 chars.next();
694 let (prefix, suffix) = text.split_at(ch.len_utf8());
695 text = suffix;
696 if let Some(replacement) = replacement(ch) {
697 let invisible_highlight = HighlightStyle {
698 background_color: Some(editor_style.status.hint_background),
699 underline: Some(UnderlineStyle {
700 color: Some(editor_style.status.hint),
701 thickness: px(1.),
702 wavy: false,
703 }),
704 ..Default::default()
705 };
706 let invisible_style = if let Some(mut style) = style {
707 style.highlight(invisible_highlight);
708 style
709 } else {
710 invisible_highlight
711 };
712 return Some(HighlightedChunk {
713 text: prefix,
714 style: Some(invisible_style),
715 is_tab: false,
716 is_inlay,
717 replacement: Some(ChunkReplacement::Str(replacement.into())),
718 });
719 } else {
720 let invisible_highlight = HighlightStyle {
721 background_color: Some(editor_style.status.hint_background),
722 underline: Some(UnderlineStyle {
723 color: Some(editor_style.status.hint),
724 thickness: px(1.),
725 wavy: false,
726 }),
727 ..Default::default()
728 };
729 let invisible_style = if let Some(mut style) = style {
730 style.highlight(invisible_highlight);
731 style
732 } else {
733 invisible_highlight
734 };
735
736 return Some(HighlightedChunk {
737 text: prefix,
738 style: Some(invisible_style),
739 is_tab: false,
740 is_inlay,
741 replacement: renderer.clone(),
742 });
743 }
744 }
745
746 if !text.is_empty() {
747 let remainder = text;
748 text = "";
749 Some(HighlightedChunk {
750 text: remainder,
751 style,
752 is_tab,
753 is_inlay,
754 replacement: renderer.clone(),
755 })
756 } else {
757 None
758 }
759 })
760 }
761}
762
763#[derive(Clone)]
764pub struct DisplaySnapshot {
765 pub buffer_snapshot: MultiBufferSnapshot,
766 pub fold_snapshot: FoldSnapshot,
767 pub crease_snapshot: CreaseSnapshot,
768 inlay_snapshot: InlaySnapshot,
769 tab_snapshot: TabSnapshot,
770 wrap_snapshot: WrapSnapshot,
771 block_snapshot: BlockSnapshot,
772 text_highlights: TextHighlights,
773 inlay_highlights: InlayHighlights,
774 clip_at_line_ends: bool,
775 masked: bool,
776 diagnostics_max_severity: DiagnosticSeverity,
777 pub(crate) fold_placeholder: FoldPlaceholder,
778}
779
780impl DisplaySnapshot {
781 #[cfg(test)]
782 pub fn fold_count(&self) -> usize {
783 self.fold_snapshot.fold_count()
784 }
785
786 pub fn is_empty(&self) -> bool {
787 self.buffer_snapshot.len() == 0
788 }
789
790 pub fn row_infos(&self, start_row: DisplayRow) -> impl Iterator<Item = RowInfo> + '_ {
791 self.block_snapshot.row_infos(BlockRow(start_row.0))
792 }
793
794 pub fn widest_line_number(&self) -> u32 {
795 self.buffer_snapshot.widest_line_number()
796 }
797
798 pub fn prev_line_boundary(&self, mut point: MultiBufferPoint) -> (Point, DisplayPoint) {
799 loop {
800 let mut inlay_point = self.inlay_snapshot.to_inlay_point(point);
801 let mut fold_point = self.fold_snapshot.to_fold_point(inlay_point, Bias::Left);
802 fold_point.0.column = 0;
803 inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
804 point = self.inlay_snapshot.to_buffer_point(inlay_point);
805
806 let mut display_point = self.point_to_display_point(point, Bias::Left);
807 *display_point.column_mut() = 0;
808 let next_point = self.display_point_to_point(display_point, Bias::Left);
809 if next_point == point {
810 return (point, display_point);
811 }
812 point = next_point;
813 }
814 }
815
816 pub fn next_line_boundary(
817 &self,
818 mut point: MultiBufferPoint,
819 ) -> (MultiBufferPoint, DisplayPoint) {
820 let original_point = point;
821 loop {
822 let mut inlay_point = self.inlay_snapshot.to_inlay_point(point);
823 let mut fold_point = self.fold_snapshot.to_fold_point(inlay_point, Bias::Right);
824 fold_point.0.column = self.fold_snapshot.line_len(fold_point.row());
825 inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
826 point = self.inlay_snapshot.to_buffer_point(inlay_point);
827
828 let mut display_point = self.point_to_display_point(point, Bias::Right);
829 *display_point.column_mut() = self.line_len(display_point.row());
830 let next_point = self.display_point_to_point(display_point, Bias::Right);
831 if next_point == point || original_point == point || original_point == next_point {
832 return (point, display_point);
833 }
834 point = next_point;
835 }
836 }
837
838 // used by line_mode selections and tries to match vim behavior
839 pub fn expand_to_line(&self, range: Range<Point>) -> Range<Point> {
840 let new_start = MultiBufferPoint::new(range.start.row, 0);
841 let new_end = if range.end.column > 0 {
842 MultiBufferPoint::new(
843 range.end.row,
844 self.buffer_snapshot.line_len(MultiBufferRow(range.end.row)),
845 )
846 } else {
847 range.end
848 };
849
850 new_start..new_end
851 }
852
853 pub fn point_to_display_point(&self, point: MultiBufferPoint, bias: Bias) -> DisplayPoint {
854 let inlay_point = self.inlay_snapshot.to_inlay_point(point);
855 let fold_point = self.fold_snapshot.to_fold_point(inlay_point, bias);
856 let tab_point = self.tab_snapshot.to_tab_point(fold_point);
857 let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
858 let block_point = self.block_snapshot.to_block_point(wrap_point);
859 DisplayPoint(block_point)
860 }
861
862 pub fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {
863 self.inlay_snapshot
864 .to_buffer_point(self.display_point_to_inlay_point(point, bias))
865 }
866
867 pub fn display_point_to_inlay_offset(&self, point: DisplayPoint, bias: Bias) -> InlayOffset {
868 self.inlay_snapshot
869 .to_offset(self.display_point_to_inlay_point(point, bias))
870 }
871
872 pub fn anchor_to_inlay_offset(&self, anchor: Anchor) -> InlayOffset {
873 self.inlay_snapshot
874 .to_inlay_offset(anchor.to_offset(&self.buffer_snapshot))
875 }
876
877 pub fn display_point_to_anchor(&self, point: DisplayPoint, bias: Bias) -> Anchor {
878 self.buffer_snapshot
879 .anchor_at(point.to_offset(self, bias), bias)
880 }
881
882 fn display_point_to_inlay_point(&self, point: DisplayPoint, bias: Bias) -> InlayPoint {
883 let block_point = point.0;
884 let wrap_point = self.block_snapshot.to_wrap_point(block_point, bias);
885 let tab_point = self.wrap_snapshot.to_tab_point(wrap_point);
886 let fold_point = self.tab_snapshot.to_fold_point(tab_point, bias).0;
887 fold_point.to_inlay_point(&self.fold_snapshot)
888 }
889
890 pub fn display_point_to_fold_point(&self, point: DisplayPoint, bias: Bias) -> FoldPoint {
891 let block_point = point.0;
892 let wrap_point = self.block_snapshot.to_wrap_point(block_point, bias);
893 let tab_point = self.wrap_snapshot.to_tab_point(wrap_point);
894 self.tab_snapshot.to_fold_point(tab_point, bias).0
895 }
896
897 pub fn fold_point_to_display_point(&self, fold_point: FoldPoint) -> DisplayPoint {
898 let tab_point = self.tab_snapshot.to_tab_point(fold_point);
899 let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
900 let block_point = self.block_snapshot.to_block_point(wrap_point);
901 DisplayPoint(block_point)
902 }
903
904 pub fn max_point(&self) -> DisplayPoint {
905 DisplayPoint(self.block_snapshot.max_point())
906 }
907
908 /// Returns text chunks starting at the given display row until the end of the file
909 pub fn text_chunks(&self, display_row: DisplayRow) -> impl Iterator<Item = &str> {
910 self.block_snapshot
911 .chunks(
912 display_row.0..self.max_point().row().next_row().0,
913 false,
914 self.masked,
915 Highlights::default(),
916 )
917 .map(|h| h.text)
918 }
919
920 /// Returns text chunks starting at the end of the given display row in reverse until the start of the file
921 pub fn reverse_text_chunks(&self, display_row: DisplayRow) -> impl Iterator<Item = &str> {
922 (0..=display_row.0).rev().flat_map(move |row| {
923 self.block_snapshot
924 .chunks(row..row + 1, false, self.masked, Highlights::default())
925 .map(|h| h.text)
926 .collect::<Vec<_>>()
927 .into_iter()
928 .rev()
929 })
930 }
931
932 pub fn chunks(
933 &self,
934 display_rows: Range<DisplayRow>,
935 language_aware: bool,
936 highlight_styles: HighlightStyles,
937 ) -> DisplayChunks<'_> {
938 self.block_snapshot.chunks(
939 display_rows.start.0..display_rows.end.0,
940 language_aware,
941 self.masked,
942 Highlights {
943 text_highlights: Some(&self.text_highlights),
944 inlay_highlights: Some(&self.inlay_highlights),
945 styles: highlight_styles,
946 },
947 )
948 }
949
950 pub fn highlighted_chunks<'a>(
951 &'a self,
952 display_rows: Range<DisplayRow>,
953 language_aware: bool,
954 editor_style: &'a EditorStyle,
955 ) -> impl Iterator<Item = HighlightedChunk<'a>> {
956 self.chunks(
957 display_rows,
958 language_aware,
959 HighlightStyles {
960 inlay_hint: Some(editor_style.inlay_hints_style),
961 edit_prediction: Some(editor_style.edit_prediction_styles),
962 },
963 )
964 .flat_map(|chunk| {
965 let mut highlight_style = chunk
966 .syntax_highlight_id
967 .and_then(|id| id.style(&editor_style.syntax));
968
969 if let Some(chunk_highlight) = chunk.highlight_style {
970 // For color inlays, blend the color with the editor background
971 let mut processed_highlight = chunk_highlight;
972 if chunk.is_inlay
973 && let Some(inlay_color) = chunk_highlight.color {
974 // Only blend if the color has transparency (alpha < 1.0)
975 if inlay_color.a < 1.0 {
976 let blended_color = editor_style.background.blend(inlay_color);
977 processed_highlight.color = Some(blended_color);
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, None)
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 }
1665 })
1666 .collect::<Vec<_>>();
1667 blocks.extend(map.insert_blocks(block_properties, cx));
1668 } else {
1669 blocks.shuffle(&mut rng);
1670 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1671 let block_ids_to_remove = (0..remove_count)
1672 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1673 .collect();
1674 log::info!("removing block ids {:?}", block_ids_to_remove);
1675 map.remove_blocks(block_ids_to_remove, cx);
1676 }
1677 });
1678 }
1679 45..=79 => {
1680 let mut ranges = Vec::new();
1681 for _ in 0..rng.gen_range(1..=3) {
1682 buffer.read_with(cx, |buffer, cx| {
1683 let buffer = buffer.read(cx);
1684 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1685 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1686 ranges.push(start..end);
1687 });
1688 }
1689
1690 if rng.r#gen() && fold_count > 0 {
1691 log::info!("unfolding ranges: {:?}", ranges);
1692 map.update(cx, |map, cx| {
1693 map.unfold_intersecting(ranges, true, cx);
1694 });
1695 } else {
1696 log::info!("folding ranges: {:?}", ranges);
1697 map.update(cx, |map, cx| {
1698 map.fold(
1699 ranges
1700 .into_iter()
1701 .map(|range| Crease::simple(range, FoldPlaceholder::test()))
1702 .collect(),
1703 cx,
1704 );
1705 });
1706 }
1707 }
1708 _ => {
1709 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1710 }
1711 }
1712
1713 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1714 notifications.next().await.unwrap();
1715 }
1716
1717 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1718 fold_count = snapshot.fold_count();
1719 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1720 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1721 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1722 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1723 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1724 log::info!("display text: {:?}", snapshot.text());
1725
1726 // Line boundaries
1727 let buffer = &snapshot.buffer_snapshot;
1728 for _ in 0..5 {
1729 let row = rng.gen_range(0..=buffer.max_point().row);
1730 let column = rng.gen_range(0..=buffer.line_len(MultiBufferRow(row)));
1731 let point = buffer.clip_point(Point::new(row, column), Left);
1732
1733 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1734 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1735
1736 assert!(prev_buffer_bound <= point);
1737 assert!(next_buffer_bound >= point);
1738 assert_eq!(prev_buffer_bound.column, 0);
1739 assert_eq!(prev_display_bound.column(), 0);
1740 if next_buffer_bound < buffer.max_point() {
1741 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1742 }
1743
1744 assert_eq!(
1745 prev_display_bound,
1746 prev_buffer_bound.to_display_point(&snapshot),
1747 "row boundary before {:?}. reported buffer row boundary: {:?}",
1748 point,
1749 prev_buffer_bound
1750 );
1751 assert_eq!(
1752 next_display_bound,
1753 next_buffer_bound.to_display_point(&snapshot),
1754 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1755 point,
1756 next_buffer_bound
1757 );
1758 assert_eq!(
1759 prev_buffer_bound,
1760 prev_display_bound.to_point(&snapshot),
1761 "row boundary before {:?}. reported display row boundary: {:?}",
1762 point,
1763 prev_display_bound
1764 );
1765 assert_eq!(
1766 next_buffer_bound,
1767 next_display_bound.to_point(&snapshot),
1768 "row boundary after {:?}. reported display row boundary: {:?}",
1769 point,
1770 next_display_bound
1771 );
1772 }
1773
1774 // Movement
1775 let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1776 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1777 for _ in 0..5 {
1778 let row = rng.gen_range(0..=snapshot.max_point().row().0);
1779 let column = rng.gen_range(0..=snapshot.line_len(DisplayRow(row)));
1780 let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1781
1782 log::info!("Moving from point {:?}", point);
1783
1784 let moved_right = movement::right(&snapshot, point);
1785 log::info!("Right {:?}", moved_right);
1786 if point < max_point {
1787 assert!(moved_right > point);
1788 if point.column() == snapshot.line_len(point.row())
1789 || snapshot.soft_wrap_indent(point.row()).is_some()
1790 && point.column() == snapshot.line_len(point.row()) - 1
1791 {
1792 assert!(moved_right.row() > point.row());
1793 }
1794 } else {
1795 assert_eq!(moved_right, point);
1796 }
1797
1798 let moved_left = movement::left(&snapshot, point);
1799 log::info!("Left {:?}", moved_left);
1800 if point > min_point {
1801 assert!(moved_left < point);
1802 if point.column() == 0 {
1803 assert!(moved_left.row() < point.row());
1804 }
1805 } else {
1806 assert_eq!(moved_left, point);
1807 }
1808 }
1809 }
1810 }
1811
1812 #[gpui::test(retries = 5)]
1813 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1814 cx.background_executor
1815 .set_block_on_ticks(usize::MAX..=usize::MAX);
1816 cx.update(|cx| {
1817 init_test(cx, |_| {});
1818 });
1819
1820 let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1821 let editor = cx.editor.clone();
1822 let window = cx.window;
1823
1824 _ = cx.update_window(window, |_, window, cx| {
1825 let text_layout_details =
1826 editor.update(cx, |editor, _cx| editor.text_layout_details(window));
1827
1828 let font_size = px(12.0);
1829 let wrap_width = Some(px(96.));
1830
1831 let text = "one two three four five\nsix seven eight";
1832 let buffer = MultiBuffer::build_simple(text, cx);
1833 let map = cx.new(|cx| {
1834 DisplayMap::new(
1835 buffer.clone(),
1836 font("Helvetica"),
1837 font_size,
1838 wrap_width,
1839 1,
1840 1,
1841 FoldPlaceholder::test(),
1842 DiagnosticSeverity::Warning,
1843 cx,
1844 )
1845 });
1846
1847 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1848 assert_eq!(
1849 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1850 "one two \nthree four \nfive\nsix seven \neight"
1851 );
1852 assert_eq!(
1853 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1854 DisplayPoint::new(DisplayRow(0), 7)
1855 );
1856 assert_eq!(
1857 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1858 DisplayPoint::new(DisplayRow(1), 0)
1859 );
1860 assert_eq!(
1861 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1862 DisplayPoint::new(DisplayRow(1), 0)
1863 );
1864 assert_eq!(
1865 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1866 DisplayPoint::new(DisplayRow(0), 7)
1867 );
1868
1869 let x = snapshot
1870 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1871 assert_eq!(
1872 movement::up(
1873 &snapshot,
1874 DisplayPoint::new(DisplayRow(1), 10),
1875 language::SelectionGoal::None,
1876 false,
1877 &text_layout_details,
1878 ),
1879 (
1880 DisplayPoint::new(DisplayRow(0), 7),
1881 language::SelectionGoal::HorizontalPosition(x.0)
1882 )
1883 );
1884 assert_eq!(
1885 movement::down(
1886 &snapshot,
1887 DisplayPoint::new(DisplayRow(0), 7),
1888 language::SelectionGoal::HorizontalPosition(x.0),
1889 false,
1890 &text_layout_details
1891 ),
1892 (
1893 DisplayPoint::new(DisplayRow(1), 10),
1894 language::SelectionGoal::HorizontalPosition(x.0)
1895 )
1896 );
1897 assert_eq!(
1898 movement::down(
1899 &snapshot,
1900 DisplayPoint::new(DisplayRow(1), 10),
1901 language::SelectionGoal::HorizontalPosition(x.0),
1902 false,
1903 &text_layout_details
1904 ),
1905 (
1906 DisplayPoint::new(DisplayRow(2), 4),
1907 language::SelectionGoal::HorizontalPosition(x.0)
1908 )
1909 );
1910
1911 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1912 buffer.update(cx, |buffer, cx| {
1913 buffer.edit([(ix..ix, "and ")], None, cx);
1914 });
1915
1916 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1917 assert_eq!(
1918 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1919 "three four \nfive\nsix and \nseven eight"
1920 );
1921
1922 // Re-wrap on font size changes
1923 map.update(cx, |map, cx| {
1924 map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1925 });
1926
1927 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1928 assert_eq!(
1929 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1930 "three \nfour five\nsix and \nseven \neight"
1931 )
1932 });
1933 }
1934
1935 #[gpui::test]
1936 fn test_text_chunks(cx: &mut gpui::App) {
1937 init_test(cx, |_| {});
1938
1939 let text = sample_text(6, 6, 'a');
1940 let buffer = MultiBuffer::build_simple(&text, cx);
1941
1942 let font_size = px(14.0);
1943 let map = cx.new(|cx| {
1944 DisplayMap::new(
1945 buffer.clone(),
1946 font("Helvetica"),
1947 font_size,
1948 None,
1949 1,
1950 1,
1951 FoldPlaceholder::test(),
1952 DiagnosticSeverity::Warning,
1953 cx,
1954 )
1955 });
1956
1957 buffer.update(cx, |buffer, cx| {
1958 buffer.edit(
1959 vec![
1960 (
1961 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1962 "\t",
1963 ),
1964 (
1965 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1966 "\t",
1967 ),
1968 (
1969 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1970 "\t",
1971 ),
1972 ],
1973 None,
1974 cx,
1975 )
1976 });
1977
1978 assert_eq!(
1979 map.update(cx, |map, cx| map.snapshot(cx))
1980 .text_chunks(DisplayRow(1))
1981 .collect::<String>()
1982 .lines()
1983 .next(),
1984 Some(" b bbbbb")
1985 );
1986 assert_eq!(
1987 map.update(cx, |map, cx| map.snapshot(cx))
1988 .text_chunks(DisplayRow(2))
1989 .collect::<String>()
1990 .lines()
1991 .next(),
1992 Some("c ccccc")
1993 );
1994 }
1995
1996 #[gpui::test]
1997 fn test_inlays_with_newlines_after_blocks(cx: &mut gpui::TestAppContext) {
1998 cx.update(|cx| init_test(cx, |_| {}));
1999
2000 let buffer = cx.new(|cx| Buffer::local("a", cx));
2001 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2002 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2003
2004 let font_size = px(14.0);
2005 let map = cx.new(|cx| {
2006 DisplayMap::new(
2007 buffer.clone(),
2008 font("Helvetica"),
2009 font_size,
2010 None,
2011 1,
2012 1,
2013 FoldPlaceholder::test(),
2014 DiagnosticSeverity::Warning,
2015 cx,
2016 )
2017 });
2018
2019 map.update(cx, |map, cx| {
2020 map.insert_blocks(
2021 [BlockProperties {
2022 placement: BlockPlacement::Above(
2023 buffer_snapshot.anchor_before(Point::new(0, 0)),
2024 ),
2025 height: Some(2),
2026 style: BlockStyle::Sticky,
2027 render: Arc::new(|_| div().into_any()),
2028 priority: 0,
2029 }],
2030 cx,
2031 );
2032 });
2033 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\na"));
2034
2035 map.update(cx, |map, cx| {
2036 map.splice_inlays(
2037 &[],
2038 vec![Inlay::edit_prediction(
2039 0,
2040 buffer_snapshot.anchor_after(0),
2041 "\n",
2042 )],
2043 cx,
2044 );
2045 });
2046 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\na"));
2047
2048 // Regression test: updating the display map does not crash when a
2049 // block is immediately followed by a multi-line inlay.
2050 buffer.update(cx, |buffer, cx| {
2051 buffer.edit([(1..1, "b")], None, cx);
2052 });
2053 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\nab"));
2054 }
2055
2056 #[gpui::test]
2057 async fn test_chunks(cx: &mut gpui::TestAppContext) {
2058 let text = r#"
2059 fn outer() {}
2060
2061 mod module {
2062 fn inner() {}
2063 }"#
2064 .unindent();
2065
2066 let theme =
2067 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2068 let language = Arc::new(
2069 Language::new(
2070 LanguageConfig {
2071 name: "Test".into(),
2072 matcher: LanguageMatcher {
2073 path_suffixes: vec![".test".to_string()],
2074 ..Default::default()
2075 },
2076 ..Default::default()
2077 },
2078 Some(tree_sitter_rust::LANGUAGE.into()),
2079 )
2080 .with_highlights_query(
2081 r#"
2082 (mod_item name: (identifier) body: _ @mod.body)
2083 (function_item name: (identifier) @fn.name)
2084 "#,
2085 )
2086 .unwrap(),
2087 );
2088 language.set_theme(&theme);
2089
2090 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
2091
2092 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2093 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2094 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2095
2096 let font_size = px(14.0);
2097
2098 let map = cx.new(|cx| {
2099 DisplayMap::new(
2100 buffer,
2101 font("Helvetica"),
2102 font_size,
2103 None,
2104 1,
2105 1,
2106 FoldPlaceholder::test(),
2107 DiagnosticSeverity::Warning,
2108 cx,
2109 )
2110 });
2111 assert_eq!(
2112 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2113 vec![
2114 ("fn ".to_string(), None),
2115 ("outer".to_string(), Some(Hsla::blue())),
2116 ("() {}\n\nmod module ".to_string(), None),
2117 ("{\n fn ".to_string(), Some(Hsla::red())),
2118 ("inner".to_string(), Some(Hsla::blue())),
2119 ("() {}\n}".to_string(), Some(Hsla::red())),
2120 ]
2121 );
2122 assert_eq!(
2123 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2124 vec![
2125 (" fn ".to_string(), Some(Hsla::red())),
2126 ("inner".to_string(), Some(Hsla::blue())),
2127 ("() {}\n}".to_string(), Some(Hsla::red())),
2128 ]
2129 );
2130
2131 map.update(cx, |map, cx| {
2132 map.fold(
2133 vec![Crease::simple(
2134 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2135 FoldPlaceholder::test(),
2136 )],
2137 cx,
2138 )
2139 });
2140 assert_eq!(
2141 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
2142 vec![
2143 ("fn ".to_string(), None),
2144 ("out".to_string(), Some(Hsla::blue())),
2145 ("⋯".to_string(), None),
2146 (" fn ".to_string(), Some(Hsla::red())),
2147 ("inner".to_string(), Some(Hsla::blue())),
2148 ("() {}\n}".to_string(), Some(Hsla::red())),
2149 ]
2150 );
2151 }
2152
2153 #[gpui::test]
2154 async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
2155 cx.background_executor
2156 .set_block_on_ticks(usize::MAX..=usize::MAX);
2157
2158 let text = r#"
2159 const A: &str = "
2160 one
2161 two
2162 three
2163 ";
2164 const B: &str = "four";
2165 "#
2166 .unindent();
2167
2168 let theme = SyntaxTheme::new_test(vec![
2169 ("string", Hsla::red()),
2170 ("punctuation", Hsla::blue()),
2171 ("keyword", Hsla::green()),
2172 ]);
2173 let language = Arc::new(
2174 Language::new(
2175 LanguageConfig {
2176 name: "Rust".into(),
2177 ..Default::default()
2178 },
2179 Some(tree_sitter_rust::LANGUAGE.into()),
2180 )
2181 .with_highlights_query(
2182 r#"
2183 (string_literal) @string
2184 "const" @keyword
2185 [":" ";"] @punctuation
2186 "#,
2187 )
2188 .unwrap(),
2189 );
2190 language.set_theme(&theme);
2191
2192 cx.update(|cx| init_test(cx, |_| {}));
2193
2194 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2195 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2196 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2197 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2198
2199 let map = cx.new(|cx| {
2200 DisplayMap::new(
2201 buffer,
2202 font("Courier"),
2203 px(16.0),
2204 None,
2205 1,
2206 1,
2207 FoldPlaceholder::test(),
2208 DiagnosticSeverity::Warning,
2209 cx,
2210 )
2211 });
2212
2213 // Insert two blocks in the middle of a multi-line string literal.
2214 // The second block has zero height.
2215 map.update(cx, |map, cx| {
2216 map.insert_blocks(
2217 [
2218 BlockProperties {
2219 placement: BlockPlacement::Below(
2220 buffer_snapshot.anchor_before(Point::new(1, 0)),
2221 ),
2222 height: Some(1),
2223 style: BlockStyle::Sticky,
2224 render: Arc::new(|_| div().into_any()),
2225 priority: 0,
2226 },
2227 BlockProperties {
2228 placement: BlockPlacement::Below(
2229 buffer_snapshot.anchor_before(Point::new(2, 0)),
2230 ),
2231 height: None,
2232 style: BlockStyle::Sticky,
2233 render: Arc::new(|_| div().into_any()),
2234 priority: 0,
2235 },
2236 ],
2237 cx,
2238 )
2239 });
2240
2241 pretty_assertions::assert_eq!(
2242 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
2243 [
2244 ("const".into(), Some(Hsla::green())),
2245 (" A".into(), None),
2246 (":".into(), Some(Hsla::blue())),
2247 (" &str = ".into(), None),
2248 ("\"\n one\n".into(), Some(Hsla::red())),
2249 ("\n".into(), None),
2250 (" two\n three\n\"".into(), Some(Hsla::red())),
2251 (";".into(), Some(Hsla::blue())),
2252 ("\n".into(), None),
2253 ("const".into(), Some(Hsla::green())),
2254 (" B".into(), None),
2255 (":".into(), Some(Hsla::blue())),
2256 (" &str = ".into(), None),
2257 ("\"four\"".into(), Some(Hsla::red())),
2258 (";".into(), Some(Hsla::blue())),
2259 ("\n".into(), None),
2260 ]
2261 );
2262 }
2263
2264 #[gpui::test]
2265 async fn test_chunks_with_diagnostics_across_blocks(cx: &mut gpui::TestAppContext) {
2266 cx.background_executor
2267 .set_block_on_ticks(usize::MAX..=usize::MAX);
2268
2269 let text = r#"
2270 struct A {
2271 b: usize;
2272 }
2273 const c: usize = 1;
2274 "#
2275 .unindent();
2276
2277 cx.update(|cx| init_test(cx, |_| {}));
2278
2279 let buffer = cx.new(|cx| Buffer::local(text, cx));
2280
2281 buffer.update(cx, |buffer, cx| {
2282 buffer.update_diagnostics(
2283 LanguageServerId(0),
2284 DiagnosticSet::new(
2285 [DiagnosticEntry {
2286 range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
2287 diagnostic: Diagnostic {
2288 severity: lsp::DiagnosticSeverity::ERROR,
2289 group_id: 1,
2290 message: "hi".into(),
2291 ..Default::default()
2292 },
2293 }],
2294 buffer,
2295 ),
2296 cx,
2297 )
2298 });
2299
2300 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2301 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2302
2303 let map = cx.new(|cx| {
2304 DisplayMap::new(
2305 buffer,
2306 font("Courier"),
2307 px(16.0),
2308 None,
2309 1,
2310 1,
2311 FoldPlaceholder::test(),
2312 DiagnosticSeverity::Warning,
2313 cx,
2314 )
2315 });
2316
2317 let black = gpui::black().to_rgb();
2318 let red = gpui::red().to_rgb();
2319
2320 // Insert a block in the middle of a multi-line diagnostic.
2321 map.update(cx, |map, cx| {
2322 map.highlight_text(
2323 HighlightKey::Type(TypeId::of::<usize>()),
2324 vec![
2325 buffer_snapshot.anchor_before(Point::new(3, 9))
2326 ..buffer_snapshot.anchor_after(Point::new(3, 14)),
2327 buffer_snapshot.anchor_before(Point::new(3, 17))
2328 ..buffer_snapshot.anchor_after(Point::new(3, 18)),
2329 ],
2330 red.into(),
2331 );
2332 map.insert_blocks(
2333 [BlockProperties {
2334 placement: BlockPlacement::Below(
2335 buffer_snapshot.anchor_before(Point::new(1, 0)),
2336 ),
2337 height: Some(1),
2338 style: BlockStyle::Sticky,
2339 render: Arc::new(|_| div().into_any()),
2340 priority: 0,
2341 }],
2342 cx,
2343 )
2344 });
2345
2346 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2347 let mut chunks = Vec::<(String, Option<lsp::DiagnosticSeverity>, Rgba)>::new();
2348 for chunk in snapshot.chunks(DisplayRow(0)..DisplayRow(5), true, Default::default()) {
2349 let color = chunk
2350 .highlight_style
2351 .and_then(|style| style.color)
2352 .map_or(black, |color| color.to_rgb());
2353 if let Some((last_chunk, last_severity, last_color)) = chunks.last_mut()
2354 && *last_severity == chunk.diagnostic_severity && *last_color == color {
2355 last_chunk.push_str(chunk.text);
2356 continue;
2357 }
2358
2359 chunks.push((chunk.text.to_string(), chunk.diagnostic_severity, color));
2360 }
2361
2362 assert_eq!(
2363 chunks,
2364 [
2365 (
2366 "struct A {\n b: usize;\n".into(),
2367 Some(lsp::DiagnosticSeverity::ERROR),
2368 black
2369 ),
2370 ("\n".into(), None, black),
2371 ("}".into(), Some(lsp::DiagnosticSeverity::ERROR), black),
2372 ("\nconst c: ".into(), None, black),
2373 ("usize".into(), None, red),
2374 (" = ".into(), None, black),
2375 ("1".into(), None, red),
2376 (";\n".into(), None, black),
2377 ]
2378 );
2379 }
2380
2381 #[gpui::test]
2382 async fn test_point_translation_with_replace_blocks(cx: &mut gpui::TestAppContext) {
2383 cx.background_executor
2384 .set_block_on_ticks(usize::MAX..=usize::MAX);
2385
2386 cx.update(|cx| init_test(cx, |_| {}));
2387
2388 let buffer = cx.update(|cx| MultiBuffer::build_simple("abcde\nfghij\nklmno\npqrst", cx));
2389 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2390 let map = cx.new(|cx| {
2391 DisplayMap::new(
2392 buffer.clone(),
2393 font("Courier"),
2394 px(16.0),
2395 None,
2396 1,
2397 1,
2398 FoldPlaceholder::test(),
2399 DiagnosticSeverity::Warning,
2400 cx,
2401 )
2402 });
2403
2404 let snapshot = map.update(cx, |map, cx| {
2405 map.insert_blocks(
2406 [BlockProperties {
2407 placement: BlockPlacement::Replace(
2408 buffer_snapshot.anchor_before(Point::new(1, 2))
2409 ..=buffer_snapshot.anchor_after(Point::new(2, 3)),
2410 ),
2411 height: Some(4),
2412 style: BlockStyle::Fixed,
2413 render: Arc::new(|_| div().into_any()),
2414 priority: 0,
2415 }],
2416 cx,
2417 );
2418 map.snapshot(cx)
2419 });
2420
2421 assert_eq!(snapshot.text(), "abcde\n\n\n\n\npqrst");
2422
2423 let point_to_display_points = [
2424 (Point::new(1, 0), DisplayPoint::new(DisplayRow(1), 0)),
2425 (Point::new(2, 0), DisplayPoint::new(DisplayRow(1), 0)),
2426 (Point::new(3, 0), DisplayPoint::new(DisplayRow(5), 0)),
2427 ];
2428 for (buffer_point, display_point) in point_to_display_points {
2429 assert_eq!(
2430 snapshot.point_to_display_point(buffer_point, Bias::Left),
2431 display_point,
2432 "point_to_display_point({:?}, Bias::Left)",
2433 buffer_point
2434 );
2435 assert_eq!(
2436 snapshot.point_to_display_point(buffer_point, Bias::Right),
2437 display_point,
2438 "point_to_display_point({:?}, Bias::Right)",
2439 buffer_point
2440 );
2441 }
2442
2443 let display_points_to_points = [
2444 (
2445 DisplayPoint::new(DisplayRow(1), 0),
2446 Point::new(1, 0),
2447 Point::new(2, 5),
2448 ),
2449 (
2450 DisplayPoint::new(DisplayRow(2), 0),
2451 Point::new(1, 0),
2452 Point::new(2, 5),
2453 ),
2454 (
2455 DisplayPoint::new(DisplayRow(3), 0),
2456 Point::new(1, 0),
2457 Point::new(2, 5),
2458 ),
2459 (
2460 DisplayPoint::new(DisplayRow(4), 0),
2461 Point::new(1, 0),
2462 Point::new(2, 5),
2463 ),
2464 (
2465 DisplayPoint::new(DisplayRow(5), 0),
2466 Point::new(3, 0),
2467 Point::new(3, 0),
2468 ),
2469 ];
2470 for (display_point, left_buffer_point, right_buffer_point) in display_points_to_points {
2471 assert_eq!(
2472 snapshot.display_point_to_point(display_point, Bias::Left),
2473 left_buffer_point,
2474 "display_point_to_point({:?}, Bias::Left)",
2475 display_point
2476 );
2477 assert_eq!(
2478 snapshot.display_point_to_point(display_point, Bias::Right),
2479 right_buffer_point,
2480 "display_point_to_point({:?}, Bias::Right)",
2481 display_point
2482 );
2483 }
2484 }
2485
2486 #[gpui::test]
2487 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
2488 cx.background_executor
2489 .set_block_on_ticks(usize::MAX..=usize::MAX);
2490
2491 let text = r#"
2492 fn outer() {}
2493
2494 mod module {
2495 fn inner() {}
2496 }"#
2497 .unindent();
2498
2499 let theme =
2500 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2501 let language = Arc::new(
2502 Language::new(
2503 LanguageConfig {
2504 name: "Test".into(),
2505 matcher: LanguageMatcher {
2506 path_suffixes: vec![".test".to_string()],
2507 ..Default::default()
2508 },
2509 ..Default::default()
2510 },
2511 Some(tree_sitter_rust::LANGUAGE.into()),
2512 )
2513 .with_highlights_query(
2514 r#"
2515 (mod_item name: (identifier) body: _ @mod.body)
2516 (function_item name: (identifier) @fn.name)
2517 "#,
2518 )
2519 .unwrap(),
2520 );
2521 language.set_theme(&theme);
2522
2523 cx.update(|cx| init_test(cx, |_| {}));
2524
2525 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2526 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2527 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2528
2529 let font_size = px(16.0);
2530
2531 let map = cx.new(|cx| {
2532 DisplayMap::new(
2533 buffer,
2534 font("Courier"),
2535 font_size,
2536 Some(px(40.0)),
2537 1,
2538 1,
2539 FoldPlaceholder::test(),
2540 DiagnosticSeverity::Warning,
2541 cx,
2542 )
2543 });
2544 assert_eq!(
2545 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2546 [
2547 ("fn \n".to_string(), None),
2548 ("oute".to_string(), Some(Hsla::blue())),
2549 ("\n".to_string(), None),
2550 ("r".to_string(), Some(Hsla::blue())),
2551 ("() \n{}\n\n".to_string(), None),
2552 ]
2553 );
2554 assert_eq!(
2555 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2556 [("{}\n\n".to_string(), None)]
2557 );
2558
2559 map.update(cx, |map, cx| {
2560 map.fold(
2561 vec![Crease::simple(
2562 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2563 FoldPlaceholder::test(),
2564 )],
2565 cx,
2566 )
2567 });
2568 assert_eq!(
2569 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
2570 [
2571 ("out".to_string(), Some(Hsla::blue())),
2572 ("⋯\n".to_string(), None),
2573 (" ".to_string(), Some(Hsla::red())),
2574 ("\n".to_string(), None),
2575 ("fn ".to_string(), Some(Hsla::red())),
2576 ("i".to_string(), Some(Hsla::blue())),
2577 ("\n".to_string(), None)
2578 ]
2579 );
2580 }
2581
2582 #[gpui::test]
2583 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
2584 cx.update(|cx| init_test(cx, |_| {}));
2585
2586 let theme =
2587 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
2588 let language = Arc::new(
2589 Language::new(
2590 LanguageConfig {
2591 name: "Test".into(),
2592 matcher: LanguageMatcher {
2593 path_suffixes: vec![".test".to_string()],
2594 ..Default::default()
2595 },
2596 ..Default::default()
2597 },
2598 Some(tree_sitter_rust::LANGUAGE.into()),
2599 )
2600 .with_highlights_query(
2601 r#"
2602 ":" @operator
2603 (string_literal) @string
2604 "#,
2605 )
2606 .unwrap(),
2607 );
2608 language.set_theme(&theme);
2609
2610 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
2611
2612 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2613 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2614
2615 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2616 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2617
2618 let font_size = px(16.0);
2619 let map = cx.new(|cx| {
2620 DisplayMap::new(
2621 buffer,
2622 font("Courier"),
2623 font_size,
2624 None,
2625 1,
2626 1,
2627 FoldPlaceholder::test(),
2628 DiagnosticSeverity::Warning,
2629 cx,
2630 )
2631 });
2632
2633 enum MyType {}
2634
2635 let style = HighlightStyle {
2636 color: Some(Hsla::blue()),
2637 ..Default::default()
2638 };
2639
2640 map.update(cx, |map, _cx| {
2641 map.highlight_text(
2642 HighlightKey::Type(TypeId::of::<MyType>()),
2643 highlighted_ranges
2644 .into_iter()
2645 .map(|range| {
2646 buffer_snapshot.anchor_before(range.start)
2647 ..buffer_snapshot.anchor_before(range.end)
2648 })
2649 .collect(),
2650 style,
2651 );
2652 });
2653
2654 assert_eq!(
2655 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
2656 [
2657 ("const ".to_string(), None, None),
2658 ("a".to_string(), None, Some(Hsla::blue())),
2659 (":".to_string(), Some(Hsla::red()), None),
2660 (" B = ".to_string(), None, None),
2661 ("\"c ".to_string(), Some(Hsla::green()), None),
2662 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2663 ("\"".to_string(), Some(Hsla::green()), None),
2664 ]
2665 );
2666 }
2667
2668 #[gpui::test]
2669 fn test_clip_point(cx: &mut gpui::App) {
2670 init_test(cx, |_| {});
2671
2672 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::App) {
2673 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2674
2675 match bias {
2676 Bias::Left => {
2677 if shift_right {
2678 *markers[1].column_mut() += 1;
2679 }
2680
2681 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2682 }
2683 Bias::Right => {
2684 if shift_right {
2685 *markers[0].column_mut() += 1;
2686 }
2687
2688 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2689 }
2690 };
2691 }
2692
2693 use Bias::{Left, Right};
2694 assert("ˇˇα", false, Left, cx);
2695 assert("ˇˇα", true, Left, cx);
2696 assert("ˇˇα", false, Right, cx);
2697 assert("ˇαˇ", true, Right, cx);
2698 assert("ˇˇ✋", false, Left, cx);
2699 assert("ˇˇ✋", true, Left, cx);
2700 assert("ˇˇ✋", false, Right, cx);
2701 assert("ˇ✋ˇ", true, Right, cx);
2702 assert("ˇˇ🍐", false, Left, cx);
2703 assert("ˇˇ🍐", true, Left, cx);
2704 assert("ˇˇ🍐", false, Right, cx);
2705 assert("ˇ🍐ˇ", true, Right, cx);
2706 assert("ˇˇ\t", false, Left, cx);
2707 assert("ˇˇ\t", true, Left, cx);
2708 assert("ˇˇ\t", false, Right, cx);
2709 assert("ˇ\tˇ", true, Right, cx);
2710 assert(" ˇˇ\t", false, Left, cx);
2711 assert(" ˇˇ\t", true, Left, cx);
2712 assert(" ˇˇ\t", false, Right, cx);
2713 assert(" ˇ\tˇ", true, Right, cx);
2714 assert(" ˇˇ\t", false, Left, cx);
2715 assert(" ˇˇ\t", false, Right, cx);
2716 }
2717
2718 #[gpui::test]
2719 fn test_clip_at_line_ends(cx: &mut gpui::App) {
2720 init_test(cx, |_| {});
2721
2722 fn assert(text: &str, cx: &mut gpui::App) {
2723 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2724 unmarked_snapshot.clip_at_line_ends = true;
2725 assert_eq!(
2726 unmarked_snapshot.clip_point(markers[1], Bias::Left),
2727 markers[0]
2728 );
2729 }
2730
2731 assert("ˇˇ", cx);
2732 assert("ˇaˇ", cx);
2733 assert("aˇbˇ", cx);
2734 assert("aˇαˇ", cx);
2735 }
2736
2737 #[gpui::test]
2738 fn test_creases(cx: &mut gpui::App) {
2739 init_test(cx, |_| {});
2740
2741 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2742 let buffer = MultiBuffer::build_simple(text, cx);
2743 let font_size = px(14.0);
2744 cx.new(|cx| {
2745 let mut map = DisplayMap::new(
2746 buffer.clone(),
2747 font("Helvetica"),
2748 font_size,
2749 None,
2750 1,
2751 1,
2752 FoldPlaceholder::test(),
2753 DiagnosticSeverity::Warning,
2754 cx,
2755 );
2756 let snapshot = map.buffer.read(cx).snapshot(cx);
2757 let range =
2758 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2759
2760 map.crease_map.insert(
2761 [Crease::inline(
2762 range,
2763 FoldPlaceholder::test(),
2764 |_row, _status, _toggle, _window, _cx| div(),
2765 |_row, _status, _window, _cx| div(),
2766 )],
2767 &map.buffer.read(cx).snapshot(cx),
2768 );
2769
2770 map
2771 });
2772 }
2773
2774 #[gpui::test]
2775 fn test_tabs_with_multibyte_chars(cx: &mut gpui::App) {
2776 init_test(cx, |_| {});
2777
2778 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
2779 let buffer = MultiBuffer::build_simple(text, cx);
2780 let font_size = px(14.0);
2781
2782 let map = cx.new(|cx| {
2783 DisplayMap::new(
2784 buffer.clone(),
2785 font("Helvetica"),
2786 font_size,
2787 None,
2788 1,
2789 1,
2790 FoldPlaceholder::test(),
2791 DiagnosticSeverity::Warning,
2792 cx,
2793 )
2794 });
2795 let map = map.update(cx, |map, cx| map.snapshot(cx));
2796 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
2797 assert_eq!(
2798 map.text_chunks(DisplayRow(0)).collect::<String>(),
2799 "✅ α\nβ \n🏀β γ"
2800 );
2801 assert_eq!(
2802 map.text_chunks(DisplayRow(1)).collect::<String>(),
2803 "β \n🏀β γ"
2804 );
2805 assert_eq!(
2806 map.text_chunks(DisplayRow(2)).collect::<String>(),
2807 "🏀β γ"
2808 );
2809
2810 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
2811 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
2812 assert_eq!(point.to_display_point(&map), display_point);
2813 assert_eq!(display_point.to_point(&map), point);
2814
2815 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2816 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
2817 assert_eq!(point.to_display_point(&map), display_point);
2818 assert_eq!(display_point.to_point(&map), point,);
2819
2820 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2821 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
2822 assert_eq!(point.to_display_point(&map), display_point);
2823 assert_eq!(display_point.to_point(&map), point,);
2824
2825 // Display points inside of expanded tabs
2826 assert_eq!(
2827 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2828 MultiBufferPoint::new(0, "✅\t".len() as u32),
2829 );
2830 assert_eq!(
2831 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2832 MultiBufferPoint::new(0, "✅".len() as u32),
2833 );
2834
2835 // Clipping display points inside of multi-byte characters
2836 assert_eq!(
2837 map.clip_point(
2838 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2839 Left
2840 ),
2841 DisplayPoint::new(DisplayRow(0), 0)
2842 );
2843 assert_eq!(
2844 map.clip_point(
2845 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2846 Bias::Right
2847 ),
2848 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
2849 );
2850 }
2851
2852 #[gpui::test]
2853 fn test_max_point(cx: &mut gpui::App) {
2854 init_test(cx, |_| {});
2855
2856 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2857 let font_size = px(14.0);
2858 let map = cx.new(|cx| {
2859 DisplayMap::new(
2860 buffer.clone(),
2861 font("Helvetica"),
2862 font_size,
2863 None,
2864 1,
2865 1,
2866 FoldPlaceholder::test(),
2867 DiagnosticSeverity::Warning,
2868 cx,
2869 )
2870 });
2871 assert_eq!(
2872 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2873 DisplayPoint::new(DisplayRow(1), 11)
2874 )
2875 }
2876
2877 fn syntax_chunks(
2878 rows: Range<DisplayRow>,
2879 map: &Entity<DisplayMap>,
2880 theme: &SyntaxTheme,
2881 cx: &mut App,
2882 ) -> Vec<(String, Option<Hsla>)> {
2883 chunks(rows, map, theme, cx)
2884 .into_iter()
2885 .map(|(text, color, _)| (text, color))
2886 .collect()
2887 }
2888
2889 fn chunks(
2890 rows: Range<DisplayRow>,
2891 map: &Entity<DisplayMap>,
2892 theme: &SyntaxTheme,
2893 cx: &mut App,
2894 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2895 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2896 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2897 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2898 let syntax_color = chunk
2899 .syntax_highlight_id
2900 .and_then(|id| id.style(theme)?.color);
2901 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2902 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut()
2903 && syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2904 last_chunk.push_str(chunk.text);
2905 continue;
2906 }
2907 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2908 }
2909 chunks
2910 }
2911
2912 fn init_test(cx: &mut App, f: impl Fn(&mut AllLanguageSettingsContent)) {
2913 let settings = SettingsStore::test(cx);
2914 cx.set_global(settings);
2915 workspace::init_settings(cx);
2916 language::init(cx);
2917 crate::init(cx);
2918 Project::init_settings(cx);
2919 theme::init(LoadThemes::JustBase, cx);
2920 cx.update_global::<SettingsStore, _>(|store, cx| {
2921 store.update_user_settings::<AllLanguageSettings>(cx, f);
2922 });
2923 }
2924}