display_map.rs

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