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