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