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