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