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