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