display_map.rs

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