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