display_map.rs

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