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