display_map.rs

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