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