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