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