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.layout_line(&line, font_size, &runs)
1033 }
1034
1035 pub fn x_for_display_point(
1036 &self,
1037 display_point: DisplayPoint,
1038 text_layout_details: &TextLayoutDetails,
1039 ) -> Pixels {
1040 let line = self.layout_row(display_point.row(), text_layout_details);
1041 line.x_for_index(display_point.column() as usize)
1042 }
1043
1044 pub fn display_column_for_x(
1045 &self,
1046 display_row: DisplayRow,
1047 x: Pixels,
1048 details: &TextLayoutDetails,
1049 ) -> u32 {
1050 let layout_line = self.layout_row(display_row, details);
1051 layout_line.closest_index_for_x(x) as u32
1052 }
1053
1054 pub fn grapheme_at(&self, mut point: DisplayPoint) -> Option<SharedString> {
1055 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
1056 let chars = self
1057 .text_chunks(point.row())
1058 .flat_map(str::chars)
1059 .skip_while({
1060 let mut column = 0;
1061 move |char| {
1062 let at_point = column >= point.column();
1063 column += char.len_utf8() as u32;
1064 !at_point
1065 }
1066 })
1067 .take_while({
1068 let mut prev = false;
1069 move |char| {
1070 let now = char.is_ascii();
1071 let end = char.is_ascii() && (char.is_ascii_whitespace() || prev);
1072 prev = now;
1073 !end
1074 }
1075 });
1076 chars.collect::<String>().graphemes(true).next().map(|s| {
1077 if let Some(invisible) = s.chars().next().filter(|&c| is_invisible(c)) {
1078 replacement(invisible).unwrap_or(s).to_owned().into()
1079 } else if s == "\n" {
1080 " ".into()
1081 } else {
1082 s.to_owned().into()
1083 }
1084 })
1085 }
1086
1087 pub fn buffer_chars_at(&self, mut offset: usize) -> impl Iterator<Item = (char, usize)> + '_ {
1088 self.buffer_snapshot.chars_at(offset).map(move |ch| {
1089 let ret = (ch, offset);
1090 offset += ch.len_utf8();
1091 ret
1092 })
1093 }
1094
1095 pub fn reverse_buffer_chars_at(
1096 &self,
1097 mut offset: usize,
1098 ) -> impl Iterator<Item = (char, usize)> + '_ {
1099 self.buffer_snapshot
1100 .reversed_chars_at(offset)
1101 .map(move |ch| {
1102 offset -= ch.len_utf8();
1103 (ch, offset)
1104 })
1105 }
1106
1107 pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
1108 let mut clipped = self.block_snapshot.clip_point(point.0, bias);
1109 if self.clip_at_line_ends {
1110 clipped = self.clip_at_line_end(DisplayPoint(clipped)).0
1111 }
1112 DisplayPoint(clipped)
1113 }
1114
1115 pub fn clip_ignoring_line_ends(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
1116 DisplayPoint(self.block_snapshot.clip_point(point.0, bias))
1117 }
1118
1119 pub fn clip_at_line_end(&self, display_point: DisplayPoint) -> DisplayPoint {
1120 let mut point = self.display_point_to_point(display_point, Bias::Left);
1121
1122 if point.column != self.buffer_snapshot.line_len(MultiBufferRow(point.row)) {
1123 return display_point;
1124 }
1125 point.column = point.column.saturating_sub(1);
1126 point = self.buffer_snapshot.clip_point(point, Bias::Left);
1127 self.point_to_display_point(point, Bias::Left)
1128 }
1129
1130 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Fold>
1131 where
1132 T: ToOffset,
1133 {
1134 self.fold_snapshot.folds_in_range(range)
1135 }
1136
1137 pub fn blocks_in_range(
1138 &self,
1139 rows: Range<DisplayRow>,
1140 ) -> impl Iterator<Item = (DisplayRow, &Block)> {
1141 self.block_snapshot
1142 .blocks_in_range(rows.start.0..rows.end.0)
1143 .map(|(row, block)| (DisplayRow(row), block))
1144 }
1145
1146 pub fn sticky_header_excerpt(&self, row: f32) -> Option<StickyHeaderExcerpt<'_>> {
1147 self.block_snapshot.sticky_header_excerpt(row)
1148 }
1149
1150 pub fn block_for_id(&self, id: BlockId) -> Option<Block> {
1151 self.block_snapshot.block_for_id(id)
1152 }
1153
1154 pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
1155 self.fold_snapshot.intersects_fold(offset)
1156 }
1157
1158 pub fn is_line_folded(&self, buffer_row: MultiBufferRow) -> bool {
1159 self.block_snapshot.is_line_replaced(buffer_row)
1160 || self.fold_snapshot.is_line_folded(buffer_row)
1161 }
1162
1163 pub fn is_block_line(&self, display_row: DisplayRow) -> bool {
1164 self.block_snapshot.is_block_line(BlockRow(display_row.0))
1165 }
1166
1167 pub fn is_folded_buffer_header(&self, display_row: DisplayRow) -> bool {
1168 self.block_snapshot
1169 .is_folded_buffer_header(BlockRow(display_row.0))
1170 }
1171
1172 pub fn soft_wrap_indent(&self, display_row: DisplayRow) -> Option<u32> {
1173 let wrap_row = self
1174 .block_snapshot
1175 .to_wrap_point(BlockPoint::new(display_row.0, 0), Bias::Left)
1176 .row();
1177 self.wrap_snapshot.soft_wrap_indent(wrap_row)
1178 }
1179
1180 pub fn text(&self) -> String {
1181 self.text_chunks(DisplayRow(0)).collect()
1182 }
1183
1184 pub fn line(&self, display_row: DisplayRow) -> String {
1185 let mut result = String::new();
1186 for chunk in self.text_chunks(display_row) {
1187 if let Some(ix) = chunk.find('\n') {
1188 result.push_str(&chunk[0..ix]);
1189 break;
1190 } else {
1191 result.push_str(chunk);
1192 }
1193 }
1194 result
1195 }
1196
1197 pub fn line_indent_for_buffer_row(&self, buffer_row: MultiBufferRow) -> LineIndent {
1198 self.buffer_snapshot.line_indent_for_row(buffer_row)
1199 }
1200
1201 pub fn line_len(&self, row: DisplayRow) -> u32 {
1202 self.block_snapshot.line_len(BlockRow(row.0))
1203 }
1204
1205 pub fn longest_row(&self) -> DisplayRow {
1206 DisplayRow(self.block_snapshot.longest_row())
1207 }
1208
1209 pub fn longest_row_in_range(&self, range: Range<DisplayRow>) -> DisplayRow {
1210 let block_range = BlockRow(range.start.0)..BlockRow(range.end.0);
1211 let longest_row = self.block_snapshot.longest_row_in_range(block_range);
1212 DisplayRow(longest_row.0)
1213 }
1214
1215 pub fn starts_indent(&self, buffer_row: MultiBufferRow) -> bool {
1216 let max_row = self.buffer_snapshot.max_row();
1217 if buffer_row >= max_row {
1218 return false;
1219 }
1220
1221 let line_indent = self.line_indent_for_buffer_row(buffer_row);
1222 if line_indent.is_line_blank() {
1223 return false;
1224 }
1225
1226 (buffer_row.0 + 1..=max_row.0)
1227 .find_map(|next_row| {
1228 let next_line_indent = self.line_indent_for_buffer_row(MultiBufferRow(next_row));
1229 if next_line_indent.raw_len() > line_indent.raw_len() {
1230 Some(true)
1231 } else if !next_line_indent.is_line_blank() {
1232 Some(false)
1233 } else {
1234 None
1235 }
1236 })
1237 .unwrap_or(false)
1238 }
1239
1240 pub fn crease_for_buffer_row(&self, buffer_row: MultiBufferRow) -> Option<Crease<Point>> {
1241 let start = MultiBufferPoint::new(buffer_row.0, self.buffer_snapshot.line_len(buffer_row));
1242 if let Some(crease) = self
1243 .crease_snapshot
1244 .query_row(buffer_row, &self.buffer_snapshot)
1245 {
1246 match crease {
1247 Crease::Inline {
1248 range,
1249 placeholder,
1250 render_toggle,
1251 render_trailer,
1252 metadata,
1253 } => Some(Crease::Inline {
1254 range: range.to_point(&self.buffer_snapshot),
1255 placeholder: placeholder.clone(),
1256 render_toggle: render_toggle.clone(),
1257 render_trailer: render_trailer.clone(),
1258 metadata: metadata.clone(),
1259 }),
1260 Crease::Block {
1261 range,
1262 block_height,
1263 block_style,
1264 render_block,
1265 block_priority,
1266 render_toggle,
1267 } => Some(Crease::Block {
1268 range: range.to_point(&self.buffer_snapshot),
1269 block_height: *block_height,
1270 block_style: *block_style,
1271 render_block: render_block.clone(),
1272 block_priority: *block_priority,
1273 render_toggle: render_toggle.clone(),
1274 }),
1275 }
1276 } else if self.starts_indent(MultiBufferRow(start.row))
1277 && !self.is_line_folded(MultiBufferRow(start.row))
1278 {
1279 let start_line_indent = self.line_indent_for_buffer_row(buffer_row);
1280 let max_point = self.buffer_snapshot.max_point();
1281 let mut end = None;
1282
1283 for row in (buffer_row.0 + 1)..=max_point.row {
1284 let line_indent = self.line_indent_for_buffer_row(MultiBufferRow(row));
1285 if !line_indent.is_line_blank()
1286 && line_indent.raw_len() <= start_line_indent.raw_len()
1287 {
1288 let prev_row = row - 1;
1289 end = Some(Point::new(
1290 prev_row,
1291 self.buffer_snapshot.line_len(MultiBufferRow(prev_row)),
1292 ));
1293 break;
1294 }
1295 }
1296
1297 let mut row_before_line_breaks = end.unwrap_or(max_point);
1298 while row_before_line_breaks.row > start.row
1299 && self
1300 .buffer_snapshot
1301 .is_line_blank(MultiBufferRow(row_before_line_breaks.row))
1302 {
1303 row_before_line_breaks.row -= 1;
1304 }
1305
1306 row_before_line_breaks = Point::new(
1307 row_before_line_breaks.row,
1308 self.buffer_snapshot
1309 .line_len(MultiBufferRow(row_before_line_breaks.row)),
1310 );
1311
1312 Some(Crease::Inline {
1313 range: start..row_before_line_breaks,
1314 placeholder: self.fold_placeholder.clone(),
1315 render_toggle: None,
1316 render_trailer: None,
1317 metadata: None,
1318 })
1319 } else {
1320 None
1321 }
1322 }
1323
1324 #[cfg(any(test, feature = "test-support"))]
1325 pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
1326 &self,
1327 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
1328 let type_id = TypeId::of::<Tag>();
1329 self.text_highlights.get(&type_id).cloned()
1330 }
1331
1332 #[allow(unused)]
1333 #[cfg(any(test, feature = "test-support"))]
1334 pub(crate) fn inlay_highlights<Tag: ?Sized + 'static>(
1335 &self,
1336 ) -> Option<&TreeMap<InlayId, (HighlightStyle, InlayHighlight)>> {
1337 let type_id = TypeId::of::<Tag>();
1338 self.inlay_highlights.get(&type_id)
1339 }
1340
1341 pub fn buffer_header_height(&self) -> u32 {
1342 self.block_snapshot.buffer_header_height
1343 }
1344
1345 pub fn excerpt_header_height(&self) -> u32 {
1346 self.block_snapshot.excerpt_header_height
1347 }
1348}
1349
1350#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
1351pub struct DisplayPoint(BlockPoint);
1352
1353impl Debug for DisplayPoint {
1354 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1355 f.write_fmt(format_args!(
1356 "DisplayPoint({}, {})",
1357 self.row().0,
1358 self.column()
1359 ))
1360 }
1361}
1362
1363impl Add for DisplayPoint {
1364 type Output = Self;
1365
1366 fn add(self, other: Self) -> Self::Output {
1367 DisplayPoint(BlockPoint(self.0.0 + other.0.0))
1368 }
1369}
1370
1371impl Sub for DisplayPoint {
1372 type Output = Self;
1373
1374 fn sub(self, other: Self) -> Self::Output {
1375 DisplayPoint(BlockPoint(self.0.0 - other.0.0))
1376 }
1377}
1378
1379#[derive(Debug, Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq, Deserialize, Hash)]
1380#[serde(transparent)]
1381pub struct DisplayRow(pub u32);
1382
1383impl Add<DisplayRow> for DisplayRow {
1384 type Output = Self;
1385
1386 fn add(self, other: Self) -> Self::Output {
1387 DisplayRow(self.0 + other.0)
1388 }
1389}
1390
1391impl Add<u32> for DisplayRow {
1392 type Output = Self;
1393
1394 fn add(self, other: u32) -> Self::Output {
1395 DisplayRow(self.0 + other)
1396 }
1397}
1398
1399impl Sub<DisplayRow> for DisplayRow {
1400 type Output = Self;
1401
1402 fn sub(self, other: Self) -> Self::Output {
1403 DisplayRow(self.0 - other.0)
1404 }
1405}
1406
1407impl Sub<u32> for DisplayRow {
1408 type Output = Self;
1409
1410 fn sub(self, other: u32) -> Self::Output {
1411 DisplayRow(self.0 - other)
1412 }
1413}
1414
1415impl DisplayPoint {
1416 pub fn new(row: DisplayRow, column: u32) -> Self {
1417 Self(BlockPoint(Point::new(row.0, column)))
1418 }
1419
1420 pub fn zero() -> Self {
1421 Self::new(DisplayRow(0), 0)
1422 }
1423
1424 pub fn is_zero(&self) -> bool {
1425 self.0.is_zero()
1426 }
1427
1428 pub fn row(self) -> DisplayRow {
1429 DisplayRow(self.0.row)
1430 }
1431
1432 pub fn column(self) -> u32 {
1433 self.0.column
1434 }
1435
1436 pub fn row_mut(&mut self) -> &mut u32 {
1437 &mut self.0.row
1438 }
1439
1440 pub fn column_mut(&mut self) -> &mut u32 {
1441 &mut self.0.column
1442 }
1443
1444 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
1445 map.display_point_to_point(self, Bias::Left)
1446 }
1447
1448 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
1449 let wrap_point = map.block_snapshot.to_wrap_point(self.0, bias);
1450 let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
1451 let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
1452 let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
1453 map.inlay_snapshot
1454 .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
1455 }
1456}
1457
1458impl ToDisplayPoint for usize {
1459 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1460 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
1461 }
1462}
1463
1464impl ToDisplayPoint for OffsetUtf16 {
1465 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1466 self.to_offset(&map.buffer_snapshot).to_display_point(map)
1467 }
1468}
1469
1470impl ToDisplayPoint for Point {
1471 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1472 map.point_to_display_point(*self, Bias::Left)
1473 }
1474}
1475
1476impl ToDisplayPoint for Anchor {
1477 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1478 self.to_point(&map.buffer_snapshot).to_display_point(map)
1479 }
1480}
1481
1482#[cfg(test)]
1483pub mod tests {
1484 use super::*;
1485 use crate::{
1486 movement,
1487 test::{marked_display_snapshot, test_font},
1488 };
1489 use Bias::*;
1490 use block_map::BlockPlacement;
1491 use gpui::{
1492 App, AppContext as _, BorrowAppContext, Element, Hsla, Rgba, div, font, observe, px,
1493 };
1494 use language::{
1495 Buffer, Diagnostic, DiagnosticEntry, DiagnosticSet, Language, LanguageConfig,
1496 LanguageMatcher,
1497 language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1498 };
1499 use lsp::LanguageServerId;
1500 use project::Project;
1501 use rand::{Rng, prelude::*};
1502 use settings::SettingsStore;
1503 use smol::stream::StreamExt;
1504 use std::{env, sync::Arc};
1505 use text::PointUtf16;
1506 use theme::{LoadThemes, SyntaxTheme};
1507 use unindent::Unindent as _;
1508 use util::test::{marked_text_ranges, sample_text};
1509
1510 #[gpui::test(iterations = 100)]
1511 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1512 cx.background_executor.set_block_on_ticks(0..=50);
1513 let operations = env::var("OPERATIONS")
1514 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1515 .unwrap_or(10);
1516
1517 let mut tab_size = rng.gen_range(1..=4);
1518 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1519 let excerpt_header_height = rng.gen_range(1..=5);
1520 let font_size = px(14.0);
1521 let max_wrap_width = 300.0;
1522 let mut wrap_width = if rng.gen_bool(0.1) {
1523 None
1524 } else {
1525 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1526 };
1527
1528 log::info!("tab size: {}", tab_size);
1529 log::info!("wrap width: {:?}", wrap_width);
1530
1531 cx.update(|cx| {
1532 init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1533 });
1534
1535 let buffer = cx.update(|cx| {
1536 if rng.r#gen() {
1537 let len = rng.gen_range(0..10);
1538 let text = util::RandomCharIter::new(&mut rng)
1539 .take(len)
1540 .collect::<String>();
1541 MultiBuffer::build_simple(&text, cx)
1542 } else {
1543 MultiBuffer::build_random(&mut rng, cx)
1544 }
1545 });
1546
1547 let font = test_font();
1548 let map = cx.new(|cx| {
1549 DisplayMap::new(
1550 buffer.clone(),
1551 font,
1552 font_size,
1553 wrap_width,
1554 buffer_start_excerpt_header_height,
1555 excerpt_header_height,
1556 FoldPlaceholder::test(),
1557 DiagnosticSeverity::Warning,
1558 cx,
1559 )
1560 });
1561 let mut notifications = observe(&map, cx);
1562 let mut fold_count = 0;
1563 let mut blocks = Vec::new();
1564
1565 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1566 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1567 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1568 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1569 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1570 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1571 log::info!("display text: {:?}", snapshot.text());
1572
1573 for _i in 0..operations {
1574 match rng.gen_range(0..100) {
1575 0..=19 => {
1576 wrap_width = if rng.gen_bool(0.2) {
1577 None
1578 } else {
1579 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1580 };
1581 log::info!("setting wrap width to {:?}", wrap_width);
1582 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1583 }
1584 20..=29 => {
1585 let mut tab_sizes = vec![1, 2, 3, 4];
1586 tab_sizes.remove((tab_size - 1) as usize);
1587 tab_size = *tab_sizes.choose(&mut rng).unwrap();
1588 log::info!("setting tab size to {:?}", tab_size);
1589 cx.update(|cx| {
1590 cx.update_global::<SettingsStore, _>(|store, cx| {
1591 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1592 s.defaults.tab_size = NonZeroU32::new(tab_size);
1593 });
1594 });
1595 });
1596 }
1597 30..=44 => {
1598 map.update(cx, |map, cx| {
1599 if rng.r#gen() || blocks.is_empty() {
1600 let buffer = map.snapshot(cx).buffer_snapshot;
1601 let block_properties = (0..rng.gen_range(1..=1))
1602 .map(|_| {
1603 let position =
1604 buffer.anchor_after(buffer.clip_offset(
1605 rng.gen_range(0..=buffer.len()),
1606 Bias::Left,
1607 ));
1608
1609 let placement = if rng.r#gen() {
1610 BlockPlacement::Above(position)
1611 } else {
1612 BlockPlacement::Below(position)
1613 };
1614 let height = rng.gen_range(1..5);
1615 log::info!(
1616 "inserting block {:?} with height {}",
1617 placement.as_ref().map(|p| p.to_point(&buffer)),
1618 height
1619 );
1620 let priority = rng.gen_range(1..100);
1621 BlockProperties {
1622 placement,
1623 style: BlockStyle::Fixed,
1624 height: Some(height),
1625 render: Arc::new(|_| div().into_any()),
1626 priority,
1627 render_in_minimap: true,
1628 }
1629 })
1630 .collect::<Vec<_>>();
1631 blocks.extend(map.insert_blocks(block_properties, cx));
1632 } else {
1633 blocks.shuffle(&mut rng);
1634 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1635 let block_ids_to_remove = (0..remove_count)
1636 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1637 .collect();
1638 log::info!("removing block ids {:?}", block_ids_to_remove);
1639 map.remove_blocks(block_ids_to_remove, cx);
1640 }
1641 });
1642 }
1643 45..=79 => {
1644 let mut ranges = Vec::new();
1645 for _ in 0..rng.gen_range(1..=3) {
1646 buffer.read_with(cx, |buffer, cx| {
1647 let buffer = buffer.read(cx);
1648 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1649 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1650 ranges.push(start..end);
1651 });
1652 }
1653
1654 if rng.r#gen() && fold_count > 0 {
1655 log::info!("unfolding ranges: {:?}", ranges);
1656 map.update(cx, |map, cx| {
1657 map.unfold_intersecting(ranges, true, cx);
1658 });
1659 } else {
1660 log::info!("folding ranges: {:?}", ranges);
1661 map.update(cx, |map, cx| {
1662 map.fold(
1663 ranges
1664 .into_iter()
1665 .map(|range| Crease::simple(range, FoldPlaceholder::test()))
1666 .collect(),
1667 cx,
1668 );
1669 });
1670 }
1671 }
1672 _ => {
1673 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1674 }
1675 }
1676
1677 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1678 notifications.next().await.unwrap();
1679 }
1680
1681 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1682 fold_count = snapshot.fold_count();
1683 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1684 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1685 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1686 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1687 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1688 log::info!("display text: {:?}", snapshot.text());
1689
1690 // Line boundaries
1691 let buffer = &snapshot.buffer_snapshot;
1692 for _ in 0..5 {
1693 let row = rng.gen_range(0..=buffer.max_point().row);
1694 let column = rng.gen_range(0..=buffer.line_len(MultiBufferRow(row)));
1695 let point = buffer.clip_point(Point::new(row, column), Left);
1696
1697 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1698 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1699
1700 assert!(prev_buffer_bound <= point);
1701 assert!(next_buffer_bound >= point);
1702 assert_eq!(prev_buffer_bound.column, 0);
1703 assert_eq!(prev_display_bound.column(), 0);
1704 if next_buffer_bound < buffer.max_point() {
1705 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1706 }
1707
1708 assert_eq!(
1709 prev_display_bound,
1710 prev_buffer_bound.to_display_point(&snapshot),
1711 "row boundary before {:?}. reported buffer row boundary: {:?}",
1712 point,
1713 prev_buffer_bound
1714 );
1715 assert_eq!(
1716 next_display_bound,
1717 next_buffer_bound.to_display_point(&snapshot),
1718 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1719 point,
1720 next_buffer_bound
1721 );
1722 assert_eq!(
1723 prev_buffer_bound,
1724 prev_display_bound.to_point(&snapshot),
1725 "row boundary before {:?}. reported display row boundary: {:?}",
1726 point,
1727 prev_display_bound
1728 );
1729 assert_eq!(
1730 next_buffer_bound,
1731 next_display_bound.to_point(&snapshot),
1732 "row boundary after {:?}. reported display row boundary: {:?}",
1733 point,
1734 next_display_bound
1735 );
1736 }
1737
1738 // Movement
1739 let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1740 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1741 for _ in 0..5 {
1742 let row = rng.gen_range(0..=snapshot.max_point().row().0);
1743 let column = rng.gen_range(0..=snapshot.line_len(DisplayRow(row)));
1744 let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1745
1746 log::info!("Moving from point {:?}", point);
1747
1748 let moved_right = movement::right(&snapshot, point);
1749 log::info!("Right {:?}", moved_right);
1750 if point < max_point {
1751 assert!(moved_right > point);
1752 if point.column() == snapshot.line_len(point.row())
1753 || snapshot.soft_wrap_indent(point.row()).is_some()
1754 && point.column() == snapshot.line_len(point.row()) - 1
1755 {
1756 assert!(moved_right.row() > point.row());
1757 }
1758 } else {
1759 assert_eq!(moved_right, point);
1760 }
1761
1762 let moved_left = movement::left(&snapshot, point);
1763 log::info!("Left {:?}", moved_left);
1764 if point > min_point {
1765 assert!(moved_left < point);
1766 if point.column() == 0 {
1767 assert!(moved_left.row() < point.row());
1768 }
1769 } else {
1770 assert_eq!(moved_left, point);
1771 }
1772 }
1773 }
1774 }
1775
1776 #[gpui::test(retries = 5)]
1777 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1778 cx.background_executor
1779 .set_block_on_ticks(usize::MAX..=usize::MAX);
1780 cx.update(|cx| {
1781 init_test(cx, |_| {});
1782 });
1783
1784 let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1785 let editor = cx.editor.clone();
1786 let window = cx.window;
1787
1788 _ = cx.update_window(window, |_, window, cx| {
1789 let text_layout_details =
1790 editor.update(cx, |editor, _cx| editor.text_layout_details(window));
1791
1792 let font_size = px(12.0);
1793 let wrap_width = Some(px(96.));
1794
1795 let text = "one two three four five\nsix seven eight";
1796 let buffer = MultiBuffer::build_simple(text, cx);
1797 let map = cx.new(|cx| {
1798 DisplayMap::new(
1799 buffer.clone(),
1800 font("Helvetica"),
1801 font_size,
1802 wrap_width,
1803 1,
1804 1,
1805 FoldPlaceholder::test(),
1806 DiagnosticSeverity::Warning,
1807 cx,
1808 )
1809 });
1810
1811 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1812 assert_eq!(
1813 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1814 "one two \nthree four \nfive\nsix seven \neight"
1815 );
1816 assert_eq!(
1817 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1818 DisplayPoint::new(DisplayRow(0), 7)
1819 );
1820 assert_eq!(
1821 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1822 DisplayPoint::new(DisplayRow(1), 0)
1823 );
1824 assert_eq!(
1825 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1826 DisplayPoint::new(DisplayRow(1), 0)
1827 );
1828 assert_eq!(
1829 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1830 DisplayPoint::new(DisplayRow(0), 7)
1831 );
1832
1833 let x = snapshot
1834 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1835 assert_eq!(
1836 movement::up(
1837 &snapshot,
1838 DisplayPoint::new(DisplayRow(1), 10),
1839 language::SelectionGoal::None,
1840 false,
1841 &text_layout_details,
1842 ),
1843 (
1844 DisplayPoint::new(DisplayRow(0), 7),
1845 language::SelectionGoal::HorizontalPosition(x.0)
1846 )
1847 );
1848 assert_eq!(
1849 movement::down(
1850 &snapshot,
1851 DisplayPoint::new(DisplayRow(0), 7),
1852 language::SelectionGoal::HorizontalPosition(x.0),
1853 false,
1854 &text_layout_details
1855 ),
1856 (
1857 DisplayPoint::new(DisplayRow(1), 10),
1858 language::SelectionGoal::HorizontalPosition(x.0)
1859 )
1860 );
1861 assert_eq!(
1862 movement::down(
1863 &snapshot,
1864 DisplayPoint::new(DisplayRow(1), 10),
1865 language::SelectionGoal::HorizontalPosition(x.0),
1866 false,
1867 &text_layout_details
1868 ),
1869 (
1870 DisplayPoint::new(DisplayRow(2), 4),
1871 language::SelectionGoal::HorizontalPosition(x.0)
1872 )
1873 );
1874
1875 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1876 buffer.update(cx, |buffer, cx| {
1877 buffer.edit([(ix..ix, "and ")], None, cx);
1878 });
1879
1880 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1881 assert_eq!(
1882 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1883 "three four \nfive\nsix and \nseven eight"
1884 );
1885
1886 // Re-wrap on font size changes
1887 map.update(cx, |map, cx| {
1888 map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1889 });
1890
1891 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1892 assert_eq!(
1893 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1894 "three \nfour five\nsix and \nseven \neight"
1895 )
1896 });
1897 }
1898
1899 #[gpui::test]
1900 fn test_text_chunks(cx: &mut gpui::App) {
1901 init_test(cx, |_| {});
1902
1903 let text = sample_text(6, 6, 'a');
1904 let buffer = MultiBuffer::build_simple(&text, cx);
1905
1906 let font_size = px(14.0);
1907 let map = cx.new(|cx| {
1908 DisplayMap::new(
1909 buffer.clone(),
1910 font("Helvetica"),
1911 font_size,
1912 None,
1913 1,
1914 1,
1915 FoldPlaceholder::test(),
1916 DiagnosticSeverity::Warning,
1917 cx,
1918 )
1919 });
1920
1921 buffer.update(cx, |buffer, cx| {
1922 buffer.edit(
1923 vec![
1924 (
1925 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1926 "\t",
1927 ),
1928 (
1929 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1930 "\t",
1931 ),
1932 (
1933 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1934 "\t",
1935 ),
1936 ],
1937 None,
1938 cx,
1939 )
1940 });
1941
1942 assert_eq!(
1943 map.update(cx, |map, cx| map.snapshot(cx))
1944 .text_chunks(DisplayRow(1))
1945 .collect::<String>()
1946 .lines()
1947 .next(),
1948 Some(" b bbbbb")
1949 );
1950 assert_eq!(
1951 map.update(cx, |map, cx| map.snapshot(cx))
1952 .text_chunks(DisplayRow(2))
1953 .collect::<String>()
1954 .lines()
1955 .next(),
1956 Some("c ccccc")
1957 );
1958 }
1959
1960 #[gpui::test]
1961 fn test_inlays_with_newlines_after_blocks(cx: &mut gpui::TestAppContext) {
1962 cx.update(|cx| init_test(cx, |_| {}));
1963
1964 let buffer = cx.new(|cx| Buffer::local("a", cx));
1965 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1966 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1967
1968 let font_size = px(14.0);
1969 let map = cx.new(|cx| {
1970 DisplayMap::new(
1971 buffer.clone(),
1972 font("Helvetica"),
1973 font_size,
1974 None,
1975 1,
1976 1,
1977 FoldPlaceholder::test(),
1978 DiagnosticSeverity::Warning,
1979 cx,
1980 )
1981 });
1982
1983 map.update(cx, |map, cx| {
1984 map.insert_blocks(
1985 [BlockProperties {
1986 placement: BlockPlacement::Above(
1987 buffer_snapshot.anchor_before(Point::new(0, 0)),
1988 ),
1989 height: Some(2),
1990 style: BlockStyle::Sticky,
1991 render: Arc::new(|_| div().into_any()),
1992 priority: 0,
1993 render_in_minimap: true,
1994 }],
1995 cx,
1996 );
1997 });
1998 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\na"));
1999
2000 map.update(cx, |map, cx| {
2001 map.splice_inlays(
2002 &[],
2003 vec![Inlay {
2004 id: InlayId::InlineCompletion(0),
2005 position: buffer_snapshot.anchor_after(0),
2006 text: "\n".into(),
2007 }],
2008 cx,
2009 );
2010 });
2011 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\na"));
2012
2013 // Regression test: updating the display map does not crash when a
2014 // block is immediately followed by a multi-line inlay.
2015 buffer.update(cx, |buffer, cx| {
2016 buffer.edit([(1..1, "b")], None, cx);
2017 });
2018 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\nab"));
2019 }
2020
2021 #[gpui::test]
2022 async fn test_chunks(cx: &mut gpui::TestAppContext) {
2023 let text = r#"
2024 fn outer() {}
2025
2026 mod module {
2027 fn inner() {}
2028 }"#
2029 .unindent();
2030
2031 let theme =
2032 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2033 let language = Arc::new(
2034 Language::new(
2035 LanguageConfig {
2036 name: "Test".into(),
2037 matcher: LanguageMatcher {
2038 path_suffixes: vec![".test".to_string()],
2039 ..Default::default()
2040 },
2041 ..Default::default()
2042 },
2043 Some(tree_sitter_rust::LANGUAGE.into()),
2044 )
2045 .with_highlights_query(
2046 r#"
2047 (mod_item name: (identifier) body: _ @mod.body)
2048 (function_item name: (identifier) @fn.name)
2049 "#,
2050 )
2051 .unwrap(),
2052 );
2053 language.set_theme(&theme);
2054
2055 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
2056
2057 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2058 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2059 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2060
2061 let font_size = px(14.0);
2062
2063 let map = cx.new(|cx| {
2064 DisplayMap::new(
2065 buffer,
2066 font("Helvetica"),
2067 font_size,
2068 None,
2069 1,
2070 1,
2071 FoldPlaceholder::test(),
2072 DiagnosticSeverity::Warning,
2073 cx,
2074 )
2075 });
2076 assert_eq!(
2077 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2078 vec![
2079 ("fn ".to_string(), None),
2080 ("outer".to_string(), Some(Hsla::blue())),
2081 ("() {}\n\nmod module ".to_string(), None),
2082 ("{\n fn ".to_string(), Some(Hsla::red())),
2083 ("inner".to_string(), Some(Hsla::blue())),
2084 ("() {}\n}".to_string(), Some(Hsla::red())),
2085 ]
2086 );
2087 assert_eq!(
2088 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2089 vec![
2090 (" fn ".to_string(), Some(Hsla::red())),
2091 ("inner".to_string(), Some(Hsla::blue())),
2092 ("() {}\n}".to_string(), Some(Hsla::red())),
2093 ]
2094 );
2095
2096 map.update(cx, |map, cx| {
2097 map.fold(
2098 vec![Crease::simple(
2099 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2100 FoldPlaceholder::test(),
2101 )],
2102 cx,
2103 )
2104 });
2105 assert_eq!(
2106 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
2107 vec![
2108 ("fn ".to_string(), None),
2109 ("out".to_string(), Some(Hsla::blue())),
2110 ("⋯".to_string(), None),
2111 (" fn ".to_string(), Some(Hsla::red())),
2112 ("inner".to_string(), Some(Hsla::blue())),
2113 ("() {}\n}".to_string(), Some(Hsla::red())),
2114 ]
2115 );
2116 }
2117
2118 #[gpui::test]
2119 async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
2120 cx.background_executor
2121 .set_block_on_ticks(usize::MAX..=usize::MAX);
2122
2123 let text = r#"
2124 const A: &str = "
2125 one
2126 two
2127 three
2128 ";
2129 const B: &str = "four";
2130 "#
2131 .unindent();
2132
2133 let theme = SyntaxTheme::new_test(vec![
2134 ("string", Hsla::red()),
2135 ("punctuation", Hsla::blue()),
2136 ("keyword", Hsla::green()),
2137 ]);
2138 let language = Arc::new(
2139 Language::new(
2140 LanguageConfig {
2141 name: "Rust".into(),
2142 ..Default::default()
2143 },
2144 Some(tree_sitter_rust::LANGUAGE.into()),
2145 )
2146 .with_highlights_query(
2147 r#"
2148 (string_literal) @string
2149 "const" @keyword
2150 [":" ";"] @punctuation
2151 "#,
2152 )
2153 .unwrap(),
2154 );
2155 language.set_theme(&theme);
2156
2157 cx.update(|cx| init_test(cx, |_| {}));
2158
2159 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2160 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2161 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2162 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2163
2164 let map = cx.new(|cx| {
2165 DisplayMap::new(
2166 buffer,
2167 font("Courier"),
2168 px(16.0),
2169 None,
2170 1,
2171 1,
2172 FoldPlaceholder::test(),
2173 DiagnosticSeverity::Warning,
2174 cx,
2175 )
2176 });
2177
2178 // Insert two blocks in the middle of a multi-line string literal.
2179 // The second block has zero height.
2180 map.update(cx, |map, cx| {
2181 map.insert_blocks(
2182 [
2183 BlockProperties {
2184 placement: BlockPlacement::Below(
2185 buffer_snapshot.anchor_before(Point::new(1, 0)),
2186 ),
2187 height: Some(1),
2188 style: BlockStyle::Sticky,
2189 render: Arc::new(|_| div().into_any()),
2190 priority: 0,
2191 render_in_minimap: true,
2192 },
2193 BlockProperties {
2194 placement: BlockPlacement::Below(
2195 buffer_snapshot.anchor_before(Point::new(2, 0)),
2196 ),
2197 height: None,
2198 style: BlockStyle::Sticky,
2199 render: Arc::new(|_| div().into_any()),
2200 priority: 0,
2201 render_in_minimap: true,
2202 },
2203 ],
2204 cx,
2205 )
2206 });
2207
2208 pretty_assertions::assert_eq!(
2209 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
2210 [
2211 ("const".into(), Some(Hsla::green())),
2212 (" A".into(), None),
2213 (":".into(), Some(Hsla::blue())),
2214 (" &str = ".into(), None),
2215 ("\"\n one\n".into(), Some(Hsla::red())),
2216 ("\n".into(), None),
2217 (" two\n three\n\"".into(), Some(Hsla::red())),
2218 (";".into(), Some(Hsla::blue())),
2219 ("\n".into(), None),
2220 ("const".into(), Some(Hsla::green())),
2221 (" B".into(), None),
2222 (":".into(), Some(Hsla::blue())),
2223 (" &str = ".into(), None),
2224 ("\"four\"".into(), Some(Hsla::red())),
2225 (";".into(), Some(Hsla::blue())),
2226 ("\n".into(), None),
2227 ]
2228 );
2229 }
2230
2231 #[gpui::test]
2232 async fn test_chunks_with_diagnostics_across_blocks(cx: &mut gpui::TestAppContext) {
2233 cx.background_executor
2234 .set_block_on_ticks(usize::MAX..=usize::MAX);
2235
2236 let text = r#"
2237 struct A {
2238 b: usize;
2239 }
2240 const c: usize = 1;
2241 "#
2242 .unindent();
2243
2244 cx.update(|cx| init_test(cx, |_| {}));
2245
2246 let buffer = cx.new(|cx| Buffer::local(text, cx));
2247
2248 buffer.update(cx, |buffer, cx| {
2249 buffer.update_diagnostics(
2250 LanguageServerId(0),
2251 DiagnosticSet::new(
2252 [DiagnosticEntry {
2253 range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
2254 diagnostic: Diagnostic {
2255 severity: lsp::DiagnosticSeverity::ERROR,
2256 group_id: 1,
2257 message: "hi".into(),
2258 ..Default::default()
2259 },
2260 }],
2261 buffer,
2262 ),
2263 cx,
2264 )
2265 });
2266
2267 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2268 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2269
2270 let map = cx.new(|cx| {
2271 DisplayMap::new(
2272 buffer,
2273 font("Courier"),
2274 px(16.0),
2275 None,
2276 1,
2277 1,
2278 FoldPlaceholder::test(),
2279 DiagnosticSeverity::Warning,
2280 cx,
2281 )
2282 });
2283
2284 let black = gpui::black().to_rgb();
2285 let red = gpui::red().to_rgb();
2286
2287 // Insert a block in the middle of a multi-line diagnostic.
2288 map.update(cx, |map, cx| {
2289 map.highlight_text(
2290 TypeId::of::<usize>(),
2291 vec![
2292 buffer_snapshot.anchor_before(Point::new(3, 9))
2293 ..buffer_snapshot.anchor_after(Point::new(3, 14)),
2294 buffer_snapshot.anchor_before(Point::new(3, 17))
2295 ..buffer_snapshot.anchor_after(Point::new(3, 18)),
2296 ],
2297 red.into(),
2298 );
2299 map.insert_blocks(
2300 [BlockProperties {
2301 placement: BlockPlacement::Below(
2302 buffer_snapshot.anchor_before(Point::new(1, 0)),
2303 ),
2304 height: Some(1),
2305 style: BlockStyle::Sticky,
2306 render: Arc::new(|_| div().into_any()),
2307 priority: 0,
2308 render_in_minimap: true,
2309 }],
2310 cx,
2311 )
2312 });
2313
2314 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2315 let mut chunks = Vec::<(String, Option<lsp::DiagnosticSeverity>, Rgba)>::new();
2316 for chunk in snapshot.chunks(DisplayRow(0)..DisplayRow(5), true, Default::default()) {
2317 let color = chunk
2318 .highlight_style
2319 .and_then(|style| style.color)
2320 .map_or(black, |color| color.to_rgb());
2321 if let Some((last_chunk, last_severity, last_color)) = chunks.last_mut() {
2322 if *last_severity == chunk.diagnostic_severity && *last_color == color {
2323 last_chunk.push_str(chunk.text);
2324 continue;
2325 }
2326 }
2327
2328 chunks.push((chunk.text.to_string(), chunk.diagnostic_severity, color));
2329 }
2330
2331 assert_eq!(
2332 chunks,
2333 [
2334 (
2335 "struct A {\n b: usize;\n".into(),
2336 Some(lsp::DiagnosticSeverity::ERROR),
2337 black
2338 ),
2339 ("\n".into(), None, black),
2340 ("}".into(), Some(lsp::DiagnosticSeverity::ERROR), black),
2341 ("\nconst c: ".into(), None, black),
2342 ("usize".into(), None, red),
2343 (" = ".into(), None, black),
2344 ("1".into(), None, red),
2345 (";\n".into(), None, black),
2346 ]
2347 );
2348 }
2349
2350 #[gpui::test]
2351 async fn test_point_translation_with_replace_blocks(cx: &mut gpui::TestAppContext) {
2352 cx.background_executor
2353 .set_block_on_ticks(usize::MAX..=usize::MAX);
2354
2355 cx.update(|cx| init_test(cx, |_| {}));
2356
2357 let buffer = cx.update(|cx| MultiBuffer::build_simple("abcde\nfghij\nklmno\npqrst", cx));
2358 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2359 let map = cx.new(|cx| {
2360 DisplayMap::new(
2361 buffer.clone(),
2362 font("Courier"),
2363 px(16.0),
2364 None,
2365 1,
2366 1,
2367 FoldPlaceholder::test(),
2368 DiagnosticSeverity::Warning,
2369 cx,
2370 )
2371 });
2372
2373 let snapshot = map.update(cx, |map, cx| {
2374 map.insert_blocks(
2375 [BlockProperties {
2376 placement: BlockPlacement::Replace(
2377 buffer_snapshot.anchor_before(Point::new(1, 2))
2378 ..=buffer_snapshot.anchor_after(Point::new(2, 3)),
2379 ),
2380 height: Some(4),
2381 style: BlockStyle::Fixed,
2382 render: Arc::new(|_| div().into_any()),
2383 priority: 0,
2384 render_in_minimap: true,
2385 }],
2386 cx,
2387 );
2388 map.snapshot(cx)
2389 });
2390
2391 assert_eq!(snapshot.text(), "abcde\n\n\n\n\npqrst");
2392
2393 let point_to_display_points = [
2394 (Point::new(1, 0), DisplayPoint::new(DisplayRow(1), 0)),
2395 (Point::new(2, 0), DisplayPoint::new(DisplayRow(1), 0)),
2396 (Point::new(3, 0), DisplayPoint::new(DisplayRow(5), 0)),
2397 ];
2398 for (buffer_point, display_point) in point_to_display_points {
2399 assert_eq!(
2400 snapshot.point_to_display_point(buffer_point, Bias::Left),
2401 display_point,
2402 "point_to_display_point({:?}, Bias::Left)",
2403 buffer_point
2404 );
2405 assert_eq!(
2406 snapshot.point_to_display_point(buffer_point, Bias::Right),
2407 display_point,
2408 "point_to_display_point({:?}, Bias::Right)",
2409 buffer_point
2410 );
2411 }
2412
2413 let display_points_to_points = [
2414 (
2415 DisplayPoint::new(DisplayRow(1), 0),
2416 Point::new(1, 0),
2417 Point::new(2, 5),
2418 ),
2419 (
2420 DisplayPoint::new(DisplayRow(2), 0),
2421 Point::new(1, 0),
2422 Point::new(2, 5),
2423 ),
2424 (
2425 DisplayPoint::new(DisplayRow(3), 0),
2426 Point::new(1, 0),
2427 Point::new(2, 5),
2428 ),
2429 (
2430 DisplayPoint::new(DisplayRow(4), 0),
2431 Point::new(1, 0),
2432 Point::new(2, 5),
2433 ),
2434 (
2435 DisplayPoint::new(DisplayRow(5), 0),
2436 Point::new(3, 0),
2437 Point::new(3, 0),
2438 ),
2439 ];
2440 for (display_point, left_buffer_point, right_buffer_point) in display_points_to_points {
2441 assert_eq!(
2442 snapshot.display_point_to_point(display_point, Bias::Left),
2443 left_buffer_point,
2444 "display_point_to_point({:?}, Bias::Left)",
2445 display_point
2446 );
2447 assert_eq!(
2448 snapshot.display_point_to_point(display_point, Bias::Right),
2449 right_buffer_point,
2450 "display_point_to_point({:?}, Bias::Right)",
2451 display_point
2452 );
2453 }
2454 }
2455
2456 #[gpui::test]
2457 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
2458 cx.background_executor
2459 .set_block_on_ticks(usize::MAX..=usize::MAX);
2460
2461 let text = r#"
2462 fn outer() {}
2463
2464 mod module {
2465 fn inner() {}
2466 }"#
2467 .unindent();
2468
2469 let theme =
2470 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2471 let language = Arc::new(
2472 Language::new(
2473 LanguageConfig {
2474 name: "Test".into(),
2475 matcher: LanguageMatcher {
2476 path_suffixes: vec![".test".to_string()],
2477 ..Default::default()
2478 },
2479 ..Default::default()
2480 },
2481 Some(tree_sitter_rust::LANGUAGE.into()),
2482 )
2483 .with_highlights_query(
2484 r#"
2485 (mod_item name: (identifier) body: _ @mod.body)
2486 (function_item name: (identifier) @fn.name)
2487 "#,
2488 )
2489 .unwrap(),
2490 );
2491 language.set_theme(&theme);
2492
2493 cx.update(|cx| init_test(cx, |_| {}));
2494
2495 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2496 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2497 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2498
2499 let font_size = px(16.0);
2500
2501 let map = cx.new(|cx| {
2502 DisplayMap::new(
2503 buffer,
2504 font("Courier"),
2505 font_size,
2506 Some(px(40.0)),
2507 1,
2508 1,
2509 FoldPlaceholder::test(),
2510 DiagnosticSeverity::Warning,
2511 cx,
2512 )
2513 });
2514 assert_eq!(
2515 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2516 [
2517 ("fn \n".to_string(), None),
2518 ("oute\nr".to_string(), Some(Hsla::blue())),
2519 ("() \n{}\n\n".to_string(), None),
2520 ]
2521 );
2522 assert_eq!(
2523 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2524 [("{}\n\n".to_string(), None)]
2525 );
2526
2527 map.update(cx, |map, cx| {
2528 map.fold(
2529 vec![Crease::simple(
2530 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2531 FoldPlaceholder::test(),
2532 )],
2533 cx,
2534 )
2535 });
2536 assert_eq!(
2537 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
2538 [
2539 ("out".to_string(), Some(Hsla::blue())),
2540 ("⋯\n".to_string(), None),
2541 (" \nfn ".to_string(), Some(Hsla::red())),
2542 ("i\n".to_string(), Some(Hsla::blue()))
2543 ]
2544 );
2545 }
2546
2547 #[gpui::test]
2548 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
2549 cx.update(|cx| init_test(cx, |_| {}));
2550
2551 let theme =
2552 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
2553 let language = Arc::new(
2554 Language::new(
2555 LanguageConfig {
2556 name: "Test".into(),
2557 matcher: LanguageMatcher {
2558 path_suffixes: vec![".test".to_string()],
2559 ..Default::default()
2560 },
2561 ..Default::default()
2562 },
2563 Some(tree_sitter_rust::LANGUAGE.into()),
2564 )
2565 .with_highlights_query(
2566 r#"
2567 ":" @operator
2568 (string_literal) @string
2569 "#,
2570 )
2571 .unwrap(),
2572 );
2573 language.set_theme(&theme);
2574
2575 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
2576
2577 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2578 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2579
2580 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2581 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2582
2583 let font_size = px(16.0);
2584 let map = cx.new(|cx| {
2585 DisplayMap::new(
2586 buffer,
2587 font("Courier"),
2588 font_size,
2589 None,
2590 1,
2591 1,
2592 FoldPlaceholder::test(),
2593 DiagnosticSeverity::Warning,
2594 cx,
2595 )
2596 });
2597
2598 enum MyType {}
2599
2600 let style = HighlightStyle {
2601 color: Some(Hsla::blue()),
2602 ..Default::default()
2603 };
2604
2605 map.update(cx, |map, _cx| {
2606 map.highlight_text(
2607 TypeId::of::<MyType>(),
2608 highlighted_ranges
2609 .into_iter()
2610 .map(|range| {
2611 buffer_snapshot.anchor_before(range.start)
2612 ..buffer_snapshot.anchor_before(range.end)
2613 })
2614 .collect(),
2615 style,
2616 );
2617 });
2618
2619 assert_eq!(
2620 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
2621 [
2622 ("const ".to_string(), None, None),
2623 ("a".to_string(), None, Some(Hsla::blue())),
2624 (":".to_string(), Some(Hsla::red()), None),
2625 (" B = ".to_string(), None, None),
2626 ("\"c ".to_string(), Some(Hsla::green()), None),
2627 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2628 ("\"".to_string(), Some(Hsla::green()), None),
2629 ]
2630 );
2631 }
2632
2633 #[gpui::test]
2634 fn test_clip_point(cx: &mut gpui::App) {
2635 init_test(cx, |_| {});
2636
2637 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::App) {
2638 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2639
2640 match bias {
2641 Bias::Left => {
2642 if shift_right {
2643 *markers[1].column_mut() += 1;
2644 }
2645
2646 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2647 }
2648 Bias::Right => {
2649 if shift_right {
2650 *markers[0].column_mut() += 1;
2651 }
2652
2653 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2654 }
2655 };
2656 }
2657
2658 use Bias::{Left, Right};
2659 assert("ˇˇα", false, Left, cx);
2660 assert("ˇˇα", true, Left, cx);
2661 assert("ˇˇα", false, Right, cx);
2662 assert("ˇαˇ", true, Right, cx);
2663 assert("ˇˇ✋", false, Left, cx);
2664 assert("ˇˇ✋", true, Left, cx);
2665 assert("ˇˇ✋", false, Right, cx);
2666 assert("ˇ✋ˇ", true, Right, cx);
2667 assert("ˇˇ🍐", false, Left, cx);
2668 assert("ˇˇ🍐", true, Left, cx);
2669 assert("ˇˇ🍐", false, Right, cx);
2670 assert("ˇ🍐ˇ", true, Right, cx);
2671 assert("ˇˇ\t", false, Left, cx);
2672 assert("ˇˇ\t", true, Left, cx);
2673 assert("ˇˇ\t", false, Right, cx);
2674 assert("ˇ\tˇ", true, Right, cx);
2675 assert(" ˇˇ\t", false, Left, cx);
2676 assert(" ˇˇ\t", true, Left, cx);
2677 assert(" ˇˇ\t", false, Right, cx);
2678 assert(" ˇ\tˇ", true, Right, cx);
2679 assert(" ˇˇ\t", false, Left, cx);
2680 assert(" ˇˇ\t", false, Right, cx);
2681 }
2682
2683 #[gpui::test]
2684 fn test_clip_at_line_ends(cx: &mut gpui::App) {
2685 init_test(cx, |_| {});
2686
2687 fn assert(text: &str, cx: &mut gpui::App) {
2688 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2689 unmarked_snapshot.clip_at_line_ends = true;
2690 assert_eq!(
2691 unmarked_snapshot.clip_point(markers[1], Bias::Left),
2692 markers[0]
2693 );
2694 }
2695
2696 assert("ˇˇ", cx);
2697 assert("ˇaˇ", cx);
2698 assert("aˇbˇ", cx);
2699 assert("aˇαˇ", cx);
2700 }
2701
2702 #[gpui::test]
2703 fn test_creases(cx: &mut gpui::App) {
2704 init_test(cx, |_| {});
2705
2706 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2707 let buffer = MultiBuffer::build_simple(text, cx);
2708 let font_size = px(14.0);
2709 cx.new(|cx| {
2710 let mut map = DisplayMap::new(
2711 buffer.clone(),
2712 font("Helvetica"),
2713 font_size,
2714 None,
2715 1,
2716 1,
2717 FoldPlaceholder::test(),
2718 DiagnosticSeverity::Warning,
2719 cx,
2720 );
2721 let snapshot = map.buffer.read(cx).snapshot(cx);
2722 let range =
2723 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2724
2725 map.crease_map.insert(
2726 [Crease::inline(
2727 range,
2728 FoldPlaceholder::test(),
2729 |_row, _status, _toggle, _window, _cx| div(),
2730 |_row, _status, _window, _cx| div(),
2731 )],
2732 &map.buffer.read(cx).snapshot(cx),
2733 );
2734
2735 map
2736 });
2737 }
2738
2739 #[gpui::test]
2740 fn test_tabs_with_multibyte_chars(cx: &mut gpui::App) {
2741 init_test(cx, |_| {});
2742
2743 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
2744 let buffer = MultiBuffer::build_simple(text, cx);
2745 let font_size = px(14.0);
2746
2747 let map = cx.new(|cx| {
2748 DisplayMap::new(
2749 buffer.clone(),
2750 font("Helvetica"),
2751 font_size,
2752 None,
2753 1,
2754 1,
2755 FoldPlaceholder::test(),
2756 DiagnosticSeverity::Warning,
2757 cx,
2758 )
2759 });
2760 let map = map.update(cx, |map, cx| map.snapshot(cx));
2761 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
2762 assert_eq!(
2763 map.text_chunks(DisplayRow(0)).collect::<String>(),
2764 "✅ α\nβ \n🏀β γ"
2765 );
2766 assert_eq!(
2767 map.text_chunks(DisplayRow(1)).collect::<String>(),
2768 "β \n🏀β γ"
2769 );
2770 assert_eq!(
2771 map.text_chunks(DisplayRow(2)).collect::<String>(),
2772 "🏀β γ"
2773 );
2774
2775 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
2776 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
2777 assert_eq!(point.to_display_point(&map), display_point);
2778 assert_eq!(display_point.to_point(&map), point);
2779
2780 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2781 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
2782 assert_eq!(point.to_display_point(&map), display_point);
2783 assert_eq!(display_point.to_point(&map), point,);
2784
2785 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2786 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
2787 assert_eq!(point.to_display_point(&map), display_point);
2788 assert_eq!(display_point.to_point(&map), point,);
2789
2790 // Display points inside of expanded tabs
2791 assert_eq!(
2792 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2793 MultiBufferPoint::new(0, "✅\t".len() as u32),
2794 );
2795 assert_eq!(
2796 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2797 MultiBufferPoint::new(0, "✅".len() as u32),
2798 );
2799
2800 // Clipping display points inside of multi-byte characters
2801 assert_eq!(
2802 map.clip_point(
2803 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2804 Left
2805 ),
2806 DisplayPoint::new(DisplayRow(0), 0)
2807 );
2808 assert_eq!(
2809 map.clip_point(
2810 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2811 Bias::Right
2812 ),
2813 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
2814 );
2815 }
2816
2817 #[gpui::test]
2818 fn test_max_point(cx: &mut gpui::App) {
2819 init_test(cx, |_| {});
2820
2821 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2822 let font_size = px(14.0);
2823 let map = cx.new(|cx| {
2824 DisplayMap::new(
2825 buffer.clone(),
2826 font("Helvetica"),
2827 font_size,
2828 None,
2829 1,
2830 1,
2831 FoldPlaceholder::test(),
2832 DiagnosticSeverity::Warning,
2833 cx,
2834 )
2835 });
2836 assert_eq!(
2837 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2838 DisplayPoint::new(DisplayRow(1), 11)
2839 )
2840 }
2841
2842 fn syntax_chunks(
2843 rows: Range<DisplayRow>,
2844 map: &Entity<DisplayMap>,
2845 theme: &SyntaxTheme,
2846 cx: &mut App,
2847 ) -> Vec<(String, Option<Hsla>)> {
2848 chunks(rows, map, theme, cx)
2849 .into_iter()
2850 .map(|(text, color, _)| (text, color))
2851 .collect()
2852 }
2853
2854 fn chunks(
2855 rows: Range<DisplayRow>,
2856 map: &Entity<DisplayMap>,
2857 theme: &SyntaxTheme,
2858 cx: &mut App,
2859 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2860 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2861 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2862 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2863 let syntax_color = chunk
2864 .syntax_highlight_id
2865 .and_then(|id| id.style(theme)?.color);
2866 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2867 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
2868 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2869 last_chunk.push_str(chunk.text);
2870 continue;
2871 }
2872 }
2873 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2874 }
2875 chunks
2876 }
2877
2878 fn init_test(cx: &mut App, f: impl Fn(&mut AllLanguageSettingsContent)) {
2879 let settings = SettingsStore::test(cx);
2880 cx.set_global(settings);
2881 workspace::init_settings(cx);
2882 language::init(cx);
2883 crate::init(cx);
2884 Project::init_settings(cx);
2885 theme::init(LoadThemes::JustBase, cx);
2886 cx.update_global::<SettingsStore, _>(|store, cx| {
2887 store.update_user_settings::<AllLanguageSettings>(cx, f);
2888 });
2889 }
2890}