display_map.rs

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