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