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