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