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