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