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