display_map.rs

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