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