display_map.rs

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