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