display_map.rs

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