display_map.rs

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