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