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