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