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