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