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: f64) -> 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    };
1533    use lsp::LanguageServerId;
1534    use project::Project;
1535    use rand::{Rng, prelude::*};
1536    use settings::{SettingsContent, SettingsStore};
1537    use smol::stream::StreamExt;
1538    use std::{env, sync::Arc};
1539    use text::PointUtf16;
1540    use theme::{LoadThemes, SyntaxTheme};
1541    use unindent::Unindent as _;
1542    use util::test::{marked_text_ranges, sample_text};
1543
1544    #[gpui::test(iterations = 100)]
1545    async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1546        cx.background_executor.set_block_on_ticks(0..=50);
1547        let operations = env::var("OPERATIONS")
1548            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1549            .unwrap_or(10);
1550
1551        let mut tab_size = rng.random_range(1..=4);
1552        let buffer_start_excerpt_header_height = rng.random_range(1..=5);
1553        let excerpt_header_height = rng.random_range(1..=5);
1554        let font_size = px(14.0);
1555        let max_wrap_width = 300.0;
1556        let mut wrap_width = if rng.random_bool(0.1) {
1557            None
1558        } else {
1559            Some(px(rng.random_range(0.0..=max_wrap_width)))
1560        };
1561
1562        log::info!("tab size: {}", tab_size);
1563        log::info!("wrap width: {:?}", wrap_width);
1564
1565        cx.update(|cx| {
1566            init_test(cx, |s| {
1567                s.project.all_languages.defaults.tab_size = NonZeroU32::new(tab_size)
1568            });
1569        });
1570
1571        let buffer = cx.update(|cx| {
1572            if rng.random() {
1573                let len = rng.random_range(0..10);
1574                let text = util::RandomCharIter::new(&mut rng)
1575                    .take(len)
1576                    .collect::<String>();
1577                MultiBuffer::build_simple(&text, cx)
1578            } else {
1579                MultiBuffer::build_random(&mut rng, cx)
1580            }
1581        });
1582
1583        let font = test_font();
1584        let map = cx.new(|cx| {
1585            DisplayMap::new(
1586                buffer.clone(),
1587                font,
1588                font_size,
1589                wrap_width,
1590                buffer_start_excerpt_header_height,
1591                excerpt_header_height,
1592                FoldPlaceholder::test(),
1593                DiagnosticSeverity::Warning,
1594                cx,
1595            )
1596        });
1597        let mut notifications = observe(&map, cx);
1598        let mut fold_count = 0;
1599        let mut blocks = Vec::new();
1600
1601        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1602        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1603        log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1604        log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1605        log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1606        log::info!("block text: {:?}", snapshot.block_snapshot.text());
1607        log::info!("display text: {:?}", snapshot.text());
1608
1609        for _i in 0..operations {
1610            match rng.random_range(0..100) {
1611                0..=19 => {
1612                    wrap_width = if rng.random_bool(0.2) {
1613                        None
1614                    } else {
1615                        Some(px(rng.random_range(0.0..=max_wrap_width)))
1616                    };
1617                    log::info!("setting wrap width to {:?}", wrap_width);
1618                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1619                }
1620                20..=29 => {
1621                    let mut tab_sizes = vec![1, 2, 3, 4];
1622                    tab_sizes.remove((tab_size - 1) as usize);
1623                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
1624                    log::info!("setting tab size to {:?}", tab_size);
1625                    cx.update(|cx| {
1626                        cx.update_global::<SettingsStore, _>(|store, cx| {
1627                            store.update_user_settings(cx, |s| {
1628                                s.project.all_languages.defaults.tab_size =
1629                                    NonZeroU32::new(tab_size);
1630                            });
1631                        });
1632                    });
1633                }
1634                30..=44 => {
1635                    map.update(cx, |map, cx| {
1636                        if rng.random() || blocks.is_empty() {
1637                            let buffer = map.snapshot(cx).buffer_snapshot;
1638                            let block_properties = (0..rng.random_range(1..=1))
1639                                .map(|_| {
1640                                    let position = buffer.anchor_after(buffer.clip_offset(
1641                                        rng.random_range(0..=buffer.len()),
1642                                        Bias::Left,
1643                                    ));
1644
1645                                    let placement = if rng.random() {
1646                                        BlockPlacement::Above(position)
1647                                    } else {
1648                                        BlockPlacement::Below(position)
1649                                    };
1650                                    let height = rng.random_range(1..5);
1651                                    log::info!(
1652                                        "inserting block {:?} with height {}",
1653                                        placement.as_ref().map(|p| p.to_point(&buffer)),
1654                                        height
1655                                    );
1656                                    let priority = rng.random_range(1..100);
1657                                    BlockProperties {
1658                                        placement,
1659                                        style: BlockStyle::Fixed,
1660                                        height: Some(height),
1661                                        render: Arc::new(|_| div().into_any()),
1662                                        priority,
1663                                    }
1664                                })
1665                                .collect::<Vec<_>>();
1666                            blocks.extend(map.insert_blocks(block_properties, cx));
1667                        } else {
1668                            blocks.shuffle(&mut rng);
1669                            let remove_count = rng.random_range(1..=4.min(blocks.len()));
1670                            let block_ids_to_remove = (0..remove_count)
1671                                .map(|_| blocks.remove(rng.random_range(0..blocks.len())))
1672                                .collect();
1673                            log::info!("removing block ids {:?}", block_ids_to_remove);
1674                            map.remove_blocks(block_ids_to_remove, cx);
1675                        }
1676                    });
1677                }
1678                45..=79 => {
1679                    let mut ranges = Vec::new();
1680                    for _ in 0..rng.random_range(1..=3) {
1681                        buffer.read_with(cx, |buffer, cx| {
1682                            let buffer = buffer.read(cx);
1683                            let end = buffer.clip_offset(rng.random_range(0..=buffer.len()), Right);
1684                            let start = buffer.clip_offset(rng.random_range(0..=end), Left);
1685                            ranges.push(start..end);
1686                        });
1687                    }
1688
1689                    if rng.random() && fold_count > 0 {
1690                        log::info!("unfolding ranges: {:?}", ranges);
1691                        map.update(cx, |map, cx| {
1692                            map.unfold_intersecting(ranges, true, cx);
1693                        });
1694                    } else {
1695                        log::info!("folding ranges: {:?}", ranges);
1696                        map.update(cx, |map, cx| {
1697                            map.fold(
1698                                ranges
1699                                    .into_iter()
1700                                    .map(|range| Crease::simple(range, FoldPlaceholder::test()))
1701                                    .collect(),
1702                                cx,
1703                            );
1704                        });
1705                    }
1706                }
1707                _ => {
1708                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1709                }
1710            }
1711
1712            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1713                notifications.next().await.unwrap();
1714            }
1715
1716            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1717            fold_count = snapshot.fold_count();
1718            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1719            log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1720            log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1721            log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1722            log::info!("block text: {:?}", snapshot.block_snapshot.text());
1723            log::info!("display text: {:?}", snapshot.text());
1724
1725            // Line boundaries
1726            let buffer = &snapshot.buffer_snapshot;
1727            for _ in 0..5 {
1728                let row = rng.random_range(0..=buffer.max_point().row);
1729                let column = rng.random_range(0..=buffer.line_len(MultiBufferRow(row)));
1730                let point = buffer.clip_point(Point::new(row, column), Left);
1731
1732                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1733                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1734
1735                assert!(prev_buffer_bound <= point);
1736                assert!(next_buffer_bound >= point);
1737                assert_eq!(prev_buffer_bound.column, 0);
1738                assert_eq!(prev_display_bound.column(), 0);
1739                if next_buffer_bound < buffer.max_point() {
1740                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1741                }
1742
1743                assert_eq!(
1744                    prev_display_bound,
1745                    prev_buffer_bound.to_display_point(&snapshot),
1746                    "row boundary before {:?}. reported buffer row boundary: {:?}",
1747                    point,
1748                    prev_buffer_bound
1749                );
1750                assert_eq!(
1751                    next_display_bound,
1752                    next_buffer_bound.to_display_point(&snapshot),
1753                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
1754                    point,
1755                    next_buffer_bound
1756                );
1757                assert_eq!(
1758                    prev_buffer_bound,
1759                    prev_display_bound.to_point(&snapshot),
1760                    "row boundary before {:?}. reported display row boundary: {:?}",
1761                    point,
1762                    prev_display_bound
1763                );
1764                assert_eq!(
1765                    next_buffer_bound,
1766                    next_display_bound.to_point(&snapshot),
1767                    "row boundary after {:?}. reported display row boundary: {:?}",
1768                    point,
1769                    next_display_bound
1770                );
1771            }
1772
1773            // Movement
1774            let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1775            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1776            for _ in 0..5 {
1777                let row = rng.random_range(0..=snapshot.max_point().row().0);
1778                let column = rng.random_range(0..=snapshot.line_len(DisplayRow(row)));
1779                let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1780
1781                log::info!("Moving from point {:?}", point);
1782
1783                let moved_right = movement::right(&snapshot, point);
1784                log::info!("Right {:?}", moved_right);
1785                if point < max_point {
1786                    assert!(moved_right > point);
1787                    if point.column() == snapshot.line_len(point.row())
1788                        || snapshot.soft_wrap_indent(point.row()).is_some()
1789                            && point.column() == snapshot.line_len(point.row()) - 1
1790                    {
1791                        assert!(moved_right.row() > point.row());
1792                    }
1793                } else {
1794                    assert_eq!(moved_right, point);
1795                }
1796
1797                let moved_left = movement::left(&snapshot, point);
1798                log::info!("Left {:?}", moved_left);
1799                if point > min_point {
1800                    assert!(moved_left < point);
1801                    if point.column() == 0 {
1802                        assert!(moved_left.row() < point.row());
1803                    }
1804                } else {
1805                    assert_eq!(moved_left, point);
1806                }
1807            }
1808        }
1809    }
1810
1811    #[gpui::test(retries = 5)]
1812    async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1813        cx.background_executor
1814            .set_block_on_ticks(usize::MAX..=usize::MAX);
1815        cx.update(|cx| {
1816            init_test(cx, |_| {});
1817        });
1818
1819        let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1820        let editor = cx.editor.clone();
1821        let window = cx.window;
1822
1823        _ = cx.update_window(window, |_, window, cx| {
1824            let text_layout_details =
1825                editor.update(cx, |editor, _cx| editor.text_layout_details(window));
1826
1827            let font_size = px(12.0);
1828            let wrap_width = Some(px(96.));
1829
1830            let text = "one two three four five\nsix seven eight";
1831            let buffer = MultiBuffer::build_simple(text, cx);
1832            let map = cx.new(|cx| {
1833                DisplayMap::new(
1834                    buffer.clone(),
1835                    font("Helvetica"),
1836                    font_size,
1837                    wrap_width,
1838                    1,
1839                    1,
1840                    FoldPlaceholder::test(),
1841                    DiagnosticSeverity::Warning,
1842                    cx,
1843                )
1844            });
1845
1846            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1847            assert_eq!(
1848                snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1849                "one two \nthree four \nfive\nsix seven \neight"
1850            );
1851            assert_eq!(
1852                snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1853                DisplayPoint::new(DisplayRow(0), 7)
1854            );
1855            assert_eq!(
1856                snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1857                DisplayPoint::new(DisplayRow(1), 0)
1858            );
1859            assert_eq!(
1860                movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1861                DisplayPoint::new(DisplayRow(1), 0)
1862            );
1863            assert_eq!(
1864                movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1865                DisplayPoint::new(DisplayRow(0), 7)
1866            );
1867
1868            let x = snapshot
1869                .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1870            assert_eq!(
1871                movement::up(
1872                    &snapshot,
1873                    DisplayPoint::new(DisplayRow(1), 10),
1874                    language::SelectionGoal::None,
1875                    false,
1876                    &text_layout_details,
1877                ),
1878                (
1879                    DisplayPoint::new(DisplayRow(0), 7),
1880                    language::SelectionGoal::HorizontalPosition(f64::from(x))
1881                )
1882            );
1883            assert_eq!(
1884                movement::down(
1885                    &snapshot,
1886                    DisplayPoint::new(DisplayRow(0), 7),
1887                    language::SelectionGoal::HorizontalPosition(f64::from(x)),
1888                    false,
1889                    &text_layout_details
1890                ),
1891                (
1892                    DisplayPoint::new(DisplayRow(1), 10),
1893                    language::SelectionGoal::HorizontalPosition(f64::from(x))
1894                )
1895            );
1896            assert_eq!(
1897                movement::down(
1898                    &snapshot,
1899                    DisplayPoint::new(DisplayRow(1), 10),
1900                    language::SelectionGoal::HorizontalPosition(f64::from(x)),
1901                    false,
1902                    &text_layout_details
1903                ),
1904                (
1905                    DisplayPoint::new(DisplayRow(2), 4),
1906                    language::SelectionGoal::HorizontalPosition(f64::from(x))
1907                )
1908            );
1909
1910            let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1911            buffer.update(cx, |buffer, cx| {
1912                buffer.edit([(ix..ix, "and ")], None, cx);
1913            });
1914
1915            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1916            assert_eq!(
1917                snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1918                "three four \nfive\nsix and \nseven eight"
1919            );
1920
1921            // Re-wrap on font size changes
1922            map.update(cx, |map, cx| {
1923                map.set_font(font("Helvetica"), font_size + Pixels::from(3.), cx)
1924            });
1925
1926            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1927            assert_eq!(
1928                snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1929                "three \nfour five\nsix and \nseven \neight"
1930            )
1931        });
1932    }
1933
1934    #[gpui::test]
1935    fn test_text_chunks(cx: &mut gpui::App) {
1936        init_test(cx, |_| {});
1937
1938        let text = sample_text(6, 6, 'a');
1939        let buffer = MultiBuffer::build_simple(&text, cx);
1940
1941        let font_size = px(14.0);
1942        let map = cx.new(|cx| {
1943            DisplayMap::new(
1944                buffer.clone(),
1945                font("Helvetica"),
1946                font_size,
1947                None,
1948                1,
1949                1,
1950                FoldPlaceholder::test(),
1951                DiagnosticSeverity::Warning,
1952                cx,
1953            )
1954        });
1955
1956        buffer.update(cx, |buffer, cx| {
1957            buffer.edit(
1958                vec![
1959                    (
1960                        MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1961                        "\t",
1962                    ),
1963                    (
1964                        MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1965                        "\t",
1966                    ),
1967                    (
1968                        MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1969                        "\t",
1970                    ),
1971                ],
1972                None,
1973                cx,
1974            )
1975        });
1976
1977        assert_eq!(
1978            map.update(cx, |map, cx| map.snapshot(cx))
1979                .text_chunks(DisplayRow(1))
1980                .collect::<String>()
1981                .lines()
1982                .next(),
1983            Some("    b   bbbbb")
1984        );
1985        assert_eq!(
1986            map.update(cx, |map, cx| map.snapshot(cx))
1987                .text_chunks(DisplayRow(2))
1988                .collect::<String>()
1989                .lines()
1990                .next(),
1991            Some("c   ccccc")
1992        );
1993    }
1994
1995    #[gpui::test]
1996    fn test_inlays_with_newlines_after_blocks(cx: &mut gpui::TestAppContext) {
1997        cx.update(|cx| init_test(cx, |_| {}));
1998
1999        let buffer = cx.new(|cx| Buffer::local("a", cx));
2000        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2001        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2002
2003        let font_size = px(14.0);
2004        let map = cx.new(|cx| {
2005            DisplayMap::new(
2006                buffer.clone(),
2007                font("Helvetica"),
2008                font_size,
2009                None,
2010                1,
2011                1,
2012                FoldPlaceholder::test(),
2013                DiagnosticSeverity::Warning,
2014                cx,
2015            )
2016        });
2017
2018        map.update(cx, |map, cx| {
2019            map.insert_blocks(
2020                [BlockProperties {
2021                    placement: BlockPlacement::Above(
2022                        buffer_snapshot.anchor_before(Point::new(0, 0)),
2023                    ),
2024                    height: Some(2),
2025                    style: BlockStyle::Sticky,
2026                    render: Arc::new(|_| div().into_any()),
2027                    priority: 0,
2028                }],
2029                cx,
2030            );
2031        });
2032        map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\na"));
2033
2034        map.update(cx, |map, cx| {
2035            map.splice_inlays(
2036                &[],
2037                vec![Inlay::edit_prediction(
2038                    0,
2039                    buffer_snapshot.anchor_after(0),
2040                    "\n",
2041                )],
2042                cx,
2043            );
2044        });
2045        map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\na"));
2046
2047        // Regression test: updating the display map does not crash when a
2048        // block is immediately followed by a multi-line inlay.
2049        buffer.update(cx, |buffer, cx| {
2050            buffer.edit([(1..1, "b")], None, cx);
2051        });
2052        map.update(cx, |m, cx| assert_eq!(m.snapshot(cx).text(), "\n\n\nab"));
2053    }
2054
2055    #[gpui::test]
2056    async fn test_chunks(cx: &mut gpui::TestAppContext) {
2057        let text = r#"
2058            fn outer() {}
2059
2060            mod module {
2061                fn inner() {}
2062            }"#
2063        .unindent();
2064
2065        let theme =
2066            SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2067        let language = Arc::new(
2068            Language::new(
2069                LanguageConfig {
2070                    name: "Test".into(),
2071                    matcher: LanguageMatcher {
2072                        path_suffixes: vec![".test".to_string()],
2073                        ..Default::default()
2074                    },
2075                    ..Default::default()
2076                },
2077                Some(tree_sitter_rust::LANGUAGE.into()),
2078            )
2079            .with_highlights_query(
2080                r#"
2081                (mod_item name: (identifier) body: _ @mod.body)
2082                (function_item name: (identifier) @fn.name)
2083                "#,
2084            )
2085            .unwrap(),
2086        );
2087        language.set_theme(&theme);
2088
2089        cx.update(|cx| {
2090            init_test(cx, |s| {
2091                s.project.all_languages.defaults.tab_size = Some(2.try_into().unwrap())
2092            })
2093        });
2094
2095        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2096        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2097        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2098
2099        let font_size = px(14.0);
2100
2101        let map = cx.new(|cx| {
2102            DisplayMap::new(
2103                buffer,
2104                font("Helvetica"),
2105                font_size,
2106                None,
2107                1,
2108                1,
2109                FoldPlaceholder::test(),
2110                DiagnosticSeverity::Warning,
2111                cx,
2112            )
2113        });
2114        assert_eq!(
2115            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2116            vec![
2117                ("fn ".to_string(), None),
2118                ("outer".to_string(), Some(Hsla::blue())),
2119                ("() {}\n\nmod module ".to_string(), None),
2120                ("{\n    fn ".to_string(), Some(Hsla::red())),
2121                ("inner".to_string(), Some(Hsla::blue())),
2122                ("() {}\n}".to_string(), Some(Hsla::red())),
2123            ]
2124        );
2125        assert_eq!(
2126            cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2127            vec![
2128                ("    fn ".to_string(), Some(Hsla::red())),
2129                ("inner".to_string(), Some(Hsla::blue())),
2130                ("() {}\n}".to_string(), Some(Hsla::red())),
2131            ]
2132        );
2133
2134        map.update(cx, |map, cx| {
2135            map.fold(
2136                vec![Crease::simple(
2137                    MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2138                    FoldPlaceholder::test(),
2139                )],
2140                cx,
2141            )
2142        });
2143        assert_eq!(
2144            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
2145            vec![
2146                ("fn ".to_string(), None),
2147                ("out".to_string(), Some(Hsla::blue())),
2148                ("".to_string(), None),
2149                ("  fn ".to_string(), Some(Hsla::red())),
2150                ("inner".to_string(), Some(Hsla::blue())),
2151                ("() {}\n}".to_string(), Some(Hsla::red())),
2152            ]
2153        );
2154    }
2155
2156    #[gpui::test]
2157    async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
2158        cx.background_executor
2159            .set_block_on_ticks(usize::MAX..=usize::MAX);
2160
2161        let text = r#"
2162            const A: &str = "
2163                one
2164                two
2165                three
2166            ";
2167            const B: &str = "four";
2168        "#
2169        .unindent();
2170
2171        let theme = SyntaxTheme::new_test(vec![
2172            ("string", Hsla::red()),
2173            ("punctuation", Hsla::blue()),
2174            ("keyword", Hsla::green()),
2175        ]);
2176        let language = Arc::new(
2177            Language::new(
2178                LanguageConfig {
2179                    name: "Rust".into(),
2180                    ..Default::default()
2181                },
2182                Some(tree_sitter_rust::LANGUAGE.into()),
2183            )
2184            .with_highlights_query(
2185                r#"
2186                (string_literal) @string
2187                "const" @keyword
2188                [":" ";"] @punctuation
2189                "#,
2190            )
2191            .unwrap(),
2192        );
2193        language.set_theme(&theme);
2194
2195        cx.update(|cx| init_test(cx, |_| {}));
2196
2197        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2198        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2199        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2200        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2201
2202        let map = cx.new(|cx| {
2203            DisplayMap::new(
2204                buffer,
2205                font("Courier"),
2206                px(16.0),
2207                None,
2208                1,
2209                1,
2210                FoldPlaceholder::test(),
2211                DiagnosticSeverity::Warning,
2212                cx,
2213            )
2214        });
2215
2216        // Insert two blocks in the middle of a multi-line string literal.
2217        // The second block has zero height.
2218        map.update(cx, |map, cx| {
2219            map.insert_blocks(
2220                [
2221                    BlockProperties {
2222                        placement: BlockPlacement::Below(
2223                            buffer_snapshot.anchor_before(Point::new(1, 0)),
2224                        ),
2225                        height: Some(1),
2226                        style: BlockStyle::Sticky,
2227                        render: Arc::new(|_| div().into_any()),
2228                        priority: 0,
2229                    },
2230                    BlockProperties {
2231                        placement: BlockPlacement::Below(
2232                            buffer_snapshot.anchor_before(Point::new(2, 0)),
2233                        ),
2234                        height: None,
2235                        style: BlockStyle::Sticky,
2236                        render: Arc::new(|_| div().into_any()),
2237                        priority: 0,
2238                    },
2239                ],
2240                cx,
2241            )
2242        });
2243
2244        pretty_assertions::assert_eq!(
2245            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
2246            [
2247                ("const".into(), Some(Hsla::green())),
2248                (" A".into(), None),
2249                (":".into(), Some(Hsla::blue())),
2250                (" &str = ".into(), None),
2251                ("\"\n    one\n".into(), Some(Hsla::red())),
2252                ("\n".into(), None),
2253                ("    two\n    three\n\"".into(), Some(Hsla::red())),
2254                (";".into(), Some(Hsla::blue())),
2255                ("\n".into(), None),
2256                ("const".into(), Some(Hsla::green())),
2257                (" B".into(), None),
2258                (":".into(), Some(Hsla::blue())),
2259                (" &str = ".into(), None),
2260                ("\"four\"".into(), Some(Hsla::red())),
2261                (";".into(), Some(Hsla::blue())),
2262                ("\n".into(), None),
2263            ]
2264        );
2265    }
2266
2267    #[gpui::test]
2268    async fn test_chunks_with_diagnostics_across_blocks(cx: &mut gpui::TestAppContext) {
2269        cx.background_executor
2270            .set_block_on_ticks(usize::MAX..=usize::MAX);
2271
2272        let text = r#"
2273            struct A {
2274                b: usize;
2275            }
2276            const c: usize = 1;
2277        "#
2278        .unindent();
2279
2280        cx.update(|cx| init_test(cx, |_| {}));
2281
2282        let buffer = cx.new(|cx| Buffer::local(text, cx));
2283
2284        buffer.update(cx, |buffer, cx| {
2285            buffer.update_diagnostics(
2286                LanguageServerId(0),
2287                DiagnosticSet::new(
2288                    [DiagnosticEntry {
2289                        range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
2290                        diagnostic: Diagnostic {
2291                            severity: lsp::DiagnosticSeverity::ERROR,
2292                            group_id: 1,
2293                            message: "hi".into(),
2294                            ..Default::default()
2295                        },
2296                    }],
2297                    buffer,
2298                ),
2299                cx,
2300            )
2301        });
2302
2303        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2304        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2305
2306        let map = cx.new(|cx| {
2307            DisplayMap::new(
2308                buffer,
2309                font("Courier"),
2310                px(16.0),
2311                None,
2312                1,
2313                1,
2314                FoldPlaceholder::test(),
2315                DiagnosticSeverity::Warning,
2316                cx,
2317            )
2318        });
2319
2320        let black = gpui::black().to_rgb();
2321        let red = gpui::red().to_rgb();
2322
2323        // Insert a block in the middle of a multi-line diagnostic.
2324        map.update(cx, |map, cx| {
2325            map.highlight_text(
2326                HighlightKey::Type(TypeId::of::<usize>()),
2327                vec![
2328                    buffer_snapshot.anchor_before(Point::new(3, 9))
2329                        ..buffer_snapshot.anchor_after(Point::new(3, 14)),
2330                    buffer_snapshot.anchor_before(Point::new(3, 17))
2331                        ..buffer_snapshot.anchor_after(Point::new(3, 18)),
2332                ],
2333                red.into(),
2334            );
2335            map.insert_blocks(
2336                [BlockProperties {
2337                    placement: BlockPlacement::Below(
2338                        buffer_snapshot.anchor_before(Point::new(1, 0)),
2339                    ),
2340                    height: Some(1),
2341                    style: BlockStyle::Sticky,
2342                    render: Arc::new(|_| div().into_any()),
2343                    priority: 0,
2344                }],
2345                cx,
2346            )
2347        });
2348
2349        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2350        let mut chunks = Vec::<(String, Option<lsp::DiagnosticSeverity>, Rgba)>::new();
2351        for chunk in snapshot.chunks(DisplayRow(0)..DisplayRow(5), true, Default::default()) {
2352            let color = chunk
2353                .highlight_style
2354                .and_then(|style| style.color)
2355                .map_or(black, |color| color.to_rgb());
2356            if let Some((last_chunk, last_severity, last_color)) = chunks.last_mut()
2357                && *last_severity == chunk.diagnostic_severity
2358                && *last_color == color
2359            {
2360                last_chunk.push_str(chunk.text);
2361                continue;
2362            }
2363
2364            chunks.push((chunk.text.to_string(), chunk.diagnostic_severity, color));
2365        }
2366
2367        assert_eq!(
2368            chunks,
2369            [
2370                (
2371                    "struct A {\n    b: usize;\n".into(),
2372                    Some(lsp::DiagnosticSeverity::ERROR),
2373                    black
2374                ),
2375                ("\n".into(), None, black),
2376                ("}".into(), Some(lsp::DiagnosticSeverity::ERROR), black),
2377                ("\nconst c: ".into(), None, black),
2378                ("usize".into(), None, red),
2379                (" = ".into(), None, black),
2380                ("1".into(), None, red),
2381                (";\n".into(), None, black),
2382            ]
2383        );
2384    }
2385
2386    #[gpui::test]
2387    async fn test_point_translation_with_replace_blocks(cx: &mut gpui::TestAppContext) {
2388        cx.background_executor
2389            .set_block_on_ticks(usize::MAX..=usize::MAX);
2390
2391        cx.update(|cx| init_test(cx, |_| {}));
2392
2393        let buffer = cx.update(|cx| MultiBuffer::build_simple("abcde\nfghij\nklmno\npqrst", cx));
2394        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2395        let map = cx.new(|cx| {
2396            DisplayMap::new(
2397                buffer.clone(),
2398                font("Courier"),
2399                px(16.0),
2400                None,
2401                1,
2402                1,
2403                FoldPlaceholder::test(),
2404                DiagnosticSeverity::Warning,
2405                cx,
2406            )
2407        });
2408
2409        let snapshot = map.update(cx, |map, cx| {
2410            map.insert_blocks(
2411                [BlockProperties {
2412                    placement: BlockPlacement::Replace(
2413                        buffer_snapshot.anchor_before(Point::new(1, 2))
2414                            ..=buffer_snapshot.anchor_after(Point::new(2, 3)),
2415                    ),
2416                    height: Some(4),
2417                    style: BlockStyle::Fixed,
2418                    render: Arc::new(|_| div().into_any()),
2419                    priority: 0,
2420                }],
2421                cx,
2422            );
2423            map.snapshot(cx)
2424        });
2425
2426        assert_eq!(snapshot.text(), "abcde\n\n\n\n\npqrst");
2427
2428        let point_to_display_points = [
2429            (Point::new(1, 0), DisplayPoint::new(DisplayRow(1), 0)),
2430            (Point::new(2, 0), DisplayPoint::new(DisplayRow(1), 0)),
2431            (Point::new(3, 0), DisplayPoint::new(DisplayRow(5), 0)),
2432        ];
2433        for (buffer_point, display_point) in point_to_display_points {
2434            assert_eq!(
2435                snapshot.point_to_display_point(buffer_point, Bias::Left),
2436                display_point,
2437                "point_to_display_point({:?}, Bias::Left)",
2438                buffer_point
2439            );
2440            assert_eq!(
2441                snapshot.point_to_display_point(buffer_point, Bias::Right),
2442                display_point,
2443                "point_to_display_point({:?}, Bias::Right)",
2444                buffer_point
2445            );
2446        }
2447
2448        let display_points_to_points = [
2449            (
2450                DisplayPoint::new(DisplayRow(1), 0),
2451                Point::new(1, 0),
2452                Point::new(2, 5),
2453            ),
2454            (
2455                DisplayPoint::new(DisplayRow(2), 0),
2456                Point::new(1, 0),
2457                Point::new(2, 5),
2458            ),
2459            (
2460                DisplayPoint::new(DisplayRow(3), 0),
2461                Point::new(1, 0),
2462                Point::new(2, 5),
2463            ),
2464            (
2465                DisplayPoint::new(DisplayRow(4), 0),
2466                Point::new(1, 0),
2467                Point::new(2, 5),
2468            ),
2469            (
2470                DisplayPoint::new(DisplayRow(5), 0),
2471                Point::new(3, 0),
2472                Point::new(3, 0),
2473            ),
2474        ];
2475        for (display_point, left_buffer_point, right_buffer_point) in display_points_to_points {
2476            assert_eq!(
2477                snapshot.display_point_to_point(display_point, Bias::Left),
2478                left_buffer_point,
2479                "display_point_to_point({:?}, Bias::Left)",
2480                display_point
2481            );
2482            assert_eq!(
2483                snapshot.display_point_to_point(display_point, Bias::Right),
2484                right_buffer_point,
2485                "display_point_to_point({:?}, Bias::Right)",
2486                display_point
2487            );
2488        }
2489    }
2490
2491    #[gpui::test]
2492    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
2493        cx.background_executor
2494            .set_block_on_ticks(usize::MAX..=usize::MAX);
2495
2496        let text = r#"
2497            fn outer() {}
2498
2499            mod module {
2500                fn inner() {}
2501            }"#
2502        .unindent();
2503
2504        let theme =
2505            SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2506        let language = Arc::new(
2507            Language::new(
2508                LanguageConfig {
2509                    name: "Test".into(),
2510                    matcher: LanguageMatcher {
2511                        path_suffixes: vec![".test".to_string()],
2512                        ..Default::default()
2513                    },
2514                    ..Default::default()
2515                },
2516                Some(tree_sitter_rust::LANGUAGE.into()),
2517            )
2518            .with_highlights_query(
2519                r#"
2520                (mod_item name: (identifier) body: _ @mod.body)
2521                (function_item name: (identifier) @fn.name)
2522                "#,
2523            )
2524            .unwrap(),
2525        );
2526        language.set_theme(&theme);
2527
2528        cx.update(|cx| init_test(cx, |_| {}));
2529
2530        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2531        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2532        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2533
2534        let font_size = px(16.0);
2535
2536        let map = cx.new(|cx| {
2537            DisplayMap::new(
2538                buffer,
2539                font("Courier"),
2540                font_size,
2541                Some(px(40.0)),
2542                1,
2543                1,
2544                FoldPlaceholder::test(),
2545                DiagnosticSeverity::Warning,
2546                cx,
2547            )
2548        });
2549        assert_eq!(
2550            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2551            [
2552                ("fn \n".to_string(), None),
2553                ("oute".to_string(), Some(Hsla::blue())),
2554                ("\n".to_string(), None),
2555                ("r".to_string(), Some(Hsla::blue())),
2556                ("() \n{}\n\n".to_string(), None),
2557            ]
2558        );
2559        assert_eq!(
2560            cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2561            [("{}\n\n".to_string(), None)]
2562        );
2563
2564        map.update(cx, |map, cx| {
2565            map.fold(
2566                vec![Crease::simple(
2567                    MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2568                    FoldPlaceholder::test(),
2569                )],
2570                cx,
2571            )
2572        });
2573        assert_eq!(
2574            cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
2575            [
2576                ("out".to_string(), Some(Hsla::blue())),
2577                ("\n".to_string(), None),
2578                ("  ".to_string(), Some(Hsla::red())),
2579                ("\n".to_string(), None),
2580                ("fn ".to_string(), Some(Hsla::red())),
2581                ("i".to_string(), Some(Hsla::blue())),
2582                ("\n".to_string(), None)
2583            ]
2584        );
2585    }
2586
2587    #[gpui::test]
2588    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
2589        cx.update(|cx| init_test(cx, |_| {}));
2590
2591        let theme =
2592            SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
2593        let language = Arc::new(
2594            Language::new(
2595                LanguageConfig {
2596                    name: "Test".into(),
2597                    matcher: LanguageMatcher {
2598                        path_suffixes: vec![".test".to_string()],
2599                        ..Default::default()
2600                    },
2601                    ..Default::default()
2602                },
2603                Some(tree_sitter_rust::LANGUAGE.into()),
2604            )
2605            .with_highlights_query(
2606                r#"
2607                ":" @operator
2608                (string_literal) @string
2609                "#,
2610            )
2611            .unwrap(),
2612        );
2613        language.set_theme(&theme);
2614
2615        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»«:» B = "c «d»""#, false);
2616
2617        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
2618        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2619
2620        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
2621        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2622
2623        let font_size = px(16.0);
2624        let map = cx.new(|cx| {
2625            DisplayMap::new(
2626                buffer,
2627                font("Courier"),
2628                font_size,
2629                None,
2630                1,
2631                1,
2632                FoldPlaceholder::test(),
2633                DiagnosticSeverity::Warning,
2634                cx,
2635            )
2636        });
2637
2638        enum MyType {}
2639
2640        let style = HighlightStyle {
2641            color: Some(Hsla::blue()),
2642            ..Default::default()
2643        };
2644
2645        map.update(cx, |map, _cx| {
2646            map.highlight_text(
2647                HighlightKey::Type(TypeId::of::<MyType>()),
2648                highlighted_ranges
2649                    .into_iter()
2650                    .map(|range| {
2651                        buffer_snapshot.anchor_before(range.start)
2652                            ..buffer_snapshot.anchor_before(range.end)
2653                    })
2654                    .collect(),
2655                style,
2656            );
2657        });
2658
2659        assert_eq!(
2660            cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
2661            [
2662                ("const ".to_string(), None, None),
2663                ("a".to_string(), None, Some(Hsla::blue())),
2664                (":".to_string(), Some(Hsla::red()), Some(Hsla::blue())),
2665                (" B = ".to_string(), None, None),
2666                ("\"c ".to_string(), Some(Hsla::green()), None),
2667                ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2668                ("\"".to_string(), Some(Hsla::green()), None),
2669            ]
2670        );
2671    }
2672
2673    #[gpui::test]
2674    fn test_clip_point(cx: &mut gpui::App) {
2675        init_test(cx, |_| {});
2676
2677        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::App) {
2678            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2679
2680            match bias {
2681                Bias::Left => {
2682                    if shift_right {
2683                        *markers[1].column_mut() += 1;
2684                    }
2685
2686                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2687                }
2688                Bias::Right => {
2689                    if shift_right {
2690                        *markers[0].column_mut() += 1;
2691                    }
2692
2693                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2694                }
2695            };
2696        }
2697
2698        use Bias::{Left, Right};
2699        assert("ˇˇα", false, Left, cx);
2700        assert("ˇˇα", true, Left, cx);
2701        assert("ˇˇα", false, Right, cx);
2702        assert("ˇαˇ", true, Right, cx);
2703        assert("ˇˇ✋", false, Left, cx);
2704        assert("ˇˇ✋", true, Left, cx);
2705        assert("ˇˇ✋", false, Right, cx);
2706        assert("ˇ✋ˇ", true, Right, cx);
2707        assert("ˇˇ🍐", false, Left, cx);
2708        assert("ˇˇ🍐", true, Left, cx);
2709        assert("ˇˇ🍐", false, Right, cx);
2710        assert("ˇ🍐ˇ", true, Right, cx);
2711        assert("ˇˇ\t", false, Left, cx);
2712        assert("ˇˇ\t", true, Left, cx);
2713        assert("ˇˇ\t", false, Right, cx);
2714        assert("ˇ\tˇ", true, Right, cx);
2715        assert(" ˇˇ\t", false, Left, cx);
2716        assert(" ˇˇ\t", true, Left, cx);
2717        assert(" ˇˇ\t", false, Right, cx);
2718        assert(" ˇ\tˇ", true, Right, cx);
2719        assert("   ˇˇ\t", false, Left, cx);
2720        assert("   ˇˇ\t", false, Right, cx);
2721    }
2722
2723    #[gpui::test]
2724    fn test_clip_at_line_ends(cx: &mut gpui::App) {
2725        init_test(cx, |_| {});
2726
2727        fn assert(text: &str, cx: &mut gpui::App) {
2728            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2729            unmarked_snapshot.clip_at_line_ends = true;
2730            assert_eq!(
2731                unmarked_snapshot.clip_point(markers[1], Bias::Left),
2732                markers[0]
2733            );
2734        }
2735
2736        assert("ˇˇ", cx);
2737        assert("ˇaˇ", cx);
2738        assert("aˇbˇ", cx);
2739        assert("aˇαˇ", cx);
2740    }
2741
2742    #[gpui::test]
2743    fn test_creases(cx: &mut gpui::App) {
2744        init_test(cx, |_| {});
2745
2746        let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2747        let buffer = MultiBuffer::build_simple(text, cx);
2748        let font_size = px(14.0);
2749        cx.new(|cx| {
2750            let mut map = DisplayMap::new(
2751                buffer.clone(),
2752                font("Helvetica"),
2753                font_size,
2754                None,
2755                1,
2756                1,
2757                FoldPlaceholder::test(),
2758                DiagnosticSeverity::Warning,
2759                cx,
2760            );
2761            let snapshot = map.buffer.read(cx).snapshot(cx);
2762            let range =
2763                snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2764
2765            map.crease_map.insert(
2766                [Crease::inline(
2767                    range,
2768                    FoldPlaceholder::test(),
2769                    |_row, _status, _toggle, _window, _cx| div(),
2770                    |_row, _status, _window, _cx| div(),
2771                )],
2772                &map.buffer.read(cx).snapshot(cx),
2773            );
2774
2775            map
2776        });
2777    }
2778
2779    #[gpui::test]
2780    fn test_tabs_with_multibyte_chars(cx: &mut gpui::App) {
2781        init_test(cx, |_| {});
2782
2783        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
2784        let buffer = MultiBuffer::build_simple(text, cx);
2785        let font_size = px(14.0);
2786
2787        let map = cx.new(|cx| {
2788            DisplayMap::new(
2789                buffer.clone(),
2790                font("Helvetica"),
2791                font_size,
2792                None,
2793                1,
2794                1,
2795                FoldPlaceholder::test(),
2796                DiagnosticSeverity::Warning,
2797                cx,
2798            )
2799        });
2800        let map = map.update(cx, |map, cx| map.snapshot(cx));
2801        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
2802        assert_eq!(
2803            map.text_chunks(DisplayRow(0)).collect::<String>(),
2804            "✅       α\nβ   \n🏀β      γ"
2805        );
2806        assert_eq!(
2807            map.text_chunks(DisplayRow(1)).collect::<String>(),
2808            "β   \n🏀β      γ"
2809        );
2810        assert_eq!(
2811            map.text_chunks(DisplayRow(2)).collect::<String>(),
2812            "🏀β      γ"
2813        );
2814
2815        let point = MultiBufferPoint::new(0, "\t\t".len() as u32);
2816        let display_point = DisplayPoint::new(DisplayRow(0), "".len() as u32);
2817        assert_eq!(point.to_display_point(&map), display_point);
2818        assert_eq!(display_point.to_point(&map), point);
2819
2820        let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2821        let display_point = DisplayPoint::new(DisplayRow(1), "β   ".len() as u32);
2822        assert_eq!(point.to_display_point(&map), display_point);
2823        assert_eq!(display_point.to_point(&map), point,);
2824
2825        let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2826        let display_point = DisplayPoint::new(DisplayRow(2), "🏀β      ".len() as u32);
2827        assert_eq!(point.to_display_point(&map), display_point);
2828        assert_eq!(display_point.to_point(&map), point,);
2829
2830        // Display points inside of expanded tabs
2831        assert_eq!(
2832            DisplayPoint::new(DisplayRow(0), "".len() as u32).to_point(&map),
2833            MultiBufferPoint::new(0, "\t".len() as u32),
2834        );
2835        assert_eq!(
2836            DisplayPoint::new(DisplayRow(0), "".len() as u32).to_point(&map),
2837            MultiBufferPoint::new(0, "".len() as u32),
2838        );
2839
2840        // Clipping display points inside of multi-byte characters
2841        assert_eq!(
2842            map.clip_point(
2843                DisplayPoint::new(DisplayRow(0), "".len() as u32 - 1),
2844                Left
2845            ),
2846            DisplayPoint::new(DisplayRow(0), 0)
2847        );
2848        assert_eq!(
2849            map.clip_point(
2850                DisplayPoint::new(DisplayRow(0), "".len() as u32 - 1),
2851                Bias::Right
2852            ),
2853            DisplayPoint::new(DisplayRow(0), "".len() as u32)
2854        );
2855    }
2856
2857    #[gpui::test]
2858    fn test_max_point(cx: &mut gpui::App) {
2859        init_test(cx, |_| {});
2860
2861        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2862        let font_size = px(14.0);
2863        let map = cx.new(|cx| {
2864            DisplayMap::new(
2865                buffer.clone(),
2866                font("Helvetica"),
2867                font_size,
2868                None,
2869                1,
2870                1,
2871                FoldPlaceholder::test(),
2872                DiagnosticSeverity::Warning,
2873                cx,
2874            )
2875        });
2876        assert_eq!(
2877            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2878            DisplayPoint::new(DisplayRow(1), 11)
2879        )
2880    }
2881
2882    fn syntax_chunks(
2883        rows: Range<DisplayRow>,
2884        map: &Entity<DisplayMap>,
2885        theme: &SyntaxTheme,
2886        cx: &mut App,
2887    ) -> Vec<(String, Option<Hsla>)> {
2888        chunks(rows, map, theme, cx)
2889            .into_iter()
2890            .map(|(text, color, _)| (text, color))
2891            .collect()
2892    }
2893
2894    fn chunks(
2895        rows: Range<DisplayRow>,
2896        map: &Entity<DisplayMap>,
2897        theme: &SyntaxTheme,
2898        cx: &mut App,
2899    ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2900        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2901        let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2902        for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2903            let syntax_color = chunk
2904                .syntax_highlight_id
2905                .and_then(|id| id.style(theme)?.color);
2906            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2907            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut()
2908                && syntax_color == *last_syntax_color
2909                && highlight_color == *last_highlight_color
2910            {
2911                last_chunk.push_str(chunk.text);
2912                continue;
2913            }
2914            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2915        }
2916        chunks
2917    }
2918
2919    fn init_test(cx: &mut App, f: impl Fn(&mut SettingsContent)) {
2920        let settings = SettingsStore::test(cx);
2921        cx.set_global(settings);
2922        workspace::init_settings(cx);
2923        language::init(cx);
2924        crate::init(cx);
2925        Project::init_settings(cx);
2926        theme::init(LoadThemes::JustBase, cx);
2927        cx.update_global::<SettingsStore, _>(|store, cx| {
2928            store.update_user_settings(cx, f);
2929        });
2930    }
2931}