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