display_map.rs

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