display_map.rs

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