display_map.rs

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