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