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 #[cfg(target_os = "macos")]
1746 #[gpui::test(retries = 5)]
1747 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1748 cx.background_executor
1749 .set_block_on_ticks(usize::MAX..=usize::MAX);
1750 cx.update(|cx| {
1751 init_test(cx, |_| {});
1752 });
1753
1754 let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1755 let editor = cx.editor.clone();
1756 let window = cx.window;
1757
1758 _ = cx.update_window(window, |_, window, cx| {
1759 let text_layout_details =
1760 editor.update(cx, |editor, _cx| editor.text_layout_details(window));
1761
1762 let font_size = px(12.0);
1763 let wrap_width = Some(px(64.));
1764
1765 let text = "one two three four five\nsix seven eight";
1766 let buffer = MultiBuffer::build_simple(text, cx);
1767 let map = cx.new(|cx| {
1768 DisplayMap::new(
1769 buffer.clone(),
1770 font("Helvetica"),
1771 font_size,
1772 wrap_width,
1773 1,
1774 1,
1775 FoldPlaceholder::test(),
1776 cx,
1777 )
1778 });
1779
1780 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1781 assert_eq!(
1782 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1783 "one two \nthree four \nfive\nsix seven \neight"
1784 );
1785 assert_eq!(
1786 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1787 DisplayPoint::new(DisplayRow(0), 7)
1788 );
1789 assert_eq!(
1790 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1791 DisplayPoint::new(DisplayRow(1), 0)
1792 );
1793 assert_eq!(
1794 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1795 DisplayPoint::new(DisplayRow(1), 0)
1796 );
1797 assert_eq!(
1798 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1799 DisplayPoint::new(DisplayRow(0), 7)
1800 );
1801
1802 let x = snapshot
1803 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1804 assert_eq!(
1805 movement::up(
1806 &snapshot,
1807 DisplayPoint::new(DisplayRow(1), 10),
1808 language::SelectionGoal::None,
1809 false,
1810 &text_layout_details,
1811 ),
1812 (
1813 DisplayPoint::new(DisplayRow(0), 7),
1814 language::SelectionGoal::HorizontalPosition(x.0)
1815 )
1816 );
1817 assert_eq!(
1818 movement::down(
1819 &snapshot,
1820 DisplayPoint::new(DisplayRow(0), 7),
1821 language::SelectionGoal::HorizontalPosition(x.0),
1822 false,
1823 &text_layout_details
1824 ),
1825 (
1826 DisplayPoint::new(DisplayRow(1), 10),
1827 language::SelectionGoal::HorizontalPosition(x.0)
1828 )
1829 );
1830 assert_eq!(
1831 movement::down(
1832 &snapshot,
1833 DisplayPoint::new(DisplayRow(1), 10),
1834 language::SelectionGoal::HorizontalPosition(x.0),
1835 false,
1836 &text_layout_details
1837 ),
1838 (
1839 DisplayPoint::new(DisplayRow(2), 4),
1840 language::SelectionGoal::HorizontalPosition(x.0)
1841 )
1842 );
1843
1844 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1845 buffer.update(cx, |buffer, cx| {
1846 buffer.edit([(ix..ix, "and ")], None, cx);
1847 });
1848
1849 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1850 assert_eq!(
1851 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1852 "three four \nfive\nsix and \nseven eight"
1853 );
1854
1855 // Re-wrap on font size changes
1856 map.update(cx, |map, cx| {
1857 map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1858 });
1859
1860 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1861 assert_eq!(
1862 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1863 "three \nfour five\nsix and \nseven \neight"
1864 )
1865 });
1866 }
1867
1868 #[gpui::test]
1869 fn test_text_chunks(cx: &mut gpui::App) {
1870 init_test(cx, |_| {});
1871
1872 let text = sample_text(6, 6, 'a');
1873 let buffer = MultiBuffer::build_simple(&text, cx);
1874
1875 let font_size = px(14.0);
1876 let map = cx.new(|cx| {
1877 DisplayMap::new(
1878 buffer.clone(),
1879 font("Helvetica"),
1880 font_size,
1881 None,
1882 1,
1883 1,
1884 FoldPlaceholder::test(),
1885 cx,
1886 )
1887 });
1888
1889 buffer.update(cx, |buffer, cx| {
1890 buffer.edit(
1891 vec![
1892 (
1893 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1894 "\t",
1895 ),
1896 (
1897 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1898 "\t",
1899 ),
1900 (
1901 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1902 "\t",
1903 ),
1904 ],
1905 None,
1906 cx,
1907 )
1908 });
1909
1910 assert_eq!(
1911 map.update(cx, |map, cx| map.snapshot(cx))
1912 .text_chunks(DisplayRow(1))
1913 .collect::<String>()
1914 .lines()
1915 .next(),
1916 Some(" b bbbbb")
1917 );
1918 assert_eq!(
1919 map.update(cx, |map, cx| map.snapshot(cx))
1920 .text_chunks(DisplayRow(2))
1921 .collect::<String>()
1922 .lines()
1923 .next(),
1924 Some("c ccccc")
1925 );
1926 }
1927
1928 #[gpui::test]
1929 fn test_inlays_with_newlines_after_blocks(cx: &mut gpui::TestAppContext) {
1930 cx.update(|cx| init_test(cx, |_| {}));
1931
1932 let buffer = cx.new(|cx| Buffer::local("a", cx));
1933 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1934 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1935
1936 let font_size = px(14.0);
1937 let map = cx.new(|cx| {
1938 DisplayMap::new(
1939 buffer.clone(),
1940 font("Helvetica"),
1941 font_size,
1942 None,
1943 1,
1944 1,
1945 FoldPlaceholder::test(),
1946 cx,
1947 )
1948 });
1949
1950 map.update(cx, |map, cx| {
1951 map.insert_blocks(
1952 [BlockProperties {
1953 placement: BlockPlacement::Above(
1954 buffer_snapshot.anchor_before(Point::new(0, 0)),
1955 ),
1956 height: Some(2),
1957 style: BlockStyle::Sticky,
1958 render: Arc::new(|_| div().into_any()),
1959 priority: 0,
1960 }],
1961 cx,
1962 );
1963 });
1964 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\na"));
1965
1966 map.update(cx, |map, cx| {
1967 map.splice_inlays(
1968 &[],
1969 vec![Inlay {
1970 id: InlayId::InlineCompletion(0),
1971 position: buffer_snapshot.anchor_after(0),
1972 text: "\n".into(),
1973 }],
1974 cx,
1975 );
1976 });
1977 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\na"));
1978
1979 // Regression test: updating the display map does not crash when a
1980 // block is immediately followed by a multi-line inlay.
1981 buffer.update(cx, |buffer, cx| {
1982 buffer.edit([(1..1, "b")], None, cx);
1983 });
1984 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\nab"));
1985 }
1986
1987 #[gpui::test]
1988 async fn test_chunks(cx: &mut gpui::TestAppContext) {
1989 let text = r#"
1990 fn outer() {}
1991
1992 mod module {
1993 fn inner() {}
1994 }"#
1995 .unindent();
1996
1997 let theme =
1998 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1999 let language = Arc::new(
2000 Language::new(
2001 LanguageConfig {
2002 name: "Test".into(),
2003 matcher: LanguageMatcher {
2004 path_suffixes: vec![".test".to_string()],
2005 ..Default::default()
2006 },
2007 ..Default::default()
2008 },
2009 Some(tree_sitter_rust::LANGUAGE.into()),
2010 )
2011 .with_highlights_query(
2012 r#"
2013 (mod_item name: (identifier) body: _ @mod.body)
2014 (function_item name: (identifier) @fn.name)
2015 "#,
2016 )
2017 .unwrap(),
2018 );
2019 language.set_theme(&theme);
2020
2021 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
2022
2023 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2024 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2025 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2026
2027 let font_size = px(14.0);
2028
2029 let map = cx.new(|cx| {
2030 DisplayMap::new(
2031 buffer,
2032 font("Helvetica"),
2033 font_size,
2034 None,
2035 1,
2036 1,
2037 FoldPlaceholder::test(),
2038 cx,
2039 )
2040 });
2041 assert_eq!(
2042 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2043 vec![
2044 ("fn ".to_string(), None),
2045 ("outer".to_string(), Some(Hsla::blue())),
2046 ("() {}\n\nmod module ".to_string(), None),
2047 ("{\n fn ".to_string(), Some(Hsla::red())),
2048 ("inner".to_string(), Some(Hsla::blue())),
2049 ("() {}\n}".to_string(), Some(Hsla::red())),
2050 ]
2051 );
2052 assert_eq!(
2053 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2054 vec![
2055 (" fn ".to_string(), Some(Hsla::red())),
2056 ("inner".to_string(), Some(Hsla::blue())),
2057 ("() {}\n}".to_string(), Some(Hsla::red())),
2058 ]
2059 );
2060
2061 map.update(cx, |map, cx| {
2062 map.fold(
2063 vec![Crease::simple(
2064 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2065 FoldPlaceholder::test(),
2066 )],
2067 cx,
2068 )
2069 });
2070 assert_eq!(
2071 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
2072 vec![
2073 ("fn ".to_string(), None),
2074 ("out".to_string(), Some(Hsla::blue())),
2075 ("⋯".to_string(), None),
2076 (" fn ".to_string(), Some(Hsla::red())),
2077 ("inner".to_string(), Some(Hsla::blue())),
2078 ("() {}\n}".to_string(), Some(Hsla::red())),
2079 ]
2080 );
2081 }
2082
2083 #[gpui::test]
2084 async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
2085 cx.background_executor
2086 .set_block_on_ticks(usize::MAX..=usize::MAX);
2087
2088 let text = r#"
2089 const A: &str = "
2090 one
2091 two
2092 three
2093 ";
2094 const B: &str = "four";
2095 "#
2096 .unindent();
2097
2098 let theme = SyntaxTheme::new_test(vec![
2099 ("string", Hsla::red()),
2100 ("punctuation", Hsla::blue()),
2101 ("keyword", Hsla::green()),
2102 ]);
2103 let language = Arc::new(
2104 Language::new(
2105 LanguageConfig {
2106 name: "Rust".into(),
2107 ..Default::default()
2108 },
2109 Some(tree_sitter_rust::LANGUAGE.into()),
2110 )
2111 .with_highlights_query(
2112 r#"
2113 (string_literal) @string
2114 "const" @keyword
2115 [":" ";"] @punctuation
2116 "#,
2117 )
2118 .unwrap(),
2119 );
2120 language.set_theme(&theme);
2121
2122 cx.update(|cx| init_test(cx, |_| {}));
2123
2124 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2125 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2126 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2127 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2128
2129 let map = cx.new(|cx| {
2130 DisplayMap::new(
2131 buffer,
2132 font("Courier"),
2133 px(16.0),
2134 None,
2135 1,
2136 1,
2137 FoldPlaceholder::test(),
2138 cx,
2139 )
2140 });
2141
2142 // Insert two blocks in the middle of a multi-line string literal.
2143 // The second block has zero height.
2144 map.update(cx, |map, cx| {
2145 map.insert_blocks(
2146 [
2147 BlockProperties {
2148 placement: BlockPlacement::Below(
2149 buffer_snapshot.anchor_before(Point::new(1, 0)),
2150 ),
2151 height: Some(1),
2152 style: BlockStyle::Sticky,
2153 render: Arc::new(|_| div().into_any()),
2154 priority: 0,
2155 },
2156 BlockProperties {
2157 placement: BlockPlacement::Below(
2158 buffer_snapshot.anchor_before(Point::new(2, 0)),
2159 ),
2160 height: None,
2161 style: BlockStyle::Sticky,
2162 render: Arc::new(|_| div().into_any()),
2163 priority: 0,
2164 },
2165 ],
2166 cx,
2167 )
2168 });
2169
2170 pretty_assertions::assert_eq!(
2171 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
2172 [
2173 ("const".into(), Some(Hsla::green())),
2174 (" A".into(), None),
2175 (":".into(), Some(Hsla::blue())),
2176 (" &str = ".into(), None),
2177 ("\"\n one\n".into(), Some(Hsla::red())),
2178 ("\n".into(), None),
2179 (" two\n three\n\"".into(), Some(Hsla::red())),
2180 (";".into(), Some(Hsla::blue())),
2181 ("\n".into(), None),
2182 ("const".into(), Some(Hsla::green())),
2183 (" B".into(), None),
2184 (":".into(), Some(Hsla::blue())),
2185 (" &str = ".into(), None),
2186 ("\"four\"".into(), Some(Hsla::red())),
2187 (";".into(), Some(Hsla::blue())),
2188 ("\n".into(), None),
2189 ]
2190 );
2191 }
2192
2193 #[gpui::test]
2194 async fn test_chunks_with_diagnostics_across_blocks(cx: &mut gpui::TestAppContext) {
2195 cx.background_executor
2196 .set_block_on_ticks(usize::MAX..=usize::MAX);
2197
2198 let text = r#"
2199 struct A {
2200 b: usize;
2201 }
2202 const c: usize = 1;
2203 "#
2204 .unindent();
2205
2206 cx.update(|cx| init_test(cx, |_| {}));
2207
2208 let buffer = cx.new(|cx| Buffer::local(text, cx));
2209
2210 buffer.update(cx, |buffer, cx| {
2211 buffer.update_diagnostics(
2212 LanguageServerId(0),
2213 DiagnosticSet::new(
2214 [DiagnosticEntry {
2215 range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
2216 diagnostic: Diagnostic {
2217 severity: DiagnosticSeverity::ERROR,
2218 group_id: 1,
2219 message: "hi".into(),
2220 ..Default::default()
2221 },
2222 }],
2223 buffer,
2224 ),
2225 cx,
2226 )
2227 });
2228
2229 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2230 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2231
2232 let map = cx.new(|cx| {
2233 DisplayMap::new(
2234 buffer,
2235 font("Courier"),
2236 px(16.0),
2237 None,
2238 1,
2239 1,
2240 FoldPlaceholder::test(),
2241 cx,
2242 )
2243 });
2244
2245 let black = gpui::black().to_rgb();
2246 let red = gpui::red().to_rgb();
2247
2248 // Insert a block in the middle of a multi-line diagnostic.
2249 map.update(cx, |map, cx| {
2250 map.highlight_text(
2251 TypeId::of::<usize>(),
2252 vec![
2253 buffer_snapshot.anchor_before(Point::new(3, 9))
2254 ..buffer_snapshot.anchor_after(Point::new(3, 14)),
2255 buffer_snapshot.anchor_before(Point::new(3, 17))
2256 ..buffer_snapshot.anchor_after(Point::new(3, 18)),
2257 ],
2258 red.into(),
2259 );
2260 map.insert_blocks(
2261 [BlockProperties {
2262 placement: BlockPlacement::Below(
2263 buffer_snapshot.anchor_before(Point::new(1, 0)),
2264 ),
2265 height: Some(1),
2266 style: BlockStyle::Sticky,
2267 render: Arc::new(|_| div().into_any()),
2268 priority: 0,
2269 }],
2270 cx,
2271 )
2272 });
2273
2274 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2275 let mut chunks = Vec::<(String, Option<DiagnosticSeverity>, Rgba)>::new();
2276 for chunk in snapshot.chunks(DisplayRow(0)..DisplayRow(5), true, Default::default()) {
2277 let color = chunk
2278 .highlight_style
2279 .and_then(|style| style.color)
2280 .map_or(black, |color| color.to_rgb());
2281 if let Some((last_chunk, last_severity, last_color)) = chunks.last_mut() {
2282 if *last_severity == chunk.diagnostic_severity && *last_color == color {
2283 last_chunk.push_str(chunk.text);
2284 continue;
2285 }
2286 }
2287
2288 chunks.push((chunk.text.to_string(), chunk.diagnostic_severity, color));
2289 }
2290
2291 assert_eq!(
2292 chunks,
2293 [
2294 (
2295 "struct A {\n b: usize;\n".into(),
2296 Some(DiagnosticSeverity::ERROR),
2297 black
2298 ),
2299 ("\n".into(), None, black),
2300 ("}".into(), Some(DiagnosticSeverity::ERROR), black),
2301 ("\nconst c: ".into(), None, black),
2302 ("usize".into(), None, red),
2303 (" = ".into(), None, black),
2304 ("1".into(), None, red),
2305 (";\n".into(), None, black),
2306 ]
2307 );
2308 }
2309
2310 #[gpui::test]
2311 async fn test_point_translation_with_replace_blocks(cx: &mut gpui::TestAppContext) {
2312 cx.background_executor
2313 .set_block_on_ticks(usize::MAX..=usize::MAX);
2314
2315 cx.update(|cx| init_test(cx, |_| {}));
2316
2317 let buffer = cx.update(|cx| MultiBuffer::build_simple("abcde\nfghij\nklmno\npqrst", cx));
2318 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2319 let map = cx.new(|cx| {
2320 DisplayMap::new(
2321 buffer.clone(),
2322 font("Courier"),
2323 px(16.0),
2324 None,
2325 1,
2326 1,
2327 FoldPlaceholder::test(),
2328 cx,
2329 )
2330 });
2331
2332 let snapshot = map.update(cx, |map, cx| {
2333 map.insert_blocks(
2334 [BlockProperties {
2335 placement: BlockPlacement::Replace(
2336 buffer_snapshot.anchor_before(Point::new(1, 2))
2337 ..=buffer_snapshot.anchor_after(Point::new(2, 3)),
2338 ),
2339 height: Some(4),
2340 style: BlockStyle::Fixed,
2341 render: Arc::new(|_| div().into_any()),
2342 priority: 0,
2343 }],
2344 cx,
2345 );
2346 map.snapshot(cx)
2347 });
2348
2349 assert_eq!(snapshot.text(), "abcde\n\n\n\n\npqrst");
2350
2351 let point_to_display_points = [
2352 (Point::new(1, 0), DisplayPoint::new(DisplayRow(1), 0)),
2353 (Point::new(2, 0), DisplayPoint::new(DisplayRow(1), 0)),
2354 (Point::new(3, 0), DisplayPoint::new(DisplayRow(5), 0)),
2355 ];
2356 for (buffer_point, display_point) in point_to_display_points {
2357 assert_eq!(
2358 snapshot.point_to_display_point(buffer_point, Bias::Left),
2359 display_point,
2360 "point_to_display_point({:?}, Bias::Left)",
2361 buffer_point
2362 );
2363 assert_eq!(
2364 snapshot.point_to_display_point(buffer_point, Bias::Right),
2365 display_point,
2366 "point_to_display_point({:?}, Bias::Right)",
2367 buffer_point
2368 );
2369 }
2370
2371 let display_points_to_points = [
2372 (
2373 DisplayPoint::new(DisplayRow(1), 0),
2374 Point::new(1, 0),
2375 Point::new(2, 5),
2376 ),
2377 (
2378 DisplayPoint::new(DisplayRow(2), 0),
2379 Point::new(1, 0),
2380 Point::new(2, 5),
2381 ),
2382 (
2383 DisplayPoint::new(DisplayRow(3), 0),
2384 Point::new(1, 0),
2385 Point::new(2, 5),
2386 ),
2387 (
2388 DisplayPoint::new(DisplayRow(4), 0),
2389 Point::new(1, 0),
2390 Point::new(2, 5),
2391 ),
2392 (
2393 DisplayPoint::new(DisplayRow(5), 0),
2394 Point::new(3, 0),
2395 Point::new(3, 0),
2396 ),
2397 ];
2398 for (display_point, left_buffer_point, right_buffer_point) in display_points_to_points {
2399 assert_eq!(
2400 snapshot.display_point_to_point(display_point, Bias::Left),
2401 left_buffer_point,
2402 "display_point_to_point({:?}, Bias::Left)",
2403 display_point
2404 );
2405 assert_eq!(
2406 snapshot.display_point_to_point(display_point, Bias::Right),
2407 right_buffer_point,
2408 "display_point_to_point({:?}, Bias::Right)",
2409 display_point
2410 );
2411 }
2412 }
2413
2414 // todo(linux) fails due to pixel differences in text rendering
2415 #[cfg(target_os = "macos")]
2416 #[gpui::test]
2417 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
2418 cx.background_executor
2419 .set_block_on_ticks(usize::MAX..=usize::MAX);
2420
2421 let text = r#"
2422 fn outer() {}
2423
2424 mod module {
2425 fn inner() {}
2426 }"#
2427 .unindent();
2428
2429 let theme =
2430 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2431 let language = Arc::new(
2432 Language::new(
2433 LanguageConfig {
2434 name: "Test".into(),
2435 matcher: LanguageMatcher {
2436 path_suffixes: vec![".test".to_string()],
2437 ..Default::default()
2438 },
2439 ..Default::default()
2440 },
2441 Some(tree_sitter_rust::LANGUAGE.into()),
2442 )
2443 .with_highlights_query(
2444 r#"
2445 (mod_item name: (identifier) body: _ @mod.body)
2446 (function_item name: (identifier) @fn.name)
2447 "#,
2448 )
2449 .unwrap(),
2450 );
2451 language.set_theme(&theme);
2452
2453 cx.update(|cx| init_test(cx, |_| {}));
2454
2455 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2456 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2457 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2458
2459 let font_size = px(16.0);
2460
2461 let map = cx.new(|cx| {
2462 DisplayMap::new(
2463 buffer,
2464 font("Courier"),
2465 font_size,
2466 Some(px(40.0)),
2467 1,
2468 1,
2469 FoldPlaceholder::test(),
2470 cx,
2471 )
2472 });
2473 assert_eq!(
2474 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2475 [
2476 ("fn \n".to_string(), None),
2477 ("oute\nr".to_string(), Some(Hsla::blue())),
2478 ("() \n{}\n\n".to_string(), None),
2479 ]
2480 );
2481 assert_eq!(
2482 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2483 [("{}\n\n".to_string(), None)]
2484 );
2485
2486 map.update(cx, |map, cx| {
2487 map.fold(
2488 vec![Crease::simple(
2489 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2490 FoldPlaceholder::test(),
2491 )],
2492 cx,
2493 )
2494 });
2495 assert_eq!(
2496 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
2497 [
2498 ("out".to_string(), Some(Hsla::blue())),
2499 ("⋯\n".to_string(), None),
2500 (" \nfn ".to_string(), Some(Hsla::red())),
2501 ("i\n".to_string(), Some(Hsla::blue()))
2502 ]
2503 );
2504 }
2505
2506 #[gpui::test]
2507 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
2508 cx.update(|cx| init_test(cx, |_| {}));
2509
2510 let theme =
2511 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
2512 let language = Arc::new(
2513 Language::new(
2514 LanguageConfig {
2515 name: "Test".into(),
2516 matcher: LanguageMatcher {
2517 path_suffixes: vec![".test".to_string()],
2518 ..Default::default()
2519 },
2520 ..Default::default()
2521 },
2522 Some(tree_sitter_rust::LANGUAGE.into()),
2523 )
2524 .with_highlights_query(
2525 r#"
2526 ":" @operator
2527 (string_literal) @string
2528 "#,
2529 )
2530 .unwrap(),
2531 );
2532 language.set_theme(&theme);
2533
2534 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
2535
2536 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2537 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2538
2539 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2540 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2541
2542 let font_size = px(16.0);
2543 let map = cx.new(|cx| {
2544 DisplayMap::new(
2545 buffer,
2546 font("Courier"),
2547 font_size,
2548 None,
2549 1,
2550 1,
2551 FoldPlaceholder::test(),
2552 cx,
2553 )
2554 });
2555
2556 enum MyType {}
2557
2558 let style = HighlightStyle {
2559 color: Some(Hsla::blue()),
2560 ..Default::default()
2561 };
2562
2563 map.update(cx, |map, _cx| {
2564 map.highlight_text(
2565 TypeId::of::<MyType>(),
2566 highlighted_ranges
2567 .into_iter()
2568 .map(|range| {
2569 buffer_snapshot.anchor_before(range.start)
2570 ..buffer_snapshot.anchor_before(range.end)
2571 })
2572 .collect(),
2573 style,
2574 );
2575 });
2576
2577 assert_eq!(
2578 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
2579 [
2580 ("const ".to_string(), None, None),
2581 ("a".to_string(), None, Some(Hsla::blue())),
2582 (":".to_string(), Some(Hsla::red()), None),
2583 (" B = ".to_string(), None, None),
2584 ("\"c ".to_string(), Some(Hsla::green()), None),
2585 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2586 ("\"".to_string(), Some(Hsla::green()), None),
2587 ]
2588 );
2589 }
2590
2591 #[gpui::test]
2592 fn test_clip_point(cx: &mut gpui::App) {
2593 init_test(cx, |_| {});
2594
2595 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::App) {
2596 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2597
2598 match bias {
2599 Bias::Left => {
2600 if shift_right {
2601 *markers[1].column_mut() += 1;
2602 }
2603
2604 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2605 }
2606 Bias::Right => {
2607 if shift_right {
2608 *markers[0].column_mut() += 1;
2609 }
2610
2611 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2612 }
2613 };
2614 }
2615
2616 use Bias::{Left, Right};
2617 assert("ˇˇα", false, Left, cx);
2618 assert("ˇˇα", true, Left, cx);
2619 assert("ˇˇα", false, Right, cx);
2620 assert("ˇαˇ", true, Right, cx);
2621 assert("ˇˇ✋", false, Left, cx);
2622 assert("ˇˇ✋", true, Left, cx);
2623 assert("ˇˇ✋", false, Right, cx);
2624 assert("ˇ✋ˇ", true, Right, cx);
2625 assert("ˇˇ🍐", false, Left, cx);
2626 assert("ˇˇ🍐", true, Left, cx);
2627 assert("ˇˇ🍐", false, Right, cx);
2628 assert("ˇ🍐ˇ", true, Right, cx);
2629 assert("ˇˇ\t", false, Left, cx);
2630 assert("ˇˇ\t", true, Left, cx);
2631 assert("ˇˇ\t", false, Right, cx);
2632 assert("ˇ\tˇ", true, Right, cx);
2633 assert(" ˇˇ\t", false, Left, cx);
2634 assert(" ˇˇ\t", true, Left, cx);
2635 assert(" ˇˇ\t", false, Right, cx);
2636 assert(" ˇ\tˇ", true, Right, cx);
2637 assert(" ˇˇ\t", false, Left, cx);
2638 assert(" ˇˇ\t", false, Right, cx);
2639 }
2640
2641 #[gpui::test]
2642 fn test_clip_at_line_ends(cx: &mut gpui::App) {
2643 init_test(cx, |_| {});
2644
2645 fn assert(text: &str, cx: &mut gpui::App) {
2646 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2647 unmarked_snapshot.clip_at_line_ends = true;
2648 assert_eq!(
2649 unmarked_snapshot.clip_point(markers[1], Bias::Left),
2650 markers[0]
2651 );
2652 }
2653
2654 assert("ˇˇ", cx);
2655 assert("ˇaˇ", cx);
2656 assert("aˇbˇ", cx);
2657 assert("aˇαˇ", cx);
2658 }
2659
2660 #[gpui::test]
2661 fn test_creases(cx: &mut gpui::App) {
2662 init_test(cx, |_| {});
2663
2664 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2665 let buffer = MultiBuffer::build_simple(text, cx);
2666 let font_size = px(14.0);
2667 cx.new(|cx| {
2668 let mut map = DisplayMap::new(
2669 buffer.clone(),
2670 font("Helvetica"),
2671 font_size,
2672 None,
2673 1,
2674 1,
2675 FoldPlaceholder::test(),
2676 cx,
2677 );
2678 let snapshot = map.buffer.read(cx).snapshot(cx);
2679 let range =
2680 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2681
2682 map.crease_map.insert(
2683 [Crease::inline(
2684 range,
2685 FoldPlaceholder::test(),
2686 |_row, _status, _toggle, _window, _cx| div(),
2687 |_row, _status, _window, _cx| div(),
2688 )],
2689 &map.buffer.read(cx).snapshot(cx),
2690 );
2691
2692 map
2693 });
2694 }
2695
2696 #[gpui::test]
2697 fn test_tabs_with_multibyte_chars(cx: &mut gpui::App) {
2698 init_test(cx, |_| {});
2699
2700 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
2701 let buffer = MultiBuffer::build_simple(text, cx);
2702 let font_size = px(14.0);
2703
2704 let map = cx.new(|cx| {
2705 DisplayMap::new(
2706 buffer.clone(),
2707 font("Helvetica"),
2708 font_size,
2709 None,
2710 1,
2711 1,
2712 FoldPlaceholder::test(),
2713 cx,
2714 )
2715 });
2716 let map = map.update(cx, |map, cx| map.snapshot(cx));
2717 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
2718 assert_eq!(
2719 map.text_chunks(DisplayRow(0)).collect::<String>(),
2720 "✅ α\nβ \n🏀β γ"
2721 );
2722 assert_eq!(
2723 map.text_chunks(DisplayRow(1)).collect::<String>(),
2724 "β \n🏀β γ"
2725 );
2726 assert_eq!(
2727 map.text_chunks(DisplayRow(2)).collect::<String>(),
2728 "🏀β γ"
2729 );
2730
2731 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
2732 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
2733 assert_eq!(point.to_display_point(&map), display_point);
2734 assert_eq!(display_point.to_point(&map), point);
2735
2736 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2737 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
2738 assert_eq!(point.to_display_point(&map), display_point);
2739 assert_eq!(display_point.to_point(&map), point,);
2740
2741 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2742 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
2743 assert_eq!(point.to_display_point(&map), display_point);
2744 assert_eq!(display_point.to_point(&map), point,);
2745
2746 // Display points inside of expanded tabs
2747 assert_eq!(
2748 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2749 MultiBufferPoint::new(0, "✅\t".len() as u32),
2750 );
2751 assert_eq!(
2752 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2753 MultiBufferPoint::new(0, "✅".len() as u32),
2754 );
2755
2756 // Clipping display points inside of multi-byte characters
2757 assert_eq!(
2758 map.clip_point(
2759 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2760 Left
2761 ),
2762 DisplayPoint::new(DisplayRow(0), 0)
2763 );
2764 assert_eq!(
2765 map.clip_point(
2766 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2767 Bias::Right
2768 ),
2769 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
2770 );
2771 }
2772
2773 #[gpui::test]
2774 fn test_max_point(cx: &mut gpui::App) {
2775 init_test(cx, |_| {});
2776
2777 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2778 let font_size = px(14.0);
2779 let map = cx.new(|cx| {
2780 DisplayMap::new(
2781 buffer.clone(),
2782 font("Helvetica"),
2783 font_size,
2784 None,
2785 1,
2786 1,
2787 FoldPlaceholder::test(),
2788 cx,
2789 )
2790 });
2791 assert_eq!(
2792 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2793 DisplayPoint::new(DisplayRow(1), 11)
2794 )
2795 }
2796
2797 fn syntax_chunks(
2798 rows: Range<DisplayRow>,
2799 map: &Entity<DisplayMap>,
2800 theme: &SyntaxTheme,
2801 cx: &mut App,
2802 ) -> Vec<(String, Option<Hsla>)> {
2803 chunks(rows, map, theme, cx)
2804 .into_iter()
2805 .map(|(text, color, _)| (text, color))
2806 .collect()
2807 }
2808
2809 fn chunks(
2810 rows: Range<DisplayRow>,
2811 map: &Entity<DisplayMap>,
2812 theme: &SyntaxTheme,
2813 cx: &mut App,
2814 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2815 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2816 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2817 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2818 let syntax_color = chunk
2819 .syntax_highlight_id
2820 .and_then(|id| id.style(theme)?.color);
2821 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2822 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
2823 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2824 last_chunk.push_str(chunk.text);
2825 continue;
2826 }
2827 }
2828 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2829 }
2830 chunks
2831 }
2832
2833 fn init_test(cx: &mut App, f: impl Fn(&mut AllLanguageSettingsContent)) {
2834 let settings = SettingsStore::test(cx);
2835 cx.set_global(settings);
2836 workspace::init_settings(cx);
2837 language::init(cx);
2838 crate::init(cx);
2839 Project::init_settings(cx);
2840 theme::init(LoadThemes::JustBase, cx);
2841 cx.update_global::<SettingsStore, _>(|store, cx| {
2842 store.update_user_settings::<AllLanguageSettings>(cx, f);
2843 });
2844 }
2845}