display_map.rs

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