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