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
 647            let end = end.unwrap_or(max_point);
 648            Some(start..end)
 649        } else {
 650            None
 651        }
 652    }
 653
 654    #[cfg(any(test, feature = "test-support"))]
 655    pub fn highlight_ranges<Tag: ?Sized + 'static>(
 656        &self,
 657    ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
 658        let type_id = TypeId::of::<Tag>();
 659        self.text_highlights.get(&Some(type_id)).cloned()
 660    }
 661}
 662
 663#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
 664pub struct DisplayPoint(BlockPoint);
 665
 666impl Debug for DisplayPoint {
 667    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 668        f.write_fmt(format_args!(
 669            "DisplayPoint({}, {})",
 670            self.row(),
 671            self.column()
 672        ))
 673    }
 674}
 675
 676impl DisplayPoint {
 677    pub fn new(row: u32, column: u32) -> Self {
 678        Self(BlockPoint(Point::new(row, column)))
 679    }
 680
 681    pub fn zero() -> Self {
 682        Self::new(0, 0)
 683    }
 684
 685    pub fn is_zero(&self) -> bool {
 686        self.0.is_zero()
 687    }
 688
 689    pub fn row(self) -> u32 {
 690        self.0.row
 691    }
 692
 693    pub fn column(self) -> u32 {
 694        self.0.column
 695    }
 696
 697    pub fn row_mut(&mut self) -> &mut u32 {
 698        &mut self.0.row
 699    }
 700
 701    pub fn column_mut(&mut self) -> &mut u32 {
 702        &mut self.0.column
 703    }
 704
 705    pub fn to_point(self, map: &DisplaySnapshot) -> Point {
 706        map.display_point_to_point(self, Bias::Left)
 707    }
 708
 709    pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
 710        let unblocked_point = map.blocks_snapshot.to_wrap_point(self.0);
 711        let unwrapped_point = map.wraps_snapshot.to_tab_point(unblocked_point);
 712        let unexpanded_point = map.tabs_snapshot.to_fold_point(unwrapped_point, bias).0;
 713        unexpanded_point.to_buffer_offset(&map.folds_snapshot)
 714    }
 715}
 716
 717impl ToDisplayPoint for usize {
 718    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 719        map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
 720    }
 721}
 722
 723impl ToDisplayPoint for OffsetUtf16 {
 724    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 725        self.to_offset(&map.buffer_snapshot).to_display_point(map)
 726    }
 727}
 728
 729impl ToDisplayPoint for Point {
 730    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 731        map.point_to_display_point(*self, Bias::Left)
 732    }
 733}
 734
 735impl ToDisplayPoint for Anchor {
 736    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 737        self.to_point(&map.buffer_snapshot).to_display_point(map)
 738    }
 739}
 740
 741pub fn next_rows(display_row: u32, display_map: &DisplaySnapshot) -> impl Iterator<Item = u32> {
 742    let max_row = display_map.max_point().row();
 743    let start_row = display_row + 1;
 744    let mut current = None;
 745    std::iter::from_fn(move || {
 746        if current == None {
 747            current = Some(start_row);
 748        } else {
 749            current = Some(current.unwrap() + 1)
 750        }
 751        if current.unwrap() > max_row {
 752            None
 753        } else {
 754            current
 755        }
 756    })
 757}
 758
 759#[cfg(test)]
 760pub mod tests {
 761    use super::*;
 762    use crate::{movement, test::marked_display_snapshot};
 763    use gpui::{color::Color, elements::*, test::observe, MutableAppContext};
 764    use language::{Buffer, Language, LanguageConfig, SelectionGoal};
 765    use rand::{prelude::*, Rng};
 766    use smol::stream::StreamExt;
 767    use std::{env, sync::Arc};
 768    use theme::SyntaxTheme;
 769    use util::test::{marked_text_offsets, marked_text_ranges, sample_text};
 770    use Bias::*;
 771
 772    #[gpui::test(iterations = 100)]
 773    async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
 774        cx.foreground().set_block_on_ticks(0..=50);
 775        cx.foreground().forbid_parking();
 776        let operations = env::var("OPERATIONS")
 777            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
 778            .unwrap_or(10);
 779
 780        let font_cache = cx.font_cache().clone();
 781        let mut tab_size = rng.gen_range(1..=4);
 782        let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
 783        let excerpt_header_height = rng.gen_range(1..=5);
 784        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 785        let font_id = font_cache
 786            .select_font(family_id, &Default::default())
 787            .unwrap();
 788        let font_size = 14.0;
 789        let max_wrap_width = 300.0;
 790        let mut wrap_width = if rng.gen_bool(0.1) {
 791            None
 792        } else {
 793            Some(rng.gen_range(0.0..=max_wrap_width))
 794        };
 795
 796        log::info!("tab size: {}", tab_size);
 797        log::info!("wrap width: {:?}", wrap_width);
 798
 799        cx.update(|cx| {
 800            let mut settings = Settings::test(cx);
 801            settings.editor_overrides.tab_size = NonZeroU32::new(tab_size);
 802            cx.set_global(settings)
 803        });
 804
 805        let buffer = cx.update(|cx| {
 806            if rng.gen() {
 807                let len = rng.gen_range(0..10);
 808                let text = util::RandomCharIter::new(&mut rng)
 809                    .take(len)
 810                    .collect::<String>();
 811                MultiBuffer::build_simple(&text, cx)
 812            } else {
 813                MultiBuffer::build_random(&mut rng, cx)
 814            }
 815        });
 816
 817        let map = cx.add_model(|cx| {
 818            DisplayMap::new(
 819                buffer.clone(),
 820                font_id,
 821                font_size,
 822                wrap_width,
 823                buffer_start_excerpt_header_height,
 824                excerpt_header_height,
 825                cx,
 826            )
 827        });
 828        let mut notifications = observe(&map, cx);
 829        let mut fold_count = 0;
 830        let mut blocks = Vec::new();
 831
 832        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 833        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
 834        log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
 835        log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
 836        log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
 837        log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
 838        log::info!("display text: {:?}", snapshot.text());
 839
 840        for _i in 0..operations {
 841            match rng.gen_range(0..100) {
 842                0..=19 => {
 843                    wrap_width = if rng.gen_bool(0.2) {
 844                        None
 845                    } else {
 846                        Some(rng.gen_range(0.0..=max_wrap_width))
 847                    };
 848                    log::info!("setting wrap width to {:?}", wrap_width);
 849                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
 850                }
 851                20..=29 => {
 852                    let mut tab_sizes = vec![1, 2, 3, 4];
 853                    tab_sizes.remove((tab_size - 1) as usize);
 854                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
 855                    log::info!("setting tab size to {:?}", tab_size);
 856                    cx.update(|cx| {
 857                        let mut settings = Settings::test(cx);
 858                        settings.editor_overrides.tab_size = NonZeroU32::new(tab_size);
 859                        cx.set_global(settings)
 860                    });
 861                }
 862                30..=44 => {
 863                    map.update(cx, |map, cx| {
 864                        if rng.gen() || blocks.is_empty() {
 865                            let buffer = map.snapshot(cx).buffer_snapshot;
 866                            let block_properties = (0..rng.gen_range(1..=1))
 867                                .map(|_| {
 868                                    let position =
 869                                        buffer.anchor_after(buffer.clip_offset(
 870                                            rng.gen_range(0..=buffer.len()),
 871                                            Bias::Left,
 872                                        ));
 873
 874                                    let disposition = if rng.gen() {
 875                                        BlockDisposition::Above
 876                                    } else {
 877                                        BlockDisposition::Below
 878                                    };
 879                                    let height = rng.gen_range(1..5);
 880                                    log::info!(
 881                                        "inserting block {:?} {:?} with height {}",
 882                                        disposition,
 883                                        position.to_point(&buffer),
 884                                        height
 885                                    );
 886                                    BlockProperties {
 887                                        style: BlockStyle::Fixed,
 888                                        position,
 889                                        height,
 890                                        disposition,
 891                                        render: Arc::new(|_| Empty::new().boxed()),
 892                                    }
 893                                })
 894                                .collect::<Vec<_>>();
 895                            blocks.extend(map.insert_blocks(block_properties, cx));
 896                        } else {
 897                            blocks.shuffle(&mut rng);
 898                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
 899                            let block_ids_to_remove = (0..remove_count)
 900                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
 901                                .collect();
 902                            log::info!("removing block ids {:?}", block_ids_to_remove);
 903                            map.remove_blocks(block_ids_to_remove, cx);
 904                        }
 905                    });
 906                }
 907                45..=79 => {
 908                    let mut ranges = Vec::new();
 909                    for _ in 0..rng.gen_range(1..=3) {
 910                        buffer.read_with(cx, |buffer, cx| {
 911                            let buffer = buffer.read(cx);
 912                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
 913                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
 914                            ranges.push(start..end);
 915                        });
 916                    }
 917
 918                    if rng.gen() && fold_count > 0 {
 919                        log::info!("unfolding ranges: {:?}", ranges);
 920                        map.update(cx, |map, cx| {
 921                            map.unfold(ranges, true, cx);
 922                        });
 923                    } else {
 924                        log::info!("folding ranges: {:?}", ranges);
 925                        map.update(cx, |map, cx| {
 926                            map.fold(ranges, cx);
 927                        });
 928                    }
 929                }
 930                _ => {
 931                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
 932                }
 933            }
 934
 935            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
 936                notifications.next().await.unwrap();
 937            }
 938
 939            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 940            fold_count = snapshot.fold_count();
 941            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
 942            log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
 943            log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
 944            log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
 945            log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
 946            log::info!("display text: {:?}", snapshot.text());
 947
 948            // Line boundaries
 949            let buffer = &snapshot.buffer_snapshot;
 950            for _ in 0..5 {
 951                let row = rng.gen_range(0..=buffer.max_point().row);
 952                let column = rng.gen_range(0..=buffer.line_len(row));
 953                let point = buffer.clip_point(Point::new(row, column), Left);
 954
 955                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
 956                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
 957
 958                assert!(prev_buffer_bound <= point);
 959                assert!(next_buffer_bound >= point);
 960                assert_eq!(prev_buffer_bound.column, 0);
 961                assert_eq!(prev_display_bound.column(), 0);
 962                if next_buffer_bound < buffer.max_point() {
 963                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
 964                }
 965
 966                assert_eq!(
 967                    prev_display_bound,
 968                    prev_buffer_bound.to_display_point(&snapshot),
 969                    "row boundary before {:?}. reported buffer row boundary: {:?}",
 970                    point,
 971                    prev_buffer_bound
 972                );
 973                assert_eq!(
 974                    next_display_bound,
 975                    next_buffer_bound.to_display_point(&snapshot),
 976                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
 977                    point,
 978                    next_buffer_bound
 979                );
 980                assert_eq!(
 981                    prev_buffer_bound,
 982                    prev_display_bound.to_point(&snapshot),
 983                    "row boundary before {:?}. reported display row boundary: {:?}",
 984                    point,
 985                    prev_display_bound
 986                );
 987                assert_eq!(
 988                    next_buffer_bound,
 989                    next_display_bound.to_point(&snapshot),
 990                    "row boundary after {:?}. reported display row boundary: {:?}",
 991                    point,
 992                    next_display_bound
 993                );
 994            }
 995
 996            // Movement
 997            let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
 998            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
 999            for _ in 0..5 {
1000                let row = rng.gen_range(0..=snapshot.max_point().row());
1001                let column = rng.gen_range(0..=snapshot.line_len(row));
1002                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1003
1004                log::info!("Moving from point {:?}", point);
1005
1006                let moved_right = movement::right(&snapshot, point);
1007                log::info!("Right {:?}", moved_right);
1008                if point < max_point {
1009                    assert!(moved_right > point);
1010                    if point.column() == snapshot.line_len(point.row())
1011                        || snapshot.soft_wrap_indent(point.row()).is_some()
1012                            && point.column() == snapshot.line_len(point.row()) - 1
1013                    {
1014                        assert!(moved_right.row() > point.row());
1015                    }
1016                } else {
1017                    assert_eq!(moved_right, point);
1018                }
1019
1020                let moved_left = movement::left(&snapshot, point);
1021                log::info!("Left {:?}", moved_left);
1022                if point > min_point {
1023                    assert!(moved_left < point);
1024                    if point.column() == 0 {
1025                        assert!(moved_left.row() < point.row());
1026                    }
1027                } else {
1028                    assert_eq!(moved_left, point);
1029                }
1030            }
1031        }
1032    }
1033
1034    #[gpui::test(retries = 5)]
1035    fn test_soft_wraps(cx: &mut MutableAppContext) {
1036        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1037        cx.foreground().forbid_parking();
1038
1039        let font_cache = cx.font_cache();
1040
1041        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1042        let font_id = font_cache
1043            .select_font(family_id, &Default::default())
1044            .unwrap();
1045        let font_size = 12.0;
1046        let wrap_width = Some(64.);
1047        cx.set_global(Settings::test(cx));
1048
1049        let text = "one two three four five\nsix seven eight";
1050        let buffer = MultiBuffer::build_simple(text, cx);
1051        let map = cx.add_model(|cx| {
1052            DisplayMap::new(buffer.clone(), font_id, font_size, wrap_width, 1, 1, cx)
1053        });
1054
1055        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1056        assert_eq!(
1057            snapshot.text_chunks(0).collect::<String>(),
1058            "one two \nthree four \nfive\nsix seven \neight"
1059        );
1060        assert_eq!(
1061            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1062            DisplayPoint::new(0, 7)
1063        );
1064        assert_eq!(
1065            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1066            DisplayPoint::new(1, 0)
1067        );
1068        assert_eq!(
1069            movement::right(&snapshot, DisplayPoint::new(0, 7)),
1070            DisplayPoint::new(1, 0)
1071        );
1072        assert_eq!(
1073            movement::left(&snapshot, DisplayPoint::new(1, 0)),
1074            DisplayPoint::new(0, 7)
1075        );
1076        assert_eq!(
1077            movement::up(
1078                &snapshot,
1079                DisplayPoint::new(1, 10),
1080                SelectionGoal::None,
1081                false
1082            ),
1083            (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
1084        );
1085        assert_eq!(
1086            movement::down(
1087                &snapshot,
1088                DisplayPoint::new(0, 7),
1089                SelectionGoal::Column(10),
1090                false
1091            ),
1092            (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
1093        );
1094        assert_eq!(
1095            movement::down(
1096                &snapshot,
1097                DisplayPoint::new(1, 10),
1098                SelectionGoal::Column(10),
1099                false
1100            ),
1101            (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
1102        );
1103
1104        let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1105        buffer.update(cx, |buffer, cx| {
1106            buffer.edit([(ix..ix, "and ")], None, cx);
1107        });
1108
1109        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1110        assert_eq!(
1111            snapshot.text_chunks(1).collect::<String>(),
1112            "three four \nfive\nsix and \nseven eight"
1113        );
1114
1115        // Re-wrap on font size changes
1116        map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
1117
1118        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1119        assert_eq!(
1120            snapshot.text_chunks(1).collect::<String>(),
1121            "three \nfour five\nsix and \nseven \neight"
1122        )
1123    }
1124
1125    #[gpui::test]
1126    fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
1127        cx.set_global(Settings::test(cx));
1128        let text = sample_text(6, 6, 'a');
1129        let buffer = MultiBuffer::build_simple(&text, cx);
1130        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
1131        let font_id = cx
1132            .font_cache()
1133            .select_font(family_id, &Default::default())
1134            .unwrap();
1135        let font_size = 14.0;
1136        let map =
1137            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1138        buffer.update(cx, |buffer, cx| {
1139            buffer.edit(
1140                vec![
1141                    (Point::new(1, 0)..Point::new(1, 0), "\t"),
1142                    (Point::new(1, 1)..Point::new(1, 1), "\t"),
1143                    (Point::new(2, 1)..Point::new(2, 1), "\t"),
1144                ],
1145                None,
1146                cx,
1147            )
1148        });
1149
1150        assert_eq!(
1151            map.update(cx, |map, cx| map.snapshot(cx))
1152                .text_chunks(1)
1153                .collect::<String>()
1154                .lines()
1155                .next(),
1156            Some("    b   bbbbb")
1157        );
1158        assert_eq!(
1159            map.update(cx, |map, cx| map.snapshot(cx))
1160                .text_chunks(2)
1161                .collect::<String>()
1162                .lines()
1163                .next(),
1164            Some("c   ccccc")
1165        );
1166    }
1167
1168    #[gpui::test]
1169    async fn test_chunks(cx: &mut gpui::TestAppContext) {
1170        use unindent::Unindent as _;
1171
1172        let text = r#"
1173            fn outer() {}
1174
1175            mod module {
1176                fn inner() {}
1177            }"#
1178        .unindent();
1179
1180        let theme = SyntaxTheme::new(vec![
1181            ("mod.body".to_string(), Color::red().into()),
1182            ("fn.name".to_string(), Color::blue().into()),
1183        ]);
1184        let language = Arc::new(
1185            Language::new(
1186                LanguageConfig {
1187                    name: "Test".into(),
1188                    path_suffixes: vec![".test".to_string()],
1189                    ..Default::default()
1190                },
1191                Some(tree_sitter_rust::language()),
1192            )
1193            .with_highlights_query(
1194                r#"
1195                (mod_item name: (identifier) body: _ @mod.body)
1196                (function_item name: (identifier) @fn.name)
1197                "#,
1198            )
1199            .unwrap(),
1200        );
1201        language.set_theme(&theme);
1202        cx.update(|cx| {
1203            let mut settings = Settings::test(cx);
1204            settings.editor_defaults.tab_size = Some(2.try_into().unwrap());
1205            cx.set_global(settings);
1206        });
1207
1208        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1209        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1210        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1211
1212        let font_cache = cx.font_cache();
1213        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1214        let font_id = font_cache
1215            .select_font(family_id, &Default::default())
1216            .unwrap();
1217        let font_size = 14.0;
1218
1219        let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1220        assert_eq!(
1221            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1222            vec![
1223                ("fn ".to_string(), None),
1224                ("outer".to_string(), Some(Color::blue())),
1225                ("() {}\n\nmod module ".to_string(), None),
1226                ("{\n    fn ".to_string(), Some(Color::red())),
1227                ("inner".to_string(), Some(Color::blue())),
1228                ("() {}\n}".to_string(), Some(Color::red())),
1229            ]
1230        );
1231        assert_eq!(
1232            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1233            vec![
1234                ("    fn ".to_string(), Some(Color::red())),
1235                ("inner".to_string(), Some(Color::blue())),
1236                ("() {}\n}".to_string(), Some(Color::red())),
1237            ]
1238        );
1239
1240        map.update(cx, |map, cx| {
1241            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1242        });
1243        assert_eq!(
1244            cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1245            vec![
1246                ("fn ".to_string(), None),
1247                ("out".to_string(), Some(Color::blue())),
1248                ("".to_string(), None),
1249                ("  fn ".to_string(), Some(Color::red())),
1250                ("inner".to_string(), Some(Color::blue())),
1251                ("() {}\n}".to_string(), Some(Color::red())),
1252            ]
1253        );
1254    }
1255
1256    #[gpui::test]
1257    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1258        use unindent::Unindent as _;
1259
1260        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1261
1262        let text = r#"
1263            fn outer() {}
1264
1265            mod module {
1266                fn inner() {}
1267            }"#
1268        .unindent();
1269
1270        let theme = SyntaxTheme::new(vec![
1271            ("mod.body".to_string(), Color::red().into()),
1272            ("fn.name".to_string(), Color::blue().into()),
1273        ]);
1274        let language = Arc::new(
1275            Language::new(
1276                LanguageConfig {
1277                    name: "Test".into(),
1278                    path_suffixes: vec![".test".to_string()],
1279                    ..Default::default()
1280                },
1281                Some(tree_sitter_rust::language()),
1282            )
1283            .with_highlights_query(
1284                r#"
1285                (mod_item name: (identifier) body: _ @mod.body)
1286                (function_item name: (identifier) @fn.name)
1287                "#,
1288            )
1289            .unwrap(),
1290        );
1291        language.set_theme(&theme);
1292
1293        cx.update(|cx| cx.set_global(Settings::test(cx)));
1294
1295        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1296        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1297        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1298
1299        let font_cache = cx.font_cache();
1300
1301        let family_id = font_cache.load_family(&["Courier"]).unwrap();
1302        let font_id = font_cache
1303            .select_font(family_id, &Default::default())
1304            .unwrap();
1305        let font_size = 16.0;
1306
1307        let map =
1308            cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, Some(40.0), 1, 1, cx));
1309        assert_eq!(
1310            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1311            [
1312                ("fn \n".to_string(), None),
1313                ("oute\nr".to_string(), Some(Color::blue())),
1314                ("() \n{}\n\n".to_string(), None),
1315            ]
1316        );
1317        assert_eq!(
1318            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1319            [("{}\n\n".to_string(), None)]
1320        );
1321
1322        map.update(cx, |map, cx| {
1323            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1324        });
1325        assert_eq!(
1326            cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1327            [
1328                ("out".to_string(), Some(Color::blue())),
1329                ("\n".to_string(), None),
1330                ("  \nfn ".to_string(), Some(Color::red())),
1331                ("i\n".to_string(), Some(Color::blue()))
1332            ]
1333        );
1334    }
1335
1336    #[gpui::test]
1337    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1338        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1339
1340        cx.update(|cx| cx.set_global(Settings::test(cx)));
1341        let theme = SyntaxTheme::new(vec![
1342            ("operator".to_string(), Color::red().into()),
1343            ("string".to_string(), Color::green().into()),
1344        ]);
1345        let language = Arc::new(
1346            Language::new(
1347                LanguageConfig {
1348                    name: "Test".into(),
1349                    path_suffixes: vec![".test".to_string()],
1350                    ..Default::default()
1351                },
1352                Some(tree_sitter_rust::language()),
1353            )
1354            .with_highlights_query(
1355                r#"
1356                ":" @operator
1357                (string_literal) @string
1358                "#,
1359            )
1360            .unwrap(),
1361        );
1362        language.set_theme(&theme);
1363
1364        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
1365
1366        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1367        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1368
1369        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1370        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1371
1372        let font_cache = cx.font_cache();
1373        let family_id = font_cache.load_family(&["Courier"]).unwrap();
1374        let font_id = font_cache
1375            .select_font(family_id, &Default::default())
1376            .unwrap();
1377        let font_size = 16.0;
1378        let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1379
1380        enum MyType {}
1381
1382        let style = HighlightStyle {
1383            color: Some(Color::blue()),
1384            ..Default::default()
1385        };
1386
1387        map.update(cx, |map, _cx| {
1388            map.highlight_text(
1389                TypeId::of::<MyType>(),
1390                highlighted_ranges
1391                    .into_iter()
1392                    .map(|range| {
1393                        buffer_snapshot.anchor_before(range.start)
1394                            ..buffer_snapshot.anchor_before(range.end)
1395                    })
1396                    .collect(),
1397                style,
1398            );
1399        });
1400
1401        assert_eq!(
1402            cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1403            [
1404                ("const ".to_string(), None, None),
1405                ("a".to_string(), None, Some(Color::blue())),
1406                (":".to_string(), Some(Color::red()), None),
1407                (" B = ".to_string(), None, None),
1408                ("\"c ".to_string(), Some(Color::green()), None),
1409                ("d".to_string(), Some(Color::green()), Some(Color::blue())),
1410                ("\"".to_string(), Some(Color::green()), None),
1411            ]
1412        );
1413    }
1414
1415    #[gpui::test]
1416    fn test_clip_point(cx: &mut gpui::MutableAppContext) {
1417        cx.set_global(Settings::test(cx));
1418        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::MutableAppContext) {
1419            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1420
1421            match bias {
1422                Bias::Left => {
1423                    if shift_right {
1424                        *markers[1].column_mut() += 1;
1425                    }
1426
1427                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1428                }
1429                Bias::Right => {
1430                    if shift_right {
1431                        *markers[0].column_mut() += 1;
1432                    }
1433
1434                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1435                }
1436            };
1437        }
1438
1439        use Bias::{Left, Right};
1440        assert("ˇˇα", false, Left, cx);
1441        assert("ˇˇα", true, Left, cx);
1442        assert("ˇˇα", false, Right, cx);
1443        assert("ˇαˇ", true, Right, cx);
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("ˇˇ\t", false, Left, cx);
1453        assert("ˇˇ\t", true, Left, cx);
1454        assert("ˇˇ\t", false, Right, cx);
1455        assert("ˇ\tˇ", 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", false, Right, cx);
1462    }
1463
1464    #[gpui::test]
1465    fn test_clip_at_line_ends(cx: &mut gpui::MutableAppContext) {
1466        cx.set_global(Settings::test(cx));
1467
1468        fn assert(text: &str, cx: &mut gpui::MutableAppContext) {
1469            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1470            unmarked_snapshot.clip_at_line_ends = true;
1471            assert_eq!(
1472                unmarked_snapshot.clip_point(markers[1], Bias::Left),
1473                markers[0]
1474            );
1475        }
1476
1477        assert("ˇˇ", cx);
1478        assert("ˇaˇ", cx);
1479        assert("aˇbˇ", cx);
1480        assert("aˇαˇ", cx);
1481    }
1482
1483    #[gpui::test]
1484    fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1485        cx.set_global(Settings::test(cx));
1486        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
1487        let buffer = MultiBuffer::build_simple(text, cx);
1488        let font_cache = cx.font_cache();
1489        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1490        let font_id = font_cache
1491            .select_font(family_id, &Default::default())
1492            .unwrap();
1493        let font_size = 14.0;
1494
1495        let map =
1496            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1497        let map = map.update(cx, |map, cx| map.snapshot(cx));
1498        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
1499        assert_eq!(
1500            map.text_chunks(0).collect::<String>(),
1501            "✅       α\nβ   \n🏀β      γ"
1502        );
1503        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \n🏀β      γ");
1504        assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β      γ");
1505
1506        let point = Point::new(0, "\t\t".len() as u32);
1507        let display_point = DisplayPoint::new(0, "".len() as u32);
1508        assert_eq!(point.to_display_point(&map), display_point);
1509        assert_eq!(display_point.to_point(&map), point);
1510
1511        let point = Point::new(1, "β\t".len() as u32);
1512        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1513        assert_eq!(point.to_display_point(&map), display_point);
1514        assert_eq!(display_point.to_point(&map), point,);
1515
1516        let point = Point::new(2, "🏀β\t\t".len() as u32);
1517        let display_point = DisplayPoint::new(2, "🏀β      ".len() as u32);
1518        assert_eq!(point.to_display_point(&map), display_point);
1519        assert_eq!(display_point.to_point(&map), point,);
1520
1521        // Display points inside of expanded tabs
1522        assert_eq!(
1523            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1524            Point::new(0, "\t".len() as u32),
1525        );
1526        assert_eq!(
1527            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1528            Point::new(0, "".len() as u32),
1529        );
1530
1531        // Clipping display points inside of multi-byte characters
1532        assert_eq!(
1533            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Left),
1534            DisplayPoint::new(0, 0)
1535        );
1536        assert_eq!(
1537            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Bias::Right),
1538            DisplayPoint::new(0, "".len() as u32)
1539        );
1540    }
1541
1542    #[gpui::test]
1543    fn test_max_point(cx: &mut gpui::MutableAppContext) {
1544        cx.set_global(Settings::test(cx));
1545        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1546        let font_cache = cx.font_cache();
1547        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1548        let font_id = font_cache
1549            .select_font(family_id, &Default::default())
1550            .unwrap();
1551        let font_size = 14.0;
1552        let map =
1553            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1554        assert_eq!(
1555            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1556            DisplayPoint::new(1, 11)
1557        )
1558    }
1559
1560    #[test]
1561    fn test_find_internal() {
1562        assert("This is a ˇtest of find internal", "test");
1563        assert("Some text ˇaˇaˇaa with repeated characters", "aa");
1564
1565        fn assert(marked_text: &str, target: &str) {
1566            let (text, expected_offsets) = marked_text_offsets(marked_text);
1567
1568            let chars = text
1569                .chars()
1570                .enumerate()
1571                .map(|(index, ch)| (ch, DisplayPoint::new(0, index as u32)));
1572            let target = target.chars();
1573
1574            assert_eq!(
1575                expected_offsets
1576                    .into_iter()
1577                    .map(|offset| offset as u32)
1578                    .collect::<Vec<_>>(),
1579                DisplaySnapshot::find_internal(chars, target.collect(), |_, _| true)
1580                    .map(|point| point.column())
1581                    .collect::<Vec<_>>()
1582            )
1583        }
1584    }
1585
1586    fn syntax_chunks<'a>(
1587        rows: Range<u32>,
1588        map: &ModelHandle<DisplayMap>,
1589        theme: &'a SyntaxTheme,
1590        cx: &mut MutableAppContext,
1591    ) -> Vec<(String, Option<Color>)> {
1592        chunks(rows, map, theme, cx)
1593            .into_iter()
1594            .map(|(text, color, _)| (text, color))
1595            .collect()
1596    }
1597
1598    fn chunks<'a>(
1599        rows: Range<u32>,
1600        map: &ModelHandle<DisplayMap>,
1601        theme: &'a SyntaxTheme,
1602        cx: &mut MutableAppContext,
1603    ) -> Vec<(String, Option<Color>, Option<Color>)> {
1604        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1605        let mut chunks: Vec<(String, Option<Color>, Option<Color>)> = Vec::new();
1606        for chunk in snapshot.chunks(rows, true) {
1607            let syntax_color = chunk
1608                .syntax_highlight_id
1609                .and_then(|id| id.style(theme)?.color);
1610            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1611            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1612                if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1613                    last_chunk.push_str(chunk.text);
1614                    continue;
1615                }
1616            }
1617            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1618        }
1619        chunks
1620    }
1621}