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