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, CompanionView, CustomBlockId,
85 EditorMargins, RenderBlock, 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};
93pub use wrap_map::{WrapPoint, WrapRow, WrapSnapshot};
94
95use collections::{HashMap, HashSet};
96use gpui::{
97 App, Context, Entity, EntityId, Font, HighlightStyle, LineLayout, Pixels, UnderlineStyle,
98 WeakEntity,
99};
100use language::{Point, Subscription as BufferSubscription, language_settings::language_settings};
101use multi_buffer::{
102 Anchor, AnchorRangeExt, ExcerptId, MultiBuffer, MultiBufferOffset, MultiBufferOffsetUtf16,
103 MultiBufferPoint, MultiBufferRow, MultiBufferSnapshot, RowInfo, ToOffset, ToPoint,
104};
105use project::InlayId;
106use project::project_settings::DiagnosticSeverity;
107use serde::Deserialize;
108use sum_tree::{Bias, TreeMap};
109use text::{BufferId, LineIndent, Patch};
110use ui::{SharedString, px};
111use unicode_segmentation::UnicodeSegmentation;
112use ztracing::instrument;
113
114use std::{
115 any::TypeId,
116 borrow::Cow,
117 fmt::Debug,
118 iter,
119 num::NonZeroU32,
120 ops::{Add, Bound, Range, Sub},
121 sync::Arc,
122};
123
124use crate::{
125 EditorStyle, RowExt, hover_links::InlayHighlight, inlays::Inlay, movement::TextLayoutDetails,
126};
127use block_map::{BlockRow, BlockSnapshot};
128use fold_map::FoldSnapshot;
129use inlay_map::InlaySnapshot;
130use tab_map::TabSnapshot;
131use wrap_map::{WrapMap, WrapPatch};
132
133#[derive(Copy, Clone, Debug, PartialEq, Eq)]
134pub enum FoldStatus {
135 Folded,
136 Foldable,
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
140pub enum HighlightKey {
141 Type(TypeId),
142 TypePlus(TypeId, usize),
143}
144
145pub trait ToDisplayPoint {
146 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
147}
148
149type TextHighlights = TreeMap<HighlightKey, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>;
150type InlayHighlights = TreeMap<TypeId, TreeMap<InlayId, (HighlightStyle, InlayHighlight)>>;
151
152#[derive(Debug)]
153pub struct CompanionExcerptPatch {
154 pub patch: Patch<MultiBufferPoint>,
155 pub edited_range: Range<MultiBufferPoint>,
156 pub source_excerpt_range: Range<MultiBufferPoint>,
157 pub target_excerpt_range: Range<MultiBufferPoint>,
158}
159
160pub type ConvertMultiBufferRows = fn(
161 &HashMap<ExcerptId, ExcerptId>,
162 &MultiBufferSnapshot,
163 &MultiBufferSnapshot,
164 (Bound<MultiBufferPoint>, Bound<MultiBufferPoint>),
165) -> Vec<CompanionExcerptPatch>;
166
167/// Decides how text in a [`MultiBuffer`] should be displayed in a buffer, handling inlay hints,
168/// folding, hard tabs, soft wrapping, custom blocks (like diagnostics), and highlighting.
169///
170/// See the [module level documentation](self) for more information.
171pub struct DisplayMap {
172 entity_id: EntityId,
173 /// The buffer that we are displaying.
174 buffer: Entity<MultiBuffer>,
175 buffer_subscription: BufferSubscription<MultiBufferOffset>,
176 /// Decides where the [`Inlay`]s should be displayed.
177 inlay_map: InlayMap,
178 /// Decides where the fold indicators should be and tracks parts of a source file that are currently folded.
179 fold_map: FoldMap,
180 /// Keeps track of hard tabs in a buffer.
181 tab_map: TabMap,
182 /// Handles soft wrapping.
183 wrap_map: Entity<WrapMap>,
184 /// Tracks custom blocks such as diagnostics that should be displayed within buffer.
185 block_map: BlockMap,
186 /// Regions of text that should be highlighted.
187 text_highlights: TextHighlights,
188 /// Regions of inlays that should be highlighted.
189 inlay_highlights: InlayHighlights,
190 /// A container for explicitly foldable ranges, which supersede indentation based fold range suggestions.
191 crease_map: CreaseMap,
192 pub(crate) fold_placeholder: FoldPlaceholder,
193 pub clip_at_line_ends: bool,
194 pub(crate) masked: bool,
195 pub(crate) diagnostics_max_severity: DiagnosticSeverity,
196 pub(crate) companion: Option<(WeakEntity<DisplayMap>, Entity<Companion>)>,
197}
198
199pub(crate) struct Companion {
200 rhs_display_map_id: EntityId,
201 rhs_folded_buffers: HashSet<BufferId>,
202 rhs_buffer_to_lhs_buffer: HashMap<BufferId, BufferId>,
203 lhs_buffer_to_rhs_buffer: HashMap<BufferId, BufferId>,
204 rhs_excerpt_to_lhs_excerpt: HashMap<ExcerptId, ExcerptId>,
205 lhs_excerpt_to_rhs_excerpt: HashMap<ExcerptId, ExcerptId>,
206 rhs_rows_to_lhs_rows: ConvertMultiBufferRows,
207 lhs_rows_to_rhs_rows: ConvertMultiBufferRows,
208}
209
210impl Companion {
211 pub(crate) fn new(
212 rhs_display_map_id: EntityId,
213 rhs_folded_buffers: HashSet<BufferId>,
214 rhs_rows_to_lhs_rows: ConvertMultiBufferRows,
215 lhs_rows_to_rhs_rows: ConvertMultiBufferRows,
216 ) -> Self {
217 Self {
218 rhs_display_map_id,
219 rhs_folded_buffers,
220 rhs_buffer_to_lhs_buffer: Default::default(),
221 lhs_buffer_to_rhs_buffer: Default::default(),
222 rhs_excerpt_to_lhs_excerpt: Default::default(),
223 lhs_excerpt_to_rhs_excerpt: Default::default(),
224 rhs_rows_to_lhs_rows,
225 lhs_rows_to_rhs_rows,
226 }
227 }
228
229 pub(crate) fn convert_rows_to_companion(
230 &self,
231 display_map_id: EntityId,
232 companion_snapshot: &MultiBufferSnapshot,
233 our_snapshot: &MultiBufferSnapshot,
234 bounds: (Bound<MultiBufferPoint>, Bound<MultiBufferPoint>),
235 ) -> Vec<CompanionExcerptPatch> {
236 let (excerpt_map, convert_fn) = if display_map_id == self.rhs_display_map_id {
237 (&self.rhs_excerpt_to_lhs_excerpt, self.rhs_rows_to_lhs_rows)
238 } else {
239 (&self.lhs_excerpt_to_rhs_excerpt, self.lhs_rows_to_rhs_rows)
240 };
241 convert_fn(excerpt_map, companion_snapshot, our_snapshot, bounds)
242 }
243
244 pub(crate) fn convert_point_from_companion(
245 &self,
246 display_map_id: EntityId,
247 our_snapshot: &MultiBufferSnapshot,
248 companion_snapshot: &MultiBufferSnapshot,
249 point: MultiBufferPoint,
250 ) -> Range<MultiBufferPoint> {
251 let (excerpt_map, convert_fn) = if display_map_id == self.rhs_display_map_id {
252 (&self.lhs_excerpt_to_rhs_excerpt, self.lhs_rows_to_rhs_rows)
253 } else {
254 (&self.rhs_excerpt_to_lhs_excerpt, self.rhs_rows_to_lhs_rows)
255 };
256
257 let excerpt = convert_fn(
258 excerpt_map,
259 our_snapshot,
260 companion_snapshot,
261 (Bound::Included(point), Bound::Included(point)),
262 )
263 .into_iter()
264 .next();
265
266 let Some(excerpt) = excerpt else {
267 return Point::zero()..our_snapshot.max_point();
268 };
269 excerpt.patch.edit_for_old_position(point).new
270 }
271
272 pub(crate) fn companion_excerpt_to_excerpt(
273 &self,
274 display_map_id: EntityId,
275 ) -> &HashMap<ExcerptId, ExcerptId> {
276 if display_map_id == self.rhs_display_map_id {
277 &self.lhs_excerpt_to_rhs_excerpt
278 } else {
279 &self.rhs_excerpt_to_lhs_excerpt
280 }
281 }
282
283 fn buffer_to_companion_buffer(&self, display_map_id: EntityId) -> &HashMap<BufferId, BufferId> {
284 if display_map_id == self.rhs_display_map_id {
285 &self.rhs_buffer_to_lhs_buffer
286 } else {
287 &self.lhs_buffer_to_rhs_buffer
288 }
289 }
290
291 pub(crate) fn add_excerpt_mapping(&mut self, lhs_id: ExcerptId, rhs_id: ExcerptId) {
292 self.lhs_excerpt_to_rhs_excerpt.insert(lhs_id, rhs_id);
293 self.rhs_excerpt_to_lhs_excerpt.insert(rhs_id, lhs_id);
294 }
295
296 pub(crate) fn remove_excerpt_mappings(
297 &mut self,
298 lhs_ids: impl IntoIterator<Item = ExcerptId>,
299 rhs_ids: impl IntoIterator<Item = ExcerptId>,
300 ) {
301 for id in lhs_ids {
302 self.lhs_excerpt_to_rhs_excerpt.remove(&id);
303 }
304 for id in rhs_ids {
305 self.rhs_excerpt_to_lhs_excerpt.remove(&id);
306 }
307 }
308
309 pub(crate) fn lhs_to_rhs_buffer(&self, lhs_buffer_id: BufferId) -> Option<BufferId> {
310 self.lhs_buffer_to_rhs_buffer.get(&lhs_buffer_id).copied()
311 }
312
313 pub(crate) fn add_buffer_mapping(&mut self, lhs_buffer: BufferId, rhs_buffer: BufferId) {
314 self.lhs_buffer_to_rhs_buffer.insert(lhs_buffer, rhs_buffer);
315 self.rhs_buffer_to_lhs_buffer.insert(rhs_buffer, lhs_buffer);
316 }
317}
318
319impl DisplayMap {
320 pub fn new(
321 buffer: Entity<MultiBuffer>,
322 font: Font,
323 font_size: Pixels,
324 wrap_width: Option<Pixels>,
325 buffer_header_height: u32,
326 excerpt_header_height: u32,
327 fold_placeholder: FoldPlaceholder,
328 diagnostics_max_severity: DiagnosticSeverity,
329 cx: &mut Context<Self>,
330 ) -> Self {
331 let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
332
333 let tab_size = Self::tab_size(&buffer, cx);
334 let buffer_snapshot = buffer.read(cx).snapshot(cx);
335 let crease_map = CreaseMap::new(&buffer_snapshot);
336 let (inlay_map, snapshot) = InlayMap::new(buffer_snapshot);
337 let (fold_map, snapshot) = FoldMap::new(snapshot);
338 let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
339 let (wrap_map, snapshot) = WrapMap::new(snapshot, font, font_size, wrap_width, cx);
340 let block_map = BlockMap::new(snapshot, buffer_header_height, excerpt_header_height);
341
342 cx.observe(&wrap_map, |_, _, cx| cx.notify()).detach();
343
344 DisplayMap {
345 entity_id: cx.entity_id(),
346 buffer,
347 buffer_subscription,
348 fold_map,
349 inlay_map,
350 tab_map,
351 wrap_map,
352 block_map,
353 crease_map,
354 fold_placeholder,
355 diagnostics_max_severity,
356 text_highlights: Default::default(),
357 inlay_highlights: Default::default(),
358 clip_at_line_ends: false,
359 masked: false,
360 companion: None,
361 }
362 }
363
364 pub(crate) fn set_companion(
365 &mut self,
366 companion: Option<(WeakEntity<DisplayMap>, Entity<Companion>)>,
367 cx: &mut Context<Self>,
368 ) {
369 let Some((companion_display_map, companion)) = companion else {
370 self.companion = None;
371 let (snapshot, edits) = self.sync_through_wrap(cx);
372 let edits = edits.compose([text::Edit {
373 old: WrapRow(0)..snapshot.max_point().row(),
374 new: WrapRow(0)..snapshot.max_point().row(),
375 }]);
376 self.block_map.read(snapshot, edits, None);
377 return;
378 };
379
380 let rhs_display_map_id = companion.read(cx).rhs_display_map_id;
381 if self.entity_id != rhs_display_map_id {
382 let buffer_mapping = companion
383 .read(cx)
384 .buffer_to_companion_buffer(rhs_display_map_id);
385 self.block_map.folded_buffers = companion
386 .read(cx)
387 .rhs_folded_buffers
388 .iter()
389 .filter_map(|id| buffer_mapping.get(id).copied())
390 .collect();
391 }
392
393 let snapshot = self.unfold_intersecting([Anchor::min()..Anchor::max()], true, cx);
394
395 self.companion = Some((companion_display_map.clone(), companion));
396
397 let companion_wrap_data = companion_display_map
398 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
399 .ok();
400 let companion = self.companion.as_ref().map(|(_, c)| c.read(cx));
401 let companion_view =
402 companion_wrap_data
403 .as_ref()
404 .zip(companion)
405 .map(|((snapshot, edits), companion)| {
406 CompanionView::new(self.entity_id, snapshot, edits, companion)
407 });
408
409 let edits = Patch::new(
410 [text::Edit {
411 old: WrapRow(0)..snapshot.max_point().row(),
412 new: WrapRow(0)..snapshot.max_point().row(),
413 }]
414 .into_iter()
415 .collect(),
416 );
417 self.block_map
418 .read(snapshot.clone(), edits.clone(), companion_view);
419
420 if let Some((companion_dm, _)) = &self.companion {
421 let _ = companion_dm.update(cx, |dm, _cx| {
422 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
423 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(_cx));
424 dm.block_map.read(
425 companion_snapshot,
426 companion_edits,
427 their_companion_ref
428 .map(|c| CompanionView::new(dm.entity_id, &snapshot, &edits, c)),
429 );
430 }
431 });
432 }
433 }
434
435 pub(crate) fn companion(&self) -> Option<&Entity<Companion>> {
436 self.companion.as_ref().map(|(_, c)| c)
437 }
438
439 pub(crate) fn companion_excerpt_to_my_excerpt(
440 &self,
441 their_id: ExcerptId,
442 cx: &App,
443 ) -> Option<ExcerptId> {
444 let (_, companion) = self.companion.as_ref()?;
445 let c = companion.read(cx);
446 c.companion_excerpt_to_excerpt(self.entity_id)
447 .get(&their_id)
448 .copied()
449 }
450
451 fn sync_through_wrap(&mut self, cx: &mut App) -> (WrapSnapshot, WrapPatch) {
452 let tab_size = Self::tab_size(&self.buffer, cx);
453 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
454 let edits = self.buffer_subscription.consume().into_inner();
455
456 let (snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
457 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
458 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
459 self.wrap_map
460 .update(cx, |map, cx| map.sync(snapshot, edits, cx))
461 }
462
463 #[instrument(skip_all)]
464 pub fn snapshot(&mut self, cx: &mut Context<Self>) -> DisplaySnapshot {
465 let (self_wrap_snapshot, self_wrap_edits) = self.sync_through_wrap(cx);
466 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
467 companion_dm
468 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
469 .ok()
470 });
471 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
472 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
473 |((snapshot, edits), companion)| {
474 CompanionView::new(self.entity_id, snapshot, edits, companion)
475 },
476 );
477
478 let block_snapshot = self
479 .block_map
480 .read(
481 self_wrap_snapshot.clone(),
482 self_wrap_edits.clone(),
483 companion_view,
484 )
485 .snapshot;
486
487 if let Some((companion_dm, _)) = &self.companion {
488 let _ = companion_dm.update(cx, |dm, _cx| {
489 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
490 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(_cx));
491 dm.block_map.read(
492 companion_snapshot,
493 companion_edits,
494 their_companion_ref.map(|c| {
495 CompanionView::new(
496 dm.entity_id,
497 &self_wrap_snapshot,
498 &self_wrap_edits,
499 c,
500 )
501 }),
502 );
503 }
504 });
505 }
506
507 let companion_display_snapshot = self.companion.as_ref().and_then(|(companion_dm, _)| {
508 companion_dm
509 .update(cx, |dm, cx| Arc::new(dm.snapshot_simple(cx)))
510 .ok()
511 });
512
513 DisplaySnapshot {
514 display_map_id: self.entity_id,
515 companion_display_snapshot,
516 block_snapshot,
517 diagnostics_max_severity: self.diagnostics_max_severity,
518 crease_snapshot: self.crease_map.snapshot(),
519 text_highlights: self.text_highlights.clone(),
520 inlay_highlights: self.inlay_highlights.clone(),
521 clip_at_line_ends: self.clip_at_line_ends,
522 masked: self.masked,
523 fold_placeholder: self.fold_placeholder.clone(),
524 }
525 }
526
527 fn snapshot_simple(&mut self, cx: &mut Context<Self>) -> DisplaySnapshot {
528 let (wrap_snapshot, wrap_edits) = self.sync_through_wrap(cx);
529
530 let block_snapshot = self
531 .block_map
532 .read(wrap_snapshot, wrap_edits, None)
533 .snapshot;
534
535 DisplaySnapshot {
536 display_map_id: self.entity_id,
537 companion_display_snapshot: None,
538 block_snapshot,
539 diagnostics_max_severity: self.diagnostics_max_severity,
540 crease_snapshot: self.crease_map.snapshot(),
541 text_highlights: self.text_highlights.clone(),
542 inlay_highlights: self.inlay_highlights.clone(),
543 clip_at_line_ends: self.clip_at_line_ends,
544 masked: self.masked,
545 fold_placeholder: self.fold_placeholder.clone(),
546 }
547 }
548
549 #[instrument(skip_all)]
550 pub fn set_state(&mut self, other: &DisplaySnapshot, cx: &mut Context<Self>) {
551 self.fold(
552 other
553 .folds_in_range(MultiBufferOffset(0)..other.buffer_snapshot().len())
554 .map(|fold| {
555 Crease::simple(
556 fold.range.to_offset(other.buffer_snapshot()),
557 fold.placeholder.clone(),
558 )
559 })
560 .collect(),
561 cx,
562 );
563 }
564
565 /// Creates folds for the given creases.
566 #[instrument(skip_all)]
567 pub fn fold<T: Clone + ToOffset>(&mut self, creases: Vec<Crease<T>>, cx: &mut Context<Self>) {
568 if self.companion().is_some() {
569 return;
570 }
571
572 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
573 let edits = self.buffer_subscription.consume().into_inner();
574 let tab_size = Self::tab_size(&self.buffer, cx);
575
576 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
577 companion_dm
578 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
579 .ok()
580 });
581
582 let (snapshot, edits) = self.inlay_map.sync(buffer_snapshot.clone(), edits);
583 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
584 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
585 let (snapshot, edits) = self
586 .wrap_map
587 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
588
589 {
590 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
591 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
592 |((snapshot, edits), companion)| {
593 CompanionView::new(self.entity_id, snapshot, edits, companion)
594 },
595 );
596 self.block_map.read(snapshot, edits, companion_view);
597 }
598
599 let inline = creases.iter().filter_map(|crease| {
600 if let Crease::Inline {
601 range, placeholder, ..
602 } = crease
603 {
604 Some((range.clone(), placeholder.clone()))
605 } else {
606 None
607 }
608 });
609 let (snapshot, edits) = fold_map.fold(inline);
610
611 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
612 let (self_new_wrap_snapshot, self_new_wrap_edits) = self
613 .wrap_map
614 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
615
616 let (self_wrap_snapshot, self_wrap_edits) =
617 (self_new_wrap_snapshot.clone(), self_new_wrap_edits.clone());
618
619 let mut block_map = {
620 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
621 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
622 |((snapshot, edits), companion)| {
623 CompanionView::new(self.entity_id, snapshot, edits, companion)
624 },
625 );
626 self.block_map
627 .write(self_new_wrap_snapshot, self_new_wrap_edits, companion_view)
628 };
629 let blocks = creases.into_iter().filter_map(|crease| {
630 if let Crease::Block {
631 range,
632 block_height,
633 render_block,
634 block_style,
635 block_priority,
636 ..
637 } = crease
638 {
639 Some((
640 range,
641 render_block,
642 block_height,
643 block_style,
644 block_priority,
645 ))
646 } else {
647 None
648 }
649 });
650 block_map.insert(
651 blocks
652 .into_iter()
653 .map(|(range, render, height, style, priority)| {
654 let start = buffer_snapshot.anchor_before(range.start);
655 let end = buffer_snapshot.anchor_after(range.end);
656 BlockProperties {
657 placement: BlockPlacement::Replace(start..=end),
658 render,
659 height: Some(height),
660 style,
661 priority,
662 }
663 }),
664 );
665
666 if let Some((companion_dm, _)) = &self.companion {
667 let _ = companion_dm.update(cx, |dm, cx| {
668 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
669 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
670 dm.block_map.read(
671 companion_snapshot,
672 companion_edits,
673 their_companion_ref.map(|c| {
674 CompanionView::new(
675 dm.entity_id,
676 &self_wrap_snapshot,
677 &self_wrap_edits,
678 c,
679 )
680 }),
681 );
682 }
683 });
684 }
685 }
686
687 /// Removes any folds with the given ranges.
688 #[instrument(skip_all)]
689 pub fn remove_folds_with_type<T: ToOffset>(
690 &mut self,
691 ranges: impl IntoIterator<Item = Range<T>>,
692 type_id: TypeId,
693 cx: &mut Context<Self>,
694 ) {
695 let snapshot = self.buffer.read(cx).snapshot(cx);
696 let edits = self.buffer_subscription.consume().into_inner();
697 let tab_size = Self::tab_size(&self.buffer, cx);
698
699 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
700 companion_dm
701 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
702 .ok()
703 });
704
705 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
706 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
707 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
708 let (snapshot, edits) = self
709 .wrap_map
710 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
711
712 {
713 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
714 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
715 |((snapshot, edits), companion)| {
716 CompanionView::new(self.entity_id, snapshot, edits, companion)
717 },
718 );
719 self.block_map.read(snapshot, edits, companion_view);
720 }
721
722 let (snapshot, edits) = fold_map.remove_folds(ranges, type_id);
723 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
724 let (self_new_wrap_snapshot, self_new_wrap_edits) = self
725 .wrap_map
726 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
727
728 let (self_wrap_snapshot, self_wrap_edits) =
729 (self_new_wrap_snapshot.clone(), self_new_wrap_edits.clone());
730
731 {
732 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
733 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
734 |((snapshot, edits), companion)| {
735 CompanionView::new(self.entity_id, snapshot, edits, companion)
736 },
737 );
738 self.block_map
739 .write(self_new_wrap_snapshot, self_new_wrap_edits, companion_view);
740 }
741
742 if let Some((companion_dm, _)) = &self.companion {
743 let _ = companion_dm.update(cx, |dm, cx| {
744 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
745 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
746 dm.block_map.read(
747 companion_snapshot,
748 companion_edits,
749 their_companion_ref.map(|c| {
750 CompanionView::new(
751 dm.entity_id,
752 &self_wrap_snapshot,
753 &self_wrap_edits,
754 c,
755 )
756 }),
757 );
758 }
759 });
760 }
761 }
762
763 /// Removes any folds whose ranges intersect any of the given ranges.
764 #[instrument(skip_all)]
765 pub fn unfold_intersecting<T: ToOffset>(
766 &mut self,
767 ranges: impl IntoIterator<Item = Range<T>>,
768 inclusive: bool,
769 cx: &mut Context<Self>,
770 ) -> WrapSnapshot {
771 let snapshot = self.buffer.read(cx).snapshot(cx);
772 let offset_ranges = ranges
773 .into_iter()
774 .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot))
775 .collect::<Vec<_>>();
776 let edits = self.buffer_subscription.consume().into_inner();
777 let tab_size = Self::tab_size(&self.buffer, cx);
778
779 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
780 companion_dm
781 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
782 .ok()
783 });
784
785 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
786 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
787 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
788 let (snapshot, edits) = self
789 .wrap_map
790 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
791
792 {
793 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
794 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
795 |((snapshot, edits), companion)| {
796 CompanionView::new(self.entity_id, snapshot, edits, companion)
797 },
798 );
799 self.block_map.read(snapshot, edits, companion_view);
800 }
801
802 let (snapshot, edits) =
803 fold_map.unfold_intersecting(offset_ranges.iter().cloned(), inclusive);
804 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
805 let (self_new_wrap_snapshot, self_new_wrap_edits) = self
806 .wrap_map
807 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
808
809 let (self_wrap_snapshot, self_wrap_edits) =
810 (self_new_wrap_snapshot.clone(), self_new_wrap_edits.clone());
811
812 let mut block_map = {
813 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
814 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
815 |((snapshot, edits), companion)| {
816 CompanionView::new(self.entity_id, snapshot, edits, companion)
817 },
818 );
819 self.block_map.write(
820 self_new_wrap_snapshot.clone(),
821 self_new_wrap_edits,
822 companion_view,
823 )
824 };
825 block_map.remove_intersecting_replace_blocks(offset_ranges, inclusive);
826
827 if let Some((companion_dm, _)) = &self.companion {
828 let _ = companion_dm.update(cx, |dm, cx| {
829 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
830 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
831 dm.block_map.read(
832 companion_snapshot,
833 companion_edits,
834 their_companion_ref.map(|c| {
835 CompanionView::new(
836 dm.entity_id,
837 &self_wrap_snapshot,
838 &self_wrap_edits,
839 c,
840 )
841 }),
842 );
843 }
844 });
845 }
846
847 self_new_wrap_snapshot
848 }
849
850 #[instrument(skip_all)]
851 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
852 let (self_wrap_snapshot, self_wrap_edits) = self.sync_through_wrap(cx);
853
854 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
855 companion_dm
856 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
857 .ok()
858 });
859
860 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
861 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
862 |((snapshot, edits), companion)| {
863 CompanionView::new(self.entity_id, snapshot, edits, companion)
864 },
865 );
866
867 let mut block_map = self.block_map.write(
868 self_wrap_snapshot.clone(),
869 self_wrap_edits.clone(),
870 companion_view,
871 );
872 block_map.disable_header_for_buffer(buffer_id);
873
874 if let Some((companion_dm, _)) = &self.companion {
875 let _ = companion_dm.update(cx, |dm, cx| {
876 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
877 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
878 dm.block_map.read(
879 companion_snapshot,
880 companion_edits,
881 their_companion_ref.map(|c| {
882 CompanionView::new(
883 dm.entity_id,
884 &self_wrap_snapshot,
885 &self_wrap_edits,
886 c,
887 )
888 }),
889 );
890 }
891 });
892 }
893 }
894
895 #[instrument(skip_all)]
896 pub fn fold_buffers(
897 &mut self,
898 buffer_ids: impl IntoIterator<Item = language::BufferId>,
899 cx: &mut App,
900 ) {
901 let buffer_ids: Vec<_> = buffer_ids.into_iter().collect();
902
903 if let Some((_, companion_entity)) = &self.companion {
904 companion_entity.update(cx, |companion, _| {
905 if self.entity_id == companion.rhs_display_map_id {
906 companion
907 .rhs_folded_buffers
908 .extend(buffer_ids.iter().copied());
909 } else {
910 let rhs_ids = buffer_ids
911 .iter()
912 .filter_map(|id| companion.lhs_buffer_to_rhs_buffer.get(id).copied());
913 companion.rhs_folded_buffers.extend(rhs_ids);
914 }
915 });
916 }
917
918 let (self_wrap_snapshot, self_wrap_edits) = self.sync_through_wrap(cx);
919
920 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
921 companion_dm
922 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
923 .ok()
924 });
925
926 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
927 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
928 |((snapshot, edits), companion)| {
929 CompanionView::new(self.entity_id, snapshot, edits, companion)
930 },
931 );
932
933 let mut block_map = self.block_map.write(
934 self_wrap_snapshot.clone(),
935 self_wrap_edits.clone(),
936 companion_view,
937 );
938 block_map.fold_buffers(buffer_ids.iter().copied(), self.buffer.read(cx), cx);
939
940 if let Some((companion_dm, companion_entity)) = &self.companion {
941 let buffer_mapping = companion_entity
942 .read(cx)
943 .buffer_to_companion_buffer(self.entity_id);
944 let their_buffer_ids: Vec<_> = buffer_ids
945 .iter()
946 .filter_map(|id| buffer_mapping.get(id).copied())
947 .collect();
948
949 let _ = companion_dm.update(cx, |dm, cx| {
950 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
951 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
952 let mut block_map = dm.block_map.write(
953 companion_snapshot,
954 companion_edits,
955 their_companion_ref.map(|c| {
956 CompanionView::new(
957 dm.entity_id,
958 &self_wrap_snapshot,
959 &self_wrap_edits,
960 c,
961 )
962 }),
963 );
964 if !their_buffer_ids.is_empty() {
965 block_map.fold_buffers(their_buffer_ids, dm.buffer.read(cx), cx);
966 }
967 }
968 });
969 }
970 }
971
972 #[instrument(skip_all)]
973 pub fn unfold_buffers(
974 &mut self,
975 buffer_ids: impl IntoIterator<Item = language::BufferId>,
976 cx: &mut Context<Self>,
977 ) {
978 let buffer_ids: Vec<_> = buffer_ids.into_iter().collect();
979
980 if let Some((_, companion_entity)) = &self.companion {
981 companion_entity.update(cx, |companion, _| {
982 if self.entity_id == companion.rhs_display_map_id {
983 for id in &buffer_ids {
984 companion.rhs_folded_buffers.remove(id);
985 }
986 } else {
987 for id in &buffer_ids {
988 if let Some(rhs_id) = companion.lhs_buffer_to_rhs_buffer.get(id) {
989 companion.rhs_folded_buffers.remove(rhs_id);
990 }
991 }
992 }
993 });
994 }
995
996 let (self_wrap_snapshot, self_wrap_edits) = self.sync_through_wrap(cx);
997
998 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
999 companion_dm
1000 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
1001 .ok()
1002 });
1003
1004 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1005 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1006 |((snapshot, edits), companion)| {
1007 CompanionView::new(self.entity_id, snapshot, edits, companion)
1008 },
1009 );
1010
1011 let mut block_map = self.block_map.write(
1012 self_wrap_snapshot.clone(),
1013 self_wrap_edits.clone(),
1014 companion_view,
1015 );
1016 block_map.unfold_buffers(buffer_ids.iter().copied(), self.buffer.read(cx), cx);
1017
1018 if let Some((companion_dm, companion_entity)) = &self.companion {
1019 let buffer_mapping = companion_entity
1020 .read(cx)
1021 .buffer_to_companion_buffer(self.entity_id);
1022 let their_buffer_ids: Vec<_> = buffer_ids
1023 .iter()
1024 .filter_map(|id| buffer_mapping.get(id).copied())
1025 .collect();
1026
1027 let _ = companion_dm.update(cx, |dm, cx| {
1028 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
1029 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
1030 let mut block_map = dm.block_map.write(
1031 companion_snapshot,
1032 companion_edits,
1033 their_companion_ref.map(|c| {
1034 CompanionView::new(
1035 dm.entity_id,
1036 &self_wrap_snapshot,
1037 &self_wrap_edits,
1038 c,
1039 )
1040 }),
1041 );
1042 if !their_buffer_ids.is_empty() {
1043 block_map.unfold_buffers(their_buffer_ids, dm.buffer.read(cx), cx);
1044 }
1045 }
1046 });
1047 }
1048 }
1049
1050 #[instrument(skip_all)]
1051 pub(crate) fn is_buffer_folded(&self, buffer_id: language::BufferId) -> bool {
1052 self.block_map.folded_buffers.contains(&buffer_id)
1053 }
1054
1055 #[instrument(skip_all)]
1056 pub(crate) fn folded_buffers(&self) -> &HashSet<BufferId> {
1057 &self.block_map.folded_buffers
1058 }
1059
1060 #[instrument(skip_all)]
1061 pub fn insert_creases(
1062 &mut self,
1063 creases: impl IntoIterator<Item = Crease<Anchor>>,
1064 cx: &mut Context<Self>,
1065 ) -> Vec<CreaseId> {
1066 let snapshot = self.buffer.read(cx).snapshot(cx);
1067 self.crease_map.insert(creases, &snapshot)
1068 }
1069
1070 #[instrument(skip_all)]
1071 pub fn remove_creases(
1072 &mut self,
1073 crease_ids: impl IntoIterator<Item = CreaseId>,
1074 cx: &mut Context<Self>,
1075 ) -> Vec<(CreaseId, Range<Anchor>)> {
1076 let snapshot = self.buffer.read(cx).snapshot(cx);
1077 self.crease_map.remove(crease_ids, &snapshot)
1078 }
1079
1080 #[instrument(skip_all)]
1081 pub fn insert_blocks(
1082 &mut self,
1083 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
1084 cx: &mut Context<Self>,
1085 ) -> Vec<CustomBlockId> {
1086 let (self_wrap_snapshot, self_wrap_edits) = self.sync_through_wrap(cx);
1087
1088 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
1089 companion_dm
1090 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
1091 .ok()
1092 });
1093
1094 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1095 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1096 |((snapshot, edits), companion)| {
1097 CompanionView::new(self.entity_id, snapshot, edits, companion)
1098 },
1099 );
1100
1101 let mut block_map = self.block_map.write(
1102 self_wrap_snapshot.clone(),
1103 self_wrap_edits.clone(),
1104 companion_view,
1105 );
1106 let result = block_map.insert(blocks);
1107
1108 if let Some((companion_dm, _)) = &self.companion {
1109 let _ = companion_dm.update(cx, |dm, cx| {
1110 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
1111 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
1112 dm.block_map.read(
1113 companion_snapshot,
1114 companion_edits,
1115 their_companion_ref.map(|c| {
1116 CompanionView::new(
1117 dm.entity_id,
1118 &self_wrap_snapshot,
1119 &self_wrap_edits,
1120 c,
1121 )
1122 }),
1123 );
1124 }
1125 });
1126 }
1127
1128 result
1129 }
1130
1131 #[instrument(skip_all)]
1132 pub fn resize_blocks(&mut self, heights: HashMap<CustomBlockId, u32>, cx: &mut Context<Self>) {
1133 let (self_wrap_snapshot, self_wrap_edits) = self.sync_through_wrap(cx);
1134
1135 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
1136 companion_dm
1137 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
1138 .ok()
1139 });
1140
1141 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1142 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1143 |((snapshot, edits), companion)| {
1144 CompanionView::new(self.entity_id, snapshot, edits, companion)
1145 },
1146 );
1147
1148 let mut block_map = self.block_map.write(
1149 self_wrap_snapshot.clone(),
1150 self_wrap_edits.clone(),
1151 companion_view,
1152 );
1153 block_map.resize(heights);
1154
1155 if let Some((companion_dm, _)) = &self.companion {
1156 let _ = companion_dm.update(cx, |dm, cx| {
1157 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
1158 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
1159 dm.block_map.read(
1160 companion_snapshot,
1161 companion_edits,
1162 their_companion_ref.map(|c| {
1163 CompanionView::new(
1164 dm.entity_id,
1165 &self_wrap_snapshot,
1166 &self_wrap_edits,
1167 c,
1168 )
1169 }),
1170 );
1171 }
1172 });
1173 }
1174 }
1175
1176 #[instrument(skip_all)]
1177 pub fn replace_blocks(&mut self, renderers: HashMap<CustomBlockId, RenderBlock>) {
1178 self.block_map.replace_blocks(renderers);
1179 }
1180
1181 #[instrument(skip_all)]
1182 pub fn remove_blocks(&mut self, ids: HashSet<CustomBlockId>, cx: &mut Context<Self>) {
1183 let (self_wrap_snapshot, self_wrap_edits) = self.sync_through_wrap(cx);
1184
1185 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
1186 companion_dm
1187 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
1188 .ok()
1189 });
1190
1191 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1192 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1193 |((snapshot, edits), companion)| {
1194 CompanionView::new(self.entity_id, snapshot, edits, companion)
1195 },
1196 );
1197
1198 let mut block_map = self.block_map.write(
1199 self_wrap_snapshot.clone(),
1200 self_wrap_edits.clone(),
1201 companion_view,
1202 );
1203 block_map.remove(ids);
1204
1205 if let Some((companion_dm, _)) = &self.companion {
1206 let _ = companion_dm.update(cx, |dm, cx| {
1207 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
1208 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
1209 dm.block_map.read(
1210 companion_snapshot,
1211 companion_edits,
1212 their_companion_ref.map(|c| {
1213 CompanionView::new(
1214 dm.entity_id,
1215 &self_wrap_snapshot,
1216 &self_wrap_edits,
1217 c,
1218 )
1219 }),
1220 );
1221 }
1222 });
1223 }
1224 }
1225
1226 #[instrument(skip_all)]
1227 pub fn row_for_block(
1228 &mut self,
1229 block_id: CustomBlockId,
1230 cx: &mut Context<Self>,
1231 ) -> Option<DisplayRow> {
1232 let (self_wrap_snapshot, self_wrap_edits) = self.sync_through_wrap(cx);
1233
1234 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
1235 companion_dm
1236 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
1237 .ok()
1238 });
1239
1240 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1241 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1242 |((snapshot, edits), companion)| {
1243 CompanionView::new(self.entity_id, snapshot, edits, companion)
1244 },
1245 );
1246
1247 let block_map = self.block_map.read(
1248 self_wrap_snapshot.clone(),
1249 self_wrap_edits.clone(),
1250 companion_view,
1251 );
1252 let block_row = block_map.row_for_block(block_id)?;
1253
1254 if let Some((companion_dm, _)) = &self.companion {
1255 let _ = companion_dm.update(cx, |dm, cx| {
1256 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
1257 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
1258 dm.block_map.read(
1259 companion_snapshot,
1260 companion_edits,
1261 their_companion_ref.map(|c| {
1262 CompanionView::new(
1263 dm.entity_id,
1264 &self_wrap_snapshot,
1265 &self_wrap_edits,
1266 c,
1267 )
1268 }),
1269 );
1270 }
1271 });
1272 }
1273
1274 Some(DisplayRow(block_row.0))
1275 }
1276
1277 #[instrument(skip_all)]
1278 pub fn highlight_text(
1279 &mut self,
1280 key: HighlightKey,
1281 ranges: Vec<Range<Anchor>>,
1282 style: HighlightStyle,
1283 merge: bool,
1284 cx: &App,
1285 ) {
1286 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
1287 let to_insert = match self.text_highlights.remove(&key).filter(|_| merge) {
1288 Some(previous) => {
1289 let mut merged_ranges = previous.1.clone();
1290 for new_range in ranges {
1291 let i = merged_ranges
1292 .binary_search_by(|probe| {
1293 probe.start.cmp(&new_range.start, &multi_buffer_snapshot)
1294 })
1295 .unwrap_or_else(|i| i);
1296 merged_ranges.insert(i, new_range);
1297 }
1298 Arc::new((style, merged_ranges))
1299 }
1300 None => Arc::new((style, ranges)),
1301 };
1302 self.text_highlights.insert(key, to_insert);
1303 }
1304
1305 #[instrument(skip_all)]
1306 pub(crate) fn highlight_inlays(
1307 &mut self,
1308 type_id: TypeId,
1309 highlights: Vec<InlayHighlight>,
1310 style: HighlightStyle,
1311 ) {
1312 for highlight in highlights {
1313 let update = self.inlay_highlights.update(&type_id, |highlights| {
1314 highlights.insert(highlight.inlay, (style, highlight.clone()))
1315 });
1316 if update.is_none() {
1317 self.inlay_highlights.insert(
1318 type_id,
1319 TreeMap::from_ordered_entries([(highlight.inlay, (style, highlight))]),
1320 );
1321 }
1322 }
1323 }
1324
1325 #[instrument(skip_all)]
1326 pub fn text_highlights(&self, type_id: TypeId) -> Option<(HighlightStyle, &[Range<Anchor>])> {
1327 let highlights = self.text_highlights.get(&HighlightKey::Type(type_id))?;
1328 Some((highlights.0, &highlights.1))
1329 }
1330
1331 #[cfg(feature = "test-support")]
1332 pub fn all_text_highlights(
1333 &self,
1334 ) -> impl Iterator<Item = &Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
1335 self.text_highlights.values()
1336 }
1337
1338 #[instrument(skip_all)]
1339 pub fn clear_highlights(&mut self, type_id: TypeId) -> bool {
1340 let mut cleared = self
1341 .text_highlights
1342 .remove(&HighlightKey::Type(type_id))
1343 .is_some();
1344 self.text_highlights.retain(|key, _| {
1345 let retain = if let HighlightKey::TypePlus(key_type_id, _) = key {
1346 key_type_id != &type_id
1347 } else {
1348 true
1349 };
1350 cleared |= !retain;
1351 retain
1352 });
1353 cleared |= self.inlay_highlights.remove(&type_id).is_some();
1354 cleared
1355 }
1356
1357 pub fn set_font(&self, font: Font, font_size: Pixels, cx: &mut Context<Self>) -> bool {
1358 self.wrap_map
1359 .update(cx, |map, cx| map.set_font_with_size(font, font_size, cx))
1360 }
1361
1362 pub fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut Context<Self>) -> bool {
1363 self.wrap_map
1364 .update(cx, |map, cx| map.set_wrap_width(width, cx))
1365 }
1366
1367 #[instrument(skip_all)]
1368 pub fn update_fold_widths(
1369 &mut self,
1370 widths: impl IntoIterator<Item = (ChunkRendererId, Pixels)>,
1371 cx: &mut Context<Self>,
1372 ) -> bool {
1373 let snapshot = self.buffer.read(cx).snapshot(cx);
1374 let edits = self.buffer_subscription.consume().into_inner();
1375 let tab_size = Self::tab_size(&self.buffer, cx);
1376
1377 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
1378 companion_dm
1379 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
1380 .ok()
1381 });
1382
1383 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
1384 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
1385 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
1386 let (snapshot, edits) = self
1387 .wrap_map
1388 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
1389
1390 {
1391 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1392 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1393 |((snapshot, edits), companion)| {
1394 CompanionView::new(self.entity_id, snapshot, edits, companion)
1395 },
1396 );
1397 self.block_map.read(snapshot, edits, companion_view);
1398 }
1399
1400 let (snapshot, edits) = fold_map.update_fold_widths(widths);
1401 let widths_changed = !edits.is_empty();
1402 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
1403 let (self_new_wrap_snapshot, self_new_wrap_edits) = self
1404 .wrap_map
1405 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
1406
1407 let (self_wrap_snapshot, self_wrap_edits) =
1408 (self_new_wrap_snapshot.clone(), self_new_wrap_edits.clone());
1409
1410 {
1411 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1412 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1413 |((snapshot, edits), companion)| {
1414 CompanionView::new(self.entity_id, snapshot, edits, companion)
1415 },
1416 );
1417 self.block_map
1418 .read(self_new_wrap_snapshot, self_new_wrap_edits, companion_view);
1419 }
1420
1421 if let Some((companion_dm, _)) = &self.companion {
1422 let _ = companion_dm.update(cx, |dm, cx| {
1423 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
1424 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
1425 dm.block_map.read(
1426 companion_snapshot,
1427 companion_edits,
1428 their_companion_ref.map(|c| {
1429 CompanionView::new(
1430 dm.entity_id,
1431 &self_wrap_snapshot,
1432 &self_wrap_edits,
1433 c,
1434 )
1435 }),
1436 );
1437 }
1438 });
1439 }
1440
1441 widths_changed
1442 }
1443
1444 pub(crate) fn current_inlays(&self) -> impl Iterator<Item = &Inlay> {
1445 self.inlay_map.current_inlays()
1446 }
1447
1448 #[instrument(skip_all)]
1449 pub(crate) fn splice_inlays(
1450 &mut self,
1451 to_remove: &[InlayId],
1452 to_insert: Vec<Inlay>,
1453 cx: &mut Context<Self>,
1454 ) {
1455 if to_remove.is_empty() && to_insert.is_empty() {
1456 return;
1457 }
1458 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
1459 let edits = self.buffer_subscription.consume().into_inner();
1460 let tab_size = Self::tab_size(&self.buffer, cx);
1461
1462 let companion_wrap_data = self.companion.as_ref().and_then(|(companion_dm, _)| {
1463 companion_dm
1464 .update(cx, |dm, cx| dm.sync_through_wrap(cx))
1465 .ok()
1466 });
1467
1468 let (snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
1469 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
1470 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
1471 let (snapshot, edits) = self
1472 .wrap_map
1473 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
1474
1475 {
1476 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1477 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1478 |((snapshot, edits), companion)| {
1479 CompanionView::new(self.entity_id, snapshot, edits, companion)
1480 },
1481 );
1482 self.block_map.read(snapshot, edits, companion_view);
1483 }
1484
1485 let (snapshot, edits) = self.inlay_map.splice(to_remove, to_insert);
1486 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
1487 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
1488 let (self_new_wrap_snapshot, self_new_wrap_edits) = self
1489 .wrap_map
1490 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
1491
1492 let (self_wrap_snapshot, self_wrap_edits) =
1493 (self_new_wrap_snapshot.clone(), self_new_wrap_edits.clone());
1494
1495 {
1496 let companion_ref = self.companion.as_ref().map(|(_, c)| c.read(cx));
1497 let companion_view = companion_wrap_data.as_ref().zip(companion_ref).map(
1498 |((snapshot, edits), companion)| {
1499 CompanionView::new(self.entity_id, snapshot, edits, companion)
1500 },
1501 );
1502 self.block_map
1503 .read(self_new_wrap_snapshot, self_new_wrap_edits, companion_view);
1504 }
1505
1506 if let Some((companion_dm, _)) = &self.companion {
1507 let _ = companion_dm.update(cx, |dm, cx| {
1508 if let Some((companion_snapshot, companion_edits)) = companion_wrap_data {
1509 let their_companion_ref = dm.companion.as_ref().map(|(_, c)| c.read(cx));
1510 dm.block_map.read(
1511 companion_snapshot,
1512 companion_edits,
1513 their_companion_ref.map(|c| {
1514 CompanionView::new(
1515 dm.entity_id,
1516 &self_wrap_snapshot,
1517 &self_wrap_edits,
1518 c,
1519 )
1520 }),
1521 );
1522 }
1523 });
1524 }
1525 }
1526
1527 #[instrument(skip_all)]
1528 fn tab_size(buffer: &Entity<MultiBuffer>, cx: &App) -> NonZeroU32 {
1529 let buffer = buffer.read(cx).as_singleton().map(|buffer| buffer.read(cx));
1530 let language = buffer
1531 .and_then(|buffer| buffer.language())
1532 .map(|l| l.name());
1533 let file = buffer.and_then(|buffer| buffer.file());
1534 language_settings(language, file, cx).tab_size
1535 }
1536
1537 #[cfg(test)]
1538 pub fn is_rewrapping(&self, cx: &gpui::App) -> bool {
1539 self.wrap_map.read(cx).is_rewrapping()
1540 }
1541}
1542
1543#[derive(Debug, Default)]
1544pub(crate) struct Highlights<'a> {
1545 pub text_highlights: Option<&'a TextHighlights>,
1546 pub inlay_highlights: Option<&'a InlayHighlights>,
1547 pub styles: HighlightStyles,
1548}
1549
1550#[derive(Clone, Copy, Debug)]
1551pub struct EditPredictionStyles {
1552 pub insertion: HighlightStyle,
1553 pub whitespace: HighlightStyle,
1554}
1555
1556#[derive(Default, Debug, Clone, Copy)]
1557pub struct HighlightStyles {
1558 pub inlay_hint: Option<HighlightStyle>,
1559 pub edit_prediction: Option<EditPredictionStyles>,
1560}
1561
1562#[derive(Clone)]
1563pub enum ChunkReplacement {
1564 Renderer(ChunkRenderer),
1565 Str(SharedString),
1566}
1567
1568pub struct HighlightedChunk<'a> {
1569 pub text: &'a str,
1570 pub style: Option<HighlightStyle>,
1571 pub is_tab: bool,
1572 pub is_inlay: bool,
1573 pub replacement: Option<ChunkReplacement>,
1574}
1575
1576impl<'a> HighlightedChunk<'a> {
1577 #[instrument(skip_all)]
1578 fn highlight_invisibles(
1579 self,
1580 editor_style: &'a EditorStyle,
1581 ) -> impl Iterator<Item = Self> + 'a {
1582 let mut chars = self.text.chars().peekable();
1583 let mut text = self.text;
1584 let style = self.style;
1585 let is_tab = self.is_tab;
1586 let renderer = self.replacement;
1587 let is_inlay = self.is_inlay;
1588 iter::from_fn(move || {
1589 let mut prefix_len = 0;
1590 while let Some(&ch) = chars.peek() {
1591 if !is_invisible(ch) {
1592 prefix_len += ch.len_utf8();
1593 chars.next();
1594 continue;
1595 }
1596 if prefix_len > 0 {
1597 let (prefix, suffix) = text.split_at(prefix_len);
1598 text = suffix;
1599 return Some(HighlightedChunk {
1600 text: prefix,
1601 style,
1602 is_tab,
1603 is_inlay,
1604 replacement: renderer.clone(),
1605 });
1606 }
1607 chars.next();
1608 let (prefix, suffix) = text.split_at(ch.len_utf8());
1609 text = suffix;
1610 if let Some(replacement) = replacement(ch) {
1611 let invisible_highlight = HighlightStyle {
1612 background_color: Some(editor_style.status.hint_background),
1613 underline: Some(UnderlineStyle {
1614 color: Some(editor_style.status.hint),
1615 thickness: px(1.),
1616 wavy: false,
1617 }),
1618 ..Default::default()
1619 };
1620 let invisible_style = if let Some(style) = style {
1621 style.highlight(invisible_highlight)
1622 } else {
1623 invisible_highlight
1624 };
1625 return Some(HighlightedChunk {
1626 text: prefix,
1627 style: Some(invisible_style),
1628 is_tab: false,
1629 is_inlay,
1630 replacement: Some(ChunkReplacement::Str(replacement.into())),
1631 });
1632 } else {
1633 let invisible_highlight = HighlightStyle {
1634 background_color: Some(editor_style.status.hint_background),
1635 underline: Some(UnderlineStyle {
1636 color: Some(editor_style.status.hint),
1637 thickness: px(1.),
1638 wavy: false,
1639 }),
1640 ..Default::default()
1641 };
1642 let invisible_style = if let Some(style) = style {
1643 style.highlight(invisible_highlight)
1644 } else {
1645 invisible_highlight
1646 };
1647
1648 return Some(HighlightedChunk {
1649 text: prefix,
1650 style: Some(invisible_style),
1651 is_tab: false,
1652 is_inlay,
1653 replacement: renderer.clone(),
1654 });
1655 }
1656 }
1657
1658 if !text.is_empty() {
1659 let remainder = text;
1660 text = "";
1661 Some(HighlightedChunk {
1662 text: remainder,
1663 style,
1664 is_tab,
1665 is_inlay,
1666 replacement: renderer.clone(),
1667 })
1668 } else {
1669 None
1670 }
1671 })
1672 }
1673}
1674
1675#[derive(Clone)]
1676pub struct DisplaySnapshot {
1677 pub display_map_id: EntityId,
1678 pub companion_display_snapshot: Option<Arc<DisplaySnapshot>>,
1679 pub crease_snapshot: CreaseSnapshot,
1680 block_snapshot: BlockSnapshot,
1681 text_highlights: TextHighlights,
1682 inlay_highlights: InlayHighlights,
1683 clip_at_line_ends: bool,
1684 masked: bool,
1685 diagnostics_max_severity: DiagnosticSeverity,
1686 pub(crate) fold_placeholder: FoldPlaceholder,
1687}
1688
1689impl DisplaySnapshot {
1690 pub fn companion_snapshot(&self) -> Option<&DisplaySnapshot> {
1691 self.companion_display_snapshot.as_deref()
1692 }
1693
1694 pub fn wrap_snapshot(&self) -> &WrapSnapshot {
1695 &self.block_snapshot.wrap_snapshot
1696 }
1697 pub fn tab_snapshot(&self) -> &TabSnapshot {
1698 &self.block_snapshot.wrap_snapshot.tab_snapshot
1699 }
1700
1701 pub fn fold_snapshot(&self) -> &FoldSnapshot {
1702 &self.block_snapshot.wrap_snapshot.tab_snapshot.fold_snapshot
1703 }
1704
1705 pub fn inlay_snapshot(&self) -> &InlaySnapshot {
1706 &self
1707 .block_snapshot
1708 .wrap_snapshot
1709 .tab_snapshot
1710 .fold_snapshot
1711 .inlay_snapshot
1712 }
1713
1714 pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
1715 &self
1716 .block_snapshot
1717 .wrap_snapshot
1718 .tab_snapshot
1719 .fold_snapshot
1720 .inlay_snapshot
1721 .buffer
1722 }
1723
1724 #[cfg(test)]
1725 pub fn fold_count(&self) -> usize {
1726 self.fold_snapshot().fold_count()
1727 }
1728
1729 pub fn is_empty(&self) -> bool {
1730 self.buffer_snapshot().len() == MultiBufferOffset(0)
1731 }
1732
1733 pub fn row_infos(&self, start_row: DisplayRow) -> impl Iterator<Item = RowInfo> + '_ {
1734 self.block_snapshot.row_infos(BlockRow(start_row.0))
1735 }
1736
1737 pub fn widest_line_number(&self) -> u32 {
1738 self.buffer_snapshot().widest_line_number()
1739 }
1740
1741 #[instrument(skip_all)]
1742 pub fn prev_line_boundary(&self, mut point: MultiBufferPoint) -> (Point, DisplayPoint) {
1743 loop {
1744 let mut inlay_point = self.inlay_snapshot().to_inlay_point(point);
1745 let mut fold_point = self.fold_snapshot().to_fold_point(inlay_point, Bias::Left);
1746 fold_point.0.column = 0;
1747 inlay_point = fold_point.to_inlay_point(self.fold_snapshot());
1748 point = self.inlay_snapshot().to_buffer_point(inlay_point);
1749
1750 let mut display_point = self.point_to_display_point(point, Bias::Left);
1751 *display_point.column_mut() = 0;
1752 let next_point = self.display_point_to_point(display_point, Bias::Left);
1753 if next_point == point {
1754 return (point, display_point);
1755 }
1756 point = next_point;
1757 }
1758 }
1759
1760 #[instrument(skip_all)]
1761 pub fn next_line_boundary(
1762 &self,
1763 mut point: MultiBufferPoint,
1764 ) -> (MultiBufferPoint, DisplayPoint) {
1765 let original_point = point;
1766 loop {
1767 let mut inlay_point = self.inlay_snapshot().to_inlay_point(point);
1768 let mut fold_point = self.fold_snapshot().to_fold_point(inlay_point, Bias::Right);
1769 fold_point.0.column = self.fold_snapshot().line_len(fold_point.row());
1770 inlay_point = fold_point.to_inlay_point(self.fold_snapshot());
1771 point = self.inlay_snapshot().to_buffer_point(inlay_point);
1772
1773 let mut display_point = self.point_to_display_point(point, Bias::Right);
1774 *display_point.column_mut() = self.line_len(display_point.row());
1775 let next_point = self.display_point_to_point(display_point, Bias::Right);
1776 if next_point == point || original_point == point || original_point == next_point {
1777 return (point, display_point);
1778 }
1779 point = next_point;
1780 }
1781 }
1782
1783 // used by line_mode selections and tries to match vim behavior
1784 pub fn expand_to_line(&self, range: Range<Point>) -> Range<Point> {
1785 let new_start = MultiBufferPoint::new(range.start.row, 0);
1786 let new_end = if range.end.column > 0 {
1787 MultiBufferPoint::new(
1788 range.end.row,
1789 self.buffer_snapshot()
1790 .line_len(MultiBufferRow(range.end.row)),
1791 )
1792 } else {
1793 range.end
1794 };
1795
1796 new_start..new_end
1797 }
1798
1799 #[instrument(skip_all)]
1800 pub fn point_to_display_point(&self, point: MultiBufferPoint, bias: Bias) -> DisplayPoint {
1801 let inlay_point = self.inlay_snapshot().to_inlay_point(point);
1802 let fold_point = self.fold_snapshot().to_fold_point(inlay_point, bias);
1803 let tab_point = self.tab_snapshot().fold_point_to_tab_point(fold_point);
1804 let wrap_point = self.wrap_snapshot().tab_point_to_wrap_point(tab_point);
1805 let block_point = self.block_snapshot.to_block_point(wrap_point);
1806 DisplayPoint(block_point)
1807 }
1808
1809 pub fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {
1810 self.inlay_snapshot()
1811 .to_buffer_point(self.display_point_to_inlay_point(point, bias))
1812 }
1813
1814 pub fn display_point_to_inlay_offset(&self, point: DisplayPoint, bias: Bias) -> InlayOffset {
1815 self.inlay_snapshot()
1816 .to_offset(self.display_point_to_inlay_point(point, bias))
1817 }
1818
1819 pub fn anchor_to_inlay_offset(&self, anchor: Anchor) -> InlayOffset {
1820 self.inlay_snapshot()
1821 .to_inlay_offset(anchor.to_offset(self.buffer_snapshot()))
1822 }
1823
1824 pub fn display_point_to_anchor(&self, point: DisplayPoint, bias: Bias) -> Anchor {
1825 self.buffer_snapshot()
1826 .anchor_at(point.to_offset(self, bias), bias)
1827 }
1828
1829 #[instrument(skip_all)]
1830 fn display_point_to_inlay_point(&self, point: DisplayPoint, bias: Bias) -> InlayPoint {
1831 let block_point = point.0;
1832 let wrap_point = self.block_snapshot.to_wrap_point(block_point, bias);
1833 let tab_point = self.wrap_snapshot().to_tab_point(wrap_point);
1834 let fold_point = self
1835 .tab_snapshot()
1836 .tab_point_to_fold_point(tab_point, bias)
1837 .0;
1838 fold_point.to_inlay_point(self.fold_snapshot())
1839 }
1840
1841 #[instrument(skip_all)]
1842 pub fn display_point_to_fold_point(&self, point: DisplayPoint, bias: Bias) -> FoldPoint {
1843 let block_point = point.0;
1844 let wrap_point = self.block_snapshot.to_wrap_point(block_point, bias);
1845 let tab_point = self.wrap_snapshot().to_tab_point(wrap_point);
1846 self.tab_snapshot()
1847 .tab_point_to_fold_point(tab_point, bias)
1848 .0
1849 }
1850
1851 #[instrument(skip_all)]
1852 pub fn fold_point_to_display_point(&self, fold_point: FoldPoint) -> DisplayPoint {
1853 let tab_point = self.tab_snapshot().fold_point_to_tab_point(fold_point);
1854 let wrap_point = self.wrap_snapshot().tab_point_to_wrap_point(tab_point);
1855 let block_point = self.block_snapshot.to_block_point(wrap_point);
1856 DisplayPoint(block_point)
1857 }
1858
1859 pub fn max_point(&self) -> DisplayPoint {
1860 DisplayPoint(self.block_snapshot.max_point())
1861 }
1862
1863 /// Returns text chunks starting at the given display row until the end of the file
1864 #[instrument(skip_all)]
1865 pub fn text_chunks(&self, display_row: DisplayRow) -> impl Iterator<Item = &str> {
1866 self.block_snapshot
1867 .chunks(
1868 BlockRow(display_row.0)..BlockRow(self.max_point().row().next_row().0),
1869 false,
1870 self.masked,
1871 Highlights::default(),
1872 )
1873 .map(|h| h.text)
1874 }
1875
1876 /// Returns text chunks starting at the end of the given display row in reverse until the start of the file
1877 #[instrument(skip_all)]
1878 pub fn reverse_text_chunks(&self, display_row: DisplayRow) -> impl Iterator<Item = &str> {
1879 (0..=display_row.0).rev().flat_map(move |row| {
1880 self.block_snapshot
1881 .chunks(
1882 BlockRow(row)..BlockRow(row + 1),
1883 false,
1884 self.masked,
1885 Highlights::default(),
1886 )
1887 .map(|h| h.text)
1888 .collect::<Vec<_>>()
1889 .into_iter()
1890 .rev()
1891 })
1892 }
1893
1894 #[instrument(skip_all)]
1895 pub fn chunks(
1896 &self,
1897 display_rows: Range<DisplayRow>,
1898 language_aware: bool,
1899 highlight_styles: HighlightStyles,
1900 ) -> DisplayChunks<'_> {
1901 self.block_snapshot.chunks(
1902 BlockRow(display_rows.start.0)..BlockRow(display_rows.end.0),
1903 language_aware,
1904 self.masked,
1905 Highlights {
1906 text_highlights: Some(&self.text_highlights),
1907 inlay_highlights: Some(&self.inlay_highlights),
1908 styles: highlight_styles,
1909 },
1910 )
1911 }
1912
1913 #[instrument(skip_all)]
1914 pub fn highlighted_chunks<'a>(
1915 &'a self,
1916 display_rows: Range<DisplayRow>,
1917 language_aware: bool,
1918 editor_style: &'a EditorStyle,
1919 ) -> impl Iterator<Item = HighlightedChunk<'a>> {
1920 self.chunks(
1921 display_rows,
1922 language_aware,
1923 HighlightStyles {
1924 inlay_hint: Some(editor_style.inlay_hints_style),
1925 edit_prediction: Some(editor_style.edit_prediction_styles),
1926 },
1927 )
1928 .flat_map(|chunk| {
1929 let highlight_style = chunk
1930 .syntax_highlight_id
1931 .and_then(|id| id.style(&editor_style.syntax));
1932
1933 let chunk_highlight = chunk.highlight_style.map(|chunk_highlight| {
1934 HighlightStyle {
1935 // For color inlays, blend the color with the editor background
1936 // if the color has transparency (alpha < 1.0)
1937 color: chunk_highlight.color.map(|color| {
1938 if chunk.is_inlay && !color.is_opaque() {
1939 editor_style.background.blend(color)
1940 } else {
1941 color
1942 }
1943 }),
1944 ..chunk_highlight
1945 }
1946 });
1947
1948 let diagnostic_highlight = chunk
1949 .diagnostic_severity
1950 .filter(|severity| {
1951 self.diagnostics_max_severity
1952 .into_lsp()
1953 .is_some_and(|max_severity| severity <= &max_severity)
1954 })
1955 .map(|severity| HighlightStyle {
1956 fade_out: chunk
1957 .is_unnecessary
1958 .then_some(editor_style.unnecessary_code_fade),
1959 underline: (chunk.underline
1960 && editor_style.show_underlines
1961 && !(chunk.is_unnecessary && severity > lsp::DiagnosticSeverity::WARNING))
1962 .then(|| {
1963 let diagnostic_color =
1964 super::diagnostic_style(severity, &editor_style.status);
1965 UnderlineStyle {
1966 color: Some(diagnostic_color),
1967 thickness: 1.0.into(),
1968 wavy: true,
1969 }
1970 }),
1971 ..Default::default()
1972 });
1973
1974 let style = [highlight_style, chunk_highlight, diagnostic_highlight]
1975 .into_iter()
1976 .flatten()
1977 .reduce(|acc, highlight| acc.highlight(highlight));
1978
1979 HighlightedChunk {
1980 text: chunk.text,
1981 style,
1982 is_tab: chunk.is_tab,
1983 is_inlay: chunk.is_inlay,
1984 replacement: chunk.renderer.map(ChunkReplacement::Renderer),
1985 }
1986 .highlight_invisibles(editor_style)
1987 })
1988 }
1989
1990 #[instrument(skip_all)]
1991 pub fn layout_row(
1992 &self,
1993 display_row: DisplayRow,
1994 TextLayoutDetails {
1995 text_system,
1996 editor_style,
1997 rem_size,
1998 scroll_anchor: _,
1999 visible_rows: _,
2000 vertical_scroll_margin: _,
2001 }: &TextLayoutDetails,
2002 ) -> Arc<LineLayout> {
2003 let mut runs = Vec::new();
2004 let mut line = String::new();
2005
2006 let range = display_row..display_row.next_row();
2007 for chunk in self.highlighted_chunks(range, false, editor_style) {
2008 line.push_str(chunk.text);
2009
2010 let text_style = if let Some(style) = chunk.style {
2011 Cow::Owned(editor_style.text.clone().highlight(style))
2012 } else {
2013 Cow::Borrowed(&editor_style.text)
2014 };
2015
2016 runs.push(text_style.to_run(chunk.text.len()))
2017 }
2018
2019 if line.ends_with('\n') {
2020 line.pop();
2021 if let Some(last_run) = runs.last_mut() {
2022 last_run.len -= 1;
2023 if last_run.len == 0 {
2024 runs.pop();
2025 }
2026 }
2027 }
2028
2029 let font_size = editor_style.text.font_size.to_pixels(*rem_size);
2030 text_system.layout_line(&line, font_size, &runs, None)
2031 }
2032
2033 pub fn x_for_display_point(
2034 &self,
2035 display_point: DisplayPoint,
2036 text_layout_details: &TextLayoutDetails,
2037 ) -> Pixels {
2038 let line = self.layout_row(display_point.row(), text_layout_details);
2039 line.x_for_index(display_point.column() as usize)
2040 }
2041
2042 pub fn display_column_for_x(
2043 &self,
2044 display_row: DisplayRow,
2045 x: Pixels,
2046 details: &TextLayoutDetails,
2047 ) -> u32 {
2048 let layout_line = self.layout_row(display_row, details);
2049 layout_line.closest_index_for_x(x) as u32
2050 }
2051
2052 #[instrument(skip_all)]
2053 pub fn grapheme_at(&self, mut point: DisplayPoint) -> Option<SharedString> {
2054 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
2055 let chars = self
2056 .text_chunks(point.row())
2057 .flat_map(str::chars)
2058 .skip_while({
2059 let mut column = 0;
2060 move |char| {
2061 let at_point = column >= point.column();
2062 column += char.len_utf8() as u32;
2063 !at_point
2064 }
2065 })
2066 .take_while({
2067 let mut prev = false;
2068 move |char| {
2069 let now = char.is_ascii();
2070 let end = char.is_ascii() && (char.is_ascii_whitespace() || prev);
2071 prev = now;
2072 !end
2073 }
2074 });
2075 chars.collect::<String>().graphemes(true).next().map(|s| {
2076 if let Some(invisible) = s.chars().next().filter(|&c| is_invisible(c)) {
2077 replacement(invisible).unwrap_or(s).to_owned().into()
2078 } else if s == "\n" {
2079 " ".into()
2080 } else {
2081 s.to_owned().into()
2082 }
2083 })
2084 }
2085
2086 pub fn buffer_chars_at(
2087 &self,
2088 mut offset: MultiBufferOffset,
2089 ) -> impl Iterator<Item = (char, MultiBufferOffset)> + '_ {
2090 self.buffer_snapshot().chars_at(offset).map(move |ch| {
2091 let ret = (ch, offset);
2092 offset += ch.len_utf8();
2093 ret
2094 })
2095 }
2096
2097 pub fn reverse_buffer_chars_at(
2098 &self,
2099 mut offset: MultiBufferOffset,
2100 ) -> impl Iterator<Item = (char, MultiBufferOffset)> + '_ {
2101 self.buffer_snapshot()
2102 .reversed_chars_at(offset)
2103 .map(move |ch| {
2104 offset -= ch.len_utf8();
2105 (ch, offset)
2106 })
2107 }
2108
2109 pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
2110 let mut clipped = self.block_snapshot.clip_point(point.0, bias);
2111 if self.clip_at_line_ends {
2112 clipped = self.clip_at_line_end(DisplayPoint(clipped)).0
2113 }
2114 DisplayPoint(clipped)
2115 }
2116
2117 pub fn clip_ignoring_line_ends(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
2118 DisplayPoint(self.block_snapshot.clip_point(point.0, bias))
2119 }
2120
2121 pub fn clip_at_line_end(&self, display_point: DisplayPoint) -> DisplayPoint {
2122 let mut point = self.display_point_to_point(display_point, Bias::Left);
2123
2124 if point.column != self.buffer_snapshot().line_len(MultiBufferRow(point.row)) {
2125 return display_point;
2126 }
2127 point.column = point.column.saturating_sub(1);
2128 point = self.buffer_snapshot().clip_point(point, Bias::Left);
2129 self.point_to_display_point(point, Bias::Left)
2130 }
2131
2132 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Fold>
2133 where
2134 T: ToOffset,
2135 {
2136 self.fold_snapshot().folds_in_range(range)
2137 }
2138
2139 pub fn blocks_in_range(
2140 &self,
2141 rows: Range<DisplayRow>,
2142 ) -> impl Iterator<Item = (DisplayRow, &Block)> {
2143 self.block_snapshot
2144 .blocks_in_range(BlockRow(rows.start.0)..BlockRow(rows.end.0))
2145 .map(|(row, block)| (DisplayRow(row.0), block))
2146 }
2147
2148 pub fn sticky_header_excerpt(&self, row: f64) -> Option<StickyHeaderExcerpt<'_>> {
2149 self.block_snapshot.sticky_header_excerpt(row)
2150 }
2151
2152 pub fn block_for_id(&self, id: BlockId) -> Option<Block> {
2153 self.block_snapshot.block_for_id(id)
2154 }
2155
2156 pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
2157 self.fold_snapshot().intersects_fold(offset)
2158 }
2159
2160 pub fn is_line_folded(&self, buffer_row: MultiBufferRow) -> bool {
2161 self.block_snapshot.is_line_replaced(buffer_row)
2162 || self.fold_snapshot().is_line_folded(buffer_row)
2163 }
2164
2165 pub fn is_block_line(&self, display_row: DisplayRow) -> bool {
2166 self.block_snapshot.is_block_line(BlockRow(display_row.0))
2167 }
2168
2169 pub fn is_folded_buffer_header(&self, display_row: DisplayRow) -> bool {
2170 self.block_snapshot
2171 .is_folded_buffer_header(BlockRow(display_row.0))
2172 }
2173
2174 pub fn soft_wrap_indent(&self, display_row: DisplayRow) -> Option<u32> {
2175 let wrap_row = self
2176 .block_snapshot
2177 .to_wrap_point(BlockPoint::new(BlockRow(display_row.0), 0), Bias::Left)
2178 .row();
2179 self.wrap_snapshot().soft_wrap_indent(wrap_row)
2180 }
2181
2182 pub fn text(&self) -> String {
2183 self.text_chunks(DisplayRow(0)).collect()
2184 }
2185
2186 pub fn line(&self, display_row: DisplayRow) -> String {
2187 let mut result = String::new();
2188 for chunk in self.text_chunks(display_row) {
2189 if let Some(ix) = chunk.find('\n') {
2190 result.push_str(&chunk[0..ix]);
2191 break;
2192 } else {
2193 result.push_str(chunk);
2194 }
2195 }
2196 result
2197 }
2198
2199 pub fn line_indent_for_buffer_row(&self, buffer_row: MultiBufferRow) -> LineIndent {
2200 self.buffer_snapshot().line_indent_for_row(buffer_row)
2201 }
2202
2203 pub fn line_len(&self, row: DisplayRow) -> u32 {
2204 self.block_snapshot.line_len(BlockRow(row.0))
2205 }
2206
2207 pub fn longest_row(&self) -> DisplayRow {
2208 DisplayRow(self.block_snapshot.longest_row().0)
2209 }
2210
2211 pub fn longest_row_in_range(&self, range: Range<DisplayRow>) -> DisplayRow {
2212 let block_range = BlockRow(range.start.0)..BlockRow(range.end.0);
2213 let longest_row = self.block_snapshot.longest_row_in_range(block_range);
2214 DisplayRow(longest_row.0)
2215 }
2216
2217 pub fn starts_indent(&self, buffer_row: MultiBufferRow) -> bool {
2218 let max_row = self.buffer_snapshot().max_row();
2219 if buffer_row >= max_row {
2220 return false;
2221 }
2222
2223 let line_indent = self.line_indent_for_buffer_row(buffer_row);
2224 if line_indent.is_line_blank() {
2225 return false;
2226 }
2227
2228 (buffer_row.0 + 1..=max_row.0)
2229 .find_map(|next_row| {
2230 let next_line_indent = self.line_indent_for_buffer_row(MultiBufferRow(next_row));
2231 if next_line_indent.raw_len() > line_indent.raw_len() {
2232 Some(true)
2233 } else if !next_line_indent.is_line_blank() {
2234 Some(false)
2235 } else {
2236 None
2237 }
2238 })
2239 .unwrap_or(false)
2240 }
2241
2242 #[instrument(skip_all)]
2243 pub fn crease_for_buffer_row(&self, buffer_row: MultiBufferRow) -> Option<Crease<Point>> {
2244 let start =
2245 MultiBufferPoint::new(buffer_row.0, self.buffer_snapshot().line_len(buffer_row));
2246 if let Some(crease) = self
2247 .crease_snapshot
2248 .query_row(buffer_row, self.buffer_snapshot())
2249 {
2250 match crease {
2251 Crease::Inline {
2252 range,
2253 placeholder,
2254 render_toggle,
2255 render_trailer,
2256 metadata,
2257 } => Some(Crease::Inline {
2258 range: range.to_point(self.buffer_snapshot()),
2259 placeholder: placeholder.clone(),
2260 render_toggle: render_toggle.clone(),
2261 render_trailer: render_trailer.clone(),
2262 metadata: metadata.clone(),
2263 }),
2264 Crease::Block {
2265 range,
2266 block_height,
2267 block_style,
2268 render_block,
2269 block_priority,
2270 render_toggle,
2271 } => Some(Crease::Block {
2272 range: range.to_point(self.buffer_snapshot()),
2273 block_height: *block_height,
2274 block_style: *block_style,
2275 render_block: render_block.clone(),
2276 block_priority: *block_priority,
2277 render_toggle: render_toggle.clone(),
2278 }),
2279 }
2280 } else if self.starts_indent(MultiBufferRow(start.row))
2281 && !self.is_line_folded(MultiBufferRow(start.row))
2282 {
2283 let start_line_indent = self.line_indent_for_buffer_row(buffer_row);
2284 let max_point = self.buffer_snapshot().max_point();
2285 let mut end = None;
2286
2287 for row in (buffer_row.0 + 1)..=max_point.row {
2288 let line_indent = self.line_indent_for_buffer_row(MultiBufferRow(row));
2289 if !line_indent.is_line_blank()
2290 && line_indent.raw_len() <= start_line_indent.raw_len()
2291 {
2292 let prev_row = row - 1;
2293 end = Some(Point::new(
2294 prev_row,
2295 self.buffer_snapshot().line_len(MultiBufferRow(prev_row)),
2296 ));
2297 break;
2298 }
2299 }
2300
2301 let mut row_before_line_breaks = end.unwrap_or(max_point);
2302 while row_before_line_breaks.row > start.row
2303 && self
2304 .buffer_snapshot()
2305 .is_line_blank(MultiBufferRow(row_before_line_breaks.row))
2306 {
2307 row_before_line_breaks.row -= 1;
2308 }
2309
2310 row_before_line_breaks = Point::new(
2311 row_before_line_breaks.row,
2312 self.buffer_snapshot()
2313 .line_len(MultiBufferRow(row_before_line_breaks.row)),
2314 );
2315
2316 Some(Crease::Inline {
2317 range: start..row_before_line_breaks,
2318 placeholder: self.fold_placeholder.clone(),
2319 render_toggle: None,
2320 render_trailer: None,
2321 metadata: None,
2322 })
2323 } else {
2324 None
2325 }
2326 }
2327
2328 #[cfg(any(test, feature = "test-support"))]
2329 #[instrument(skip_all)]
2330 pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
2331 &self,
2332 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
2333 let type_id = TypeId::of::<Tag>();
2334 self.text_highlights
2335 .get(&HighlightKey::Type(type_id))
2336 .cloned()
2337 }
2338
2339 #[cfg(any(test, feature = "test-support"))]
2340 #[instrument(skip_all)]
2341 pub fn all_text_highlight_ranges<Tag: ?Sized + 'static>(
2342 &self,
2343 ) -> Vec<(gpui::Hsla, Range<Point>)> {
2344 use itertools::Itertools;
2345
2346 let required_type_id = TypeId::of::<Tag>();
2347 self.text_highlights
2348 .iter()
2349 .filter(|(key, _)| match key {
2350 HighlightKey::Type(type_id) => type_id == &required_type_id,
2351 HighlightKey::TypePlus(type_id, _) => type_id == &required_type_id,
2352 })
2353 .map(|(_, value)| value.clone())
2354 .flat_map(|ranges| {
2355 ranges
2356 .1
2357 .iter()
2358 .flat_map(|range| {
2359 Some((ranges.0.color?, range.to_point(self.buffer_snapshot())))
2360 })
2361 .collect::<Vec<_>>()
2362 })
2363 .sorted_by_key(|(_, range)| range.start)
2364 .collect()
2365 }
2366
2367 #[allow(unused)]
2368 #[cfg(any(test, feature = "test-support"))]
2369 pub(crate) fn inlay_highlights<Tag: ?Sized + 'static>(
2370 &self,
2371 ) -> Option<&TreeMap<InlayId, (HighlightStyle, InlayHighlight)>> {
2372 let type_id = TypeId::of::<Tag>();
2373 self.inlay_highlights.get(&type_id)
2374 }
2375
2376 pub fn buffer_header_height(&self) -> u32 {
2377 self.block_snapshot.buffer_header_height
2378 }
2379
2380 pub fn excerpt_header_height(&self) -> u32 {
2381 self.block_snapshot.excerpt_header_height
2382 }
2383
2384 /// Given a `DisplayPoint`, returns another `DisplayPoint` corresponding to
2385 /// the start of the buffer row that is a given number of buffer rows away
2386 /// from the provided point.
2387 ///
2388 /// This moves by buffer rows instead of display rows, a distinction that is
2389 /// important when soft wrapping is enabled.
2390 #[instrument(skip_all)]
2391 pub fn start_of_relative_buffer_row(&self, point: DisplayPoint, times: isize) -> DisplayPoint {
2392 let start = self.display_point_to_fold_point(point, Bias::Left);
2393 let target = start.row() as isize + times;
2394 let new_row = (target.max(0) as u32).min(self.fold_snapshot().max_point().row());
2395
2396 self.clip_point(
2397 self.fold_point_to_display_point(
2398 self.fold_snapshot()
2399 .clip_point(FoldPoint::new(new_row, 0), Bias::Right),
2400 ),
2401 Bias::Right,
2402 )
2403 }
2404}
2405
2406impl std::ops::Deref for DisplaySnapshot {
2407 type Target = BlockSnapshot;
2408
2409 fn deref(&self) -> &Self::Target {
2410 &self.block_snapshot
2411 }
2412}
2413
2414/// A zero-indexed point in a text buffer consisting of a row and column adjusted for inserted blocks.
2415#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
2416pub struct DisplayPoint(BlockPoint);
2417
2418impl Debug for DisplayPoint {
2419 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2420 f.write_fmt(format_args!(
2421 "DisplayPoint({}, {})",
2422 self.row().0,
2423 self.column()
2424 ))
2425 }
2426}
2427
2428impl Add for DisplayPoint {
2429 type Output = Self;
2430
2431 fn add(self, other: Self) -> Self::Output {
2432 DisplayPoint(BlockPoint(self.0.0 + other.0.0))
2433 }
2434}
2435
2436impl Sub for DisplayPoint {
2437 type Output = Self;
2438
2439 fn sub(self, other: Self) -> Self::Output {
2440 DisplayPoint(BlockPoint(self.0.0 - other.0.0))
2441 }
2442}
2443
2444#[derive(Debug, Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq, Deserialize, Hash)]
2445#[serde(transparent)]
2446pub struct DisplayRow(pub u32);
2447
2448impl DisplayRow {
2449 pub(crate) fn as_display_point(&self) -> DisplayPoint {
2450 DisplayPoint::new(*self, 0)
2451 }
2452}
2453
2454impl Add<DisplayRow> for DisplayRow {
2455 type Output = Self;
2456
2457 fn add(self, other: Self) -> Self::Output {
2458 DisplayRow(self.0 + other.0)
2459 }
2460}
2461
2462impl Add<u32> for DisplayRow {
2463 type Output = Self;
2464
2465 fn add(self, other: u32) -> Self::Output {
2466 DisplayRow(self.0 + other)
2467 }
2468}
2469
2470impl Sub<DisplayRow> for DisplayRow {
2471 type Output = Self;
2472
2473 fn sub(self, other: Self) -> Self::Output {
2474 DisplayRow(self.0 - other.0)
2475 }
2476}
2477
2478impl Sub<u32> for DisplayRow {
2479 type Output = Self;
2480
2481 fn sub(self, other: u32) -> Self::Output {
2482 DisplayRow(self.0 - other)
2483 }
2484}
2485
2486impl DisplayPoint {
2487 pub fn new(row: DisplayRow, column: u32) -> Self {
2488 Self(BlockPoint(Point::new(row.0, column)))
2489 }
2490
2491 pub fn zero() -> Self {
2492 Self::new(DisplayRow(0), 0)
2493 }
2494
2495 pub fn is_zero(&self) -> bool {
2496 self.0.is_zero()
2497 }
2498
2499 pub fn row(self) -> DisplayRow {
2500 DisplayRow(self.0.row)
2501 }
2502
2503 pub fn column(self) -> u32 {
2504 self.0.column
2505 }
2506
2507 pub fn row_mut(&mut self) -> &mut u32 {
2508 &mut self.0.row
2509 }
2510
2511 pub fn column_mut(&mut self) -> &mut u32 {
2512 &mut self.0.column
2513 }
2514
2515 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
2516 map.display_point_to_point(self, Bias::Left)
2517 }
2518
2519 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> MultiBufferOffset {
2520 let wrap_point = map.block_snapshot.to_wrap_point(self.0, bias);
2521 let tab_point = map.wrap_snapshot().to_tab_point(wrap_point);
2522 let fold_point = map
2523 .tab_snapshot()
2524 .tab_point_to_fold_point(tab_point, bias)
2525 .0;
2526 let inlay_point = fold_point.to_inlay_point(map.fold_snapshot());
2527 map.inlay_snapshot()
2528 .to_buffer_offset(map.inlay_snapshot().to_offset(inlay_point))
2529 }
2530}
2531
2532impl ToDisplayPoint for MultiBufferOffset {
2533 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
2534 map.point_to_display_point(self.to_point(map.buffer_snapshot()), Bias::Left)
2535 }
2536}
2537
2538impl ToDisplayPoint for MultiBufferOffsetUtf16 {
2539 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
2540 self.to_offset(map.buffer_snapshot()).to_display_point(map)
2541 }
2542}
2543
2544impl ToDisplayPoint for Point {
2545 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
2546 map.point_to_display_point(*self, Bias::Left)
2547 }
2548}
2549
2550impl ToDisplayPoint for Anchor {
2551 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
2552 self.to_point(map.buffer_snapshot()).to_display_point(map)
2553 }
2554}
2555
2556#[cfg(test)]
2557pub mod tests {
2558 use super::*;
2559 use crate::{
2560 movement,
2561 test::{marked_display_snapshot, test_font},
2562 };
2563 use Bias::*;
2564 use block_map::BlockPlacement;
2565 use gpui::{
2566 App, AppContext as _, BorrowAppContext, Element, Hsla, Rgba, div, font, observe, px,
2567 };
2568 use language::{
2569 Buffer, Diagnostic, DiagnosticEntry, DiagnosticSet, Language, LanguageConfig,
2570 LanguageMatcher,
2571 };
2572 use lsp::LanguageServerId;
2573
2574 use rand::{Rng, prelude::*};
2575 use settings::{SettingsContent, SettingsStore};
2576 use smol::stream::StreamExt;
2577 use std::{env, sync::Arc};
2578 use text::PointUtf16;
2579 use theme::{LoadThemes, SyntaxTheme};
2580 use unindent::Unindent as _;
2581 use util::test::{marked_text_ranges, sample_text};
2582
2583 #[gpui::test(iterations = 100)]
2584 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
2585 cx.background_executor.set_block_on_ticks(0..=50);
2586 let operations = env::var("OPERATIONS")
2587 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2588 .unwrap_or(10);
2589
2590 let mut tab_size = rng.random_range(1..=4);
2591 let buffer_start_excerpt_header_height = rng.random_range(1..=5);
2592 let excerpt_header_height = rng.random_range(1..=5);
2593 let font_size = px(14.0);
2594 let max_wrap_width = 300.0;
2595 let mut wrap_width = if rng.random_bool(0.1) {
2596 None
2597 } else {
2598 Some(px(rng.random_range(0.0..=max_wrap_width)))
2599 };
2600
2601 log::info!("tab size: {}", tab_size);
2602 log::info!("wrap width: {:?}", wrap_width);
2603
2604 cx.update(|cx| {
2605 init_test(cx, |s| {
2606 s.project.all_languages.defaults.tab_size = NonZeroU32::new(tab_size)
2607 });
2608 });
2609
2610 let buffer = cx.update(|cx| {
2611 if rng.random() {
2612 let len = rng.random_range(0..10);
2613 let text = util::RandomCharIter::new(&mut rng)
2614 .take(len)
2615 .collect::<String>();
2616 MultiBuffer::build_simple(&text, cx)
2617 } else {
2618 MultiBuffer::build_random(&mut rng, cx)
2619 }
2620 });
2621
2622 let font = test_font();
2623 let map = cx.new(|cx| {
2624 DisplayMap::new(
2625 buffer.clone(),
2626 font,
2627 font_size,
2628 wrap_width,
2629 buffer_start_excerpt_header_height,
2630 excerpt_header_height,
2631 FoldPlaceholder::test(),
2632 DiagnosticSeverity::Warning,
2633 cx,
2634 )
2635 });
2636 let mut notifications = observe(&map, cx);
2637 let mut fold_count = 0;
2638 let mut blocks = Vec::new();
2639
2640 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2641 log::info!("buffer text: {:?}", snapshot.buffer_snapshot().text());
2642 log::info!("fold text: {:?}", snapshot.fold_snapshot().text());
2643 log::info!("tab text: {:?}", snapshot.tab_snapshot().text());
2644 log::info!("wrap text: {:?}", snapshot.wrap_snapshot().text());
2645 log::info!("block text: {:?}", snapshot.block_snapshot.text());
2646 log::info!("display text: {:?}", snapshot.text());
2647
2648 for _i in 0..operations {
2649 match rng.random_range(0..100) {
2650 0..=19 => {
2651 wrap_width = if rng.random_bool(0.2) {
2652 None
2653 } else {
2654 Some(px(rng.random_range(0.0..=max_wrap_width)))
2655 };
2656 log::info!("setting wrap width to {:?}", wrap_width);
2657 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
2658 }
2659 20..=29 => {
2660 let mut tab_sizes = vec![1, 2, 3, 4];
2661 tab_sizes.remove((tab_size - 1) as usize);
2662 tab_size = *tab_sizes.choose(&mut rng).unwrap();
2663 log::info!("setting tab size to {:?}", tab_size);
2664 cx.update(|cx| {
2665 cx.update_global::<SettingsStore, _>(|store, cx| {
2666 store.update_user_settings(cx, |s| {
2667 s.project.all_languages.defaults.tab_size =
2668 NonZeroU32::new(tab_size);
2669 });
2670 });
2671 });
2672 }
2673 30..=44 => {
2674 map.update(cx, |map, cx| {
2675 if rng.random() || blocks.is_empty() {
2676 let snapshot = map.snapshot(cx);
2677 let buffer = snapshot.buffer_snapshot();
2678 let block_properties = (0..rng.random_range(1..=1))
2679 .map(|_| {
2680 let position = buffer.anchor_after(buffer.clip_offset(
2681 rng.random_range(MultiBufferOffset(0)..=buffer.len()),
2682 Bias::Left,
2683 ));
2684
2685 let placement = if rng.random() {
2686 BlockPlacement::Above(position)
2687 } else {
2688 BlockPlacement::Below(position)
2689 };
2690 let height = rng.random_range(1..5);
2691 log::info!(
2692 "inserting block {:?} with height {}",
2693 placement.as_ref().map(|p| p.to_point(&buffer)),
2694 height
2695 );
2696 let priority = rng.random_range(1..100);
2697 BlockProperties {
2698 placement,
2699 style: BlockStyle::Fixed,
2700 height: Some(height),
2701 render: Arc::new(|_| div().into_any()),
2702 priority,
2703 }
2704 })
2705 .collect::<Vec<_>>();
2706 blocks.extend(map.insert_blocks(block_properties, cx));
2707 } else {
2708 blocks.shuffle(&mut rng);
2709 let remove_count = rng.random_range(1..=4.min(blocks.len()));
2710 let block_ids_to_remove = (0..remove_count)
2711 .map(|_| blocks.remove(rng.random_range(0..blocks.len())))
2712 .collect();
2713 log::info!("removing block ids {:?}", block_ids_to_remove);
2714 map.remove_blocks(block_ids_to_remove, cx);
2715 }
2716 });
2717 }
2718 45..=79 => {
2719 let mut ranges = Vec::new();
2720 for _ in 0..rng.random_range(1..=3) {
2721 buffer.read_with(cx, |buffer, cx| {
2722 let buffer = buffer.read(cx);
2723 let end = buffer.clip_offset(
2724 rng.random_range(MultiBufferOffset(0)..=buffer.len()),
2725 Right,
2726 );
2727 let start = buffer
2728 .clip_offset(rng.random_range(MultiBufferOffset(0)..=end), Left);
2729 ranges.push(start..end);
2730 });
2731 }
2732
2733 if rng.random() && fold_count > 0 {
2734 log::info!("unfolding ranges: {:?}", ranges);
2735 map.update(cx, |map, cx| {
2736 map.unfold_intersecting(ranges, true, cx);
2737 });
2738 } else {
2739 log::info!("folding ranges: {:?}", ranges);
2740 map.update(cx, |map, cx| {
2741 map.fold(
2742 ranges
2743 .into_iter()
2744 .map(|range| Crease::simple(range, FoldPlaceholder::test()))
2745 .collect(),
2746 cx,
2747 );
2748 });
2749 }
2750 }
2751 _ => {
2752 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
2753 }
2754 }
2755
2756 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
2757 notifications.next().await.unwrap();
2758 }
2759
2760 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2761 fold_count = snapshot.fold_count();
2762 log::info!("buffer text: {:?}", snapshot.buffer_snapshot().text());
2763 log::info!("fold text: {:?}", snapshot.fold_snapshot().text());
2764 log::info!("tab text: {:?}", snapshot.tab_snapshot().text());
2765 log::info!("wrap text: {:?}", snapshot.wrap_snapshot().text());
2766 log::info!("block text: {:?}", snapshot.block_snapshot.text());
2767 log::info!("display text: {:?}", snapshot.text());
2768
2769 // Line boundaries
2770 let buffer = snapshot.buffer_snapshot();
2771 for _ in 0..5 {
2772 let row = rng.random_range(0..=buffer.max_point().row);
2773 let column = rng.random_range(0..=buffer.line_len(MultiBufferRow(row)));
2774 let point = buffer.clip_point(Point::new(row, column), Left);
2775
2776 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
2777 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
2778
2779 assert!(prev_buffer_bound <= point);
2780 assert!(next_buffer_bound >= point);
2781 assert_eq!(prev_buffer_bound.column, 0);
2782 assert_eq!(prev_display_bound.column(), 0);
2783 if next_buffer_bound < buffer.max_point() {
2784 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
2785 }
2786
2787 assert_eq!(
2788 prev_display_bound,
2789 prev_buffer_bound.to_display_point(&snapshot),
2790 "row boundary before {:?}. reported buffer row boundary: {:?}",
2791 point,
2792 prev_buffer_bound
2793 );
2794 assert_eq!(
2795 next_display_bound,
2796 next_buffer_bound.to_display_point(&snapshot),
2797 "display row boundary after {:?}. reported buffer row boundary: {:?}",
2798 point,
2799 next_buffer_bound
2800 );
2801 assert_eq!(
2802 prev_buffer_bound,
2803 prev_display_bound.to_point(&snapshot),
2804 "row boundary before {:?}. reported display row boundary: {:?}",
2805 point,
2806 prev_display_bound
2807 );
2808 assert_eq!(
2809 next_buffer_bound,
2810 next_display_bound.to_point(&snapshot),
2811 "row boundary after {:?}. reported display row boundary: {:?}",
2812 point,
2813 next_display_bound
2814 );
2815 }
2816
2817 // Movement
2818 let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
2819 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
2820 for _ in 0..5 {
2821 let row = rng.random_range(0..=snapshot.max_point().row().0);
2822 let column = rng.random_range(0..=snapshot.line_len(DisplayRow(row)));
2823 let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
2824
2825 log::info!("Moving from point {:?}", point);
2826
2827 let moved_right = movement::right(&snapshot, point);
2828 log::info!("Right {:?}", moved_right);
2829 if point < max_point {
2830 assert!(moved_right > point);
2831 if point.column() == snapshot.line_len(point.row())
2832 || snapshot.soft_wrap_indent(point.row()).is_some()
2833 && point.column() == snapshot.line_len(point.row()) - 1
2834 {
2835 assert!(moved_right.row() > point.row());
2836 }
2837 } else {
2838 assert_eq!(moved_right, point);
2839 }
2840
2841 let moved_left = movement::left(&snapshot, point);
2842 log::info!("Left {:?}", moved_left);
2843 if point > min_point {
2844 assert!(moved_left < point);
2845 if point.column() == 0 {
2846 assert!(moved_left.row() < point.row());
2847 }
2848 } else {
2849 assert_eq!(moved_left, point);
2850 }
2851 }
2852 }
2853 }
2854
2855 #[gpui::test(retries = 5)]
2856 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
2857 cx.background_executor
2858 .set_block_on_ticks(usize::MAX..=usize::MAX);
2859 cx.update(|cx| {
2860 init_test(cx, |_| {});
2861 });
2862
2863 let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
2864 let editor = cx.editor.clone();
2865 let window = cx.window;
2866
2867 _ = cx.update_window(window, |_, window, cx| {
2868 let text_layout_details =
2869 editor.update(cx, |editor, cx| editor.text_layout_details(window, cx));
2870
2871 let font_size = px(12.0);
2872 let wrap_width = Some(px(96.));
2873
2874 let text = "one two three four five\nsix seven eight";
2875 let buffer = MultiBuffer::build_simple(text, cx);
2876 let map = cx.new(|cx| {
2877 DisplayMap::new(
2878 buffer.clone(),
2879 font("Helvetica"),
2880 font_size,
2881 wrap_width,
2882 1,
2883 1,
2884 FoldPlaceholder::test(),
2885 DiagnosticSeverity::Warning,
2886 cx,
2887 )
2888 });
2889
2890 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2891 assert_eq!(
2892 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
2893 "one two \nthree four \nfive\nsix seven \neight"
2894 );
2895 assert_eq!(
2896 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
2897 DisplayPoint::new(DisplayRow(0), 7)
2898 );
2899 assert_eq!(
2900 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
2901 DisplayPoint::new(DisplayRow(1), 0)
2902 );
2903 assert_eq!(
2904 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
2905 DisplayPoint::new(DisplayRow(1), 0)
2906 );
2907 assert_eq!(
2908 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
2909 DisplayPoint::new(DisplayRow(0), 7)
2910 );
2911
2912 let x = snapshot
2913 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
2914 assert_eq!(
2915 movement::up(
2916 &snapshot,
2917 DisplayPoint::new(DisplayRow(1), 10),
2918 language::SelectionGoal::None,
2919 false,
2920 &text_layout_details,
2921 ),
2922 (
2923 DisplayPoint::new(DisplayRow(0), 7),
2924 language::SelectionGoal::HorizontalPosition(f64::from(x))
2925 )
2926 );
2927 assert_eq!(
2928 movement::down(
2929 &snapshot,
2930 DisplayPoint::new(DisplayRow(0), 7),
2931 language::SelectionGoal::HorizontalPosition(f64::from(x)),
2932 false,
2933 &text_layout_details
2934 ),
2935 (
2936 DisplayPoint::new(DisplayRow(1), 10),
2937 language::SelectionGoal::HorizontalPosition(f64::from(x))
2938 )
2939 );
2940 assert_eq!(
2941 movement::down(
2942 &snapshot,
2943 DisplayPoint::new(DisplayRow(1), 10),
2944 language::SelectionGoal::HorizontalPosition(f64::from(x)),
2945 false,
2946 &text_layout_details
2947 ),
2948 (
2949 DisplayPoint::new(DisplayRow(2), 4),
2950 language::SelectionGoal::HorizontalPosition(f64::from(x))
2951 )
2952 );
2953
2954 let ix = MultiBufferOffset(snapshot.buffer_snapshot().text().find("seven").unwrap());
2955 buffer.update(cx, |buffer, cx| {
2956 buffer.edit([(ix..ix, "and ")], None, cx);
2957 });
2958
2959 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2960 assert_eq!(
2961 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
2962 "three four \nfive\nsix and \nseven eight"
2963 );
2964
2965 // Re-wrap on font size changes
2966 map.update(cx, |map, cx| {
2967 map.set_font(font("Helvetica"), font_size + Pixels::from(3.), cx)
2968 });
2969
2970 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2971 assert_eq!(
2972 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
2973 "three \nfour five\nsix and \nseven \neight"
2974 )
2975 });
2976 }
2977
2978 #[gpui::test]
2979 fn test_text_chunks(cx: &mut gpui::App) {
2980 init_test(cx, |_| {});
2981
2982 let text = sample_text(6, 6, 'a');
2983 let buffer = MultiBuffer::build_simple(&text, cx);
2984
2985 let font_size = px(14.0);
2986 let map = cx.new(|cx| {
2987 DisplayMap::new(
2988 buffer.clone(),
2989 font("Helvetica"),
2990 font_size,
2991 None,
2992 1,
2993 1,
2994 FoldPlaceholder::test(),
2995 DiagnosticSeverity::Warning,
2996 cx,
2997 )
2998 });
2999
3000 buffer.update(cx, |buffer, cx| {
3001 buffer.edit(
3002 vec![
3003 (
3004 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
3005 "\t",
3006 ),
3007 (
3008 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
3009 "\t",
3010 ),
3011 (
3012 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
3013 "\t",
3014 ),
3015 ],
3016 None,
3017 cx,
3018 )
3019 });
3020
3021 assert_eq!(
3022 map.update(cx, |map, cx| map.snapshot(cx))
3023 .text_chunks(DisplayRow(1))
3024 .collect::<String>()
3025 .lines()
3026 .next(),
3027 Some(" b bbbbb")
3028 );
3029 assert_eq!(
3030 map.update(cx, |map, cx| map.snapshot(cx))
3031 .text_chunks(DisplayRow(2))
3032 .collect::<String>()
3033 .lines()
3034 .next(),
3035 Some("c ccccc")
3036 );
3037 }
3038
3039 #[gpui::test]
3040 fn test_inlays_with_newlines_after_blocks(cx: &mut gpui::TestAppContext) {
3041 cx.update(|cx| init_test(cx, |_| {}));
3042
3043 let buffer = cx.new(|cx| Buffer::local("a", cx));
3044 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3045 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
3046
3047 let font_size = px(14.0);
3048 let map = cx.new(|cx| {
3049 DisplayMap::new(
3050 buffer.clone(),
3051 font("Helvetica"),
3052 font_size,
3053 None,
3054 1,
3055 1,
3056 FoldPlaceholder::test(),
3057 DiagnosticSeverity::Warning,
3058 cx,
3059 )
3060 });
3061
3062 map.update(cx, |map, cx| {
3063 map.insert_blocks(
3064 [BlockProperties {
3065 placement: BlockPlacement::Above(
3066 buffer_snapshot.anchor_before(Point::new(0, 0)),
3067 ),
3068 height: Some(2),
3069 style: BlockStyle::Sticky,
3070 render: Arc::new(|_| div().into_any()),
3071 priority: 0,
3072 }],
3073 cx,
3074 );
3075 });
3076 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\na"));
3077
3078 map.update(cx, |map, cx| {
3079 map.splice_inlays(
3080 &[],
3081 vec![Inlay::edit_prediction(
3082 0,
3083 buffer_snapshot.anchor_after(MultiBufferOffset(0)),
3084 "\n",
3085 )],
3086 cx,
3087 );
3088 });
3089 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\na"));
3090
3091 // Regression test: updating the display map does not crash when a
3092 // block is immediately followed by a multi-line inlay.
3093 buffer.update(cx, |buffer, cx| {
3094 buffer.edit(
3095 [(MultiBufferOffset(1)..MultiBufferOffset(1), "b")],
3096 None,
3097 cx,
3098 );
3099 });
3100 map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\nab"));
3101 }
3102
3103 #[gpui::test]
3104 async fn test_chunks(cx: &mut gpui::TestAppContext) {
3105 let text = r#"
3106 fn outer() {}
3107
3108 mod module {
3109 fn inner() {}
3110 }"#
3111 .unindent();
3112
3113 let theme =
3114 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
3115 let language = Arc::new(
3116 Language::new(
3117 LanguageConfig {
3118 name: "Test".into(),
3119 matcher: LanguageMatcher {
3120 path_suffixes: vec![".test".to_string()],
3121 ..Default::default()
3122 },
3123 ..Default::default()
3124 },
3125 Some(tree_sitter_rust::LANGUAGE.into()),
3126 )
3127 .with_highlights_query(
3128 r#"
3129 (mod_item name: (identifier) body: _ @mod.body)
3130 (function_item name: (identifier) @fn.name)
3131 "#,
3132 )
3133 .unwrap(),
3134 );
3135 language.set_theme(&theme);
3136
3137 cx.update(|cx| {
3138 init_test(cx, |s| {
3139 s.project.all_languages.defaults.tab_size = Some(2.try_into().unwrap())
3140 })
3141 });
3142
3143 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
3144 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
3145 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3146
3147 let font_size = px(14.0);
3148
3149 let map = cx.new(|cx| {
3150 DisplayMap::new(
3151 buffer,
3152 font("Helvetica"),
3153 font_size,
3154 None,
3155 1,
3156 1,
3157 FoldPlaceholder::test(),
3158 DiagnosticSeverity::Warning,
3159 cx,
3160 )
3161 });
3162 assert_eq!(
3163 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
3164 vec![
3165 ("fn ".to_string(), None),
3166 ("outer".to_string(), Some(Hsla::blue())),
3167 ("() {}\n\nmod module ".to_string(), None),
3168 ("{\n fn ".to_string(), Some(Hsla::red())),
3169 ("inner".to_string(), Some(Hsla::blue())),
3170 ("() {}\n}".to_string(), Some(Hsla::red())),
3171 ]
3172 );
3173 assert_eq!(
3174 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
3175 vec![
3176 (" fn ".to_string(), Some(Hsla::red())),
3177 ("inner".to_string(), Some(Hsla::blue())),
3178 ("() {}\n}".to_string(), Some(Hsla::red())),
3179 ]
3180 );
3181
3182 map.update(cx, |map, cx| {
3183 map.fold(
3184 vec![Crease::simple(
3185 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
3186 FoldPlaceholder::test(),
3187 )],
3188 cx,
3189 )
3190 });
3191 assert_eq!(
3192 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
3193 vec![
3194 ("fn ".to_string(), None),
3195 ("out".to_string(), Some(Hsla::blue())),
3196 ("⋯".to_string(), None),
3197 (" fn ".to_string(), Some(Hsla::red())),
3198 ("inner".to_string(), Some(Hsla::blue())),
3199 ("() {}\n}".to_string(), Some(Hsla::red())),
3200 ]
3201 );
3202 }
3203
3204 #[gpui::test]
3205 async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
3206 cx.background_executor
3207 .set_block_on_ticks(usize::MAX..=usize::MAX);
3208
3209 let text = r#"
3210 const A: &str = "
3211 one
3212 two
3213 three
3214 ";
3215 const B: &str = "four";
3216 "#
3217 .unindent();
3218
3219 let theme = SyntaxTheme::new_test(vec![
3220 ("string", Hsla::red()),
3221 ("punctuation", Hsla::blue()),
3222 ("keyword", Hsla::green()),
3223 ]);
3224 let language = Arc::new(
3225 Language::new(
3226 LanguageConfig {
3227 name: "Rust".into(),
3228 ..Default::default()
3229 },
3230 Some(tree_sitter_rust::LANGUAGE.into()),
3231 )
3232 .with_highlights_query(
3233 r#"
3234 (string_literal) @string
3235 "const" @keyword
3236 [":" ";"] @punctuation
3237 "#,
3238 )
3239 .unwrap(),
3240 );
3241 language.set_theme(&theme);
3242
3243 cx.update(|cx| init_test(cx, |_| {}));
3244
3245 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
3246 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
3247 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3248 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
3249
3250 let map = cx.new(|cx| {
3251 DisplayMap::new(
3252 buffer,
3253 font("Courier"),
3254 px(16.0),
3255 None,
3256 1,
3257 1,
3258 FoldPlaceholder::test(),
3259 DiagnosticSeverity::Warning,
3260 cx,
3261 )
3262 });
3263
3264 // Insert two blocks in the middle of a multi-line string literal.
3265 // The second block has zero height.
3266 map.update(cx, |map, cx| {
3267 map.insert_blocks(
3268 [
3269 BlockProperties {
3270 placement: BlockPlacement::Below(
3271 buffer_snapshot.anchor_before(Point::new(1, 0)),
3272 ),
3273 height: Some(1),
3274 style: BlockStyle::Sticky,
3275 render: Arc::new(|_| div().into_any()),
3276 priority: 0,
3277 },
3278 BlockProperties {
3279 placement: BlockPlacement::Below(
3280 buffer_snapshot.anchor_before(Point::new(2, 0)),
3281 ),
3282 height: None,
3283 style: BlockStyle::Sticky,
3284 render: Arc::new(|_| div().into_any()),
3285 priority: 0,
3286 },
3287 ],
3288 cx,
3289 )
3290 });
3291
3292 pretty_assertions::assert_eq!(
3293 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
3294 [
3295 ("const".into(), Some(Hsla::green())),
3296 (" A".into(), None),
3297 (":".into(), Some(Hsla::blue())),
3298 (" &str = ".into(), None),
3299 ("\"\n one\n".into(), Some(Hsla::red())),
3300 ("\n".into(), None),
3301 (" two\n three\n\"".into(), Some(Hsla::red())),
3302 (";".into(), Some(Hsla::blue())),
3303 ("\n".into(), None),
3304 ("const".into(), Some(Hsla::green())),
3305 (" B".into(), None),
3306 (":".into(), Some(Hsla::blue())),
3307 (" &str = ".into(), None),
3308 ("\"four\"".into(), Some(Hsla::red())),
3309 (";".into(), Some(Hsla::blue())),
3310 ("\n".into(), None),
3311 ]
3312 );
3313 }
3314
3315 #[gpui::test]
3316 async fn test_chunks_with_diagnostics_across_blocks(cx: &mut gpui::TestAppContext) {
3317 cx.background_executor
3318 .set_block_on_ticks(usize::MAX..=usize::MAX);
3319
3320 let text = r#"
3321 struct A {
3322 b: usize;
3323 }
3324 const c: usize = 1;
3325 "#
3326 .unindent();
3327
3328 cx.update(|cx| init_test(cx, |_| {}));
3329
3330 let buffer = cx.new(|cx| Buffer::local(text, cx));
3331
3332 buffer.update(cx, |buffer, cx| {
3333 buffer.update_diagnostics(
3334 LanguageServerId(0),
3335 DiagnosticSet::new(
3336 [DiagnosticEntry {
3337 range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
3338 diagnostic: Diagnostic {
3339 severity: lsp::DiagnosticSeverity::ERROR,
3340 group_id: 1,
3341 message: "hi".into(),
3342 ..Default::default()
3343 },
3344 }],
3345 buffer,
3346 ),
3347 cx,
3348 )
3349 });
3350
3351 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3352 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
3353
3354 let map = cx.new(|cx| {
3355 DisplayMap::new(
3356 buffer,
3357 font("Courier"),
3358 px(16.0),
3359 None,
3360 1,
3361 1,
3362 FoldPlaceholder::test(),
3363 DiagnosticSeverity::Warning,
3364 cx,
3365 )
3366 });
3367
3368 let black = gpui::black().to_rgb();
3369 let red = gpui::red().to_rgb();
3370
3371 // Insert a block in the middle of a multi-line diagnostic.
3372 map.update(cx, |map, cx| {
3373 map.highlight_text(
3374 HighlightKey::Type(TypeId::of::<usize>()),
3375 vec![
3376 buffer_snapshot.anchor_before(Point::new(3, 9))
3377 ..buffer_snapshot.anchor_after(Point::new(3, 14)),
3378 buffer_snapshot.anchor_before(Point::new(3, 17))
3379 ..buffer_snapshot.anchor_after(Point::new(3, 18)),
3380 ],
3381 red.into(),
3382 false,
3383 cx,
3384 );
3385 map.insert_blocks(
3386 [BlockProperties {
3387 placement: BlockPlacement::Below(
3388 buffer_snapshot.anchor_before(Point::new(1, 0)),
3389 ),
3390 height: Some(1),
3391 style: BlockStyle::Sticky,
3392 render: Arc::new(|_| div().into_any()),
3393 priority: 0,
3394 }],
3395 cx,
3396 )
3397 });
3398
3399 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
3400 let mut chunks = Vec::<(String, Option<lsp::DiagnosticSeverity>, Rgba)>::new();
3401 for chunk in snapshot.chunks(DisplayRow(0)..DisplayRow(5), true, Default::default()) {
3402 let color = chunk
3403 .highlight_style
3404 .and_then(|style| style.color)
3405 .map_or(black, |color| color.to_rgb());
3406 if let Some((last_chunk, last_severity, last_color)) = chunks.last_mut()
3407 && *last_severity == chunk.diagnostic_severity
3408 && *last_color == color
3409 {
3410 last_chunk.push_str(chunk.text);
3411 continue;
3412 }
3413
3414 chunks.push((chunk.text.to_string(), chunk.diagnostic_severity, color));
3415 }
3416
3417 assert_eq!(
3418 chunks,
3419 [
3420 (
3421 "struct A {\n b: usize;\n".into(),
3422 Some(lsp::DiagnosticSeverity::ERROR),
3423 black
3424 ),
3425 ("\n".into(), None, black),
3426 ("}".into(), Some(lsp::DiagnosticSeverity::ERROR), black),
3427 ("\nconst c: ".into(), None, black),
3428 ("usize".into(), None, red),
3429 (" = ".into(), None, black),
3430 ("1".into(), None, red),
3431 (";\n".into(), None, black),
3432 ]
3433 );
3434 }
3435
3436 #[gpui::test]
3437 async fn test_point_translation_with_replace_blocks(cx: &mut gpui::TestAppContext) {
3438 cx.background_executor
3439 .set_block_on_ticks(usize::MAX..=usize::MAX);
3440
3441 cx.update(|cx| init_test(cx, |_| {}));
3442
3443 let buffer = cx.update(|cx| MultiBuffer::build_simple("abcde\nfghij\nklmno\npqrst", cx));
3444 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
3445 let map = cx.new(|cx| {
3446 DisplayMap::new(
3447 buffer.clone(),
3448 font("Courier"),
3449 px(16.0),
3450 None,
3451 1,
3452 1,
3453 FoldPlaceholder::test(),
3454 DiagnosticSeverity::Warning,
3455 cx,
3456 )
3457 });
3458
3459 let snapshot = map.update(cx, |map, cx| {
3460 map.insert_blocks(
3461 [BlockProperties {
3462 placement: BlockPlacement::Replace(
3463 buffer_snapshot.anchor_before(Point::new(1, 2))
3464 ..=buffer_snapshot.anchor_after(Point::new(2, 3)),
3465 ),
3466 height: Some(4),
3467 style: BlockStyle::Fixed,
3468 render: Arc::new(|_| div().into_any()),
3469 priority: 0,
3470 }],
3471 cx,
3472 );
3473 map.snapshot(cx)
3474 });
3475
3476 assert_eq!(snapshot.text(), "abcde\n\n\n\n\npqrst");
3477
3478 let point_to_display_points = [
3479 (Point::new(1, 0), DisplayPoint::new(DisplayRow(1), 0)),
3480 (Point::new(2, 0), DisplayPoint::new(DisplayRow(1), 0)),
3481 (Point::new(3, 0), DisplayPoint::new(DisplayRow(5), 0)),
3482 ];
3483 for (buffer_point, display_point) in point_to_display_points {
3484 assert_eq!(
3485 snapshot.point_to_display_point(buffer_point, Bias::Left),
3486 display_point,
3487 "point_to_display_point({:?}, Bias::Left)",
3488 buffer_point
3489 );
3490 assert_eq!(
3491 snapshot.point_to_display_point(buffer_point, Bias::Right),
3492 display_point,
3493 "point_to_display_point({:?}, Bias::Right)",
3494 buffer_point
3495 );
3496 }
3497
3498 let display_points_to_points = [
3499 (
3500 DisplayPoint::new(DisplayRow(1), 0),
3501 Point::new(1, 0),
3502 Point::new(2, 5),
3503 ),
3504 (
3505 DisplayPoint::new(DisplayRow(2), 0),
3506 Point::new(1, 0),
3507 Point::new(2, 5),
3508 ),
3509 (
3510 DisplayPoint::new(DisplayRow(3), 0),
3511 Point::new(1, 0),
3512 Point::new(2, 5),
3513 ),
3514 (
3515 DisplayPoint::new(DisplayRow(4), 0),
3516 Point::new(1, 0),
3517 Point::new(2, 5),
3518 ),
3519 (
3520 DisplayPoint::new(DisplayRow(5), 0),
3521 Point::new(3, 0),
3522 Point::new(3, 0),
3523 ),
3524 ];
3525 for (display_point, left_buffer_point, right_buffer_point) in display_points_to_points {
3526 assert_eq!(
3527 snapshot.display_point_to_point(display_point, Bias::Left),
3528 left_buffer_point,
3529 "display_point_to_point({:?}, Bias::Left)",
3530 display_point
3531 );
3532 assert_eq!(
3533 snapshot.display_point_to_point(display_point, Bias::Right),
3534 right_buffer_point,
3535 "display_point_to_point({:?}, Bias::Right)",
3536 display_point
3537 );
3538 }
3539 }
3540
3541 #[gpui::test]
3542 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
3543 cx.background_executor
3544 .set_block_on_ticks(usize::MAX..=usize::MAX);
3545
3546 let text = r#"
3547 fn outer() {}
3548
3549 mod module {
3550 fn inner() {}
3551 }"#
3552 .unindent();
3553
3554 let theme =
3555 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
3556 let language = Arc::new(
3557 Language::new(
3558 LanguageConfig {
3559 name: "Test".into(),
3560 matcher: LanguageMatcher {
3561 path_suffixes: vec![".test".to_string()],
3562 ..Default::default()
3563 },
3564 ..Default::default()
3565 },
3566 Some(tree_sitter_rust::LANGUAGE.into()),
3567 )
3568 .with_highlights_query(
3569 r#"
3570 (mod_item name: (identifier) body: _ @mod.body)
3571 (function_item name: (identifier) @fn.name)
3572 "#,
3573 )
3574 .unwrap(),
3575 );
3576 language.set_theme(&theme);
3577
3578 cx.update(|cx| init_test(cx, |_| {}));
3579
3580 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
3581 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
3582 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3583
3584 let font_size = px(16.0);
3585
3586 let map = cx.new(|cx| {
3587 DisplayMap::new(
3588 buffer,
3589 font("Courier"),
3590 font_size,
3591 Some(px(40.0)),
3592 1,
3593 1,
3594 FoldPlaceholder::test(),
3595 DiagnosticSeverity::Warning,
3596 cx,
3597 )
3598 });
3599 assert_eq!(
3600 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
3601 [
3602 ("fn \n".to_string(), None),
3603 ("oute".to_string(), Some(Hsla::blue())),
3604 ("\n".to_string(), None),
3605 ("r".to_string(), Some(Hsla::blue())),
3606 ("() \n{}\n\n".to_string(), None),
3607 ]
3608 );
3609 assert_eq!(
3610 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
3611 [("{}\n\n".to_string(), None)]
3612 );
3613
3614 map.update(cx, |map, cx| {
3615 map.fold(
3616 vec![Crease::simple(
3617 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
3618 FoldPlaceholder::test(),
3619 )],
3620 cx,
3621 )
3622 });
3623 assert_eq!(
3624 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
3625 [
3626 ("out".to_string(), Some(Hsla::blue())),
3627 ("⋯\n".to_string(), None),
3628 (" ".to_string(), Some(Hsla::red())),
3629 ("\n".to_string(), None),
3630 ("fn ".to_string(), Some(Hsla::red())),
3631 ("i".to_string(), Some(Hsla::blue())),
3632 ("\n".to_string(), None)
3633 ]
3634 );
3635 }
3636
3637 #[gpui::test]
3638 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
3639 cx.update(|cx| init_test(cx, |_| {}));
3640
3641 let theme =
3642 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
3643 let language = Arc::new(
3644 Language::new(
3645 LanguageConfig {
3646 name: "Test".into(),
3647 matcher: LanguageMatcher {
3648 path_suffixes: vec![".test".to_string()],
3649 ..Default::default()
3650 },
3651 ..Default::default()
3652 },
3653 Some(tree_sitter_rust::LANGUAGE.into()),
3654 )
3655 .with_highlights_query(
3656 r#"
3657 ":" @operator
3658 (string_literal) @string
3659 "#,
3660 )
3661 .unwrap(),
3662 );
3663 language.set_theme(&theme);
3664
3665 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»«:» B = "c «d»""#, false);
3666
3667 let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
3668 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
3669
3670 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3671 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
3672
3673 let font_size = px(16.0);
3674 let map = cx.new(|cx| {
3675 DisplayMap::new(
3676 buffer,
3677 font("Courier"),
3678 font_size,
3679 None,
3680 1,
3681 1,
3682 FoldPlaceholder::test(),
3683 DiagnosticSeverity::Warning,
3684 cx,
3685 )
3686 });
3687
3688 enum MyType {}
3689
3690 let style = HighlightStyle {
3691 color: Some(Hsla::blue()),
3692 ..Default::default()
3693 };
3694
3695 map.update(cx, |map, cx| {
3696 map.highlight_text(
3697 HighlightKey::Type(TypeId::of::<MyType>()),
3698 highlighted_ranges
3699 .into_iter()
3700 .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end))
3701 .map(|range| {
3702 buffer_snapshot.anchor_before(range.start)
3703 ..buffer_snapshot.anchor_before(range.end)
3704 })
3705 .collect(),
3706 style,
3707 false,
3708 cx,
3709 );
3710 });
3711
3712 assert_eq!(
3713 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
3714 [
3715 ("const ".to_string(), None, None),
3716 ("a".to_string(), None, Some(Hsla::blue())),
3717 (":".to_string(), Some(Hsla::red()), Some(Hsla::blue())),
3718 (" B = ".to_string(), None, None),
3719 ("\"c ".to_string(), Some(Hsla::green()), None),
3720 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
3721 ("\"".to_string(), Some(Hsla::green()), None),
3722 ]
3723 );
3724 }
3725
3726 #[gpui::test]
3727 fn test_clip_point(cx: &mut gpui::App) {
3728 init_test(cx, |_| {});
3729
3730 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::App) {
3731 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
3732
3733 match bias {
3734 Bias::Left => {
3735 if shift_right {
3736 *markers[1].column_mut() += 1;
3737 }
3738
3739 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
3740 }
3741 Bias::Right => {
3742 if shift_right {
3743 *markers[0].column_mut() += 1;
3744 }
3745
3746 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
3747 }
3748 };
3749 }
3750
3751 use Bias::{Left, Right};
3752 assert("ˇˇα", false, Left, cx);
3753 assert("ˇˇα", true, Left, cx);
3754 assert("ˇˇα", false, Right, cx);
3755 assert("ˇαˇ", true, Right, cx);
3756 assert("ˇˇ✋", false, Left, cx);
3757 assert("ˇˇ✋", true, Left, cx);
3758 assert("ˇˇ✋", false, Right, cx);
3759 assert("ˇ✋ˇ", true, Right, cx);
3760 assert("ˇˇ🍐", false, Left, cx);
3761 assert("ˇˇ🍐", true, Left, cx);
3762 assert("ˇˇ🍐", false, Right, cx);
3763 assert("ˇ🍐ˇ", true, Right, cx);
3764 assert("ˇˇ\t", false, Left, cx);
3765 assert("ˇˇ\t", true, Left, cx);
3766 assert("ˇˇ\t", false, Right, cx);
3767 assert("ˇ\tˇ", true, Right, cx);
3768 assert(" ˇˇ\t", false, Left, cx);
3769 assert(" ˇˇ\t", true, Left, cx);
3770 assert(" ˇˇ\t", false, Right, cx);
3771 assert(" ˇ\tˇ", true, Right, cx);
3772 assert(" ˇˇ\t", false, Left, cx);
3773 assert(" ˇˇ\t", false, Right, cx);
3774 }
3775
3776 #[gpui::test]
3777 fn test_clip_at_line_ends(cx: &mut gpui::App) {
3778 init_test(cx, |_| {});
3779
3780 fn assert(text: &str, cx: &mut gpui::App) {
3781 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
3782 unmarked_snapshot.clip_at_line_ends = true;
3783 assert_eq!(
3784 unmarked_snapshot.clip_point(markers[1], Bias::Left),
3785 markers[0]
3786 );
3787 }
3788
3789 assert("ˇˇ", cx);
3790 assert("ˇaˇ", cx);
3791 assert("aˇbˇ", cx);
3792 assert("aˇαˇ", cx);
3793 }
3794
3795 #[gpui::test]
3796 fn test_creases(cx: &mut gpui::App) {
3797 init_test(cx, |_| {});
3798
3799 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
3800 let buffer = MultiBuffer::build_simple(text, cx);
3801 let font_size = px(14.0);
3802 cx.new(|cx| {
3803 let mut map = DisplayMap::new(
3804 buffer.clone(),
3805 font("Helvetica"),
3806 font_size,
3807 None,
3808 1,
3809 1,
3810 FoldPlaceholder::test(),
3811 DiagnosticSeverity::Warning,
3812 cx,
3813 );
3814 let snapshot = map.buffer.read(cx).snapshot(cx);
3815 let range =
3816 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
3817
3818 map.crease_map.insert(
3819 [Crease::inline(
3820 range,
3821 FoldPlaceholder::test(),
3822 |_row, _status, _toggle, _window, _cx| div(),
3823 |_row, _status, _window, _cx| div(),
3824 )],
3825 &map.buffer.read(cx).snapshot(cx),
3826 );
3827
3828 map
3829 });
3830 }
3831
3832 #[gpui::test]
3833 fn test_tabs_with_multibyte_chars(cx: &mut gpui::App) {
3834 init_test(cx, |_| {});
3835
3836 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
3837 let buffer = MultiBuffer::build_simple(text, cx);
3838 let font_size = px(14.0);
3839
3840 let map = cx.new(|cx| {
3841 DisplayMap::new(
3842 buffer.clone(),
3843 font("Helvetica"),
3844 font_size,
3845 None,
3846 1,
3847 1,
3848 FoldPlaceholder::test(),
3849 DiagnosticSeverity::Warning,
3850 cx,
3851 )
3852 });
3853 let map = map.update(cx, |map, cx| map.snapshot(cx));
3854 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
3855 assert_eq!(
3856 map.text_chunks(DisplayRow(0)).collect::<String>(),
3857 "✅ α\nβ \n🏀β γ"
3858 );
3859 assert_eq!(
3860 map.text_chunks(DisplayRow(1)).collect::<String>(),
3861 "β \n🏀β γ"
3862 );
3863 assert_eq!(
3864 map.text_chunks(DisplayRow(2)).collect::<String>(),
3865 "🏀β γ"
3866 );
3867
3868 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
3869 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
3870 assert_eq!(point.to_display_point(&map), display_point);
3871 assert_eq!(display_point.to_point(&map), point);
3872
3873 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
3874 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
3875 assert_eq!(point.to_display_point(&map), display_point);
3876 assert_eq!(display_point.to_point(&map), point,);
3877
3878 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
3879 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
3880 assert_eq!(point.to_display_point(&map), display_point);
3881 assert_eq!(display_point.to_point(&map), point,);
3882
3883 // Display points inside of expanded tabs
3884 assert_eq!(
3885 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
3886 MultiBufferPoint::new(0, "✅\t".len() as u32),
3887 );
3888 assert_eq!(
3889 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
3890 MultiBufferPoint::new(0, "✅".len() as u32),
3891 );
3892
3893 // Clipping display points inside of multi-byte characters
3894 assert_eq!(
3895 map.clip_point(
3896 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
3897 Left
3898 ),
3899 DisplayPoint::new(DisplayRow(0), 0)
3900 );
3901 assert_eq!(
3902 map.clip_point(
3903 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
3904 Bias::Right
3905 ),
3906 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
3907 );
3908 }
3909
3910 #[gpui::test]
3911 fn test_max_point(cx: &mut gpui::App) {
3912 init_test(cx, |_| {});
3913
3914 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
3915 let font_size = px(14.0);
3916 let map = cx.new(|cx| {
3917 DisplayMap::new(
3918 buffer.clone(),
3919 font("Helvetica"),
3920 font_size,
3921 None,
3922 1,
3923 1,
3924 FoldPlaceholder::test(),
3925 DiagnosticSeverity::Warning,
3926 cx,
3927 )
3928 });
3929 assert_eq!(
3930 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
3931 DisplayPoint::new(DisplayRow(1), 11)
3932 )
3933 }
3934
3935 fn syntax_chunks(
3936 rows: Range<DisplayRow>,
3937 map: &Entity<DisplayMap>,
3938 theme: &SyntaxTheme,
3939 cx: &mut App,
3940 ) -> Vec<(String, Option<Hsla>)> {
3941 chunks(rows, map, theme, cx)
3942 .into_iter()
3943 .map(|(text, color, _)| (text, color))
3944 .collect()
3945 }
3946
3947 fn chunks(
3948 rows: Range<DisplayRow>,
3949 map: &Entity<DisplayMap>,
3950 theme: &SyntaxTheme,
3951 cx: &mut App,
3952 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
3953 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
3954 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
3955 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
3956 let syntax_color = chunk
3957 .syntax_highlight_id
3958 .and_then(|id| id.style(theme)?.color);
3959 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
3960 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut()
3961 && syntax_color == *last_syntax_color
3962 && highlight_color == *last_highlight_color
3963 {
3964 last_chunk.push_str(chunk.text);
3965 continue;
3966 }
3967 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
3968 }
3969 chunks
3970 }
3971
3972 fn init_test(cx: &mut App, f: impl Fn(&mut SettingsContent)) {
3973 let settings = SettingsStore::test(cx);
3974 cx.set_global(settings);
3975 crate::init(cx);
3976 theme::init(LoadThemes::JustBase, cx);
3977 cx.update_global::<SettingsStore, _>(|store, cx| {
3978 store.update_user_settings(cx, f);
3979 });
3980 }
3981}