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