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