display_map.rs

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