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