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