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