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<Option<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(Some(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(&Some(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(&Some(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 starts_indent(&self, buffer_row: MultiBufferRow) -> bool {
1129        let max_row = self.buffer_snapshot.max_row();
1130        if buffer_row >= max_row {
1131            return false;
1132        }
1133
1134        let line_indent = self.line_indent_for_buffer_row(buffer_row);
1135        if line_indent.is_line_blank() {
1136            return false;
1137        }
1138
1139        (buffer_row.0 + 1..=max_row.0)
1140            .find_map(|next_row| {
1141                let next_line_indent = self.line_indent_for_buffer_row(MultiBufferRow(next_row));
1142                if next_line_indent.raw_len() > line_indent.raw_len() {
1143                    Some(true)
1144                } else if !next_line_indent.is_line_blank() {
1145                    Some(false)
1146                } else {
1147                    None
1148                }
1149            })
1150            .unwrap_or(false)
1151    }
1152
1153    pub fn crease_for_buffer_row(&self, buffer_row: MultiBufferRow) -> Option<Crease<Point>> {
1154        let start = MultiBufferPoint::new(buffer_row.0, self.buffer_snapshot.line_len(buffer_row));
1155        if let Some(crease) = self
1156            .crease_snapshot
1157            .query_row(buffer_row, &self.buffer_snapshot)
1158        {
1159            match crease {
1160                Crease::Inline {
1161                    range,
1162                    placeholder,
1163                    render_toggle,
1164                    render_trailer,
1165                    metadata,
1166                } => Some(Crease::Inline {
1167                    range: range.to_point(&self.buffer_snapshot),
1168                    placeholder: placeholder.clone(),
1169                    render_toggle: render_toggle.clone(),
1170                    render_trailer: render_trailer.clone(),
1171                    metadata: metadata.clone(),
1172                }),
1173                Crease::Block {
1174                    range,
1175                    block_height,
1176                    block_style,
1177                    render_block,
1178                    block_priority,
1179                    render_toggle,
1180                } => Some(Crease::Block {
1181                    range: range.to_point(&self.buffer_snapshot),
1182                    block_height: *block_height,
1183                    block_style: *block_style,
1184                    render_block: render_block.clone(),
1185                    block_priority: *block_priority,
1186                    render_toggle: render_toggle.clone(),
1187                }),
1188            }
1189        } else if self.starts_indent(MultiBufferRow(start.row))
1190            && !self.is_line_folded(MultiBufferRow(start.row))
1191        {
1192            let start_line_indent = self.line_indent_for_buffer_row(buffer_row);
1193            let max_point = self.buffer_snapshot.max_point();
1194            let mut end = None;
1195
1196            for row in (buffer_row.0 + 1)..=max_point.row {
1197                let line_indent = self.line_indent_for_buffer_row(MultiBufferRow(row));
1198                if !line_indent.is_line_blank()
1199                    && line_indent.raw_len() <= start_line_indent.raw_len()
1200                {
1201                    let prev_row = row - 1;
1202                    end = Some(Point::new(
1203                        prev_row,
1204                        self.buffer_snapshot.line_len(MultiBufferRow(prev_row)),
1205                    ));
1206                    break;
1207                }
1208            }
1209
1210            let mut row_before_line_breaks = end.unwrap_or(max_point);
1211            while row_before_line_breaks.row > start.row
1212                && self
1213                    .buffer_snapshot
1214                    .is_line_blank(MultiBufferRow(row_before_line_breaks.row))
1215            {
1216                row_before_line_breaks.row -= 1;
1217            }
1218
1219            row_before_line_breaks = Point::new(
1220                row_before_line_breaks.row,
1221                self.buffer_snapshot
1222                    .line_len(MultiBufferRow(row_before_line_breaks.row)),
1223            );
1224
1225            Some(Crease::Inline {
1226                range: start..row_before_line_breaks,
1227                placeholder: self.fold_placeholder.clone(),
1228                render_toggle: None,
1229                render_trailer: None,
1230                metadata: None,
1231            })
1232        } else {
1233            None
1234        }
1235    }
1236
1237    #[cfg(any(test, feature = "test-support"))]
1238    pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
1239        &self,
1240    ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
1241        let type_id = TypeId::of::<Tag>();
1242        self.text_highlights.get(&Some(type_id)).cloned()
1243    }
1244
1245    #[allow(unused)]
1246    #[cfg(any(test, feature = "test-support"))]
1247    pub(crate) fn inlay_highlights<Tag: ?Sized + 'static>(
1248        &self,
1249    ) -> Option<&TreeMap<InlayId, (HighlightStyle, InlayHighlight)>> {
1250        let type_id = TypeId::of::<Tag>();
1251        self.inlay_highlights.get(&type_id)
1252    }
1253
1254    pub fn buffer_header_height(&self) -> u32 {
1255        self.block_snapshot.buffer_header_height
1256    }
1257
1258    pub fn excerpt_footer_height(&self) -> u32 {
1259        self.block_snapshot.excerpt_footer_height
1260    }
1261
1262    pub fn excerpt_header_height(&self) -> u32 {
1263        self.block_snapshot.excerpt_header_height
1264    }
1265}
1266
1267#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
1268pub struct DisplayPoint(BlockPoint);
1269
1270impl Debug for DisplayPoint {
1271    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1272        f.write_fmt(format_args!(
1273            "DisplayPoint({}, {})",
1274            self.row().0,
1275            self.column()
1276        ))
1277    }
1278}
1279
1280impl Add for DisplayPoint {
1281    type Output = Self;
1282
1283    fn add(self, other: Self) -> Self::Output {
1284        DisplayPoint(BlockPoint(self.0 .0 + other.0 .0))
1285    }
1286}
1287
1288impl Sub for DisplayPoint {
1289    type Output = Self;
1290
1291    fn sub(self, other: Self) -> Self::Output {
1292        DisplayPoint(BlockPoint(self.0 .0 - other.0 .0))
1293    }
1294}
1295
1296#[derive(Debug, Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq, Deserialize, Hash)]
1297#[serde(transparent)]
1298pub struct DisplayRow(pub u32);
1299
1300impl Add<DisplayRow> for DisplayRow {
1301    type Output = Self;
1302
1303    fn add(self, other: Self) -> Self::Output {
1304        DisplayRow(self.0 + other.0)
1305    }
1306}
1307
1308impl Add<u32> for DisplayRow {
1309    type Output = Self;
1310
1311    fn add(self, other: u32) -> Self::Output {
1312        DisplayRow(self.0 + other)
1313    }
1314}
1315
1316impl Sub<DisplayRow> for DisplayRow {
1317    type Output = Self;
1318
1319    fn sub(self, other: Self) -> Self::Output {
1320        DisplayRow(self.0 - other.0)
1321    }
1322}
1323
1324impl Sub<u32> for DisplayRow {
1325    type Output = Self;
1326
1327    fn sub(self, other: u32) -> Self::Output {
1328        DisplayRow(self.0 - other)
1329    }
1330}
1331
1332impl DisplayPoint {
1333    pub fn new(row: DisplayRow, column: u32) -> Self {
1334        Self(BlockPoint(Point::new(row.0, column)))
1335    }
1336
1337    pub fn zero() -> Self {
1338        Self::new(DisplayRow(0), 0)
1339    }
1340
1341    pub fn is_zero(&self) -> bool {
1342        self.0.is_zero()
1343    }
1344
1345    pub fn row(self) -> DisplayRow {
1346        DisplayRow(self.0.row)
1347    }
1348
1349    pub fn column(self) -> u32 {
1350        self.0.column
1351    }
1352
1353    pub fn row_mut(&mut self) -> &mut u32 {
1354        &mut self.0.row
1355    }
1356
1357    pub fn column_mut(&mut self) -> &mut u32 {
1358        &mut self.0.column
1359    }
1360
1361    pub fn to_point(self, map: &DisplaySnapshot) -> Point {
1362        map.display_point_to_point(self, Bias::Left)
1363    }
1364
1365    pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
1366        let wrap_point = map.block_snapshot.to_wrap_point(self.0, bias);
1367        let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
1368        let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
1369        let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
1370        map.inlay_snapshot
1371            .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
1372    }
1373}
1374
1375impl ToDisplayPoint for usize {
1376    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1377        map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
1378    }
1379}
1380
1381impl ToDisplayPoint for OffsetUtf16 {
1382    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1383        self.to_offset(&map.buffer_snapshot).to_display_point(map)
1384    }
1385}
1386
1387impl ToDisplayPoint for Point {
1388    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1389        map.point_to_display_point(*self, Bias::Left)
1390    }
1391}
1392
1393impl ToDisplayPoint for Anchor {
1394    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1395        self.to_point(&map.buffer_snapshot).to_display_point(map)
1396    }
1397}
1398
1399#[cfg(test)]
1400pub mod tests {
1401    use super::*;
1402    use crate::{movement, test::marked_display_snapshot};
1403    use block_map::BlockPlacement;
1404    use gpui::{
1405        div, font, observe, px, AppContext, BorrowAppContext, Context, Element, Hsla, Rgba,
1406    };
1407    use language::{
1408        language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1409        Buffer, Diagnostic, DiagnosticEntry, DiagnosticSet, Language, LanguageConfig,
1410        LanguageMatcher,
1411    };
1412    use lsp::LanguageServerId;
1413    use project::Project;
1414    use rand::{prelude::*, Rng};
1415    use settings::SettingsStore;
1416    use smol::stream::StreamExt;
1417    use std::{env, sync::Arc};
1418    use text::PointUtf16;
1419    use theme::{LoadThemes, SyntaxTheme};
1420    use unindent::Unindent as _;
1421    use util::test::{marked_text_ranges, sample_text};
1422    use Bias::*;
1423
1424    #[gpui::test(iterations = 100)]
1425    async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1426        cx.background_executor.set_block_on_ticks(0..=50);
1427        let operations = env::var("OPERATIONS")
1428            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1429            .unwrap_or(10);
1430
1431        let mut tab_size = rng.gen_range(1..=4);
1432        let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1433        let excerpt_header_height = rng.gen_range(1..=5);
1434        let font_size = px(14.0);
1435        let max_wrap_width = 300.0;
1436        let mut wrap_width = if rng.gen_bool(0.1) {
1437            None
1438        } else {
1439            Some(px(rng.gen_range(0.0..=max_wrap_width)))
1440        };
1441
1442        log::info!("tab size: {}", tab_size);
1443        log::info!("wrap width: {:?}", wrap_width);
1444
1445        cx.update(|cx| {
1446            init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1447        });
1448
1449        let buffer = cx.update(|cx| {
1450            if rng.gen() {
1451                let len = rng.gen_range(0..10);
1452                let text = util::RandomCharIter::new(&mut rng)
1453                    .take(len)
1454                    .collect::<String>();
1455                MultiBuffer::build_simple(&text, cx)
1456            } else {
1457                MultiBuffer::build_random(&mut rng, cx)
1458            }
1459        });
1460
1461        let map = cx.new_model(|cx| {
1462            DisplayMap::new(
1463                buffer.clone(),
1464                font("Helvetica"),
1465                font_size,
1466                wrap_width,
1467                true,
1468                buffer_start_excerpt_header_height,
1469                excerpt_header_height,
1470                0,
1471                FoldPlaceholder::test(),
1472                cx,
1473            )
1474        });
1475        let mut notifications = observe(&map, cx);
1476        let mut fold_count = 0;
1477        let mut blocks = Vec::new();
1478
1479        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1480        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1481        log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1482        log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1483        log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1484        log::info!("block text: {:?}", snapshot.block_snapshot.text());
1485        log::info!("display text: {:?}", snapshot.text());
1486
1487        for _i in 0..operations {
1488            match rng.gen_range(0..100) {
1489                0..=19 => {
1490                    wrap_width = if rng.gen_bool(0.2) {
1491                        None
1492                    } else {
1493                        Some(px(rng.gen_range(0.0..=max_wrap_width)))
1494                    };
1495                    log::info!("setting wrap width to {:?}", wrap_width);
1496                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1497                }
1498                20..=29 => {
1499                    let mut tab_sizes = vec![1, 2, 3, 4];
1500                    tab_sizes.remove((tab_size - 1) as usize);
1501                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
1502                    log::info!("setting tab size to {:?}", tab_size);
1503                    cx.update(|cx| {
1504                        cx.update_global::<SettingsStore, _>(|store, cx| {
1505                            store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1506                                s.defaults.tab_size = NonZeroU32::new(tab_size);
1507                            });
1508                        });
1509                    });
1510                }
1511                30..=44 => {
1512                    map.update(cx, |map, cx| {
1513                        if rng.gen() || blocks.is_empty() {
1514                            let buffer = map.snapshot(cx).buffer_snapshot;
1515                            let block_properties = (0..rng.gen_range(1..=1))
1516                                .map(|_| {
1517                                    let position =
1518                                        buffer.anchor_after(buffer.clip_offset(
1519                                            rng.gen_range(0..=buffer.len()),
1520                                            Bias::Left,
1521                                        ));
1522
1523                                    let placement = if rng.gen() {
1524                                        BlockPlacement::Above(position)
1525                                    } else {
1526                                        BlockPlacement::Below(position)
1527                                    };
1528                                    let height = rng.gen_range(1..5);
1529                                    log::info!(
1530                                        "inserting block {:?} with height {}",
1531                                        placement.as_ref().map(|p| p.to_point(&buffer)),
1532                                        height
1533                                    );
1534                                    let priority = rng.gen_range(1..100);
1535                                    BlockProperties {
1536                                        placement,
1537                                        style: BlockStyle::Fixed,
1538                                        height,
1539                                        render: Arc::new(|_| div().into_any()),
1540                                        priority,
1541                                    }
1542                                })
1543                                .collect::<Vec<_>>();
1544                            blocks.extend(map.insert_blocks(block_properties, cx));
1545                        } else {
1546                            blocks.shuffle(&mut rng);
1547                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1548                            let block_ids_to_remove = (0..remove_count)
1549                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1550                                .collect();
1551                            log::info!("removing block ids {:?}", block_ids_to_remove);
1552                            map.remove_blocks(block_ids_to_remove, cx);
1553                        }
1554                    });
1555                }
1556                45..=79 => {
1557                    let mut ranges = Vec::new();
1558                    for _ in 0..rng.gen_range(1..=3) {
1559                        buffer.read_with(cx, |buffer, cx| {
1560                            let buffer = buffer.read(cx);
1561                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1562                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1563                            ranges.push(start..end);
1564                        });
1565                    }
1566
1567                    if rng.gen() && fold_count > 0 {
1568                        log::info!("unfolding ranges: {:?}", ranges);
1569                        map.update(cx, |map, cx| {
1570                            map.unfold_intersecting(ranges, true, cx);
1571                        });
1572                    } else {
1573                        log::info!("folding ranges: {:?}", ranges);
1574                        map.update(cx, |map, cx| {
1575                            map.fold(
1576                                ranges
1577                                    .into_iter()
1578                                    .map(|range| Crease::simple(range, FoldPlaceholder::test()))
1579                                    .collect(),
1580                                cx,
1581                            );
1582                        });
1583                    }
1584                }
1585                _ => {
1586                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1587                }
1588            }
1589
1590            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1591                notifications.next().await.unwrap();
1592            }
1593
1594            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1595            fold_count = snapshot.fold_count();
1596            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1597            log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1598            log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1599            log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1600            log::info!("block text: {:?}", snapshot.block_snapshot.text());
1601            log::info!("display text: {:?}", snapshot.text());
1602
1603            // Line boundaries
1604            let buffer = &snapshot.buffer_snapshot;
1605            for _ in 0..5 {
1606                let row = rng.gen_range(0..=buffer.max_point().row);
1607                let column = rng.gen_range(0..=buffer.line_len(MultiBufferRow(row)));
1608                let point = buffer.clip_point(Point::new(row, column), Left);
1609
1610                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1611                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1612
1613                assert!(prev_buffer_bound <= point);
1614                assert!(next_buffer_bound >= point);
1615                assert_eq!(prev_buffer_bound.column, 0);
1616                assert_eq!(prev_display_bound.column(), 0);
1617                if next_buffer_bound < buffer.max_point() {
1618                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1619                }
1620
1621                assert_eq!(
1622                    prev_display_bound,
1623                    prev_buffer_bound.to_display_point(&snapshot),
1624                    "row boundary before {:?}. reported buffer row boundary: {:?}",
1625                    point,
1626                    prev_buffer_bound
1627                );
1628                assert_eq!(
1629                    next_display_bound,
1630                    next_buffer_bound.to_display_point(&snapshot),
1631                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
1632                    point,
1633                    next_buffer_bound
1634                );
1635                assert_eq!(
1636                    prev_buffer_bound,
1637                    prev_display_bound.to_point(&snapshot),
1638                    "row boundary before {:?}. reported display row boundary: {:?}",
1639                    point,
1640                    prev_display_bound
1641                );
1642                assert_eq!(
1643                    next_buffer_bound,
1644                    next_display_bound.to_point(&snapshot),
1645                    "row boundary after {:?}. reported display row boundary: {:?}",
1646                    point,
1647                    next_display_bound
1648                );
1649            }
1650
1651            // Movement
1652            let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1653            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1654            for _ in 0..5 {
1655                let row = rng.gen_range(0..=snapshot.max_point().row().0);
1656                let column = rng.gen_range(0..=snapshot.line_len(DisplayRow(row)));
1657                let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1658
1659                log::info!("Moving from point {:?}", point);
1660
1661                let moved_right = movement::right(&snapshot, point);
1662                log::info!("Right {:?}", moved_right);
1663                if point < max_point {
1664                    assert!(moved_right > point);
1665                    if point.column() == snapshot.line_len(point.row())
1666                        || snapshot.soft_wrap_indent(point.row()).is_some()
1667                            && point.column() == snapshot.line_len(point.row()) - 1
1668                    {
1669                        assert!(moved_right.row() > point.row());
1670                    }
1671                } else {
1672                    assert_eq!(moved_right, point);
1673                }
1674
1675                let moved_left = movement::left(&snapshot, point);
1676                log::info!("Left {:?}", moved_left);
1677                if point > min_point {
1678                    assert!(moved_left < point);
1679                    if point.column() == 0 {
1680                        assert!(moved_left.row() < point.row());
1681                    }
1682                } else {
1683                    assert_eq!(moved_left, point);
1684                }
1685            }
1686        }
1687    }
1688
1689    #[cfg(target_os = "macos")]
1690    #[gpui::test(retries = 5)]
1691    async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1692        cx.background_executor
1693            .set_block_on_ticks(usize::MAX..=usize::MAX);
1694        cx.update(|cx| {
1695            init_test(cx, |_| {});
1696        });
1697
1698        let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1699        let editor = cx.editor.clone();
1700        let window = cx.window;
1701
1702        _ = cx.update_window(window, |_, cx| {
1703            let text_layout_details =
1704                editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1705
1706            let font_size = px(12.0);
1707            let wrap_width = Some(px(64.));
1708
1709            let text = "one two three four five\nsix seven eight";
1710            let buffer = MultiBuffer::build_simple(text, cx);
1711            let map = cx.new_model(|cx| {
1712                DisplayMap::new(
1713                    buffer.clone(),
1714                    font("Helvetica"),
1715                    font_size,
1716                    wrap_width,
1717                    true,
1718                    1,
1719                    1,
1720                    0,
1721                    FoldPlaceholder::test(),
1722                    cx,
1723                )
1724            });
1725
1726            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1727            assert_eq!(
1728                snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1729                "one two \nthree four \nfive\nsix seven \neight"
1730            );
1731            assert_eq!(
1732                snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1733                DisplayPoint::new(DisplayRow(0), 7)
1734            );
1735            assert_eq!(
1736                snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1737                DisplayPoint::new(DisplayRow(1), 0)
1738            );
1739            assert_eq!(
1740                movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1741                DisplayPoint::new(DisplayRow(1), 0)
1742            );
1743            assert_eq!(
1744                movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1745                DisplayPoint::new(DisplayRow(0), 7)
1746            );
1747
1748            let x = snapshot
1749                .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1750            assert_eq!(
1751                movement::up(
1752                    &snapshot,
1753                    DisplayPoint::new(DisplayRow(1), 10),
1754                    language::SelectionGoal::None,
1755                    false,
1756                    &text_layout_details,
1757                ),
1758                (
1759                    DisplayPoint::new(DisplayRow(0), 7),
1760                    language::SelectionGoal::HorizontalPosition(x.0)
1761                )
1762            );
1763            assert_eq!(
1764                movement::down(
1765                    &snapshot,
1766                    DisplayPoint::new(DisplayRow(0), 7),
1767                    language::SelectionGoal::HorizontalPosition(x.0),
1768                    false,
1769                    &text_layout_details
1770                ),
1771                (
1772                    DisplayPoint::new(DisplayRow(1), 10),
1773                    language::SelectionGoal::HorizontalPosition(x.0)
1774                )
1775            );
1776            assert_eq!(
1777                movement::down(
1778                    &snapshot,
1779                    DisplayPoint::new(DisplayRow(1), 10),
1780                    language::SelectionGoal::HorizontalPosition(x.0),
1781                    false,
1782                    &text_layout_details
1783                ),
1784                (
1785                    DisplayPoint::new(DisplayRow(2), 4),
1786                    language::SelectionGoal::HorizontalPosition(x.0)
1787                )
1788            );
1789
1790            let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1791            buffer.update(cx, |buffer, cx| {
1792                buffer.edit([(ix..ix, "and ")], None, cx);
1793            });
1794
1795            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1796            assert_eq!(
1797                snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1798                "three four \nfive\nsix and \nseven eight"
1799            );
1800
1801            // Re-wrap on font size changes
1802            map.update(cx, |map, cx| {
1803                map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1804            });
1805
1806            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1807            assert_eq!(
1808                snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1809                "three \nfour five\nsix and \nseven \neight"
1810            )
1811        });
1812    }
1813
1814    #[gpui::test]
1815    fn test_text_chunks(cx: &mut gpui::AppContext) {
1816        init_test(cx, |_| {});
1817
1818        let text = sample_text(6, 6, 'a');
1819        let buffer = MultiBuffer::build_simple(&text, cx);
1820
1821        let font_size = px(14.0);
1822        let map = cx.new_model(|cx| {
1823            DisplayMap::new(
1824                buffer.clone(),
1825                font("Helvetica"),
1826                font_size,
1827                None,
1828                true,
1829                1,
1830                1,
1831                0,
1832                FoldPlaceholder::test(),
1833                cx,
1834            )
1835        });
1836
1837        buffer.update(cx, |buffer, cx| {
1838            buffer.edit(
1839                vec![
1840                    (
1841                        MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1842                        "\t",
1843                    ),
1844                    (
1845                        MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1846                        "\t",
1847                    ),
1848                    (
1849                        MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1850                        "\t",
1851                    ),
1852                ],
1853                None,
1854                cx,
1855            )
1856        });
1857
1858        assert_eq!(
1859            map.update(cx, |map, cx| map.snapshot(cx))
1860                .text_chunks(DisplayRow(1))
1861                .collect::<String>()
1862                .lines()
1863                .next(),
1864            Some("    b   bbbbb")
1865        );
1866        assert_eq!(
1867            map.update(cx, |map, cx| map.snapshot(cx))
1868                .text_chunks(DisplayRow(2))
1869                .collect::<String>()
1870                .lines()
1871                .next(),
1872            Some("c   ccccc")
1873        );
1874    }
1875
1876    #[gpui::test]
1877    async fn test_chunks(cx: &mut gpui::TestAppContext) {
1878        let text = r#"
1879            fn outer() {}
1880
1881            mod module {
1882                fn inner() {}
1883            }"#
1884        .unindent();
1885
1886        let theme =
1887            SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1888        let language = Arc::new(
1889            Language::new(
1890                LanguageConfig {
1891                    name: "Test".into(),
1892                    matcher: LanguageMatcher {
1893                        path_suffixes: vec![".test".to_string()],
1894                        ..Default::default()
1895                    },
1896                    ..Default::default()
1897                },
1898                Some(tree_sitter_rust::LANGUAGE.into()),
1899            )
1900            .with_highlights_query(
1901                r#"
1902                (mod_item name: (identifier) body: _ @mod.body)
1903                (function_item name: (identifier) @fn.name)
1904                "#,
1905            )
1906            .unwrap(),
1907        );
1908        language.set_theme(&theme);
1909
1910        cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1911
1912        let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1913        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1914        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1915
1916        let font_size = px(14.0);
1917
1918        let map = cx.new_model(|cx| {
1919            DisplayMap::new(
1920                buffer,
1921                font("Helvetica"),
1922                font_size,
1923                None,
1924                true,
1925                1,
1926                1,
1927                1,
1928                FoldPlaceholder::test(),
1929                cx,
1930            )
1931        });
1932        assert_eq!(
1933            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1934            vec![
1935                ("fn ".to_string(), None),
1936                ("outer".to_string(), Some(Hsla::blue())),
1937                ("() {}\n\nmod module ".to_string(), None),
1938                ("{\n    fn ".to_string(), Some(Hsla::red())),
1939                ("inner".to_string(), Some(Hsla::blue())),
1940                ("() {}\n}".to_string(), Some(Hsla::red())),
1941            ]
1942        );
1943        assert_eq!(
1944            cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1945            vec![
1946                ("    fn ".to_string(), Some(Hsla::red())),
1947                ("inner".to_string(), Some(Hsla::blue())),
1948                ("() {}\n}".to_string(), Some(Hsla::red())),
1949            ]
1950        );
1951
1952        map.update(cx, |map, cx| {
1953            map.fold(
1954                vec![Crease::simple(
1955                    MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1956                    FoldPlaceholder::test(),
1957                )],
1958                cx,
1959            )
1960        });
1961        assert_eq!(
1962            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
1963            vec![
1964                ("fn ".to_string(), None),
1965                ("out".to_string(), Some(Hsla::blue())),
1966                ("".to_string(), None),
1967                ("  fn ".to_string(), Some(Hsla::red())),
1968                ("inner".to_string(), Some(Hsla::blue())),
1969                ("() {}\n}".to_string(), Some(Hsla::red())),
1970            ]
1971        );
1972    }
1973
1974    #[gpui::test]
1975    async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
1976        cx.background_executor
1977            .set_block_on_ticks(usize::MAX..=usize::MAX);
1978
1979        let text = r#"
1980            const A: &str = "
1981                one
1982                two
1983                three
1984            ";
1985            const B: &str = "four";
1986        "#
1987        .unindent();
1988
1989        let theme = SyntaxTheme::new_test(vec![
1990            ("string", Hsla::red()),
1991            ("punctuation", Hsla::blue()),
1992            ("keyword", Hsla::green()),
1993        ]);
1994        let language = Arc::new(
1995            Language::new(
1996                LanguageConfig {
1997                    name: "Rust".into(),
1998                    ..Default::default()
1999                },
2000                Some(tree_sitter_rust::LANGUAGE.into()),
2001            )
2002            .with_highlights_query(
2003                r#"
2004                (string_literal) @string
2005                "const" @keyword
2006                [":" ";"] @punctuation
2007                "#,
2008            )
2009            .unwrap(),
2010        );
2011        language.set_theme(&theme);
2012
2013        cx.update(|cx| init_test(cx, |_| {}));
2014
2015        let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
2016        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2017        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
2018        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2019
2020        let map = cx.new_model(|cx| {
2021            DisplayMap::new(
2022                buffer,
2023                font("Courier"),
2024                px(16.0),
2025                None,
2026                true,
2027                1,
2028                1,
2029                0,
2030                FoldPlaceholder::test(),
2031                cx,
2032            )
2033        });
2034
2035        // Insert a block in the middle of a multi-line string literal
2036        map.update(cx, |map, cx| {
2037            map.insert_blocks(
2038                [BlockProperties {
2039                    placement: BlockPlacement::Below(
2040                        buffer_snapshot.anchor_before(Point::new(1, 0)),
2041                    ),
2042                    height: 1,
2043                    style: BlockStyle::Sticky,
2044                    render: Arc::new(|_| div().into_any()),
2045                    priority: 0,
2046                }],
2047                cx,
2048            )
2049        });
2050
2051        pretty_assertions::assert_eq!(
2052            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
2053            [
2054                ("const".into(), Some(Hsla::green())),
2055                (" A".into(), None),
2056                (":".into(), Some(Hsla::blue())),
2057                (" &str = ".into(), None),
2058                ("\"\n    one\n".into(), Some(Hsla::red())),
2059                ("\n".into(), None),
2060                ("    two\n    three\n\"".into(), Some(Hsla::red())),
2061                (";".into(), Some(Hsla::blue())),
2062                ("\n".into(), None),
2063                ("const".into(), Some(Hsla::green())),
2064                (" B".into(), None),
2065                (":".into(), Some(Hsla::blue())),
2066                (" &str = ".into(), None),
2067                ("\"four\"".into(), Some(Hsla::red())),
2068                (";".into(), Some(Hsla::blue())),
2069                ("\n".into(), None),
2070            ]
2071        );
2072    }
2073
2074    #[gpui::test]
2075    async fn test_chunks_with_diagnostics_across_blocks(cx: &mut gpui::TestAppContext) {
2076        cx.background_executor
2077            .set_block_on_ticks(usize::MAX..=usize::MAX);
2078
2079        let text = r#"
2080            struct A {
2081                b: usize;
2082            }
2083            const c: usize = 1;
2084        "#
2085        .unindent();
2086
2087        cx.update(|cx| init_test(cx, |_| {}));
2088
2089        let buffer = cx.new_model(|cx| Buffer::local(text, cx));
2090
2091        buffer.update(cx, |buffer, cx| {
2092            buffer.update_diagnostics(
2093                LanguageServerId(0),
2094                DiagnosticSet::new(
2095                    [DiagnosticEntry {
2096                        range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
2097                        diagnostic: Diagnostic {
2098                            severity: DiagnosticSeverity::ERROR,
2099                            group_id: 1,
2100                            message: "hi".into(),
2101                            ..Default::default()
2102                        },
2103                    }],
2104                    buffer,
2105                ),
2106                cx,
2107            )
2108        });
2109
2110        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
2111        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2112
2113        let map = cx.new_model(|cx| {
2114            DisplayMap::new(
2115                buffer,
2116                font("Courier"),
2117                px(16.0),
2118                None,
2119                true,
2120                1,
2121                1,
2122                0,
2123                FoldPlaceholder::test(),
2124                cx,
2125            )
2126        });
2127
2128        let black = gpui::black().to_rgb();
2129        let red = gpui::red().to_rgb();
2130
2131        // Insert a block in the middle of a multi-line diagnostic.
2132        map.update(cx, |map, cx| {
2133            map.highlight_text(
2134                TypeId::of::<usize>(),
2135                vec![
2136                    buffer_snapshot.anchor_before(Point::new(3, 9))
2137                        ..buffer_snapshot.anchor_after(Point::new(3, 14)),
2138                    buffer_snapshot.anchor_before(Point::new(3, 17))
2139                        ..buffer_snapshot.anchor_after(Point::new(3, 18)),
2140                ],
2141                red.into(),
2142            );
2143            map.insert_blocks(
2144                [BlockProperties {
2145                    placement: BlockPlacement::Below(
2146                        buffer_snapshot.anchor_before(Point::new(1, 0)),
2147                    ),
2148                    height: 1,
2149                    style: BlockStyle::Sticky,
2150                    render: Arc::new(|_| div().into_any()),
2151                    priority: 0,
2152                }],
2153                cx,
2154            )
2155        });
2156
2157        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2158        let mut chunks = Vec::<(String, Option<DiagnosticSeverity>, Rgba)>::new();
2159        for chunk in snapshot.chunks(DisplayRow(0)..DisplayRow(5), true, Default::default()) {
2160            let color = chunk
2161                .highlight_style
2162                .and_then(|style| style.color)
2163                .map_or(black, |color| color.to_rgb());
2164            if let Some((last_chunk, last_severity, last_color)) = chunks.last_mut() {
2165                if *last_severity == chunk.diagnostic_severity && *last_color == color {
2166                    last_chunk.push_str(chunk.text);
2167                    continue;
2168                }
2169            }
2170
2171            chunks.push((chunk.text.to_string(), chunk.diagnostic_severity, color));
2172        }
2173
2174        assert_eq!(
2175            chunks,
2176            [
2177                (
2178                    "struct A {\n    b: usize;\n".into(),
2179                    Some(DiagnosticSeverity::ERROR),
2180                    black
2181                ),
2182                ("\n".into(), None, black),
2183                ("}".into(), Some(DiagnosticSeverity::ERROR), black),
2184                ("\nconst c: ".into(), None, black),
2185                ("usize".into(), None, red),
2186                (" = ".into(), None, black),
2187                ("1".into(), None, red),
2188                (";\n".into(), None, black),
2189            ]
2190        );
2191    }
2192
2193    #[gpui::test]
2194    async fn test_point_translation_with_replace_blocks(cx: &mut gpui::TestAppContext) {
2195        cx.background_executor
2196            .set_block_on_ticks(usize::MAX..=usize::MAX);
2197
2198        cx.update(|cx| init_test(cx, |_| {}));
2199
2200        let buffer = cx.update(|cx| MultiBuffer::build_simple("abcde\nfghij\nklmno\npqrst", cx));
2201        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2202        let map = cx.new_model(|cx| {
2203            DisplayMap::new(
2204                buffer.clone(),
2205                font("Courier"),
2206                px(16.0),
2207                None,
2208                true,
2209                1,
2210                1,
2211                0,
2212                FoldPlaceholder::test(),
2213                cx,
2214            )
2215        });
2216
2217        let snapshot = map.update(cx, |map, cx| {
2218            map.insert_blocks(
2219                [BlockProperties {
2220                    placement: BlockPlacement::Replace(
2221                        buffer_snapshot.anchor_before(Point::new(1, 2))
2222                            ..buffer_snapshot.anchor_after(Point::new(2, 3)),
2223                    ),
2224                    height: 4,
2225                    style: BlockStyle::Fixed,
2226                    render: Arc::new(|_| div().into_any()),
2227                    priority: 0,
2228                }],
2229                cx,
2230            );
2231            map.snapshot(cx)
2232        });
2233
2234        assert_eq!(snapshot.text(), "abcde\n\n\n\n\npqrst");
2235
2236        let point_to_display_points = [
2237            (Point::new(1, 0), DisplayPoint::new(DisplayRow(1), 0)),
2238            (Point::new(2, 0), DisplayPoint::new(DisplayRow(1), 0)),
2239            (Point::new(3, 0), DisplayPoint::new(DisplayRow(5), 0)),
2240        ];
2241        for (buffer_point, display_point) in point_to_display_points {
2242            assert_eq!(
2243                snapshot.point_to_display_point(buffer_point, Bias::Left),
2244                display_point,
2245                "point_to_display_point({:?}, Bias::Left)",
2246                buffer_point
2247            );
2248            assert_eq!(
2249                snapshot.point_to_display_point(buffer_point, Bias::Right),
2250                display_point,
2251                "point_to_display_point({:?}, Bias::Right)",
2252                buffer_point
2253            );
2254        }
2255
2256        let display_points_to_points = [
2257            (
2258                DisplayPoint::new(DisplayRow(1), 0),
2259                Point::new(1, 0),
2260                Point::new(2, 5),
2261            ),
2262            (
2263                DisplayPoint::new(DisplayRow(2), 0),
2264                Point::new(1, 0),
2265                Point::new(2, 5),
2266            ),
2267            (
2268                DisplayPoint::new(DisplayRow(3), 0),
2269                Point::new(1, 0),
2270                Point::new(2, 5),
2271            ),
2272            (
2273                DisplayPoint::new(DisplayRow(4), 0),
2274                Point::new(1, 0),
2275                Point::new(2, 5),
2276            ),
2277            (
2278                DisplayPoint::new(DisplayRow(5), 0),
2279                Point::new(3, 0),
2280                Point::new(3, 0),
2281            ),
2282        ];
2283        for (display_point, left_buffer_point, right_buffer_point) in display_points_to_points {
2284            assert_eq!(
2285                snapshot.display_point_to_point(display_point, Bias::Left),
2286                left_buffer_point,
2287                "display_point_to_point({:?}, Bias::Left)",
2288                display_point
2289            );
2290            assert_eq!(
2291                snapshot.display_point_to_point(display_point, Bias::Right),
2292                right_buffer_point,
2293                "display_point_to_point({:?}, Bias::Right)",
2294                display_point
2295            );
2296        }
2297    }
2298
2299    // todo(linux) fails due to pixel differences in text rendering
2300    #[cfg(target_os = "macos")]
2301    #[gpui::test]
2302    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
2303        cx.background_executor
2304            .set_block_on_ticks(usize::MAX..=usize::MAX);
2305
2306        let text = r#"
2307            fn outer() {}
2308
2309            mod module {
2310                fn inner() {}
2311            }"#
2312        .unindent();
2313
2314        let theme =
2315            SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
2316        let language = Arc::new(
2317            Language::new(
2318                LanguageConfig {
2319                    name: "Test".into(),
2320                    matcher: LanguageMatcher {
2321                        path_suffixes: vec![".test".to_string()],
2322                        ..Default::default()
2323                    },
2324                    ..Default::default()
2325                },
2326                Some(tree_sitter_rust::LANGUAGE.into()),
2327            )
2328            .with_highlights_query(
2329                r#"
2330                (mod_item name: (identifier) body: _ @mod.body)
2331                (function_item name: (identifier) @fn.name)
2332                "#,
2333            )
2334            .unwrap(),
2335        );
2336        language.set_theme(&theme);
2337
2338        cx.update(|cx| init_test(cx, |_| {}));
2339
2340        let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
2341        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2342        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
2343
2344        let font_size = px(16.0);
2345
2346        let map = cx.new_model(|cx| {
2347            DisplayMap::new(
2348                buffer,
2349                font("Courier"),
2350                font_size,
2351                Some(px(40.0)),
2352                true,
2353                1,
2354                1,
2355                0,
2356                FoldPlaceholder::test(),
2357                cx,
2358            )
2359        });
2360        assert_eq!(
2361            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
2362            [
2363                ("fn \n".to_string(), None),
2364                ("oute\nr".to_string(), Some(Hsla::blue())),
2365                ("() \n{}\n\n".to_string(), None),
2366            ]
2367        );
2368        assert_eq!(
2369            cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
2370            [("{}\n\n".to_string(), None)]
2371        );
2372
2373        map.update(cx, |map, cx| {
2374            map.fold(
2375                vec![Crease::simple(
2376                    MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
2377                    FoldPlaceholder::test(),
2378                )],
2379                cx,
2380            )
2381        });
2382        assert_eq!(
2383            cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
2384            [
2385                ("out".to_string(), Some(Hsla::blue())),
2386                ("\n".to_string(), None),
2387                ("  \nfn ".to_string(), Some(Hsla::red())),
2388                ("i\n".to_string(), Some(Hsla::blue()))
2389            ]
2390        );
2391    }
2392
2393    #[gpui::test]
2394    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
2395        cx.update(|cx| init_test(cx, |_| {}));
2396
2397        let theme =
2398            SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
2399        let language = Arc::new(
2400            Language::new(
2401                LanguageConfig {
2402                    name: "Test".into(),
2403                    matcher: LanguageMatcher {
2404                        path_suffixes: vec![".test".to_string()],
2405                        ..Default::default()
2406                    },
2407                    ..Default::default()
2408                },
2409                Some(tree_sitter_rust::LANGUAGE.into()),
2410            )
2411            .with_highlights_query(
2412                r#"
2413                ":" @operator
2414                (string_literal) @string
2415                "#,
2416            )
2417            .unwrap(),
2418        );
2419        language.set_theme(&theme);
2420
2421        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
2422
2423        let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
2424        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
2425
2426        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
2427        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
2428
2429        let font_size = px(16.0);
2430        let map = cx.new_model(|cx| {
2431            DisplayMap::new(
2432                buffer,
2433                font("Courier"),
2434                font_size,
2435                None,
2436                true,
2437                1,
2438                1,
2439                1,
2440                FoldPlaceholder::test(),
2441                cx,
2442            )
2443        });
2444
2445        enum MyType {}
2446
2447        let style = HighlightStyle {
2448            color: Some(Hsla::blue()),
2449            ..Default::default()
2450        };
2451
2452        map.update(cx, |map, _cx| {
2453            map.highlight_text(
2454                TypeId::of::<MyType>(),
2455                highlighted_ranges
2456                    .into_iter()
2457                    .map(|range| {
2458                        buffer_snapshot.anchor_before(range.start)
2459                            ..buffer_snapshot.anchor_before(range.end)
2460                    })
2461                    .collect(),
2462                style,
2463            );
2464        });
2465
2466        assert_eq!(
2467            cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
2468            [
2469                ("const ".to_string(), None, None),
2470                ("a".to_string(), None, Some(Hsla::blue())),
2471                (":".to_string(), Some(Hsla::red()), None),
2472                (" B = ".to_string(), None, None),
2473                ("\"c ".to_string(), Some(Hsla::green()), None),
2474                ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2475                ("\"".to_string(), Some(Hsla::green()), None),
2476            ]
2477        );
2478    }
2479
2480    #[gpui::test]
2481    fn test_clip_point(cx: &mut gpui::AppContext) {
2482        init_test(cx, |_| {});
2483
2484        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
2485            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2486
2487            match bias {
2488                Bias::Left => {
2489                    if shift_right {
2490                        *markers[1].column_mut() += 1;
2491                    }
2492
2493                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2494                }
2495                Bias::Right => {
2496                    if shift_right {
2497                        *markers[0].column_mut() += 1;
2498                    }
2499
2500                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2501                }
2502            };
2503        }
2504
2505        use Bias::{Left, Right};
2506        assert("ˇˇα", false, Left, cx);
2507        assert("ˇˇα", true, Left, cx);
2508        assert("ˇˇα", false, Right, cx);
2509        assert("ˇαˇ", true, Right, cx);
2510        assert("ˇˇ✋", false, Left, cx);
2511        assert("ˇˇ✋", true, Left, cx);
2512        assert("ˇˇ✋", false, Right, cx);
2513        assert("ˇ✋ˇ", true, Right, cx);
2514        assert("ˇˇ🍐", false, Left, cx);
2515        assert("ˇˇ🍐", true, Left, cx);
2516        assert("ˇˇ🍐", false, Right, cx);
2517        assert("ˇ🍐ˇ", true, Right, cx);
2518        assert("ˇˇ\t", false, Left, cx);
2519        assert("ˇˇ\t", true, Left, cx);
2520        assert("ˇˇ\t", false, Right, cx);
2521        assert("ˇ\tˇ", true, Right, cx);
2522        assert(" ˇˇ\t", false, Left, cx);
2523        assert(" ˇˇ\t", true, Left, cx);
2524        assert(" ˇˇ\t", false, Right, cx);
2525        assert(" ˇ\tˇ", true, Right, cx);
2526        assert("   ˇˇ\t", false, Left, cx);
2527        assert("   ˇˇ\t", false, Right, cx);
2528    }
2529
2530    #[gpui::test]
2531    fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
2532        init_test(cx, |_| {});
2533
2534        fn assert(text: &str, cx: &mut gpui::AppContext) {
2535            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2536            unmarked_snapshot.clip_at_line_ends = true;
2537            assert_eq!(
2538                unmarked_snapshot.clip_point(markers[1], Bias::Left),
2539                markers[0]
2540            );
2541        }
2542
2543        assert("ˇˇ", cx);
2544        assert("ˇaˇ", cx);
2545        assert("aˇbˇ", cx);
2546        assert("aˇαˇ", cx);
2547    }
2548
2549    #[gpui::test]
2550    fn test_creases(cx: &mut gpui::AppContext) {
2551        init_test(cx, |_| {});
2552
2553        let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2554        let buffer = MultiBuffer::build_simple(text, cx);
2555        let font_size = px(14.0);
2556        cx.new_model(|cx| {
2557            let mut map = DisplayMap::new(
2558                buffer.clone(),
2559                font("Helvetica"),
2560                font_size,
2561                None,
2562                true,
2563                1,
2564                1,
2565                0,
2566                FoldPlaceholder::test(),
2567                cx,
2568            );
2569            let snapshot = map.buffer.read(cx).snapshot(cx);
2570            let range =
2571                snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2572
2573            map.crease_map.insert(
2574                [Crease::inline(
2575                    range,
2576                    FoldPlaceholder::test(),
2577                    |_row, _status, _toggle, _cx| div(),
2578                    |_row, _status, _cx| div(),
2579                )],
2580                &map.buffer.read(cx).snapshot(cx),
2581            );
2582
2583            map
2584        });
2585    }
2586
2587    #[gpui::test]
2588    fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
2589        init_test(cx, |_| {});
2590
2591        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
2592        let buffer = MultiBuffer::build_simple(text, cx);
2593        let font_size = px(14.0);
2594
2595        let map = cx.new_model(|cx| {
2596            DisplayMap::new(
2597                buffer.clone(),
2598                font("Helvetica"),
2599                font_size,
2600                None,
2601                true,
2602                1,
2603                1,
2604                0,
2605                FoldPlaceholder::test(),
2606                cx,
2607            )
2608        });
2609        let map = map.update(cx, |map, cx| map.snapshot(cx));
2610        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
2611        assert_eq!(
2612            map.text_chunks(DisplayRow(0)).collect::<String>(),
2613            "✅       α\nβ   \n🏀β      γ"
2614        );
2615        assert_eq!(
2616            map.text_chunks(DisplayRow(1)).collect::<String>(),
2617            "β   \n🏀β      γ"
2618        );
2619        assert_eq!(
2620            map.text_chunks(DisplayRow(2)).collect::<String>(),
2621            "🏀β      γ"
2622        );
2623
2624        let point = MultiBufferPoint::new(0, "\t\t".len() as u32);
2625        let display_point = DisplayPoint::new(DisplayRow(0), "".len() as u32);
2626        assert_eq!(point.to_display_point(&map), display_point);
2627        assert_eq!(display_point.to_point(&map), point);
2628
2629        let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2630        let display_point = DisplayPoint::new(DisplayRow(1), "β   ".len() as u32);
2631        assert_eq!(point.to_display_point(&map), display_point);
2632        assert_eq!(display_point.to_point(&map), point,);
2633
2634        let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2635        let display_point = DisplayPoint::new(DisplayRow(2), "🏀β      ".len() as u32);
2636        assert_eq!(point.to_display_point(&map), display_point);
2637        assert_eq!(display_point.to_point(&map), point,);
2638
2639        // Display points inside of expanded tabs
2640        assert_eq!(
2641            DisplayPoint::new(DisplayRow(0), "".len() as u32).to_point(&map),
2642            MultiBufferPoint::new(0, "\t".len() as u32),
2643        );
2644        assert_eq!(
2645            DisplayPoint::new(DisplayRow(0), "".len() as u32).to_point(&map),
2646            MultiBufferPoint::new(0, "".len() as u32),
2647        );
2648
2649        // Clipping display points inside of multi-byte characters
2650        assert_eq!(
2651            map.clip_point(
2652                DisplayPoint::new(DisplayRow(0), "".len() as u32 - 1),
2653                Left
2654            ),
2655            DisplayPoint::new(DisplayRow(0), 0)
2656        );
2657        assert_eq!(
2658            map.clip_point(
2659                DisplayPoint::new(DisplayRow(0), "".len() as u32 - 1),
2660                Bias::Right
2661            ),
2662            DisplayPoint::new(DisplayRow(0), "".len() as u32)
2663        );
2664    }
2665
2666    #[gpui::test]
2667    fn test_max_point(cx: &mut gpui::AppContext) {
2668        init_test(cx, |_| {});
2669
2670        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2671        let font_size = px(14.0);
2672        let map = cx.new_model(|cx| {
2673            DisplayMap::new(
2674                buffer.clone(),
2675                font("Helvetica"),
2676                font_size,
2677                None,
2678                true,
2679                1,
2680                1,
2681                0,
2682                FoldPlaceholder::test(),
2683                cx,
2684            )
2685        });
2686        assert_eq!(
2687            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2688            DisplayPoint::new(DisplayRow(1), 11)
2689        )
2690    }
2691
2692    fn syntax_chunks(
2693        rows: Range<DisplayRow>,
2694        map: &Model<DisplayMap>,
2695        theme: &SyntaxTheme,
2696        cx: &mut AppContext,
2697    ) -> Vec<(String, Option<Hsla>)> {
2698        chunks(rows, map, theme, cx)
2699            .into_iter()
2700            .map(|(text, color, _)| (text, color))
2701            .collect()
2702    }
2703
2704    fn chunks(
2705        rows: Range<DisplayRow>,
2706        map: &Model<DisplayMap>,
2707        theme: &SyntaxTheme,
2708        cx: &mut AppContext,
2709    ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2710        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2711        let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2712        for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2713            let syntax_color = chunk
2714                .syntax_highlight_id
2715                .and_then(|id| id.style(theme)?.color);
2716            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2717            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
2718                if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2719                    last_chunk.push_str(chunk.text);
2720                    continue;
2721                }
2722            }
2723            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2724        }
2725        chunks
2726    }
2727
2728    fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
2729        let settings = SettingsStore::test(cx);
2730        cx.set_global(settings);
2731        language::init(cx);
2732        crate::init(cx);
2733        Project::init_settings(cx);
2734        theme::init(LoadThemes::JustBase, cx);
2735        cx.update_global::<SettingsStore, _>(|store, cx| {
2736            store.update_user_settings::<AllLanguageSettings>(cx, f);
2737        });
2738    }
2739}