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