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