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 text::BufferId;
1011    use theme::{LoadThemes, SyntaxTheme};
1012    use util::test::{marked_text_ranges, sample_text};
1013    use Bias::*;
1014
1015    #[gpui::test(iterations = 100)]
1016    async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1017        cx.background_executor.set_block_on_ticks(0..=50);
1018        let operations = env::var("OPERATIONS")
1019            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1020            .unwrap_or(10);
1021
1022        let mut tab_size = rng.gen_range(1..=4);
1023        let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1024        let excerpt_header_height = rng.gen_range(1..=5);
1025        let font_size = px(14.0);
1026        let max_wrap_width = 300.0;
1027        let mut wrap_width = if rng.gen_bool(0.1) {
1028            None
1029        } else {
1030            Some(px(rng.gen_range(0.0..=max_wrap_width)))
1031        };
1032
1033        log::info!("tab size: {}", tab_size);
1034        log::info!("wrap width: {:?}", wrap_width);
1035
1036        cx.update(|cx| {
1037            init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1038        });
1039
1040        let buffer = cx.update(|cx| {
1041            if rng.gen() {
1042                let len = rng.gen_range(0..10);
1043                let text = util::RandomCharIter::new(&mut rng)
1044                    .take(len)
1045                    .collect::<String>();
1046                MultiBuffer::build_simple(&text, cx)
1047            } else {
1048                MultiBuffer::build_random(&mut rng, cx)
1049            }
1050        });
1051
1052        let map = cx.new_model(|cx| {
1053            DisplayMap::new(
1054                buffer.clone(),
1055                font("Helvetica"),
1056                font_size,
1057                wrap_width,
1058                buffer_start_excerpt_header_height,
1059                excerpt_header_height,
1060                cx,
1061            )
1062        });
1063        let mut notifications = observe(&map, cx);
1064        let mut fold_count = 0;
1065        let mut blocks = Vec::new();
1066
1067        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1068        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1069        log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1070        log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1071        log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1072        log::info!("block text: {:?}", snapshot.block_snapshot.text());
1073        log::info!("display text: {:?}", snapshot.text());
1074
1075        for _i in 0..operations {
1076            match rng.gen_range(0..100) {
1077                0..=19 => {
1078                    wrap_width = if rng.gen_bool(0.2) {
1079                        None
1080                    } else {
1081                        Some(px(rng.gen_range(0.0..=max_wrap_width)))
1082                    };
1083                    log::info!("setting wrap width to {:?}", wrap_width);
1084                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1085                }
1086                20..=29 => {
1087                    let mut tab_sizes = vec![1, 2, 3, 4];
1088                    tab_sizes.remove((tab_size - 1) as usize);
1089                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
1090                    log::info!("setting tab size to {:?}", tab_size);
1091                    cx.update(|cx| {
1092                        cx.update_global::<SettingsStore, _>(|store, cx| {
1093                            store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1094                                s.defaults.tab_size = NonZeroU32::new(tab_size);
1095                            });
1096                        });
1097                    });
1098                }
1099                30..=44 => {
1100                    map.update(cx, |map, cx| {
1101                        if rng.gen() || blocks.is_empty() {
1102                            let buffer = map.snapshot(cx).buffer_snapshot;
1103                            let block_properties = (0..rng.gen_range(1..=1))
1104                                .map(|_| {
1105                                    let position =
1106                                        buffer.anchor_after(buffer.clip_offset(
1107                                            rng.gen_range(0..=buffer.len()),
1108                                            Bias::Left,
1109                                        ));
1110
1111                                    let disposition = if rng.gen() {
1112                                        BlockDisposition::Above
1113                                    } else {
1114                                        BlockDisposition::Below
1115                                    };
1116                                    let height = rng.gen_range(1..5);
1117                                    log::info!(
1118                                        "inserting block {:?} {:?} with height {}",
1119                                        disposition,
1120                                        position.to_point(&buffer),
1121                                        height
1122                                    );
1123                                    BlockProperties {
1124                                        style: BlockStyle::Fixed,
1125                                        position,
1126                                        height,
1127                                        disposition,
1128                                        render: Arc::new(|_| div().into_any()),
1129                                    }
1130                                })
1131                                .collect::<Vec<_>>();
1132                            blocks.extend(map.insert_blocks(block_properties, cx));
1133                        } else {
1134                            blocks.shuffle(&mut rng);
1135                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1136                            let block_ids_to_remove = (0..remove_count)
1137                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1138                                .collect();
1139                            log::info!("removing block ids {:?}", block_ids_to_remove);
1140                            map.remove_blocks(block_ids_to_remove, cx);
1141                        }
1142                    });
1143                }
1144                45..=79 => {
1145                    let mut ranges = Vec::new();
1146                    for _ in 0..rng.gen_range(1..=3) {
1147                        buffer.read_with(cx, |buffer, cx| {
1148                            let buffer = buffer.read(cx);
1149                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1150                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1151                            ranges.push(start..end);
1152                        });
1153                    }
1154
1155                    if rng.gen() && fold_count > 0 {
1156                        log::info!("unfolding ranges: {:?}", ranges);
1157                        map.update(cx, |map, cx| {
1158                            map.unfold(ranges, true, cx);
1159                        });
1160                    } else {
1161                        log::info!("folding ranges: {:?}", ranges);
1162                        map.update(cx, |map, cx| {
1163                            map.fold(ranges, cx);
1164                        });
1165                    }
1166                }
1167                _ => {
1168                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1169                }
1170            }
1171
1172            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1173                notifications.next().await.unwrap();
1174            }
1175
1176            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1177            fold_count = snapshot.fold_count();
1178            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1179            log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1180            log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1181            log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1182            log::info!("block text: {:?}", snapshot.block_snapshot.text());
1183            log::info!("display text: {:?}", snapshot.text());
1184
1185            // Line boundaries
1186            let buffer = &snapshot.buffer_snapshot;
1187            for _ in 0..5 {
1188                let row = rng.gen_range(0..=buffer.max_point().row);
1189                let column = rng.gen_range(0..=buffer.line_len(row));
1190                let point = buffer.clip_point(Point::new(row, column), Left);
1191
1192                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1193                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1194
1195                assert!(prev_buffer_bound <= point);
1196                assert!(next_buffer_bound >= point);
1197                assert_eq!(prev_buffer_bound.column, 0);
1198                assert_eq!(prev_display_bound.column(), 0);
1199                if next_buffer_bound < buffer.max_point() {
1200                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1201                }
1202
1203                assert_eq!(
1204                    prev_display_bound,
1205                    prev_buffer_bound.to_display_point(&snapshot),
1206                    "row boundary before {:?}. reported buffer row boundary: {:?}",
1207                    point,
1208                    prev_buffer_bound
1209                );
1210                assert_eq!(
1211                    next_display_bound,
1212                    next_buffer_bound.to_display_point(&snapshot),
1213                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
1214                    point,
1215                    next_buffer_bound
1216                );
1217                assert_eq!(
1218                    prev_buffer_bound,
1219                    prev_display_bound.to_point(&snapshot),
1220                    "row boundary before {:?}. reported display row boundary: {:?}",
1221                    point,
1222                    prev_display_bound
1223                );
1224                assert_eq!(
1225                    next_buffer_bound,
1226                    next_display_bound.to_point(&snapshot),
1227                    "row boundary after {:?}. reported display row boundary: {:?}",
1228                    point,
1229                    next_display_bound
1230                );
1231            }
1232
1233            // Movement
1234            let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1235            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1236            for _ in 0..5 {
1237                let row = rng.gen_range(0..=snapshot.max_point().row());
1238                let column = rng.gen_range(0..=snapshot.line_len(row));
1239                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1240
1241                log::info!("Moving from point {:?}", point);
1242
1243                let moved_right = movement::right(&snapshot, point);
1244                log::info!("Right {:?}", moved_right);
1245                if point < max_point {
1246                    assert!(moved_right > point);
1247                    if point.column() == snapshot.line_len(point.row())
1248                        || snapshot.soft_wrap_indent(point.row()).is_some()
1249                            && point.column() == snapshot.line_len(point.row()) - 1
1250                    {
1251                        assert!(moved_right.row() > point.row());
1252                    }
1253                } else {
1254                    assert_eq!(moved_right, point);
1255                }
1256
1257                let moved_left = movement::left(&snapshot, point);
1258                log::info!("Left {:?}", moved_left);
1259                if point > min_point {
1260                    assert!(moved_left < point);
1261                    if point.column() == 0 {
1262                        assert!(moved_left.row() < point.row());
1263                    }
1264                } else {
1265                    assert_eq!(moved_left, point);
1266                }
1267            }
1268        }
1269    }
1270
1271    #[gpui::test(retries = 5)]
1272    async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1273        cx.background_executor
1274            .set_block_on_ticks(usize::MAX..=usize::MAX);
1275        cx.update(|cx| {
1276            init_test(cx, |_| {});
1277        });
1278
1279        let mut cx = EditorTestContext::new(cx).await;
1280        let editor = cx.editor.clone();
1281        let window = cx.window.clone();
1282
1283        _ = cx.update_window(window, |_, cx| {
1284            let text_layout_details =
1285                editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1286
1287            let font_size = px(12.0);
1288            let wrap_width = Some(px(64.));
1289
1290            let text = "one two three four five\nsix seven eight";
1291            let buffer = MultiBuffer::build_simple(text, cx);
1292            let map = cx.new_model(|cx| {
1293                DisplayMap::new(
1294                    buffer.clone(),
1295                    font("Helvetica"),
1296                    font_size,
1297                    wrap_width,
1298                    1,
1299                    1,
1300                    cx,
1301                )
1302            });
1303
1304            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1305            assert_eq!(
1306                snapshot.text_chunks(0).collect::<String>(),
1307                "one two \nthree four \nfive\nsix seven \neight"
1308            );
1309            assert_eq!(
1310                snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1311                DisplayPoint::new(0, 7)
1312            );
1313            assert_eq!(
1314                snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1315                DisplayPoint::new(1, 0)
1316            );
1317            assert_eq!(
1318                movement::right(&snapshot, DisplayPoint::new(0, 7)),
1319                DisplayPoint::new(1, 0)
1320            );
1321            assert_eq!(
1322                movement::left(&snapshot, DisplayPoint::new(1, 0)),
1323                DisplayPoint::new(0, 7)
1324            );
1325
1326            let x = snapshot.x_for_display_point(DisplayPoint::new(1, 10), &text_layout_details);
1327            assert_eq!(
1328                movement::up(
1329                    &snapshot,
1330                    DisplayPoint::new(1, 10),
1331                    SelectionGoal::None,
1332                    false,
1333                    &text_layout_details,
1334                ),
1335                (
1336                    DisplayPoint::new(0, 7),
1337                    SelectionGoal::HorizontalPosition(x.0)
1338                )
1339            );
1340            assert_eq!(
1341                movement::down(
1342                    &snapshot,
1343                    DisplayPoint::new(0, 7),
1344                    SelectionGoal::HorizontalPosition(x.0),
1345                    false,
1346                    &text_layout_details
1347                ),
1348                (
1349                    DisplayPoint::new(1, 10),
1350                    SelectionGoal::HorizontalPosition(x.0)
1351                )
1352            );
1353            assert_eq!(
1354                movement::down(
1355                    &snapshot,
1356                    DisplayPoint::new(1, 10),
1357                    SelectionGoal::HorizontalPosition(x.0),
1358                    false,
1359                    &text_layout_details
1360                ),
1361                (
1362                    DisplayPoint::new(2, 4),
1363                    SelectionGoal::HorizontalPosition(x.0)
1364                )
1365            );
1366
1367            let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1368            buffer.update(cx, |buffer, cx| {
1369                buffer.edit([(ix..ix, "and ")], None, cx);
1370            });
1371
1372            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1373            assert_eq!(
1374                snapshot.text_chunks(1).collect::<String>(),
1375                "three four \nfive\nsix and \nseven eight"
1376            );
1377
1378            // Re-wrap on font size changes
1379            map.update(cx, |map, cx| {
1380                map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1381            });
1382
1383            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1384            assert_eq!(
1385                snapshot.text_chunks(1).collect::<String>(),
1386                "three \nfour five\nsix and \nseven \neight"
1387            )
1388        });
1389    }
1390
1391    #[gpui::test]
1392    fn test_text_chunks(cx: &mut gpui::AppContext) {
1393        init_test(cx, |_| {});
1394
1395        let text = sample_text(6, 6, 'a');
1396        let buffer = MultiBuffer::build_simple(&text, cx);
1397
1398        let font_size = px(14.0);
1399        let map = cx.new_model(|cx| {
1400            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1401        });
1402
1403        buffer.update(cx, |buffer, cx| {
1404            buffer.edit(
1405                vec![
1406                    (Point::new(1, 0)..Point::new(1, 0), "\t"),
1407                    (Point::new(1, 1)..Point::new(1, 1), "\t"),
1408                    (Point::new(2, 1)..Point::new(2, 1), "\t"),
1409                ],
1410                None,
1411                cx,
1412            )
1413        });
1414
1415        assert_eq!(
1416            map.update(cx, |map, cx| map.snapshot(cx))
1417                .text_chunks(1)
1418                .collect::<String>()
1419                .lines()
1420                .next(),
1421            Some("    b   bbbbb")
1422        );
1423        assert_eq!(
1424            map.update(cx, |map, cx| map.snapshot(cx))
1425                .text_chunks(2)
1426                .collect::<String>()
1427                .lines()
1428                .next(),
1429            Some("c   ccccc")
1430        );
1431    }
1432
1433    #[gpui::test]
1434    async fn test_chunks(cx: &mut gpui::TestAppContext) {
1435        use unindent::Unindent as _;
1436
1437        let text = r#"
1438            fn outer() {}
1439
1440            mod module {
1441                fn inner() {}
1442            }"#
1443        .unindent();
1444
1445        let theme = SyntaxTheme::new_test(vec![
1446            ("mod.body", Hsla::red().into()),
1447            ("fn.name", Hsla::blue().into()),
1448        ]);
1449        let language = Arc::new(
1450            Language::new(
1451                LanguageConfig {
1452                    name: "Test".into(),
1453                    path_suffixes: vec![".test".to_string()],
1454                    ..Default::default()
1455                },
1456                Some(tree_sitter_rust::language()),
1457            )
1458            .with_highlights_query(
1459                r#"
1460                (mod_item name: (identifier) body: _ @mod.body)
1461                (function_item name: (identifier) @fn.name)
1462                "#,
1463            )
1464            .unwrap(),
1465        );
1466        language.set_theme(&theme);
1467
1468        cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1469
1470        let buffer = cx.new_model(|cx| {
1471            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
1472                .with_language(language, cx)
1473        });
1474        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1475        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1476
1477        let font_size = px(14.0);
1478
1479        let map = cx
1480            .new_model(|cx| DisplayMap::new(buffer, font("Helvetica"), font_size, None, 1, 1, cx));
1481        assert_eq!(
1482            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1483            vec![
1484                ("fn ".to_string(), None),
1485                ("outer".to_string(), Some(Hsla::blue())),
1486                ("() {}\n\nmod module ".to_string(), None),
1487                ("{\n    fn ".to_string(), Some(Hsla::red())),
1488                ("inner".to_string(), Some(Hsla::blue())),
1489                ("() {}\n}".to_string(), Some(Hsla::red())),
1490            ]
1491        );
1492        assert_eq!(
1493            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1494            vec![
1495                ("    fn ".to_string(), Some(Hsla::red())),
1496                ("inner".to_string(), Some(Hsla::blue())),
1497                ("() {}\n}".to_string(), Some(Hsla::red())),
1498            ]
1499        );
1500
1501        map.update(cx, |map, cx| {
1502            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1503        });
1504        assert_eq!(
1505            cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1506            vec![
1507                ("fn ".to_string(), None),
1508                ("out".to_string(), Some(Hsla::blue())),
1509                ("⋯".to_string(), None),
1510                ("  fn ".to_string(), Some(Hsla::red())),
1511                ("inner".to_string(), Some(Hsla::blue())),
1512                ("() {}\n}".to_string(), Some(Hsla::red())),
1513            ]
1514        );
1515    }
1516
1517    #[gpui::test]
1518    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1519        use unindent::Unindent as _;
1520
1521        cx.background_executor
1522            .set_block_on_ticks(usize::MAX..=usize::MAX);
1523
1524        let text = r#"
1525            fn outer() {}
1526
1527            mod module {
1528                fn inner() {}
1529            }"#
1530        .unindent();
1531
1532        let theme = SyntaxTheme::new_test(vec![
1533            ("mod.body", Hsla::red().into()),
1534            ("fn.name", Hsla::blue().into()),
1535        ]);
1536        let language = Arc::new(
1537            Language::new(
1538                LanguageConfig {
1539                    name: "Test".into(),
1540                    path_suffixes: vec![".test".to_string()],
1541                    ..Default::default()
1542                },
1543                Some(tree_sitter_rust::language()),
1544            )
1545            .with_highlights_query(
1546                r#"
1547                (mod_item name: (identifier) body: _ @mod.body)
1548                (function_item name: (identifier) @fn.name)
1549                "#,
1550            )
1551            .unwrap(),
1552        );
1553        language.set_theme(&theme);
1554
1555        cx.update(|cx| init_test(cx, |_| {}));
1556
1557        let buffer = cx.new_model(|cx| {
1558            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
1559                .with_language(language, cx)
1560        });
1561        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1562        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1563
1564        let font_size = px(16.0);
1565
1566        let map = cx.new_model(|cx| {
1567            DisplayMap::new(buffer, font("Courier"), font_size, Some(px(40.0)), 1, 1, cx)
1568        });
1569        assert_eq!(
1570            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1571            [
1572                ("fn \n".to_string(), None),
1573                ("oute\nr".to_string(), Some(Hsla::blue())),
1574                ("() \n{}\n\n".to_string(), None),
1575            ]
1576        );
1577        assert_eq!(
1578            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1579            [("{}\n\n".to_string(), None)]
1580        );
1581
1582        map.update(cx, |map, cx| {
1583            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1584        });
1585        assert_eq!(
1586            cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1587            [
1588                ("out".to_string(), Some(Hsla::blue())),
1589                ("⋯\n".to_string(), None),
1590                ("  \nfn ".to_string(), Some(Hsla::red())),
1591                ("i\n".to_string(), Some(Hsla::blue()))
1592            ]
1593        );
1594    }
1595
1596    #[gpui::test]
1597    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1598        cx.update(|cx| init_test(cx, |_| {}));
1599
1600        let theme = SyntaxTheme::new_test(vec![
1601            ("operator", Hsla::red().into()),
1602            ("string", Hsla::green().into()),
1603        ]);
1604        let language = Arc::new(
1605            Language::new(
1606                LanguageConfig {
1607                    name: "Test".into(),
1608                    path_suffixes: vec![".test".to_string()],
1609                    ..Default::default()
1610                },
1611                Some(tree_sitter_rust::language()),
1612            )
1613            .with_highlights_query(
1614                r#"
1615                ":" @operator
1616                (string_literal) @string
1617                "#,
1618            )
1619            .unwrap(),
1620        );
1621        language.set_theme(&theme);
1622
1623        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ Ā«aĀ»: B = "c Ā«dĀ»""#, false);
1624
1625        let buffer = cx.new_model(|cx| {
1626            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
1627                .with_language(language, cx)
1628        });
1629        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1630
1631        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1632        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1633
1634        let font_size = px(16.0);
1635        let map =
1636            cx.new_model(|cx| DisplayMap::new(buffer, font("Courier"), font_size, None, 1, 1, cx));
1637
1638        enum MyType {}
1639
1640        let style = HighlightStyle {
1641            color: Some(Hsla::blue()),
1642            ..Default::default()
1643        };
1644
1645        map.update(cx, |map, _cx| {
1646            map.highlight_text(
1647                TypeId::of::<MyType>(),
1648                highlighted_ranges
1649                    .into_iter()
1650                    .map(|range| {
1651                        buffer_snapshot.anchor_before(range.start)
1652                            ..buffer_snapshot.anchor_before(range.end)
1653                    })
1654                    .collect(),
1655                style,
1656            );
1657        });
1658
1659        assert_eq!(
1660            cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1661            [
1662                ("const ".to_string(), None, None),
1663                ("a".to_string(), None, Some(Hsla::blue())),
1664                (":".to_string(), Some(Hsla::red()), None),
1665                (" B = ".to_string(), None, None),
1666                ("\"c ".to_string(), Some(Hsla::green()), None),
1667                ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
1668                ("\"".to_string(), Some(Hsla::green()), None),
1669            ]
1670        );
1671    }
1672
1673    #[gpui::test]
1674    fn test_clip_point(cx: &mut gpui::AppContext) {
1675        init_test(cx, |_| {});
1676
1677        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1678            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1679
1680            match bias {
1681                Bias::Left => {
1682                    if shift_right {
1683                        *markers[1].column_mut() += 1;
1684                    }
1685
1686                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1687                }
1688                Bias::Right => {
1689                    if shift_right {
1690                        *markers[0].column_mut() += 1;
1691                    }
1692
1693                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1694                }
1695            };
1696        }
1697
1698        use Bias::{Left, Right};
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("Ė‡Ė‡šŸ", false, Left, cx);
1708        assert("Ė‡Ė‡šŸ", true, Left, cx);
1709        assert("Ė‡Ė‡šŸ", false, Right, cx);
1710        assert("Ė‡šŸĖ‡", 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", true, Left, cx);
1717        assert(" ˇˇ\t", false, Right, cx);
1718        assert(" ˇ\tˇ", true, Right, cx);
1719        assert("   ˇˇ\t", false, Left, cx);
1720        assert("   ˇˇ\t", false, Right, cx);
1721    }
1722
1723    #[gpui::test]
1724    fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1725        init_test(cx, |_| {});
1726
1727        fn assert(text: &str, cx: &mut gpui::AppContext) {
1728            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1729            unmarked_snapshot.clip_at_line_ends = true;
1730            assert_eq!(
1731                unmarked_snapshot.clip_point(markers[1], Bias::Left),
1732                markers[0]
1733            );
1734        }
1735
1736        assert("ˇˇ", cx);
1737        assert("ˇaˇ", cx);
1738        assert("aˇbˇ", cx);
1739        assert("aˇαˇ", cx);
1740    }
1741
1742    #[gpui::test]
1743    fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1744        init_test(cx, |_| {});
1745
1746        let text = "āœ…\t\tα\nβ\t\nšŸ€Ī²\t\tγ";
1747        let buffer = MultiBuffer::build_simple(text, cx);
1748        let font_size = px(14.0);
1749
1750        let map = cx.new_model(|cx| {
1751            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1752        });
1753        let map = map.update(cx, |map, cx| map.snapshot(cx));
1754        assert_eq!(map.text(), "āœ…       α\nβ   \nšŸ€Ī²      γ");
1755        assert_eq!(
1756            map.text_chunks(0).collect::<String>(),
1757            "āœ…       α\nβ   \nšŸ€Ī²      γ"
1758        );
1759        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \nšŸ€Ī²      γ");
1760        assert_eq!(map.text_chunks(2).collect::<String>(), "šŸ€Ī²      γ");
1761
1762        let point = Point::new(0, "āœ…\t\t".len() as u32);
1763        let display_point = DisplayPoint::new(0, "āœ…       ".len() as u32);
1764        assert_eq!(point.to_display_point(&map), display_point);
1765        assert_eq!(display_point.to_point(&map), point);
1766
1767        let point = Point::new(1, "β\t".len() as u32);
1768        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1769        assert_eq!(point.to_display_point(&map), display_point);
1770        assert_eq!(display_point.to_point(&map), point,);
1771
1772        let point = Point::new(2, "šŸ€Ī²\t\t".len() as u32);
1773        let display_point = DisplayPoint::new(2, "šŸ€Ī²      ".len() as u32);
1774        assert_eq!(point.to_display_point(&map), display_point);
1775        assert_eq!(display_point.to_point(&map), point,);
1776
1777        // Display points inside of expanded tabs
1778        assert_eq!(
1779            DisplayPoint::new(0, "āœ…      ".len() as u32).to_point(&map),
1780            Point::new(0, "āœ…\t".len() as u32),
1781        );
1782        assert_eq!(
1783            DisplayPoint::new(0, "āœ… ".len() as u32).to_point(&map),
1784            Point::new(0, "āœ…".len() as u32),
1785        );
1786
1787        // Clipping display points inside of multi-byte characters
1788        assert_eq!(
1789            map.clip_point(DisplayPoint::new(0, "āœ…".len() as u32 - 1), Left),
1790            DisplayPoint::new(0, 0)
1791        );
1792        assert_eq!(
1793            map.clip_point(DisplayPoint::new(0, "āœ…".len() as u32 - 1), Bias::Right),
1794            DisplayPoint::new(0, "āœ…".len() as u32)
1795        );
1796    }
1797
1798    #[gpui::test]
1799    fn test_max_point(cx: &mut gpui::AppContext) {
1800        init_test(cx, |_| {});
1801
1802        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1803        let font_size = px(14.0);
1804        let map = cx.new_model(|cx| {
1805            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1806        });
1807        assert_eq!(
1808            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1809            DisplayPoint::new(1, 11)
1810        )
1811    }
1812
1813    fn syntax_chunks<'a>(
1814        rows: Range<u32>,
1815        map: &Model<DisplayMap>,
1816        theme: &'a SyntaxTheme,
1817        cx: &mut AppContext,
1818    ) -> Vec<(String, Option<Hsla>)> {
1819        chunks(rows, map, theme, cx)
1820            .into_iter()
1821            .map(|(text, color, _)| (text, color))
1822            .collect()
1823    }
1824
1825    fn chunks<'a>(
1826        rows: Range<u32>,
1827        map: &Model<DisplayMap>,
1828        theme: &'a SyntaxTheme,
1829        cx: &mut AppContext,
1830    ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
1831        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1832        let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
1833        for chunk in snapshot.chunks(rows, true, None, None) {
1834            let syntax_color = chunk
1835                .syntax_highlight_id
1836                .and_then(|id| id.style(theme)?.color);
1837            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1838            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1839                if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1840                    last_chunk.push_str(chunk.text);
1841                    continue;
1842                }
1843            }
1844            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1845        }
1846        chunks
1847    }
1848
1849    fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
1850        let settings = SettingsStore::test(cx);
1851        cx.set_global(settings);
1852        language::init(cx);
1853        crate::init(cx);
1854        Project::init_settings(cx);
1855        theme::init(LoadThemes::JustBase, cx);
1856        cx.update_global::<SettingsStore, _>(|store, cx| {
1857            store.update_user_settings::<AllLanguageSettings>(cx, f);
1858        });
1859    }
1860}