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    link_go_to_definition::InlayHighlight, movement::TextLayoutDetails, Anchor, AnchorRangeExt,
  29    InlayId, 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        }: &TextLayoutDetails,
 590    ) -> Arc<LineLayout> {
 591        let mut runs = Vec::new();
 592        let mut line = String::new();
 593
 594        let range = display_row..display_row + 1;
 595        for chunk in self.highlighted_chunks(range, false, &editor_style) {
 596            line.push_str(chunk.chunk);
 597
 598            let text_style = if let Some(style) = chunk.style {
 599                Cow::Owned(editor_style.text.clone().highlight(style))
 600            } else {
 601                Cow::Borrowed(&editor_style.text)
 602            };
 603
 604            runs.push(text_style.to_run(chunk.chunk.len()))
 605        }
 606
 607        if line.ends_with('\n') {
 608            line.pop();
 609            if let Some(last_run) = runs.last_mut() {
 610                last_run.len -= 1;
 611                if last_run.len == 0 {
 612                    runs.pop();
 613                }
 614            }
 615        }
 616
 617        let font_size = editor_style.text.font_size.to_pixels(*rem_size);
 618        text_system
 619            .layout_line(&line, font_size, &runs)
 620            .expect("we expect the font to be loaded because it's rendered by the editor")
 621    }
 622
 623    pub fn x_for_display_point(
 624        &self,
 625        display_point: DisplayPoint,
 626        text_layout_details: &TextLayoutDetails,
 627    ) -> Pixels {
 628        let line = self.layout_row(display_point.row(), text_layout_details);
 629        line.x_for_index(display_point.column() as usize)
 630    }
 631
 632    pub fn display_column_for_x(
 633        &self,
 634        display_row: u32,
 635        x: Pixels,
 636        details: &TextLayoutDetails,
 637    ) -> u32 {
 638        let layout_line = self.layout_row(display_row, details);
 639        layout_line.closest_index_for_x(x) as u32
 640    }
 641
 642    pub fn chars_at(
 643        &self,
 644        mut point: DisplayPoint,
 645    ) -> impl Iterator<Item = (char, DisplayPoint)> + '_ {
 646        point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
 647        self.text_chunks(point.row())
 648            .flat_map(str::chars)
 649            .skip_while({
 650                let mut column = 0;
 651                move |char| {
 652                    let at_point = column >= point.column();
 653                    column += char.len_utf8() as u32;
 654                    !at_point
 655                }
 656            })
 657            .map(move |ch| {
 658                let result = (ch, point);
 659                if ch == '\n' {
 660                    *point.row_mut() += 1;
 661                    *point.column_mut() = 0;
 662                } else {
 663                    *point.column_mut() += ch.len_utf8() as u32;
 664                }
 665                result
 666            })
 667    }
 668
 669    pub fn reverse_chars_at(
 670        &self,
 671        mut point: DisplayPoint,
 672    ) -> impl Iterator<Item = (char, DisplayPoint)> + '_ {
 673        point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
 674        self.reverse_text_chunks(point.row())
 675            .flat_map(|chunk| chunk.chars().rev())
 676            .skip_while({
 677                let mut column = self.line_len(point.row());
 678                if self.max_point().row() > point.row() {
 679                    column += 1;
 680                }
 681
 682                move |char| {
 683                    let at_point = column <= point.column();
 684                    column = column.saturating_sub(char.len_utf8() as u32);
 685                    !at_point
 686                }
 687            })
 688            .map(move |ch| {
 689                if ch == '\n' {
 690                    *point.row_mut() -= 1;
 691                    *point.column_mut() = self.line_len(point.row());
 692                } else {
 693                    *point.column_mut() = point.column().saturating_sub(ch.len_utf8() as u32);
 694                }
 695                (ch, point)
 696            })
 697    }
 698
 699    pub fn column_to_chars(&self, display_row: u32, target: u32) -> u32 {
 700        let mut count = 0;
 701        let mut column = 0;
 702        for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
 703            if column >= target {
 704                break;
 705            }
 706            count += 1;
 707            column += c.len_utf8() as u32;
 708        }
 709        count
 710    }
 711
 712    pub fn column_from_chars(&self, display_row: u32, char_count: u32) -> u32 {
 713        let mut column = 0;
 714
 715        for (count, (c, _)) in self.chars_at(DisplayPoint::new(display_row, 0)).enumerate() {
 716            if c == '\n' || count >= char_count as usize {
 717                break;
 718            }
 719            column += c.len_utf8() as u32;
 720        }
 721
 722        column
 723    }
 724
 725    pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
 726        let mut clipped = self.block_snapshot.clip_point(point.0, bias);
 727        if self.clip_at_line_ends {
 728            clipped = self.clip_at_line_end(DisplayPoint(clipped)).0
 729        }
 730        DisplayPoint(clipped)
 731    }
 732
 733    pub fn clip_at_line_end(&self, point: DisplayPoint) -> DisplayPoint {
 734        let mut point = point.0;
 735        if point.column == self.line_len(point.row) {
 736            point.column = point.column.saturating_sub(1);
 737            point = self.block_snapshot.clip_point(point, Bias::Left);
 738        }
 739        DisplayPoint(point)
 740    }
 741
 742    pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Fold>
 743    where
 744        T: ToOffset,
 745    {
 746        self.fold_snapshot.folds_in_range(range)
 747    }
 748
 749    pub fn blocks_in_range(
 750        &self,
 751        rows: Range<u32>,
 752    ) -> impl Iterator<Item = (u32, &TransformBlock)> {
 753        self.block_snapshot.blocks_in_range(rows)
 754    }
 755
 756    pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
 757        self.fold_snapshot.intersects_fold(offset)
 758    }
 759
 760    pub fn is_line_folded(&self, buffer_row: u32) -> bool {
 761        self.fold_snapshot.is_line_folded(buffer_row)
 762    }
 763
 764    pub fn is_block_line(&self, display_row: u32) -> bool {
 765        self.block_snapshot.is_block_line(display_row)
 766    }
 767
 768    pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
 769        let wrap_row = self
 770            .block_snapshot
 771            .to_wrap_point(BlockPoint::new(display_row, 0))
 772            .row();
 773        self.wrap_snapshot.soft_wrap_indent(wrap_row)
 774    }
 775
 776    pub fn text(&self) -> String {
 777        self.text_chunks(0).collect()
 778    }
 779
 780    pub fn line(&self, display_row: u32) -> String {
 781        let mut result = String::new();
 782        for chunk in self.text_chunks(display_row) {
 783            if let Some(ix) = chunk.find('\n') {
 784                result.push_str(&chunk[0..ix]);
 785                break;
 786            } else {
 787                result.push_str(chunk);
 788            }
 789        }
 790        result
 791    }
 792
 793    pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
 794        let mut indent = 0;
 795        let mut is_blank = true;
 796        for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
 797            if c == ' ' {
 798                indent += 1;
 799            } else {
 800                is_blank = c == '\n';
 801                break;
 802            }
 803        }
 804        (indent, is_blank)
 805    }
 806
 807    pub fn line_indent_for_buffer_row(&self, buffer_row: u32) -> (u32, bool) {
 808        let (buffer, range) = self
 809            .buffer_snapshot
 810            .buffer_line_for_row(buffer_row)
 811            .unwrap();
 812
 813        let mut indent_size = 0;
 814        let mut is_blank = false;
 815        for c in buffer.chars_at(Point::new(range.start.row, 0)) {
 816            if c == ' ' || c == '\t' {
 817                indent_size += 1;
 818            } else {
 819                if c == '\n' {
 820                    is_blank = true;
 821                }
 822                break;
 823            }
 824        }
 825
 826        (indent_size, is_blank)
 827    }
 828
 829    pub fn line_len(&self, row: u32) -> u32 {
 830        self.block_snapshot.line_len(row)
 831    }
 832
 833    pub fn longest_row(&self) -> u32 {
 834        self.block_snapshot.longest_row()
 835    }
 836
 837    pub fn fold_for_line(self: &Self, buffer_row: u32) -> Option<FoldStatus> {
 838        if self.is_line_folded(buffer_row) {
 839            Some(FoldStatus::Folded)
 840        } else if self.is_foldable(buffer_row) {
 841            Some(FoldStatus::Foldable)
 842        } else {
 843            None
 844        }
 845    }
 846
 847    pub fn is_foldable(self: &Self, buffer_row: u32) -> bool {
 848        let max_row = self.buffer_snapshot.max_buffer_row();
 849        if buffer_row >= max_row {
 850            return false;
 851        }
 852
 853        let (indent_size, is_blank) = self.line_indent_for_buffer_row(buffer_row);
 854        if is_blank {
 855            return false;
 856        }
 857
 858        for next_row in (buffer_row + 1)..=max_row {
 859            let (next_indent_size, next_line_is_blank) = self.line_indent_for_buffer_row(next_row);
 860            if next_indent_size > indent_size {
 861                return true;
 862            } else if !next_line_is_blank {
 863                break;
 864            }
 865        }
 866
 867        false
 868    }
 869
 870    pub fn foldable_range(self: &Self, buffer_row: u32) -> Option<Range<Point>> {
 871        let start = Point::new(buffer_row, self.buffer_snapshot.line_len(buffer_row));
 872        if self.is_foldable(start.row) && !self.is_line_folded(start.row) {
 873            let (start_indent, _) = self.line_indent_for_buffer_row(buffer_row);
 874            let max_point = self.buffer_snapshot.max_point();
 875            let mut end = None;
 876
 877            for row in (buffer_row + 1)..=max_point.row {
 878                let (indent, is_blank) = self.line_indent_for_buffer_row(row);
 879                if !is_blank && indent <= start_indent {
 880                    let prev_row = row - 1;
 881                    end = Some(Point::new(
 882                        prev_row,
 883                        self.buffer_snapshot.line_len(prev_row),
 884                    ));
 885                    break;
 886                }
 887            }
 888            let end = end.unwrap_or(max_point);
 889            Some(start..end)
 890        } else {
 891            None
 892        }
 893    }
 894
 895    #[cfg(any(test, feature = "test-support"))]
 896    pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
 897        &self,
 898    ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
 899        let type_id = TypeId::of::<Tag>();
 900        self.text_highlights.get(&Some(type_id)).cloned()
 901    }
 902
 903    #[allow(unused)]
 904    #[cfg(any(test, feature = "test-support"))]
 905    pub(crate) fn inlay_highlights<Tag: ?Sized + 'static>(
 906        &self,
 907    ) -> Option<&HashMap<InlayId, (HighlightStyle, InlayHighlight)>> {
 908        let type_id = TypeId::of::<Tag>();
 909        self.inlay_highlights.get(&type_id)
 910    }
 911}
 912
 913#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
 914pub struct DisplayPoint(BlockPoint);
 915
 916impl Debug for DisplayPoint {
 917    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 918        f.write_fmt(format_args!(
 919            "DisplayPoint({}, {})",
 920            self.row(),
 921            self.column()
 922        ))
 923    }
 924}
 925
 926impl DisplayPoint {
 927    pub fn new(row: u32, column: u32) -> Self {
 928        Self(BlockPoint(Point::new(row, column)))
 929    }
 930
 931    pub fn zero() -> Self {
 932        Self::new(0, 0)
 933    }
 934
 935    pub fn is_zero(&self) -> bool {
 936        self.0.is_zero()
 937    }
 938
 939    pub fn row(self) -> u32 {
 940        self.0.row
 941    }
 942
 943    pub fn column(self) -> u32 {
 944        self.0.column
 945    }
 946
 947    pub fn row_mut(&mut self) -> &mut u32 {
 948        &mut self.0.row
 949    }
 950
 951    pub fn column_mut(&mut self) -> &mut u32 {
 952        &mut self.0.column
 953    }
 954
 955    pub fn to_point(self, map: &DisplaySnapshot) -> Point {
 956        map.display_point_to_point(self, Bias::Left)
 957    }
 958
 959    pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
 960        let wrap_point = map.block_snapshot.to_wrap_point(self.0);
 961        let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
 962        let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
 963        let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
 964        map.inlay_snapshot
 965            .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
 966    }
 967}
 968
 969impl ToDisplayPoint for usize {
 970    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 971        map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
 972    }
 973}
 974
 975impl ToDisplayPoint for OffsetUtf16 {
 976    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 977        self.to_offset(&map.buffer_snapshot).to_display_point(map)
 978    }
 979}
 980
 981impl ToDisplayPoint for Point {
 982    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 983        map.point_to_display_point(*self, Bias::Left)
 984    }
 985}
 986
 987impl ToDisplayPoint for Anchor {
 988    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 989        self.to_point(&map.buffer_snapshot).to_display_point(map)
 990    }
 991}
 992
 993#[cfg(test)]
 994pub mod tests {
 995    use super::*;
 996    use crate::{
 997        movement,
 998        test::{editor_test_context::EditorTestContext, marked_display_snapshot},
 999    };
1000    use gpui::{div, font, observe, px, AppContext, Context, Element, Hsla};
1001    use language::{
1002        language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1003        Buffer, Language, LanguageConfig, SelectionGoal,
1004    };
1005    use project::Project;
1006    use rand::{prelude::*, Rng};
1007    use settings::SettingsStore;
1008    use smol::stream::StreamExt;
1009    use std::{env, sync::Arc};
1010    use theme::{LoadThemes, SyntaxTheme};
1011    use util::test::{marked_text_ranges, sample_text};
1012    use Bias::*;
1013
1014    #[gpui::test(iterations = 100)]
1015    async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1016        cx.background_executor.set_block_on_ticks(0..=50);
1017        let operations = env::var("OPERATIONS")
1018            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1019            .unwrap_or(10);
1020
1021        let mut tab_size = rng.gen_range(1..=4);
1022        let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1023        let excerpt_header_height = rng.gen_range(1..=5);
1024        let font_size = px(14.0);
1025        let max_wrap_width = 300.0;
1026        let mut wrap_width = if rng.gen_bool(0.1) {
1027            None
1028        } else {
1029            Some(px(rng.gen_range(0.0..=max_wrap_width)))
1030        };
1031
1032        log::info!("tab size: {}", tab_size);
1033        log::info!("wrap width: {:?}", wrap_width);
1034
1035        cx.update(|cx| {
1036            init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1037        });
1038
1039        let buffer = cx.update(|cx| {
1040            if rng.gen() {
1041                let len = rng.gen_range(0..10);
1042                let text = util::RandomCharIter::new(&mut rng)
1043                    .take(len)
1044                    .collect::<String>();
1045                MultiBuffer::build_simple(&text, cx)
1046            } else {
1047                MultiBuffer::build_random(&mut rng, cx)
1048            }
1049        });
1050
1051        let map = cx.new_model(|cx| {
1052            DisplayMap::new(
1053                buffer.clone(),
1054                font("Helvetica"),
1055                font_size,
1056                wrap_width,
1057                buffer_start_excerpt_header_height,
1058                excerpt_header_height,
1059                cx,
1060            )
1061        });
1062        let mut notifications = observe(&map, cx);
1063        let mut fold_count = 0;
1064        let mut blocks = Vec::new();
1065
1066        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1067        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1068        log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1069        log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1070        log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1071        log::info!("block text: {:?}", snapshot.block_snapshot.text());
1072        log::info!("display text: {:?}", snapshot.text());
1073
1074        for _i in 0..operations {
1075            match rng.gen_range(0..100) {
1076                0..=19 => {
1077                    wrap_width = if rng.gen_bool(0.2) {
1078                        None
1079                    } else {
1080                        Some(px(rng.gen_range(0.0..=max_wrap_width)))
1081                    };
1082                    log::info!("setting wrap width to {:?}", wrap_width);
1083                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1084                }
1085                20..=29 => {
1086                    let mut tab_sizes = vec![1, 2, 3, 4];
1087                    tab_sizes.remove((tab_size - 1) as usize);
1088                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
1089                    log::info!("setting tab size to {:?}", tab_size);
1090                    cx.update(|cx| {
1091                        cx.update_global::<SettingsStore, _>(|store, cx| {
1092                            store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1093                                s.defaults.tab_size = NonZeroU32::new(tab_size);
1094                            });
1095                        });
1096                    });
1097                }
1098                30..=44 => {
1099                    map.update(cx, |map, cx| {
1100                        if rng.gen() || blocks.is_empty() {
1101                            let buffer = map.snapshot(cx).buffer_snapshot;
1102                            let block_properties = (0..rng.gen_range(1..=1))
1103                                .map(|_| {
1104                                    let position =
1105                                        buffer.anchor_after(buffer.clip_offset(
1106                                            rng.gen_range(0..=buffer.len()),
1107                                            Bias::Left,
1108                                        ));
1109
1110                                    let disposition = if rng.gen() {
1111                                        BlockDisposition::Above
1112                                    } else {
1113                                        BlockDisposition::Below
1114                                    };
1115                                    let height = rng.gen_range(1..5);
1116                                    log::info!(
1117                                        "inserting block {:?} {:?} with height {}",
1118                                        disposition,
1119                                        position.to_point(&buffer),
1120                                        height
1121                                    );
1122                                    BlockProperties {
1123                                        style: BlockStyle::Fixed,
1124                                        position,
1125                                        height,
1126                                        disposition,
1127                                        render: Arc::new(|_| div().into_any()),
1128                                    }
1129                                })
1130                                .collect::<Vec<_>>();
1131                            blocks.extend(map.insert_blocks(block_properties, cx));
1132                        } else {
1133                            blocks.shuffle(&mut rng);
1134                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1135                            let block_ids_to_remove = (0..remove_count)
1136                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1137                                .collect();
1138                            log::info!("removing block ids {:?}", block_ids_to_remove);
1139                            map.remove_blocks(block_ids_to_remove, cx);
1140                        }
1141                    });
1142                }
1143                45..=79 => {
1144                    let mut ranges = Vec::new();
1145                    for _ in 0..rng.gen_range(1..=3) {
1146                        buffer.read_with(cx, |buffer, cx| {
1147                            let buffer = buffer.read(cx);
1148                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1149                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1150                            ranges.push(start..end);
1151                        });
1152                    }
1153
1154                    if rng.gen() && fold_count > 0 {
1155                        log::info!("unfolding ranges: {:?}", ranges);
1156                        map.update(cx, |map, cx| {
1157                            map.unfold(ranges, true, cx);
1158                        });
1159                    } else {
1160                        log::info!("folding ranges: {:?}", ranges);
1161                        map.update(cx, |map, cx| {
1162                            map.fold(ranges, cx);
1163                        });
1164                    }
1165                }
1166                _ => {
1167                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1168                }
1169            }
1170
1171            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1172                notifications.next().await.unwrap();
1173            }
1174
1175            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1176            fold_count = snapshot.fold_count();
1177            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1178            log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1179            log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1180            log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1181            log::info!("block text: {:?}", snapshot.block_snapshot.text());
1182            log::info!("display text: {:?}", snapshot.text());
1183
1184            // Line boundaries
1185            let buffer = &snapshot.buffer_snapshot;
1186            for _ in 0..5 {
1187                let row = rng.gen_range(0..=buffer.max_point().row);
1188                let column = rng.gen_range(0..=buffer.line_len(row));
1189                let point = buffer.clip_point(Point::new(row, column), Left);
1190
1191                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1192                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1193
1194                assert!(prev_buffer_bound <= point);
1195                assert!(next_buffer_bound >= point);
1196                assert_eq!(prev_buffer_bound.column, 0);
1197                assert_eq!(prev_display_bound.column(), 0);
1198                if next_buffer_bound < buffer.max_point() {
1199                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1200                }
1201
1202                assert_eq!(
1203                    prev_display_bound,
1204                    prev_buffer_bound.to_display_point(&snapshot),
1205                    "row boundary before {:?}. reported buffer row boundary: {:?}",
1206                    point,
1207                    prev_buffer_bound
1208                );
1209                assert_eq!(
1210                    next_display_bound,
1211                    next_buffer_bound.to_display_point(&snapshot),
1212                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
1213                    point,
1214                    next_buffer_bound
1215                );
1216                assert_eq!(
1217                    prev_buffer_bound,
1218                    prev_display_bound.to_point(&snapshot),
1219                    "row boundary before {:?}. reported display row boundary: {:?}",
1220                    point,
1221                    prev_display_bound
1222                );
1223                assert_eq!(
1224                    next_buffer_bound,
1225                    next_display_bound.to_point(&snapshot),
1226                    "row boundary after {:?}. reported display row boundary: {:?}",
1227                    point,
1228                    next_display_bound
1229                );
1230            }
1231
1232            // Movement
1233            let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1234            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1235            for _ in 0..5 {
1236                let row = rng.gen_range(0..=snapshot.max_point().row());
1237                let column = rng.gen_range(0..=snapshot.line_len(row));
1238                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1239
1240                log::info!("Moving from point {:?}", point);
1241
1242                let moved_right = movement::right(&snapshot, point);
1243                log::info!("Right {:?}", moved_right);
1244                if point < max_point {
1245                    assert!(moved_right > point);
1246                    if point.column() == snapshot.line_len(point.row())
1247                        || snapshot.soft_wrap_indent(point.row()).is_some()
1248                            && point.column() == snapshot.line_len(point.row()) - 1
1249                    {
1250                        assert!(moved_right.row() > point.row());
1251                    }
1252                } else {
1253                    assert_eq!(moved_right, point);
1254                }
1255
1256                let moved_left = movement::left(&snapshot, point);
1257                log::info!("Left {:?}", moved_left);
1258                if point > min_point {
1259                    assert!(moved_left < point);
1260                    if point.column() == 0 {
1261                        assert!(moved_left.row() < point.row());
1262                    }
1263                } else {
1264                    assert_eq!(moved_left, point);
1265                }
1266            }
1267        }
1268    }
1269
1270    #[gpui::test(retries = 5)]
1271    async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1272        cx.background_executor
1273            .set_block_on_ticks(usize::MAX..=usize::MAX);
1274        cx.update(|cx| {
1275            init_test(cx, |_| {});
1276        });
1277
1278        let mut cx = EditorTestContext::new(cx).await;
1279        let editor = cx.editor.clone();
1280        let window = cx.window.clone();
1281
1282        _ = cx.update_window(window, |_, cx| {
1283            let text_layout_details =
1284                editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1285
1286            let font_size = px(12.0);
1287            let wrap_width = Some(px(64.));
1288
1289            let text = "one two three four five\nsix seven eight";
1290            let buffer = MultiBuffer::build_simple(text, cx);
1291            let map = cx.new_model(|cx| {
1292                DisplayMap::new(
1293                    buffer.clone(),
1294                    font("Helvetica"),
1295                    font_size,
1296                    wrap_width,
1297                    1,
1298                    1,
1299                    cx,
1300                )
1301            });
1302
1303            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1304            assert_eq!(
1305                snapshot.text_chunks(0).collect::<String>(),
1306                "one two \nthree four \nfive\nsix seven \neight"
1307            );
1308            assert_eq!(
1309                snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1310                DisplayPoint::new(0, 7)
1311            );
1312            assert_eq!(
1313                snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1314                DisplayPoint::new(1, 0)
1315            );
1316            assert_eq!(
1317                movement::right(&snapshot, DisplayPoint::new(0, 7)),
1318                DisplayPoint::new(1, 0)
1319            );
1320            assert_eq!(
1321                movement::left(&snapshot, DisplayPoint::new(1, 0)),
1322                DisplayPoint::new(0, 7)
1323            );
1324
1325            let x = snapshot.x_for_display_point(DisplayPoint::new(1, 10), &text_layout_details);
1326            assert_eq!(
1327                movement::up(
1328                    &snapshot,
1329                    DisplayPoint::new(1, 10),
1330                    SelectionGoal::None,
1331                    false,
1332                    &text_layout_details,
1333                ),
1334                (
1335                    DisplayPoint::new(0, 7),
1336                    SelectionGoal::HorizontalPosition(x.0)
1337                )
1338            );
1339            assert_eq!(
1340                movement::down(
1341                    &snapshot,
1342                    DisplayPoint::new(0, 7),
1343                    SelectionGoal::HorizontalPosition(x.0),
1344                    false,
1345                    &text_layout_details
1346                ),
1347                (
1348                    DisplayPoint::new(1, 10),
1349                    SelectionGoal::HorizontalPosition(x.0)
1350                )
1351            );
1352            assert_eq!(
1353                movement::down(
1354                    &snapshot,
1355                    DisplayPoint::new(1, 10),
1356                    SelectionGoal::HorizontalPosition(x.0),
1357                    false,
1358                    &text_layout_details
1359                ),
1360                (
1361                    DisplayPoint::new(2, 4),
1362                    SelectionGoal::HorizontalPosition(x.0)
1363                )
1364            );
1365
1366            let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1367            buffer.update(cx, |buffer, cx| {
1368                buffer.edit([(ix..ix, "and ")], None, cx);
1369            });
1370
1371            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1372            assert_eq!(
1373                snapshot.text_chunks(1).collect::<String>(),
1374                "three four \nfive\nsix and \nseven eight"
1375            );
1376
1377            // Re-wrap on font size changes
1378            map.update(cx, |map, cx| {
1379                map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1380            });
1381
1382            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1383            assert_eq!(
1384                snapshot.text_chunks(1).collect::<String>(),
1385                "three \nfour five\nsix and \nseven \neight"
1386            )
1387        });
1388    }
1389
1390    #[gpui::test]
1391    fn test_text_chunks(cx: &mut gpui::AppContext) {
1392        init_test(cx, |_| {});
1393
1394        let text = sample_text(6, 6, 'a');
1395        let buffer = MultiBuffer::build_simple(&text, cx);
1396
1397        let font_size = px(14.0);
1398        let map = cx.new_model(|cx| {
1399            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1400        });
1401
1402        buffer.update(cx, |buffer, cx| {
1403            buffer.edit(
1404                vec![
1405                    (Point::new(1, 0)..Point::new(1, 0), "\t"),
1406                    (Point::new(1, 1)..Point::new(1, 1), "\t"),
1407                    (Point::new(2, 1)..Point::new(2, 1), "\t"),
1408                ],
1409                None,
1410                cx,
1411            )
1412        });
1413
1414        assert_eq!(
1415            map.update(cx, |map, cx| map.snapshot(cx))
1416                .text_chunks(1)
1417                .collect::<String>()
1418                .lines()
1419                .next(),
1420            Some("    b   bbbbb")
1421        );
1422        assert_eq!(
1423            map.update(cx, |map, cx| map.snapshot(cx))
1424                .text_chunks(2)
1425                .collect::<String>()
1426                .lines()
1427                .next(),
1428            Some("c   ccccc")
1429        );
1430    }
1431
1432    #[gpui::test]
1433    async fn test_chunks(cx: &mut gpui::TestAppContext) {
1434        use unindent::Unindent as _;
1435
1436        let text = r#"
1437            fn outer() {}
1438
1439            mod module {
1440                fn inner() {}
1441            }"#
1442        .unindent();
1443
1444        let theme = SyntaxTheme::new_test(vec![
1445            ("mod.body", Hsla::red().into()),
1446            ("fn.name", Hsla::blue().into()),
1447        ]);
1448        let language = Arc::new(
1449            Language::new(
1450                LanguageConfig {
1451                    name: "Test".into(),
1452                    path_suffixes: vec![".test".to_string()],
1453                    ..Default::default()
1454                },
1455                Some(tree_sitter_rust::language()),
1456            )
1457            .with_highlights_query(
1458                r#"
1459                (mod_item name: (identifier) body: _ @mod.body)
1460                (function_item name: (identifier) @fn.name)
1461                "#,
1462            )
1463            .unwrap(),
1464        );
1465        language.set_theme(&theme);
1466
1467        cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1468
1469        let buffer = cx.new_model(|cx| {
1470            Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
1471        });
1472        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1473        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1474
1475        let font_size = px(14.0);
1476
1477        let map = cx
1478            .new_model(|cx| DisplayMap::new(buffer, font("Helvetica"), font_size, None, 1, 1, cx));
1479        assert_eq!(
1480            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1481            vec![
1482                ("fn ".to_string(), None),
1483                ("outer".to_string(), Some(Hsla::blue())),
1484                ("() {}\n\nmod module ".to_string(), None),
1485                ("{\n    fn ".to_string(), Some(Hsla::red())),
1486                ("inner".to_string(), Some(Hsla::blue())),
1487                ("() {}\n}".to_string(), Some(Hsla::red())),
1488            ]
1489        );
1490        assert_eq!(
1491            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1492            vec![
1493                ("    fn ".to_string(), Some(Hsla::red())),
1494                ("inner".to_string(), Some(Hsla::blue())),
1495                ("() {}\n}".to_string(), Some(Hsla::red())),
1496            ]
1497        );
1498
1499        map.update(cx, |map, cx| {
1500            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1501        });
1502        assert_eq!(
1503            cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1504            vec![
1505                ("fn ".to_string(), None),
1506                ("out".to_string(), Some(Hsla::blue())),
1507                ("⋯".to_string(), None),
1508                ("  fn ".to_string(), Some(Hsla::red())),
1509                ("inner".to_string(), Some(Hsla::blue())),
1510                ("() {}\n}".to_string(), Some(Hsla::red())),
1511            ]
1512        );
1513    }
1514
1515    #[gpui::test]
1516    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1517        use unindent::Unindent as _;
1518
1519        cx.background_executor
1520            .set_block_on_ticks(usize::MAX..=usize::MAX);
1521
1522        let text = r#"
1523            fn outer() {}
1524
1525            mod module {
1526                fn inner() {}
1527            }"#
1528        .unindent();
1529
1530        let theme = SyntaxTheme::new_test(vec![
1531            ("mod.body", Hsla::red().into()),
1532            ("fn.name", Hsla::blue().into()),
1533        ]);
1534        let language = Arc::new(
1535            Language::new(
1536                LanguageConfig {
1537                    name: "Test".into(),
1538                    path_suffixes: vec![".test".to_string()],
1539                    ..Default::default()
1540                },
1541                Some(tree_sitter_rust::language()),
1542            )
1543            .with_highlights_query(
1544                r#"
1545                (mod_item name: (identifier) body: _ @mod.body)
1546                (function_item name: (identifier) @fn.name)
1547                "#,
1548            )
1549            .unwrap(),
1550        );
1551        language.set_theme(&theme);
1552
1553        cx.update(|cx| init_test(cx, |_| {}));
1554
1555        let buffer = cx.new_model(|cx| {
1556            Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
1557        });
1558        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1559        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1560
1561        let font_size = px(16.0);
1562
1563        let map = cx.new_model(|cx| {
1564            DisplayMap::new(buffer, font("Courier"), font_size, Some(px(40.0)), 1, 1, cx)
1565        });
1566        assert_eq!(
1567            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1568            [
1569                ("fn \n".to_string(), None),
1570                ("oute\nr".to_string(), Some(Hsla::blue())),
1571                ("() \n{}\n\n".to_string(), None),
1572            ]
1573        );
1574        assert_eq!(
1575            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1576            [("{}\n\n".to_string(), None)]
1577        );
1578
1579        map.update(cx, |map, cx| {
1580            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1581        });
1582        assert_eq!(
1583            cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1584            [
1585                ("out".to_string(), Some(Hsla::blue())),
1586                ("⋯\n".to_string(), None),
1587                ("  \nfn ".to_string(), Some(Hsla::red())),
1588                ("i\n".to_string(), Some(Hsla::blue()))
1589            ]
1590        );
1591    }
1592
1593    #[gpui::test]
1594    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1595        cx.update(|cx| init_test(cx, |_| {}));
1596
1597        let theme = SyntaxTheme::new_test(vec![
1598            ("operator", Hsla::red().into()),
1599            ("string", Hsla::green().into()),
1600        ]);
1601        let language = Arc::new(
1602            Language::new(
1603                LanguageConfig {
1604                    name: "Test".into(),
1605                    path_suffixes: vec![".test".to_string()],
1606                    ..Default::default()
1607                },
1608                Some(tree_sitter_rust::language()),
1609            )
1610            .with_highlights_query(
1611                r#"
1612                ":" @operator
1613                (string_literal) @string
1614                "#,
1615            )
1616            .unwrap(),
1617        );
1618        language.set_theme(&theme);
1619
1620        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ Ā«aĀ»: B = "c Ā«dĀ»""#, false);
1621
1622        let buffer = cx.new_model(|cx| {
1623            Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
1624        });
1625        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1626
1627        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1628        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1629
1630        let font_size = px(16.0);
1631        let map =
1632            cx.new_model(|cx| DisplayMap::new(buffer, font("Courier"), font_size, None, 1, 1, cx));
1633
1634        enum MyType {}
1635
1636        let style = HighlightStyle {
1637            color: Some(Hsla::blue()),
1638            ..Default::default()
1639        };
1640
1641        map.update(cx, |map, _cx| {
1642            map.highlight_text(
1643                TypeId::of::<MyType>(),
1644                highlighted_ranges
1645                    .into_iter()
1646                    .map(|range| {
1647                        buffer_snapshot.anchor_before(range.start)
1648                            ..buffer_snapshot.anchor_before(range.end)
1649                    })
1650                    .collect(),
1651                style,
1652            );
1653        });
1654
1655        assert_eq!(
1656            cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1657            [
1658                ("const ".to_string(), None, None),
1659                ("a".to_string(), None, Some(Hsla::blue())),
1660                (":".to_string(), Some(Hsla::red()), None),
1661                (" B = ".to_string(), None, None),
1662                ("\"c ".to_string(), Some(Hsla::green()), None),
1663                ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
1664                ("\"".to_string(), Some(Hsla::green()), None),
1665            ]
1666        );
1667    }
1668
1669    #[gpui::test]
1670    fn test_clip_point(cx: &mut gpui::AppContext) {
1671        init_test(cx, |_| {});
1672
1673        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1674            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1675
1676            match bias {
1677                Bias::Left => {
1678                    if shift_right {
1679                        *markers[1].column_mut() += 1;
1680                    }
1681
1682                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1683                }
1684                Bias::Right => {
1685                    if shift_right {
1686                        *markers[0].column_mut() += 1;
1687                    }
1688
1689                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1690                }
1691            };
1692        }
1693
1694        use Bias::{Left, Right};
1695        assert("ˇˇα", false, Left, cx);
1696        assert("ˇˇα", true, Left, cx);
1697        assert("ˇˇα", false, Right, cx);
1698        assert("ˇαˇ", true, Right, cx);
1699        assert("Ė‡Ė‡āœ‹", false, Left, cx);
1700        assert("Ė‡Ė‡āœ‹", true, Left, cx);
1701        assert("Ė‡Ė‡āœ‹", false, Right, cx);
1702        assert("Ė‡āœ‹Ė‡", true, Right, cx);
1703        assert("Ė‡Ė‡šŸ", false, Left, cx);
1704        assert("Ė‡Ė‡šŸ", true, Left, cx);
1705        assert("Ė‡Ė‡šŸ", false, Right, cx);
1706        assert("Ė‡šŸĖ‡", true, Right, cx);
1707        assert("ˇˇ\t", false, Left, cx);
1708        assert("ˇˇ\t", true, Left, cx);
1709        assert("ˇˇ\t", false, Right, cx);
1710        assert("ˇ\tˇ", true, Right, cx);
1711        assert(" ˇˇ\t", false, Left, cx);
1712        assert(" ˇˇ\t", true, Left, cx);
1713        assert(" ˇˇ\t", false, Right, cx);
1714        assert(" ˇ\tˇ", true, Right, cx);
1715        assert("   ˇˇ\t", false, Left, cx);
1716        assert("   ˇˇ\t", false, Right, cx);
1717    }
1718
1719    #[gpui::test]
1720    fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1721        init_test(cx, |_| {});
1722
1723        fn assert(text: &str, cx: &mut gpui::AppContext) {
1724            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1725            unmarked_snapshot.clip_at_line_ends = true;
1726            assert_eq!(
1727                unmarked_snapshot.clip_point(markers[1], Bias::Left),
1728                markers[0]
1729            );
1730        }
1731
1732        assert("ˇˇ", cx);
1733        assert("ˇaˇ", cx);
1734        assert("aˇbˇ", cx);
1735        assert("aˇαˇ", cx);
1736    }
1737
1738    #[gpui::test]
1739    fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1740        init_test(cx, |_| {});
1741
1742        let text = "āœ…\t\tα\nβ\t\nšŸ€Ī²\t\tγ";
1743        let buffer = MultiBuffer::build_simple(text, cx);
1744        let font_size = px(14.0);
1745
1746        let map = cx.new_model(|cx| {
1747            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1748        });
1749        let map = map.update(cx, |map, cx| map.snapshot(cx));
1750        assert_eq!(map.text(), "āœ…       α\nβ   \nšŸ€Ī²      γ");
1751        assert_eq!(
1752            map.text_chunks(0).collect::<String>(),
1753            "āœ…       α\nβ   \nšŸ€Ī²      γ"
1754        );
1755        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \nšŸ€Ī²      γ");
1756        assert_eq!(map.text_chunks(2).collect::<String>(), "šŸ€Ī²      γ");
1757
1758        let point = Point::new(0, "āœ…\t\t".len() as u32);
1759        let display_point = DisplayPoint::new(0, "āœ…       ".len() as u32);
1760        assert_eq!(point.to_display_point(&map), display_point);
1761        assert_eq!(display_point.to_point(&map), point);
1762
1763        let point = Point::new(1, "β\t".len() as u32);
1764        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1765        assert_eq!(point.to_display_point(&map), display_point);
1766        assert_eq!(display_point.to_point(&map), point,);
1767
1768        let point = Point::new(2, "šŸ€Ī²\t\t".len() as u32);
1769        let display_point = DisplayPoint::new(2, "šŸ€Ī²      ".len() as u32);
1770        assert_eq!(point.to_display_point(&map), display_point);
1771        assert_eq!(display_point.to_point(&map), point,);
1772
1773        // Display points inside of expanded tabs
1774        assert_eq!(
1775            DisplayPoint::new(0, "āœ…      ".len() as u32).to_point(&map),
1776            Point::new(0, "āœ…\t".len() as u32),
1777        );
1778        assert_eq!(
1779            DisplayPoint::new(0, "āœ… ".len() as u32).to_point(&map),
1780            Point::new(0, "āœ…".len() as u32),
1781        );
1782
1783        // Clipping display points inside of multi-byte characters
1784        assert_eq!(
1785            map.clip_point(DisplayPoint::new(0, "āœ…".len() as u32 - 1), Left),
1786            DisplayPoint::new(0, 0)
1787        );
1788        assert_eq!(
1789            map.clip_point(DisplayPoint::new(0, "āœ…".len() as u32 - 1), Bias::Right),
1790            DisplayPoint::new(0, "āœ…".len() as u32)
1791        );
1792    }
1793
1794    #[gpui::test]
1795    fn test_max_point(cx: &mut gpui::AppContext) {
1796        init_test(cx, |_| {});
1797
1798        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1799        let font_size = px(14.0);
1800        let map = cx.new_model(|cx| {
1801            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1802        });
1803        assert_eq!(
1804            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1805            DisplayPoint::new(1, 11)
1806        )
1807    }
1808
1809    fn syntax_chunks<'a>(
1810        rows: Range<u32>,
1811        map: &Model<DisplayMap>,
1812        theme: &'a SyntaxTheme,
1813        cx: &mut AppContext,
1814    ) -> Vec<(String, Option<Hsla>)> {
1815        chunks(rows, map, theme, cx)
1816            .into_iter()
1817            .map(|(text, color, _)| (text, color))
1818            .collect()
1819    }
1820
1821    fn chunks<'a>(
1822        rows: Range<u32>,
1823        map: &Model<DisplayMap>,
1824        theme: &'a SyntaxTheme,
1825        cx: &mut AppContext,
1826    ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
1827        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1828        let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
1829        for chunk in snapshot.chunks(rows, true, None, None) {
1830            let syntax_color = chunk
1831                .syntax_highlight_id
1832                .and_then(|id| id.style(theme)?.color);
1833            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1834            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1835                if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1836                    last_chunk.push_str(chunk.text);
1837                    continue;
1838                }
1839            }
1840            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1841        }
1842        chunks
1843    }
1844
1845    fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
1846        let settings = SettingsStore::test(cx);
1847        cx.set_global(settings);
1848        language::init(cx);
1849        crate::init(cx);
1850        Project::init_settings(cx);
1851        theme::init(LoadThemes::JustBase, cx);
1852        cx.update_global::<SettingsStore, _>(|store, cx| {
1853            store.update_user_settings::<AllLanguageSettings>(cx, f);
1854        });
1855    }
1856}