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