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