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