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 _test_platform = &cx.test_platform;
1019        let mut tab_size = rng.gen_range(1..=4);
1020        let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1021        let excerpt_header_height = rng.gen_range(1..=5);
1022        let font_size = px(14.0);
1023        let max_wrap_width = 300.0;
1024        let mut wrap_width = if rng.gen_bool(0.1) {
1025            None
1026        } else {
1027            Some(px(rng.gen_range(0.0..=max_wrap_width)))
1028        };
1029
1030        log::info!("tab size: {}", tab_size);
1031        log::info!("wrap width: {:?}", wrap_width);
1032
1033        cx.update(|cx| {
1034            init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1035        });
1036
1037        let buffer = cx.update(|cx| {
1038            if rng.gen() {
1039                let len = rng.gen_range(0..10);
1040                let text = util::RandomCharIter::new(&mut rng)
1041                    .take(len)
1042                    .collect::<String>();
1043                MultiBuffer::build_simple(&text, cx)
1044            } else {
1045                MultiBuffer::build_random(&mut rng, cx)
1046            }
1047        });
1048
1049        let map = cx.new_model(|cx| {
1050            DisplayMap::new(
1051                buffer.clone(),
1052                font("Helvetica"),
1053                font_size,
1054                wrap_width,
1055                buffer_start_excerpt_header_height,
1056                excerpt_header_height,
1057                cx,
1058            )
1059        });
1060        let mut notifications = observe(&map, cx);
1061        let mut fold_count = 0;
1062        let mut blocks = Vec::new();
1063
1064        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1065        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1066        log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1067        log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1068        log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1069        log::info!("block text: {:?}", snapshot.block_snapshot.text());
1070        log::info!("display text: {:?}", snapshot.text());
1071
1072        for _i in 0..operations {
1073            match rng.gen_range(0..100) {
1074                0..=19 => {
1075                    wrap_width = if rng.gen_bool(0.2) {
1076                        None
1077                    } else {
1078                        Some(px(rng.gen_range(0.0..=max_wrap_width)))
1079                    };
1080                    log::info!("setting wrap width to {:?}", wrap_width);
1081                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1082                }
1083                20..=29 => {
1084                    let mut tab_sizes = vec![1, 2, 3, 4];
1085                    tab_sizes.remove((tab_size - 1) as usize);
1086                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
1087                    log::info!("setting tab size to {:?}", tab_size);
1088                    cx.update(|cx| {
1089                        cx.update_global::<SettingsStore, _>(|store, cx| {
1090                            store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1091                                s.defaults.tab_size = NonZeroU32::new(tab_size);
1092                            });
1093                        });
1094                    });
1095                }
1096                30..=44 => {
1097                    map.update(cx, |map, cx| {
1098                        if rng.gen() || blocks.is_empty() {
1099                            let buffer = map.snapshot(cx).buffer_snapshot;
1100                            let block_properties = (0..rng.gen_range(1..=1))
1101                                .map(|_| {
1102                                    let position =
1103                                        buffer.anchor_after(buffer.clip_offset(
1104                                            rng.gen_range(0..=buffer.len()),
1105                                            Bias::Left,
1106                                        ));
1107
1108                                    let disposition = if rng.gen() {
1109                                        BlockDisposition::Above
1110                                    } else {
1111                                        BlockDisposition::Below
1112                                    };
1113                                    let height = rng.gen_range(1..5);
1114                                    log::info!(
1115                                        "inserting block {:?} {:?} with height {}",
1116                                        disposition,
1117                                        position.to_point(&buffer),
1118                                        height
1119                                    );
1120                                    BlockProperties {
1121                                        style: BlockStyle::Fixed,
1122                                        position,
1123                                        height,
1124                                        disposition,
1125                                        render: Arc::new(|_| div().into_any()),
1126                                    }
1127                                })
1128                                .collect::<Vec<_>>();
1129                            blocks.extend(map.insert_blocks(block_properties, cx));
1130                        } else {
1131                            blocks.shuffle(&mut rng);
1132                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1133                            let block_ids_to_remove = (0..remove_count)
1134                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1135                                .collect();
1136                            log::info!("removing block ids {:?}", block_ids_to_remove);
1137                            map.remove_blocks(block_ids_to_remove, cx);
1138                        }
1139                    });
1140                }
1141                45..=79 => {
1142                    let mut ranges = Vec::new();
1143                    for _ in 0..rng.gen_range(1..=3) {
1144                        buffer.read_with(cx, |buffer, cx| {
1145                            let buffer = buffer.read(cx);
1146                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1147                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1148                            ranges.push(start..end);
1149                        });
1150                    }
1151
1152                    if rng.gen() && fold_count > 0 {
1153                        log::info!("unfolding ranges: {:?}", ranges);
1154                        map.update(cx, |map, cx| {
1155                            map.unfold(ranges, true, cx);
1156                        });
1157                    } else {
1158                        log::info!("folding ranges: {:?}", ranges);
1159                        map.update(cx, |map, cx| {
1160                            map.fold(ranges, cx);
1161                        });
1162                    }
1163                }
1164                _ => {
1165                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1166                }
1167            }
1168
1169            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1170                notifications.next().await.unwrap();
1171            }
1172
1173            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1174            fold_count = snapshot.fold_count();
1175            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1176            log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1177            log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1178            log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1179            log::info!("block text: {:?}", snapshot.block_snapshot.text());
1180            log::info!("display text: {:?}", snapshot.text());
1181
1182            // Line boundaries
1183            let buffer = &snapshot.buffer_snapshot;
1184            for _ in 0..5 {
1185                let row = rng.gen_range(0..=buffer.max_point().row);
1186                let column = rng.gen_range(0..=buffer.line_len(row));
1187                let point = buffer.clip_point(Point::new(row, column), Left);
1188
1189                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1190                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1191
1192                assert!(prev_buffer_bound <= point);
1193                assert!(next_buffer_bound >= point);
1194                assert_eq!(prev_buffer_bound.column, 0);
1195                assert_eq!(prev_display_bound.column(), 0);
1196                if next_buffer_bound < buffer.max_point() {
1197                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1198                }
1199
1200                assert_eq!(
1201                    prev_display_bound,
1202                    prev_buffer_bound.to_display_point(&snapshot),
1203                    "row boundary before {:?}. reported buffer row boundary: {:?}",
1204                    point,
1205                    prev_buffer_bound
1206                );
1207                assert_eq!(
1208                    next_display_bound,
1209                    next_buffer_bound.to_display_point(&snapshot),
1210                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
1211                    point,
1212                    next_buffer_bound
1213                );
1214                assert_eq!(
1215                    prev_buffer_bound,
1216                    prev_display_bound.to_point(&snapshot),
1217                    "row boundary before {:?}. reported display row boundary: {:?}",
1218                    point,
1219                    prev_display_bound
1220                );
1221                assert_eq!(
1222                    next_buffer_bound,
1223                    next_display_bound.to_point(&snapshot),
1224                    "row boundary after {:?}. reported display row boundary: {:?}",
1225                    point,
1226                    next_display_bound
1227                );
1228            }
1229
1230            // Movement
1231            let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1232            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1233            for _ in 0..5 {
1234                let row = rng.gen_range(0..=snapshot.max_point().row());
1235                let column = rng.gen_range(0..=snapshot.line_len(row));
1236                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1237
1238                log::info!("Moving from point {:?}", point);
1239
1240                let moved_right = movement::right(&snapshot, point);
1241                log::info!("Right {:?}", moved_right);
1242                if point < max_point {
1243                    assert!(moved_right > point);
1244                    if point.column() == snapshot.line_len(point.row())
1245                        || snapshot.soft_wrap_indent(point.row()).is_some()
1246                            && point.column() == snapshot.line_len(point.row()) - 1
1247                    {
1248                        assert!(moved_right.row() > point.row());
1249                    }
1250                } else {
1251                    assert_eq!(moved_right, point);
1252                }
1253
1254                let moved_left = movement::left(&snapshot, point);
1255                log::info!("Left {:?}", moved_left);
1256                if point > min_point {
1257                    assert!(moved_left < point);
1258                    if point.column() == 0 {
1259                        assert!(moved_left.row() < point.row());
1260                    }
1261                } else {
1262                    assert_eq!(moved_left, point);
1263                }
1264            }
1265        }
1266    }
1267
1268    #[gpui::test(retries = 5)]
1269    async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1270        cx.background_executor
1271            .set_block_on_ticks(usize::MAX..=usize::MAX);
1272        cx.update(|cx| {
1273            init_test(cx, |_| {});
1274        });
1275
1276        let mut cx = EditorTestContext::new(cx).await;
1277        let editor = cx.editor.clone();
1278        let window = cx.window.clone();
1279
1280        _ = cx.update_window(window, |_, cx| {
1281            let text_layout_details =
1282                editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1283
1284            let font_size = px(12.0);
1285            let wrap_width = Some(px(64.));
1286
1287            let text = "one two three four five\nsix seven eight";
1288            let buffer = MultiBuffer::build_simple(text, cx);
1289            let map = cx.new_model(|cx| {
1290                DisplayMap::new(
1291                    buffer.clone(),
1292                    font("Helvetica"),
1293                    font_size,
1294                    wrap_width,
1295                    1,
1296                    1,
1297                    cx,
1298                )
1299            });
1300
1301            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1302            assert_eq!(
1303                snapshot.text_chunks(0).collect::<String>(),
1304                "one two \nthree four \nfive\nsix seven \neight"
1305            );
1306            assert_eq!(
1307                snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1308                DisplayPoint::new(0, 7)
1309            );
1310            assert_eq!(
1311                snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1312                DisplayPoint::new(1, 0)
1313            );
1314            assert_eq!(
1315                movement::right(&snapshot, DisplayPoint::new(0, 7)),
1316                DisplayPoint::new(1, 0)
1317            );
1318            assert_eq!(
1319                movement::left(&snapshot, DisplayPoint::new(1, 0)),
1320                DisplayPoint::new(0, 7)
1321            );
1322
1323            let x = snapshot.x_for_display_point(DisplayPoint::new(1, 10), &text_layout_details);
1324            assert_eq!(
1325                movement::up(
1326                    &snapshot,
1327                    DisplayPoint::new(1, 10),
1328                    SelectionGoal::None,
1329                    false,
1330                    &text_layout_details,
1331                ),
1332                (
1333                    DisplayPoint::new(0, 7),
1334                    SelectionGoal::HorizontalPosition(x.0)
1335                )
1336            );
1337            assert_eq!(
1338                movement::down(
1339                    &snapshot,
1340                    DisplayPoint::new(0, 7),
1341                    SelectionGoal::HorizontalPosition(x.0),
1342                    false,
1343                    &text_layout_details
1344                ),
1345                (
1346                    DisplayPoint::new(1, 10),
1347                    SelectionGoal::HorizontalPosition(x.0)
1348                )
1349            );
1350            assert_eq!(
1351                movement::down(
1352                    &snapshot,
1353                    DisplayPoint::new(1, 10),
1354                    SelectionGoal::HorizontalPosition(x.0),
1355                    false,
1356                    &text_layout_details
1357                ),
1358                (
1359                    DisplayPoint::new(2, 4),
1360                    SelectionGoal::HorizontalPosition(x.0)
1361                )
1362            );
1363
1364            let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1365            buffer.update(cx, |buffer, cx| {
1366                buffer.edit([(ix..ix, "and ")], None, cx);
1367            });
1368
1369            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1370            assert_eq!(
1371                snapshot.text_chunks(1).collect::<String>(),
1372                "three four \nfive\nsix and \nseven eight"
1373            );
1374
1375            // Re-wrap on font size changes
1376            map.update(cx, |map, cx| {
1377                map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1378            });
1379
1380            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1381            assert_eq!(
1382                snapshot.text_chunks(1).collect::<String>(),
1383                "three \nfour five\nsix and \nseven \neight"
1384            )
1385        });
1386    }
1387
1388    #[gpui::test]
1389    fn test_text_chunks(cx: &mut gpui::AppContext) {
1390        init_test(cx, |_| {});
1391
1392        let text = sample_text(6, 6, 'a');
1393        let buffer = MultiBuffer::build_simple(&text, cx);
1394
1395        let font_size = px(14.0);
1396        let map = cx.new_model(|cx| {
1397            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1398        });
1399
1400        buffer.update(cx, |buffer, cx| {
1401            buffer.edit(
1402                vec![
1403                    (Point::new(1, 0)..Point::new(1, 0), "\t"),
1404                    (Point::new(1, 1)..Point::new(1, 1), "\t"),
1405                    (Point::new(2, 1)..Point::new(2, 1), "\t"),
1406                ],
1407                None,
1408                cx,
1409            )
1410        });
1411
1412        assert_eq!(
1413            map.update(cx, |map, cx| map.snapshot(cx))
1414                .text_chunks(1)
1415                .collect::<String>()
1416                .lines()
1417                .next(),
1418            Some("    b   bbbbb")
1419        );
1420        assert_eq!(
1421            map.update(cx, |map, cx| map.snapshot(cx))
1422                .text_chunks(2)
1423                .collect::<String>()
1424                .lines()
1425                .next(),
1426            Some("c   ccccc")
1427        );
1428    }
1429
1430    #[gpui::test]
1431    async fn test_chunks(cx: &mut gpui::TestAppContext) {
1432        use unindent::Unindent as _;
1433
1434        let text = r#"
1435            fn outer() {}
1436
1437            mod module {
1438                fn inner() {}
1439            }"#
1440        .unindent();
1441
1442        let theme = SyntaxTheme::new_test(vec![
1443            ("mod.body", Hsla::red().into()),
1444            ("fn.name", Hsla::blue().into()),
1445        ]);
1446        let language = Arc::new(
1447            Language::new(
1448                LanguageConfig {
1449                    name: "Test".into(),
1450                    path_suffixes: vec![".test".to_string()],
1451                    ..Default::default()
1452                },
1453                Some(tree_sitter_rust::language()),
1454            )
1455            .with_highlights_query(
1456                r#"
1457                (mod_item name: (identifier) body: _ @mod.body)
1458                (function_item name: (identifier) @fn.name)
1459                "#,
1460            )
1461            .unwrap(),
1462        );
1463        language.set_theme(&theme);
1464
1465        cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1466
1467        let buffer = cx.new_model(|cx| {
1468            Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
1469        });
1470        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1471        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1472
1473        let font_size = px(14.0);
1474
1475        let map = cx
1476            .new_model(|cx| DisplayMap::new(buffer, font("Helvetica"), font_size, None, 1, 1, cx));
1477        assert_eq!(
1478            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1479            vec![
1480                ("fn ".to_string(), None),
1481                ("outer".to_string(), Some(Hsla::blue())),
1482                ("() {}\n\nmod module ".to_string(), None),
1483                ("{\n    fn ".to_string(), Some(Hsla::red())),
1484                ("inner".to_string(), Some(Hsla::blue())),
1485                ("() {}\n}".to_string(), Some(Hsla::red())),
1486            ]
1487        );
1488        assert_eq!(
1489            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1490            vec![
1491                ("    fn ".to_string(), Some(Hsla::red())),
1492                ("inner".to_string(), Some(Hsla::blue())),
1493                ("() {}\n}".to_string(), Some(Hsla::red())),
1494            ]
1495        );
1496
1497        map.update(cx, |map, cx| {
1498            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1499        });
1500        assert_eq!(
1501            cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1502            vec![
1503                ("fn ".to_string(), None),
1504                ("out".to_string(), Some(Hsla::blue())),
1505                ("⋯".to_string(), None),
1506                ("  fn ".to_string(), Some(Hsla::red())),
1507                ("inner".to_string(), Some(Hsla::blue())),
1508                ("() {}\n}".to_string(), Some(Hsla::red())),
1509            ]
1510        );
1511    }
1512
1513    #[gpui::test]
1514    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1515        use unindent::Unindent as _;
1516
1517        cx.background_executor
1518            .set_block_on_ticks(usize::MAX..=usize::MAX);
1519
1520        let text = r#"
1521            fn outer() {}
1522
1523            mod module {
1524                fn inner() {}
1525            }"#
1526        .unindent();
1527
1528        let theme = SyntaxTheme::new_test(vec![
1529            ("mod.body", Hsla::red().into()),
1530            ("fn.name", Hsla::blue().into()),
1531        ]);
1532        let language = Arc::new(
1533            Language::new(
1534                LanguageConfig {
1535                    name: "Test".into(),
1536                    path_suffixes: vec![".test".to_string()],
1537                    ..Default::default()
1538                },
1539                Some(tree_sitter_rust::language()),
1540            )
1541            .with_highlights_query(
1542                r#"
1543                (mod_item name: (identifier) body: _ @mod.body)
1544                (function_item name: (identifier) @fn.name)
1545                "#,
1546            )
1547            .unwrap(),
1548        );
1549        language.set_theme(&theme);
1550
1551        cx.update(|cx| init_test(cx, |_| {}));
1552
1553        let buffer = cx.new_model(|cx| {
1554            Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
1555        });
1556        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1557        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1558
1559        let font_size = px(16.0);
1560
1561        let map = cx.new_model(|cx| {
1562            DisplayMap::new(buffer, font("Courier"), font_size, Some(px(40.0)), 1, 1, cx)
1563        });
1564        assert_eq!(
1565            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1566            [
1567                ("fn \n".to_string(), None),
1568                ("oute\nr".to_string(), Some(Hsla::blue())),
1569                ("() \n{}\n\n".to_string(), None),
1570            ]
1571        );
1572        assert_eq!(
1573            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1574            [("{}\n\n".to_string(), None)]
1575        );
1576
1577        map.update(cx, |map, cx| {
1578            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1579        });
1580        assert_eq!(
1581            cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1582            [
1583                ("out".to_string(), Some(Hsla::blue())),
1584                ("⋯\n".to_string(), None),
1585                ("  \nfn ".to_string(), Some(Hsla::red())),
1586                ("i\n".to_string(), Some(Hsla::blue()))
1587            ]
1588        );
1589    }
1590
1591    #[gpui::test]
1592    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1593        cx.update(|cx| init_test(cx, |_| {}));
1594
1595        let theme = SyntaxTheme::new_test(vec![
1596            ("operator", Hsla::red().into()),
1597            ("string", Hsla::green().into()),
1598        ]);
1599        let language = Arc::new(
1600            Language::new(
1601                LanguageConfig {
1602                    name: "Test".into(),
1603                    path_suffixes: vec![".test".to_string()],
1604                    ..Default::default()
1605                },
1606                Some(tree_sitter_rust::language()),
1607            )
1608            .with_highlights_query(
1609                r#"
1610                ":" @operator
1611                (string_literal) @string
1612                "#,
1613            )
1614            .unwrap(),
1615        );
1616        language.set_theme(&theme);
1617
1618        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ Ā«aĀ»: B = "c Ā«dĀ»""#, false);
1619
1620        let buffer = cx.new_model(|cx| {
1621            Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
1622        });
1623        cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1624
1625        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1626        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1627
1628        let font_size = px(16.0);
1629        let map =
1630            cx.new_model(|cx| DisplayMap::new(buffer, font("Courier"), font_size, None, 1, 1, cx));
1631
1632        enum MyType {}
1633
1634        let style = HighlightStyle {
1635            color: Some(Hsla::blue()),
1636            ..Default::default()
1637        };
1638
1639        map.update(cx, |map, _cx| {
1640            map.highlight_text(
1641                TypeId::of::<MyType>(),
1642                highlighted_ranges
1643                    .into_iter()
1644                    .map(|range| {
1645                        buffer_snapshot.anchor_before(range.start)
1646                            ..buffer_snapshot.anchor_before(range.end)
1647                    })
1648                    .collect(),
1649                style,
1650            );
1651        });
1652
1653        assert_eq!(
1654            cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1655            [
1656                ("const ".to_string(), None, None),
1657                ("a".to_string(), None, Some(Hsla::blue())),
1658                (":".to_string(), Some(Hsla::red()), None),
1659                (" B = ".to_string(), None, None),
1660                ("\"c ".to_string(), Some(Hsla::green()), None),
1661                ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
1662                ("\"".to_string(), Some(Hsla::green()), None),
1663            ]
1664        );
1665    }
1666
1667    #[gpui::test]
1668    fn test_clip_point(cx: &mut gpui::AppContext) {
1669        init_test(cx, |_| {});
1670
1671        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1672            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1673
1674            match bias {
1675                Bias::Left => {
1676                    if shift_right {
1677                        *markers[1].column_mut() += 1;
1678                    }
1679
1680                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1681                }
1682                Bias::Right => {
1683                    if shift_right {
1684                        *markers[0].column_mut() += 1;
1685                    }
1686
1687                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1688                }
1689            };
1690        }
1691
1692        use Bias::{Left, Right};
1693        assert("ˇˇα", false, Left, cx);
1694        assert("ˇˇα", true, Left, cx);
1695        assert("ˇˇα", false, Right, cx);
1696        assert("ˇαˇ", true, Right, cx);
1697        assert("Ė‡Ė‡āœ‹", false, Left, cx);
1698        assert("Ė‡Ė‡āœ‹", true, Left, cx);
1699        assert("Ė‡Ė‡āœ‹", false, Right, cx);
1700        assert("Ė‡āœ‹Ė‡", true, Right, cx);
1701        assert("Ė‡Ė‡šŸ", false, Left, cx);
1702        assert("Ė‡Ė‡šŸ", true, Left, cx);
1703        assert("Ė‡Ė‡šŸ", false, Right, cx);
1704        assert("Ė‡šŸĖ‡", true, Right, cx);
1705        assert("ˇˇ\t", false, Left, cx);
1706        assert("ˇˇ\t", true, Left, cx);
1707        assert("ˇˇ\t", false, Right, cx);
1708        assert("ˇ\tˇ", true, Right, cx);
1709        assert(" ˇˇ\t", false, Left, cx);
1710        assert(" ˇˇ\t", true, Left, cx);
1711        assert(" ˇˇ\t", false, Right, cx);
1712        assert(" ˇ\tˇ", true, Right, cx);
1713        assert("   ˇˇ\t", false, Left, cx);
1714        assert("   ˇˇ\t", false, Right, cx);
1715    }
1716
1717    #[gpui::test]
1718    fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1719        init_test(cx, |_| {});
1720
1721        fn assert(text: &str, cx: &mut gpui::AppContext) {
1722            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1723            unmarked_snapshot.clip_at_line_ends = true;
1724            assert_eq!(
1725                unmarked_snapshot.clip_point(markers[1], Bias::Left),
1726                markers[0]
1727            );
1728        }
1729
1730        assert("ˇˇ", cx);
1731        assert("ˇaˇ", cx);
1732        assert("aˇbˇ", cx);
1733        assert("aˇαˇ", cx);
1734    }
1735
1736    #[gpui::test]
1737    fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1738        init_test(cx, |_| {});
1739
1740        let text = "āœ…\t\tα\nβ\t\nšŸ€Ī²\t\tγ";
1741        let buffer = MultiBuffer::build_simple(text, cx);
1742        let font_size = px(14.0);
1743
1744        let map = cx.new_model(|cx| {
1745            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1746        });
1747        let map = map.update(cx, |map, cx| map.snapshot(cx));
1748        assert_eq!(map.text(), "āœ…       α\nβ   \nšŸ€Ī²      γ");
1749        assert_eq!(
1750            map.text_chunks(0).collect::<String>(),
1751            "āœ…       α\nβ   \nšŸ€Ī²      γ"
1752        );
1753        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \nšŸ€Ī²      γ");
1754        assert_eq!(map.text_chunks(2).collect::<String>(), "šŸ€Ī²      γ");
1755
1756        let point = Point::new(0, "āœ…\t\t".len() as u32);
1757        let display_point = DisplayPoint::new(0, "āœ…       ".len() as u32);
1758        assert_eq!(point.to_display_point(&map), display_point);
1759        assert_eq!(display_point.to_point(&map), point);
1760
1761        let point = Point::new(1, "β\t".len() as u32);
1762        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1763        assert_eq!(point.to_display_point(&map), display_point);
1764        assert_eq!(display_point.to_point(&map), point,);
1765
1766        let point = Point::new(2, "šŸ€Ī²\t\t".len() as u32);
1767        let display_point = DisplayPoint::new(2, "šŸ€Ī²      ".len() as u32);
1768        assert_eq!(point.to_display_point(&map), display_point);
1769        assert_eq!(display_point.to_point(&map), point,);
1770
1771        // Display points inside of expanded tabs
1772        assert_eq!(
1773            DisplayPoint::new(0, "āœ…      ".len() as u32).to_point(&map),
1774            Point::new(0, "āœ…\t".len() as u32),
1775        );
1776        assert_eq!(
1777            DisplayPoint::new(0, "āœ… ".len() as u32).to_point(&map),
1778            Point::new(0, "āœ…".len() as u32),
1779        );
1780
1781        // Clipping display points inside of multi-byte characters
1782        assert_eq!(
1783            map.clip_point(DisplayPoint::new(0, "āœ…".len() as u32 - 1), Left),
1784            DisplayPoint::new(0, 0)
1785        );
1786        assert_eq!(
1787            map.clip_point(DisplayPoint::new(0, "āœ…".len() as u32 - 1), Bias::Right),
1788            DisplayPoint::new(0, "āœ…".len() as u32)
1789        );
1790    }
1791
1792    #[gpui::test]
1793    fn test_max_point(cx: &mut gpui::AppContext) {
1794        init_test(cx, |_| {});
1795
1796        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1797        let font_size = px(14.0);
1798        let map = cx.new_model(|cx| {
1799            DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1800        });
1801        assert_eq!(
1802            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1803            DisplayPoint::new(1, 11)
1804        )
1805    }
1806
1807    fn syntax_chunks<'a>(
1808        rows: Range<u32>,
1809        map: &Model<DisplayMap>,
1810        theme: &'a SyntaxTheme,
1811        cx: &mut AppContext,
1812    ) -> Vec<(String, Option<Hsla>)> {
1813        chunks(rows, map, theme, cx)
1814            .into_iter()
1815            .map(|(text, color, _)| (text, color))
1816            .collect()
1817    }
1818
1819    fn chunks<'a>(
1820        rows: Range<u32>,
1821        map: &Model<DisplayMap>,
1822        theme: &'a SyntaxTheme,
1823        cx: &mut AppContext,
1824    ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
1825        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1826        let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
1827        for chunk in snapshot.chunks(rows, true, None, None) {
1828            let syntax_color = chunk
1829                .syntax_highlight_id
1830                .and_then(|id| id.style(theme)?.color);
1831            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1832            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1833                if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1834                    last_chunk.push_str(chunk.text);
1835                    continue;
1836                }
1837            }
1838            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1839        }
1840        chunks
1841    }
1842
1843    fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
1844        let settings = SettingsStore::test(cx);
1845        cx.set_global(settings);
1846        language::init(cx);
1847        crate::init(cx);
1848        Project::init_settings(cx);
1849        theme::init(LoadThemes::JustBase, cx);
1850        cx.update_global::<SettingsStore, _>(|store, cx| {
1851            store.update_user_settings::<AllLanguageSettings>(cx, f);
1852        });
1853    }
1854}