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