display_map.rs

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