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