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