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