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::{div, font, observe, px, AppContext, BorrowAppContext, Context, Element, Hsla};
1161    use language::{
1162        language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1163        Buffer, Language, LanguageConfig, LanguageMatcher,
1164    };
1165    use project::Project;
1166    use rand::{prelude::*, Rng};
1167    use settings::SettingsStore;
1168    use smol::stream::StreamExt;
1169    use std::{env, sync::Arc};
1170    use theme::{LoadThemes, SyntaxTheme};
1171    use unindent::Unindent as _;
1172    use util::test::{marked_text_ranges, sample_text};
1173    use Bias::*;
1174
1175    #[gpui::test(iterations = 100)]
1176    async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1177        cx.background_executor.set_block_on_ticks(0..=50);
1178        let operations = env::var("OPERATIONS")
1179            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1180            .unwrap_or(10);
1181
1182        let mut tab_size = rng.gen_range(1..=4);
1183        let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1184        let excerpt_header_height = rng.gen_range(1..=5);
1185        let font_size = px(14.0);
1186        let max_wrap_width = 300.0;
1187        let mut wrap_width = if rng.gen_bool(0.1) {
1188            None
1189        } else {
1190            Some(px(rng.gen_range(0.0..=max_wrap_width)))
1191        };
1192
1193        log::info!("tab size: {}", tab_size);
1194        log::info!("wrap width: {:?}", wrap_width);
1195
1196        cx.update(|cx| {
1197            init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1198        });
1199
1200        let buffer = cx.update(|cx| {
1201            if rng.gen() {
1202                let len = rng.gen_range(0..10);
1203                let text = util::RandomCharIter::new(&mut rng)
1204                    .take(len)
1205                    .collect::<String>();
1206                MultiBuffer::build_simple(&text, cx)
1207            } else {
1208                MultiBuffer::build_random(&mut rng, cx)
1209            }
1210        });
1211
1212        let map = cx.new_model(|cx| {
1213            DisplayMap::new(
1214                buffer.clone(),
1215                font("Helvetica"),
1216                font_size,
1217                wrap_width,
1218                true,
1219                buffer_start_excerpt_header_height,
1220                excerpt_header_height,
1221                0,
1222                FoldPlaceholder::test(),
1223                cx,
1224            )
1225        });
1226        let mut notifications = observe(&map, cx);
1227        let mut fold_count = 0;
1228        let mut blocks = Vec::new();
1229
1230        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1231        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1232        log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1233        log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1234        log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1235        log::info!("block text: {:?}", snapshot.block_snapshot.text());
1236        log::info!("display text: {:?}", snapshot.text());
1237
1238        for _i in 0..operations {
1239            match rng.gen_range(0..100) {
1240                0..=19 => {
1241                    wrap_width = if rng.gen_bool(0.2) {
1242                        None
1243                    } else {
1244                        Some(px(rng.gen_range(0.0..=max_wrap_width)))
1245                    };
1246                    log::info!("setting wrap width to {:?}", wrap_width);
1247                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1248                }
1249                20..=29 => {
1250                    let mut tab_sizes = vec![1, 2, 3, 4];
1251                    tab_sizes.remove((tab_size - 1) as usize);
1252                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
1253                    log::info!("setting tab size to {:?}", tab_size);
1254                    cx.update(|cx| {
1255                        cx.update_global::<SettingsStore, _>(|store, cx| {
1256                            store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1257                                s.defaults.tab_size = NonZeroU32::new(tab_size);
1258                            });
1259                        });
1260                    });
1261                }
1262                30..=44 => {
1263                    map.update(cx, |map, cx| {
1264                        if rng.gen() || blocks.is_empty() {
1265                            let buffer = map.snapshot(cx).buffer_snapshot;
1266                            let block_properties = (0..rng.gen_range(1..=1))
1267                                .map(|_| {
1268                                    let position =
1269                                        buffer.anchor_after(buffer.clip_offset(
1270                                            rng.gen_range(0..=buffer.len()),
1271                                            Bias::Left,
1272                                        ));
1273
1274                                    let placement = if rng.gen() {
1275                                        BlockPlacement::Above(position)
1276                                    } else {
1277                                        BlockPlacement::Below(position)
1278                                    };
1279                                    let height = rng.gen_range(1..5);
1280                                    log::info!(
1281                                        "inserting block {:?} with height {}",
1282                                        placement.as_ref().map(|p| p.to_point(&buffer)),
1283                                        height
1284                                    );
1285                                    let priority = rng.gen_range(1..100);
1286                                    BlockProperties {
1287                                        placement,
1288                                        style: BlockStyle::Fixed,
1289                                        height,
1290                                        render: Box::new(|_| div().into_any()),
1291                                        priority,
1292                                    }
1293                                })
1294                                .collect::<Vec<_>>();
1295                            blocks.extend(map.insert_blocks(block_properties, cx));
1296                        } else {
1297                            blocks.shuffle(&mut rng);
1298                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1299                            let block_ids_to_remove = (0..remove_count)
1300                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1301                                .collect();
1302                            log::info!("removing block ids {:?}", block_ids_to_remove);
1303                            map.remove_blocks(block_ids_to_remove, cx);
1304                        }
1305                    });
1306                }
1307                45..=79 => {
1308                    let mut ranges = Vec::new();
1309                    for _ in 0..rng.gen_range(1..=3) {
1310                        buffer.read_with(cx, |buffer, cx| {
1311                            let buffer = buffer.read(cx);
1312                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1313                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1314                            ranges.push(start..end);
1315                        });
1316                    }
1317
1318                    if rng.gen() && fold_count > 0 {
1319                        log::info!("unfolding ranges: {:?}", ranges);
1320                        map.update(cx, |map, cx| {
1321                            map.unfold(ranges, true, cx);
1322                        });
1323                    } else {
1324                        log::info!("folding ranges: {:?}", ranges);
1325                        map.update(cx, |map, cx| {
1326                            map.fold(
1327                                ranges
1328                                    .into_iter()
1329                                    .map(|range| (range, FoldPlaceholder::test())),
1330                                cx,
1331                            );
1332                        });
1333                    }
1334                }
1335                _ => {
1336                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1337                }
1338            }
1339
1340            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1341                notifications.next().await.unwrap();
1342            }
1343
1344            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1345            fold_count = snapshot.fold_count();
1346            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1347            log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1348            log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1349            log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1350            log::info!("block text: {:?}", snapshot.block_snapshot.text());
1351            log::info!("display text: {:?}", snapshot.text());
1352
1353            // Line boundaries
1354            let buffer = &snapshot.buffer_snapshot;
1355            for _ in 0..5 {
1356                let row = rng.gen_range(0..=buffer.max_point().row);
1357                let column = rng.gen_range(0..=buffer.line_len(MultiBufferRow(row)));
1358                let point = buffer.clip_point(Point::new(row, column), Left);
1359
1360                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1361                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1362
1363                assert!(prev_buffer_bound <= point);
1364                assert!(next_buffer_bound >= point);
1365                assert_eq!(prev_buffer_bound.column, 0);
1366                assert_eq!(prev_display_bound.column(), 0);
1367                if next_buffer_bound < buffer.max_point() {
1368                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1369                }
1370
1371                assert_eq!(
1372                    prev_display_bound,
1373                    prev_buffer_bound.to_display_point(&snapshot),
1374                    "row boundary before {:?}. reported buffer row boundary: {:?}",
1375                    point,
1376                    prev_buffer_bound
1377                );
1378                assert_eq!(
1379                    next_display_bound,
1380                    next_buffer_bound.to_display_point(&snapshot),
1381                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
1382                    point,
1383                    next_buffer_bound
1384                );
1385                assert_eq!(
1386                    prev_buffer_bound,
1387                    prev_display_bound.to_point(&snapshot),
1388                    "row boundary before {:?}. reported display row boundary: {:?}",
1389                    point,
1390                    prev_display_bound
1391                );
1392                assert_eq!(
1393                    next_buffer_bound,
1394                    next_display_bound.to_point(&snapshot),
1395                    "row boundary after {:?}. reported display row boundary: {:?}",
1396                    point,
1397                    next_display_bound
1398                );
1399            }
1400
1401            // Movement
1402            let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1403            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1404            for _ in 0..5 {
1405                let row = rng.gen_range(0..=snapshot.max_point().row().0);
1406                let column = rng.gen_range(0..=snapshot.line_len(DisplayRow(row)));
1407                let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1408
1409                log::info!("Moving from point {:?}", point);
1410
1411                let moved_right = movement::right(&snapshot, point);
1412                log::info!("Right {:?}", moved_right);
1413                if point < max_point {
1414                    assert!(moved_right > point);
1415                    if point.column() == snapshot.line_len(point.row())
1416                        || snapshot.soft_wrap_indent(point.row()).is_some()
1417                            && point.column() == snapshot.line_len(point.row()) - 1
1418                    {
1419                        assert!(moved_right.row() > point.row());
1420                    }
1421                } else {
1422                    assert_eq!(moved_right, point);
1423                }
1424
1425                let moved_left = movement::left(&snapshot, point);
1426                log::info!("Left {:?}", moved_left);
1427                if point > min_point {
1428                    assert!(moved_left < point);
1429                    if point.column() == 0 {
1430                        assert!(moved_left.row() < point.row());
1431                    }
1432                } else {
1433                    assert_eq!(moved_left, point);
1434                }
1435            }
1436        }
1437    }
1438
1439    #[cfg(target_os = "macos")]
1440    #[gpui::test(retries = 5)]
1441    async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1442        cx.background_executor
1443            .set_block_on_ticks(usize::MAX..=usize::MAX);
1444        cx.update(|cx| {
1445            init_test(cx, |_| {});
1446        });
1447
1448        let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1449        let editor = cx.editor.clone();
1450        let window = cx.window;
1451
1452        _ = cx.update_window(window, |_, cx| {
1453            let text_layout_details =
1454                editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1455
1456            let font_size = px(12.0);
1457            let wrap_width = Some(px(64.));
1458
1459            let text = "one two three four five\nsix seven eight";
1460            let buffer = MultiBuffer::build_simple(text, cx);
1461            let map = cx.new_model(|cx| {
1462                DisplayMap::new(
1463                    buffer.clone(),
1464                    font("Helvetica"),
1465                    font_size,
1466                    wrap_width,
1467                    true,
1468                    1,
1469                    1,
1470                    0,
1471                    FoldPlaceholder::test(),
1472                    cx,
1473                )
1474            });
1475
1476            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1477            assert_eq!(
1478                snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1479                "one two \nthree four \nfive\nsix seven \neight"
1480            );
1481            assert_eq!(
1482                snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1483                DisplayPoint::new(DisplayRow(0), 7)
1484            );
1485            assert_eq!(
1486                snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1487                DisplayPoint::new(DisplayRow(1), 0)
1488            );
1489            assert_eq!(
1490                movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1491                DisplayPoint::new(DisplayRow(1), 0)
1492            );
1493            assert_eq!(
1494                movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1495                DisplayPoint::new(DisplayRow(0), 7)
1496            );
1497
1498            let x = snapshot
1499                .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1500            assert_eq!(
1501                movement::up(
1502                    &snapshot,
1503                    DisplayPoint::new(DisplayRow(1), 10),
1504                    language::SelectionGoal::None,
1505                    false,
1506                    &text_layout_details,
1507                ),
1508                (
1509                    DisplayPoint::new(DisplayRow(0), 7),
1510                    language::SelectionGoal::HorizontalPosition(x.0)
1511                )
1512            );
1513            assert_eq!(
1514                movement::down(
1515                    &snapshot,
1516                    DisplayPoint::new(DisplayRow(0), 7),
1517                    language::SelectionGoal::HorizontalPosition(x.0),
1518                    false,
1519                    &text_layout_details
1520                ),
1521                (
1522                    DisplayPoint::new(DisplayRow(1), 10),
1523                    language::SelectionGoal::HorizontalPosition(x.0)
1524                )
1525            );
1526            assert_eq!(
1527                movement::down(
1528                    &snapshot,
1529                    DisplayPoint::new(DisplayRow(1), 10),
1530                    language::SelectionGoal::HorizontalPosition(x.0),
1531                    false,
1532                    &text_layout_details
1533                ),
1534                (
1535                    DisplayPoint::new(DisplayRow(2), 4),
1536                    language::SelectionGoal::HorizontalPosition(x.0)
1537                )
1538            );
1539
1540            let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1541            buffer.update(cx, |buffer, cx| {
1542                buffer.edit([(ix..ix, "and ")], None, cx);
1543            });
1544
1545            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1546            assert_eq!(
1547                snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1548                "three four \nfive\nsix and \nseven eight"
1549            );
1550
1551            // Re-wrap on font size changes
1552            map.update(cx, |map, cx| {
1553                map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1554            });
1555
1556            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1557            assert_eq!(
1558                snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1559                "three \nfour five\nsix and \nseven \neight"
1560            )
1561        });
1562    }
1563
1564    #[gpui::test]
1565    fn test_text_chunks(cx: &mut gpui::AppContext) {
1566        init_test(cx, |_| {});
1567
1568        let text = sample_text(6, 6, 'a');
1569        let buffer = MultiBuffer::build_simple(&text, cx);
1570
1571        let font_size = px(14.0);
1572        let map = cx.new_model(|cx| {
1573            DisplayMap::new(
1574                buffer.clone(),
1575                font("Helvetica"),
1576                font_size,
1577                None,
1578                true,
1579                1,
1580                1,
1581                0,
1582                FoldPlaceholder::test(),
1583                cx,
1584            )
1585        });
1586
1587        buffer.update(cx, |buffer, cx| {
1588            buffer.edit(
1589                vec![
1590                    (
1591                        MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1592                        "\t",
1593                    ),
1594                    (
1595                        MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1596                        "\t",
1597                    ),
1598                    (
1599                        MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1600                        "\t",
1601                    ),
1602                ],
1603                None,
1604                cx,
1605            )
1606        });
1607
1608        assert_eq!(
1609            map.update(cx, |map, cx| map.snapshot(cx))
1610                .text_chunks(DisplayRow(1))
1611                .collect::<String>()
1612                .lines()
1613                .next(),
1614            Some("    b   bbbbb")
1615        );
1616        assert_eq!(
1617            map.update(cx, |map, cx| map.snapshot(cx))
1618                .text_chunks(DisplayRow(2))
1619                .collect::<String>()
1620                .lines()
1621                .next(),
1622            Some("c   ccccc")
1623        );
1624    }
1625
1626    #[gpui::test]
1627    async fn test_chunks(cx: &mut gpui::TestAppContext) {
1628        let text = r#"
1629            fn outer() {}
1630
1631            mod module {
1632                fn inner() {}
1633            }"#
1634        .unindent();
1635
1636        let theme =
1637            SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1638        let language = Arc::new(
1639            Language::new(
1640                LanguageConfig {
1641                    name: "Test".into(),
1642                    matcher: LanguageMatcher {
1643                        path_suffixes: vec![".test".to_string()],
1644                        ..Default::default()
1645                    },
1646                    ..Default::default()
1647                },
1648                Some(tree_sitter_rust::LANGUAGE.into()),
1649            )
1650            .with_highlights_query(
1651                r#"
1652                (mod_item name: (identifier) body: _ @mod.body)
1653                (function_item name: (identifier) @fn.name)
1654                "#,
1655            )
1656            .unwrap(),
1657        );
1658        language.set_theme(&theme);
1659
1660        cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1661
1662        let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1663        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1664        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1665
1666        let font_size = px(14.0);
1667
1668        let map = cx.new_model(|cx| {
1669            DisplayMap::new(
1670                buffer,
1671                font("Helvetica"),
1672                font_size,
1673                None,
1674                true,
1675                1,
1676                1,
1677                1,
1678                FoldPlaceholder::test(),
1679                cx,
1680            )
1681        });
1682        assert_eq!(
1683            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1684            vec![
1685                ("fn ".to_string(), None),
1686                ("outer".to_string(), Some(Hsla::blue())),
1687                ("() {}\n\nmod module ".to_string(), None),
1688                ("{\n    fn ".to_string(), Some(Hsla::red())),
1689                ("inner".to_string(), Some(Hsla::blue())),
1690                ("() {}\n}".to_string(), Some(Hsla::red())),
1691            ]
1692        );
1693        assert_eq!(
1694            cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1695            vec![
1696                ("    fn ".to_string(), Some(Hsla::red())),
1697                ("inner".to_string(), Some(Hsla::blue())),
1698                ("() {}\n}".to_string(), Some(Hsla::red())),
1699            ]
1700        );
1701
1702        map.update(cx, |map, cx| {
1703            map.fold(
1704                vec![(
1705                    MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1706                    FoldPlaceholder::test(),
1707                )],
1708                cx,
1709            )
1710        });
1711        assert_eq!(
1712            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
1713            vec![
1714                ("fn ".to_string(), None),
1715                ("out".to_string(), Some(Hsla::blue())),
1716                ("".to_string(), None),
1717                ("  fn ".to_string(), Some(Hsla::red())),
1718                ("inner".to_string(), Some(Hsla::blue())),
1719                ("() {}\n}".to_string(), Some(Hsla::red())),
1720            ]
1721        );
1722    }
1723
1724    #[gpui::test]
1725    async fn test_chunks_with_syntax_highlighting_across_blocks(cx: &mut gpui::TestAppContext) {
1726        cx.background_executor
1727            .set_block_on_ticks(usize::MAX..=usize::MAX);
1728
1729        let text = r#"
1730            const A: &str = "
1731                one
1732                two
1733                three
1734            ";
1735            const B: &str = "four";
1736        "#
1737        .unindent();
1738
1739        let theme = SyntaxTheme::new_test(vec![
1740            ("string", Hsla::red()),
1741            ("punctuation", Hsla::blue()),
1742            ("keyword", Hsla::green()),
1743        ]);
1744        let language = Arc::new(
1745            Language::new(
1746                LanguageConfig {
1747                    name: "Rust".into(),
1748                    ..Default::default()
1749                },
1750                Some(tree_sitter_rust::LANGUAGE.into()),
1751            )
1752            .with_highlights_query(
1753                r#"
1754                (string_literal) @string
1755                "const" @keyword
1756                [":" ";"] @punctuation
1757                "#,
1758            )
1759            .unwrap(),
1760        );
1761        language.set_theme(&theme);
1762
1763        cx.update(|cx| init_test(cx, |_| {}));
1764
1765        let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1766        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1767        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1768        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1769
1770        let map = cx.new_model(|cx| {
1771            DisplayMap::new(
1772                buffer,
1773                font("Courier"),
1774                px(16.0),
1775                None,
1776                true,
1777                1,
1778                1,
1779                0,
1780                FoldPlaceholder::test(),
1781                cx,
1782            )
1783        });
1784
1785        // Insert a block in the middle of a multi-line string literal
1786        map.update(cx, |map, cx| {
1787            map.insert_blocks(
1788                [BlockProperties {
1789                    placement: BlockPlacement::Below(
1790                        buffer_snapshot.anchor_before(Point::new(1, 0)),
1791                    ),
1792                    height: 1,
1793                    style: BlockStyle::Sticky,
1794                    render: Box::new(|_| div().into_any()),
1795                    priority: 0,
1796                }],
1797                cx,
1798            )
1799        });
1800
1801        pretty_assertions::assert_eq!(
1802            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(7), &map, &theme, cx)),
1803            [
1804                ("const".into(), Some(Hsla::green())),
1805                (" A".into(), None),
1806                (":".into(), Some(Hsla::blue())),
1807                (" &str = ".into(), None),
1808                ("\"\n    one\n".into(), Some(Hsla::red())),
1809                ("\n".into(), None),
1810                ("    two\n    three\n\"".into(), Some(Hsla::red())),
1811                (";".into(), Some(Hsla::blue())),
1812                ("\n".into(), None),
1813                ("const".into(), Some(Hsla::green())),
1814                (" B".into(), None),
1815                (":".into(), Some(Hsla::blue())),
1816                (" &str = ".into(), None),
1817                ("\"four\"".into(), Some(Hsla::red())),
1818                (";".into(), Some(Hsla::blue())),
1819                ("\n".into(), None),
1820            ]
1821        );
1822    }
1823
1824    // todo(linux) fails due to pixel differences in text rendering
1825    #[cfg(target_os = "macos")]
1826    #[gpui::test]
1827    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1828        cx.background_executor
1829            .set_block_on_ticks(usize::MAX..=usize::MAX);
1830
1831        let text = r#"
1832            fn outer() {}
1833
1834            mod module {
1835                fn inner() {}
1836            }"#
1837        .unindent();
1838
1839        let theme =
1840            SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1841        let language = Arc::new(
1842            Language::new(
1843                LanguageConfig {
1844                    name: "Test".into(),
1845                    matcher: LanguageMatcher {
1846                        path_suffixes: vec![".test".to_string()],
1847                        ..Default::default()
1848                    },
1849                    ..Default::default()
1850                },
1851                Some(tree_sitter_rust::LANGUAGE.into()),
1852            )
1853            .with_highlights_query(
1854                r#"
1855                (mod_item name: (identifier) body: _ @mod.body)
1856                (function_item name: (identifier) @fn.name)
1857                "#,
1858            )
1859            .unwrap(),
1860        );
1861        language.set_theme(&theme);
1862
1863        cx.update(|cx| init_test(cx, |_| {}));
1864
1865        let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1866        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1867        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1868
1869        let font_size = px(16.0);
1870
1871        let map = cx.new_model(|cx| {
1872            DisplayMap::new(
1873                buffer,
1874                font("Courier"),
1875                font_size,
1876                Some(px(40.0)),
1877                true,
1878                1,
1879                1,
1880                0,
1881                FoldPlaceholder::test(),
1882                cx,
1883            )
1884        });
1885        assert_eq!(
1886            cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1887            [
1888                ("fn \n".to_string(), None),
1889                ("oute\nr".to_string(), Some(Hsla::blue())),
1890                ("() \n{}\n\n".to_string(), None),
1891            ]
1892        );
1893        assert_eq!(
1894            cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1895            [("{}\n\n".to_string(), None)]
1896        );
1897
1898        map.update(cx, |map, cx| {
1899            map.fold(
1900                vec![(
1901                    MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1902                    FoldPlaceholder::test(),
1903                )],
1904                cx,
1905            )
1906        });
1907        assert_eq!(
1908            cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
1909            [
1910                ("out".to_string(), Some(Hsla::blue())),
1911                ("\n".to_string(), None),
1912                ("  \nfn ".to_string(), Some(Hsla::red())),
1913                ("i\n".to_string(), Some(Hsla::blue()))
1914            ]
1915        );
1916    }
1917
1918    #[gpui::test]
1919    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1920        cx.update(|cx| init_test(cx, |_| {}));
1921
1922        let theme =
1923            SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
1924        let language = Arc::new(
1925            Language::new(
1926                LanguageConfig {
1927                    name: "Test".into(),
1928                    matcher: LanguageMatcher {
1929                        path_suffixes: vec![".test".to_string()],
1930                        ..Default::default()
1931                    },
1932                    ..Default::default()
1933                },
1934                Some(tree_sitter_rust::LANGUAGE.into()),
1935            )
1936            .with_highlights_query(
1937                r#"
1938                ":" @operator
1939                (string_literal) @string
1940                "#,
1941            )
1942            .unwrap(),
1943        );
1944        language.set_theme(&theme);
1945
1946        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
1947
1948        let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1949        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1950
1951        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1952        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1953
1954        let font_size = px(16.0);
1955        let map = cx.new_model(|cx| {
1956            DisplayMap::new(
1957                buffer,
1958                font("Courier"),
1959                font_size,
1960                None,
1961                true,
1962                1,
1963                1,
1964                1,
1965                FoldPlaceholder::test(),
1966                cx,
1967            )
1968        });
1969
1970        enum MyType {}
1971
1972        let style = HighlightStyle {
1973            color: Some(Hsla::blue()),
1974            ..Default::default()
1975        };
1976
1977        map.update(cx, |map, _cx| {
1978            map.highlight_text(
1979                TypeId::of::<MyType>(),
1980                highlighted_ranges
1981                    .into_iter()
1982                    .map(|range| {
1983                        buffer_snapshot.anchor_before(range.start)
1984                            ..buffer_snapshot.anchor_before(range.end)
1985                    })
1986                    .collect(),
1987                style,
1988            );
1989        });
1990
1991        assert_eq!(
1992            cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
1993            [
1994                ("const ".to_string(), None, None),
1995                ("a".to_string(), None, Some(Hsla::blue())),
1996                (":".to_string(), Some(Hsla::red()), None),
1997                (" B = ".to_string(), None, None),
1998                ("\"c ".to_string(), Some(Hsla::green()), None),
1999                ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
2000                ("\"".to_string(), Some(Hsla::green()), None),
2001            ]
2002        );
2003    }
2004
2005    #[gpui::test]
2006    fn test_clip_point(cx: &mut gpui::AppContext) {
2007        init_test(cx, |_| {});
2008
2009        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
2010            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
2011
2012            match bias {
2013                Bias::Left => {
2014                    if shift_right {
2015                        *markers[1].column_mut() += 1;
2016                    }
2017
2018                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
2019                }
2020                Bias::Right => {
2021                    if shift_right {
2022                        *markers[0].column_mut() += 1;
2023                    }
2024
2025                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
2026                }
2027            };
2028        }
2029
2030        use Bias::{Left, Right};
2031        assert("ˇˇα", false, Left, cx);
2032        assert("ˇˇα", true, Left, cx);
2033        assert("ˇˇα", false, Right, cx);
2034        assert("ˇαˇ", true, Right, cx);
2035        assert("ˇˇ✋", false, Left, cx);
2036        assert("ˇˇ✋", true, Left, cx);
2037        assert("ˇˇ✋", false, Right, cx);
2038        assert("ˇ✋ˇ", true, Right, cx);
2039        assert("ˇˇ🍐", false, Left, cx);
2040        assert("ˇˇ🍐", true, Left, cx);
2041        assert("ˇˇ🍐", false, Right, cx);
2042        assert("ˇ🍐ˇ", true, Right, cx);
2043        assert("ˇˇ\t", false, Left, cx);
2044        assert("ˇˇ\t", true, Left, cx);
2045        assert("ˇˇ\t", false, Right, cx);
2046        assert("ˇ\tˇ", true, Right, cx);
2047        assert(" ˇˇ\t", false, Left, cx);
2048        assert(" ˇˇ\t", true, Left, cx);
2049        assert(" ˇˇ\t", false, Right, cx);
2050        assert(" ˇ\tˇ", true, Right, cx);
2051        assert("   ˇˇ\t", false, Left, cx);
2052        assert("   ˇˇ\t", false, Right, cx);
2053    }
2054
2055    #[gpui::test]
2056    fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
2057        init_test(cx, |_| {});
2058
2059        fn assert(text: &str, cx: &mut gpui::AppContext) {
2060            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
2061            unmarked_snapshot.clip_at_line_ends = true;
2062            assert_eq!(
2063                unmarked_snapshot.clip_point(markers[1], Bias::Left),
2064                markers[0]
2065            );
2066        }
2067
2068        assert("ˇˇ", cx);
2069        assert("ˇaˇ", cx);
2070        assert("aˇbˇ", cx);
2071        assert("aˇαˇ", cx);
2072    }
2073
2074    #[gpui::test]
2075    fn test_creases(cx: &mut gpui::AppContext) {
2076        init_test(cx, |_| {});
2077
2078        let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
2079        let buffer = MultiBuffer::build_simple(text, cx);
2080        let font_size = px(14.0);
2081        cx.new_model(|cx| {
2082            let mut map = DisplayMap::new(
2083                buffer.clone(),
2084                font("Helvetica"),
2085                font_size,
2086                None,
2087                true,
2088                1,
2089                1,
2090                0,
2091                FoldPlaceholder::test(),
2092                cx,
2093            );
2094            let snapshot = map.buffer.read(cx).snapshot(cx);
2095            let range =
2096                snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
2097
2098            map.crease_map.insert(
2099                [Crease::new(
2100                    range,
2101                    FoldPlaceholder::test(),
2102                    |_row, _status, _toggle, _cx| div(),
2103                    |_row, _status, _cx| div(),
2104                )],
2105                &map.buffer.read(cx).snapshot(cx),
2106            );
2107
2108            map
2109        });
2110    }
2111
2112    #[gpui::test]
2113    fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
2114        init_test(cx, |_| {});
2115
2116        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
2117        let buffer = MultiBuffer::build_simple(text, cx);
2118        let font_size = px(14.0);
2119
2120        let map = cx.new_model(|cx| {
2121            DisplayMap::new(
2122                buffer.clone(),
2123                font("Helvetica"),
2124                font_size,
2125                None,
2126                true,
2127                1,
2128                1,
2129                0,
2130                FoldPlaceholder::test(),
2131                cx,
2132            )
2133        });
2134        let map = map.update(cx, |map, cx| map.snapshot(cx));
2135        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
2136        assert_eq!(
2137            map.text_chunks(DisplayRow(0)).collect::<String>(),
2138            "✅       α\nβ   \n🏀β      γ"
2139        );
2140        assert_eq!(
2141            map.text_chunks(DisplayRow(1)).collect::<String>(),
2142            "β   \n🏀β      γ"
2143        );
2144        assert_eq!(
2145            map.text_chunks(DisplayRow(2)).collect::<String>(),
2146            "🏀β      γ"
2147        );
2148
2149        let point = MultiBufferPoint::new(0, "\t\t".len() as u32);
2150        let display_point = DisplayPoint::new(DisplayRow(0), "".len() as u32);
2151        assert_eq!(point.to_display_point(&map), display_point);
2152        assert_eq!(display_point.to_point(&map), point);
2153
2154        let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2155        let display_point = DisplayPoint::new(DisplayRow(1), "β   ".len() as u32);
2156        assert_eq!(point.to_display_point(&map), display_point);
2157        assert_eq!(display_point.to_point(&map), point,);
2158
2159        let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2160        let display_point = DisplayPoint::new(DisplayRow(2), "🏀β      ".len() as u32);
2161        assert_eq!(point.to_display_point(&map), display_point);
2162        assert_eq!(display_point.to_point(&map), point,);
2163
2164        // Display points inside of expanded tabs
2165        assert_eq!(
2166            DisplayPoint::new(DisplayRow(0), "".len() as u32).to_point(&map),
2167            MultiBufferPoint::new(0, "\t".len() as u32),
2168        );
2169        assert_eq!(
2170            DisplayPoint::new(DisplayRow(0), "".len() as u32).to_point(&map),
2171            MultiBufferPoint::new(0, "".len() as u32),
2172        );
2173
2174        // Clipping display points inside of multi-byte characters
2175        assert_eq!(
2176            map.clip_point(
2177                DisplayPoint::new(DisplayRow(0), "".len() as u32 - 1),
2178                Left
2179            ),
2180            DisplayPoint::new(DisplayRow(0), 0)
2181        );
2182        assert_eq!(
2183            map.clip_point(
2184                DisplayPoint::new(DisplayRow(0), "".len() as u32 - 1),
2185                Bias::Right
2186            ),
2187            DisplayPoint::new(DisplayRow(0), "".len() as u32)
2188        );
2189    }
2190
2191    #[gpui::test]
2192    fn test_max_point(cx: &mut gpui::AppContext) {
2193        init_test(cx, |_| {});
2194
2195        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2196        let font_size = px(14.0);
2197        let map = cx.new_model(|cx| {
2198            DisplayMap::new(
2199                buffer.clone(),
2200                font("Helvetica"),
2201                font_size,
2202                None,
2203                true,
2204                1,
2205                1,
2206                0,
2207                FoldPlaceholder::test(),
2208                cx,
2209            )
2210        });
2211        assert_eq!(
2212            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2213            DisplayPoint::new(DisplayRow(1), 11)
2214        )
2215    }
2216
2217    fn syntax_chunks(
2218        rows: Range<DisplayRow>,
2219        map: &Model<DisplayMap>,
2220        theme: &SyntaxTheme,
2221        cx: &mut AppContext,
2222    ) -> Vec<(String, Option<Hsla>)> {
2223        chunks(rows, map, theme, cx)
2224            .into_iter()
2225            .map(|(text, color, _)| (text, color))
2226            .collect()
2227    }
2228
2229    fn chunks(
2230        rows: Range<DisplayRow>,
2231        map: &Model<DisplayMap>,
2232        theme: &SyntaxTheme,
2233        cx: &mut AppContext,
2234    ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2235        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2236        let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2237        for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2238            let syntax_color = chunk
2239                .syntax_highlight_id
2240                .and_then(|id| id.style(theme)?.color);
2241            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2242            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
2243                if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2244                    last_chunk.push_str(chunk.text);
2245                    continue;
2246                }
2247            }
2248            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2249        }
2250        chunks
2251    }
2252
2253    fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
2254        let settings = SettingsStore::test(cx);
2255        cx.set_global(settings);
2256        language::init(cx);
2257        crate::init(cx);
2258        Project::init_settings(cx);
2259        theme::init(LoadThemes::JustBase, cx);
2260        cx.update_global::<SettingsStore, _>(|store, cx| {
2261            store.update_user_settings::<AllLanguageSettings>(cx, f);
2262        });
2263    }
2264}