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