display_map.rs

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