display_map.rs

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