display_map.rs

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