display_map.rs

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