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