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