display_map.rs

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