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