display_map.rs

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