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