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, PartialEq, Eq)]
  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()) {
 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<DisplayPoint>> {
 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();
 641                    break;
 642                }
 643            }
 644
 645            let end = end.map(|end_row| end_row.end(self)).unwrap_or(max_point);
 646            Some(start..end)
 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
 664impl Debug for DisplayPoint {
 665    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 666        f.write_fmt(format_args!(
 667            "DisplayPoint({}, {})",
 668            self.row(),
 669            self.column()
 670        ))
 671    }
 672}
 673
 674impl DisplayPoint {
 675    pub fn new(row: u32, column: u32) -> Self {
 676        Self(BlockPoint(Point::new(row, column)))
 677    }
 678
 679    pub fn zero() -> Self {
 680        Self::new(0, 0)
 681    }
 682
 683    pub fn is_zero(&self) -> bool {
 684        self.0.is_zero()
 685    }
 686
 687    pub fn row(self) -> u32 {
 688        self.0.row
 689    }
 690
 691    pub fn column(self) -> u32 {
 692        self.0.column
 693    }
 694
 695    pub fn row_mut(&mut self) -> &mut u32 {
 696        &mut self.0.row
 697    }
 698
 699    pub fn column_mut(&mut self) -> &mut u32 {
 700        &mut self.0.column
 701    }
 702
 703    pub fn to_point(self, map: &DisplaySnapshot) -> Point {
 704        map.display_point_to_point(self, Bias::Left)
 705    }
 706
 707    pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
 708        let unblocked_point = map.blocks_snapshot.to_wrap_point(self.0);
 709        let unwrapped_point = map.wraps_snapshot.to_tab_point(unblocked_point);
 710        let unexpanded_point = map.tabs_snapshot.to_fold_point(unwrapped_point, bias).0;
 711        unexpanded_point.to_buffer_offset(&map.folds_snapshot)
 712    }
 713}
 714
 715impl ToDisplayPoint for usize {
 716    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 717        map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
 718    }
 719}
 720
 721impl ToDisplayPoint for OffsetUtf16 {
 722    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 723        self.to_offset(&map.buffer_snapshot).to_display_point(map)
 724    }
 725}
 726
 727impl ToDisplayPoint for Point {
 728    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 729        map.point_to_display_point(*self, Bias::Left)
 730    }
 731}
 732
 733impl ToDisplayPoint for Anchor {
 734    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 735        self.to_point(&map.buffer_snapshot).to_display_point(map)
 736    }
 737}
 738
 739#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq, Deserialize, Serialize)]
 740#[repr(transparent)]
 741pub struct DisplayRow(pub u32);
 742
 743// TODO: Move display_map check into new, and then remove it from everywhere else
 744impl DisplayRow {
 745    pub fn new(display_row: u32) -> Self {
 746        DisplayRow(display_row)
 747    }
 748
 749    pub fn to_line_span(&self, display_map: &DisplaySnapshot) -> Range<DisplayPoint> {
 750        self.start()..self.end(&display_map)
 751    }
 752
 753    pub fn previous_row(&self) -> Option<DisplayRow> {
 754        self.0.checked_sub(1).map(|prev_row| DisplayRow(prev_row))
 755    }
 756
 757    pub fn next_row(&self, display_map: &DisplaySnapshot) -> Option<DisplayRow> {
 758        if self.0 + 1 > display_map.max_point().row() {
 759            None
 760        } else {
 761            Some(DisplayRow(self.0 + 1))
 762        }
 763    }
 764
 765    // TODO: Remove and use next_row
 766    fn next_unchecked(&self) -> Option<DisplayRow> {
 767        Some(DisplayRow(self.0 + 1))
 768    }
 769
 770    pub fn next_rows(
 771        &self,
 772        display_map: &DisplaySnapshot,
 773    ) -> Option<impl Iterator<Item = DisplayRow>> {
 774        self.next_row(display_map)
 775            .and_then(|next_row| next_row.span_to(display_map.max_point()))
 776    }
 777
 778    pub fn span_to<I: Into<DisplayRow>>(
 779        &self,
 780        end_row: I,
 781    ) -> Option<impl Iterator<Item = DisplayRow>> {
 782        let end_row = end_row.into();
 783        if self.0 <= end_row.0 {
 784            let start = *self;
 785            let mut current = None;
 786
 787            Some(std::iter::from_fn(move || {
 788                if current == None {
 789                    current = Some(start);
 790                } else {
 791                    current = current.unwrap().next_unchecked();
 792                }
 793                if current.unwrap().0 > end_row.0 {
 794                    None
 795                } else {
 796                    current
 797                }
 798            }))
 799        } else {
 800            None
 801        }
 802    }
 803
 804    pub fn start(&self) -> DisplayPoint {
 805        DisplayPoint::new(self.0, 0)
 806    }
 807
 808    pub fn end(&self, display_map: &DisplaySnapshot) -> DisplayPoint {
 809        DisplayPoint::new(self.0, display_map.line_len(self.0))
 810    }
 811}
 812
 813impl From<DisplayPoint> for DisplayRow {
 814    fn from(value: DisplayPoint) -> Self {
 815        DisplayRow(value.row())
 816    }
 817}
 818
 819#[cfg(test)]
 820pub mod tests {
 821    use super::*;
 822    use crate::{movement, test::marked_display_snapshot};
 823    use gpui::{color::Color, elements::*, test::observe, MutableAppContext};
 824    use language::{Buffer, Language, LanguageConfig, SelectionGoal};
 825    use rand::{prelude::*, Rng};
 826    use smol::stream::StreamExt;
 827    use std::{env, sync::Arc};
 828    use theme::SyntaxTheme;
 829    use util::test::{marked_text_offsets, marked_text_ranges, sample_text};
 830    use Bias::*;
 831
 832    #[gpui::test(iterations = 100)]
 833    async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
 834        cx.foreground().set_block_on_ticks(0..=50);
 835        cx.foreground().forbid_parking();
 836        let operations = env::var("OPERATIONS")
 837            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
 838            .unwrap_or(10);
 839
 840        let font_cache = cx.font_cache().clone();
 841        let mut tab_size = rng.gen_range(1..=4);
 842        let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
 843        let excerpt_header_height = rng.gen_range(1..=5);
 844        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 845        let font_id = font_cache
 846            .select_font(family_id, &Default::default())
 847            .unwrap();
 848        let font_size = 14.0;
 849        let max_wrap_width = 300.0;
 850        let mut wrap_width = if rng.gen_bool(0.1) {
 851            None
 852        } else {
 853            Some(rng.gen_range(0.0..=max_wrap_width))
 854        };
 855
 856        log::info!("tab size: {}", tab_size);
 857        log::info!("wrap width: {:?}", wrap_width);
 858
 859        cx.update(|cx| {
 860            let mut settings = Settings::test(cx);
 861            settings.editor_overrides.tab_size = NonZeroU32::new(tab_size);
 862            cx.set_global(settings)
 863        });
 864
 865        let buffer = cx.update(|cx| {
 866            if rng.gen() {
 867                let len = rng.gen_range(0..10);
 868                let text = util::RandomCharIter::new(&mut rng)
 869                    .take(len)
 870                    .collect::<String>();
 871                MultiBuffer::build_simple(&text, cx)
 872            } else {
 873                MultiBuffer::build_random(&mut rng, cx)
 874            }
 875        });
 876
 877        let map = cx.add_model(|cx| {
 878            DisplayMap::new(
 879                buffer.clone(),
 880                font_id,
 881                font_size,
 882                wrap_width,
 883                buffer_start_excerpt_header_height,
 884                excerpt_header_height,
 885                cx,
 886            )
 887        });
 888        let mut notifications = observe(&map, cx);
 889        let mut fold_count = 0;
 890        let mut blocks = Vec::new();
 891
 892        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 893        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
 894        log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
 895        log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
 896        log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
 897        log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
 898        log::info!("display text: {:?}", snapshot.text());
 899
 900        for _i in 0..operations {
 901            match rng.gen_range(0..100) {
 902                0..=19 => {
 903                    wrap_width = if rng.gen_bool(0.2) {
 904                        None
 905                    } else {
 906                        Some(rng.gen_range(0.0..=max_wrap_width))
 907                    };
 908                    log::info!("setting wrap width to {:?}", wrap_width);
 909                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
 910                }
 911                20..=29 => {
 912                    let mut tab_sizes = vec![1, 2, 3, 4];
 913                    tab_sizes.remove((tab_size - 1) as usize);
 914                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
 915                    log::info!("setting tab size to {:?}", tab_size);
 916                    cx.update(|cx| {
 917                        let mut settings = Settings::test(cx);
 918                        settings.editor_overrides.tab_size = NonZeroU32::new(tab_size);
 919                        cx.set_global(settings)
 920                    });
 921                }
 922                30..=44 => {
 923                    map.update(cx, |map, cx| {
 924                        if rng.gen() || blocks.is_empty() {
 925                            let buffer = map.snapshot(cx).buffer_snapshot;
 926                            let block_properties = (0..rng.gen_range(1..=1))
 927                                .map(|_| {
 928                                    let position =
 929                                        buffer.anchor_after(buffer.clip_offset(
 930                                            rng.gen_range(0..=buffer.len()),
 931                                            Bias::Left,
 932                                        ));
 933
 934                                    let disposition = if rng.gen() {
 935                                        BlockDisposition::Above
 936                                    } else {
 937                                        BlockDisposition::Below
 938                                    };
 939                                    let height = rng.gen_range(1..5);
 940                                    log::info!(
 941                                        "inserting block {:?} {:?} with height {}",
 942                                        disposition,
 943                                        position.to_point(&buffer),
 944                                        height
 945                                    );
 946                                    BlockProperties {
 947                                        style: BlockStyle::Fixed,
 948                                        position,
 949                                        height,
 950                                        disposition,
 951                                        render: Arc::new(|_| Empty::new().boxed()),
 952                                    }
 953                                })
 954                                .collect::<Vec<_>>();
 955                            blocks.extend(map.insert_blocks(block_properties, cx));
 956                        } else {
 957                            blocks.shuffle(&mut rng);
 958                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
 959                            let block_ids_to_remove = (0..remove_count)
 960                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
 961                                .collect();
 962                            log::info!("removing block ids {:?}", block_ids_to_remove);
 963                            map.remove_blocks(block_ids_to_remove, cx);
 964                        }
 965                    });
 966                }
 967                45..=79 => {
 968                    let mut ranges = Vec::new();
 969                    for _ in 0..rng.gen_range(1..=3) {
 970                        buffer.read_with(cx, |buffer, cx| {
 971                            let buffer = buffer.read(cx);
 972                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
 973                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
 974                            ranges.push(start..end);
 975                        });
 976                    }
 977
 978                    if rng.gen() && fold_count > 0 {
 979                        log::info!("unfolding ranges: {:?}", ranges);
 980                        map.update(cx, |map, cx| {
 981                            map.unfold(ranges, true, cx);
 982                        });
 983                    } else {
 984                        log::info!("folding ranges: {:?}", ranges);
 985                        map.update(cx, |map, cx| {
 986                            map.fold(ranges, cx);
 987                        });
 988                    }
 989                }
 990                _ => {
 991                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
 992                }
 993            }
 994
 995            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
 996                notifications.next().await.unwrap();
 997            }
 998
 999            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1000            fold_count = snapshot.fold_count();
1001            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1002            log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
1003            log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
1004            log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
1005            log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
1006            log::info!("display text: {:?}", snapshot.text());
1007
1008            // Line boundaries
1009            let buffer = &snapshot.buffer_snapshot;
1010            for _ in 0..5 {
1011                let row = rng.gen_range(0..=buffer.max_point().row);
1012                let column = rng.gen_range(0..=buffer.line_len(row));
1013                let point = buffer.clip_point(Point::new(row, column), Left);
1014
1015                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1016                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1017
1018                assert!(prev_buffer_bound <= point);
1019                assert!(next_buffer_bound >= point);
1020                assert_eq!(prev_buffer_bound.column, 0);
1021                assert_eq!(prev_display_bound.column(), 0);
1022                if next_buffer_bound < buffer.max_point() {
1023                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1024                }
1025
1026                assert_eq!(
1027                    prev_display_bound,
1028                    prev_buffer_bound.to_display_point(&snapshot),
1029                    "row boundary before {:?}. reported buffer row boundary: {:?}",
1030                    point,
1031                    prev_buffer_bound
1032                );
1033                assert_eq!(
1034                    next_display_bound,
1035                    next_buffer_bound.to_display_point(&snapshot),
1036                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
1037                    point,
1038                    next_buffer_bound
1039                );
1040                assert_eq!(
1041                    prev_buffer_bound,
1042                    prev_display_bound.to_point(&snapshot),
1043                    "row boundary before {:?}. reported display row boundary: {:?}",
1044                    point,
1045                    prev_display_bound
1046                );
1047                assert_eq!(
1048                    next_buffer_bound,
1049                    next_display_bound.to_point(&snapshot),
1050                    "row boundary after {:?}. reported display row boundary: {:?}",
1051                    point,
1052                    next_display_bound
1053                );
1054            }
1055
1056            // Movement
1057            let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1058            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1059            for _ in 0..5 {
1060                let row = rng.gen_range(0..=snapshot.max_point().row());
1061                let column = rng.gen_range(0..=snapshot.line_len(row));
1062                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1063
1064                log::info!("Moving from point {:?}", point);
1065
1066                let moved_right = movement::right(&snapshot, point);
1067                log::info!("Right {:?}", moved_right);
1068                if point < max_point {
1069                    assert!(moved_right > point);
1070                    if point.column() == snapshot.line_len(point.row())
1071                        || snapshot.soft_wrap_indent(point.row()).is_some()
1072                            && point.column() == snapshot.line_len(point.row()) - 1
1073                    {
1074                        assert!(moved_right.row() > point.row());
1075                    }
1076                } else {
1077                    assert_eq!(moved_right, point);
1078                }
1079
1080                let moved_left = movement::left(&snapshot, point);
1081                log::info!("Left {:?}", moved_left);
1082                if point > min_point {
1083                    assert!(moved_left < point);
1084                    if point.column() == 0 {
1085                        assert!(moved_left.row() < point.row());
1086                    }
1087                } else {
1088                    assert_eq!(moved_left, point);
1089                }
1090            }
1091        }
1092    }
1093
1094    #[gpui::test(retries = 5)]
1095    fn test_soft_wraps(cx: &mut MutableAppContext) {
1096        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1097        cx.foreground().forbid_parking();
1098
1099        let font_cache = cx.font_cache();
1100
1101        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1102        let font_id = font_cache
1103            .select_font(family_id, &Default::default())
1104            .unwrap();
1105        let font_size = 12.0;
1106        let wrap_width = Some(64.);
1107        cx.set_global(Settings::test(cx));
1108
1109        let text = "one two three four five\nsix seven eight";
1110        let buffer = MultiBuffer::build_simple(text, cx);
1111        let map = cx.add_model(|cx| {
1112            DisplayMap::new(buffer.clone(), font_id, font_size, wrap_width, 1, 1, cx)
1113        });
1114
1115        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1116        assert_eq!(
1117            snapshot.text_chunks(0).collect::<String>(),
1118            "one two \nthree four \nfive\nsix seven \neight"
1119        );
1120        assert_eq!(
1121            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1122            DisplayPoint::new(0, 7)
1123        );
1124        assert_eq!(
1125            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1126            DisplayPoint::new(1, 0)
1127        );
1128        assert_eq!(
1129            movement::right(&snapshot, DisplayPoint::new(0, 7)),
1130            DisplayPoint::new(1, 0)
1131        );
1132        assert_eq!(
1133            movement::left(&snapshot, DisplayPoint::new(1, 0)),
1134            DisplayPoint::new(0, 7)
1135        );
1136        assert_eq!(
1137            movement::up(
1138                &snapshot,
1139                DisplayPoint::new(1, 10),
1140                SelectionGoal::None,
1141                false
1142            ),
1143            (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
1144        );
1145        assert_eq!(
1146            movement::down(
1147                &snapshot,
1148                DisplayPoint::new(0, 7),
1149                SelectionGoal::Column(10),
1150                false
1151            ),
1152            (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
1153        );
1154        assert_eq!(
1155            movement::down(
1156                &snapshot,
1157                DisplayPoint::new(1, 10),
1158                SelectionGoal::Column(10),
1159                false
1160            ),
1161            (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
1162        );
1163
1164        let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1165        buffer.update(cx, |buffer, cx| {
1166            buffer.edit([(ix..ix, "and ")], None, cx);
1167        });
1168
1169        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1170        assert_eq!(
1171            snapshot.text_chunks(1).collect::<String>(),
1172            "three four \nfive\nsix and \nseven eight"
1173        );
1174
1175        // Re-wrap on font size changes
1176        map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
1177
1178        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1179        assert_eq!(
1180            snapshot.text_chunks(1).collect::<String>(),
1181            "three \nfour five\nsix and \nseven \neight"
1182        )
1183    }
1184
1185    #[gpui::test]
1186    fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
1187        cx.set_global(Settings::test(cx));
1188        let text = sample_text(6, 6, 'a');
1189        let buffer = MultiBuffer::build_simple(&text, cx);
1190        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
1191        let font_id = cx
1192            .font_cache()
1193            .select_font(family_id, &Default::default())
1194            .unwrap();
1195        let font_size = 14.0;
1196        let map =
1197            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1198        buffer.update(cx, |buffer, cx| {
1199            buffer.edit(
1200                vec![
1201                    (Point::new(1, 0)..Point::new(1, 0), "\t"),
1202                    (Point::new(1, 1)..Point::new(1, 1), "\t"),
1203                    (Point::new(2, 1)..Point::new(2, 1), "\t"),
1204                ],
1205                None,
1206                cx,
1207            )
1208        });
1209
1210        assert_eq!(
1211            map.update(cx, |map, cx| map.snapshot(cx))
1212                .text_chunks(1)
1213                .collect::<String>()
1214                .lines()
1215                .next(),
1216            Some("    b   bbbbb")
1217        );
1218        assert_eq!(
1219            map.update(cx, |map, cx| map.snapshot(cx))
1220                .text_chunks(2)
1221                .collect::<String>()
1222                .lines()
1223                .next(),
1224            Some("c   ccccc")
1225        );
1226    }
1227
1228    #[gpui::test]
1229    async fn test_chunks(cx: &mut gpui::TestAppContext) {
1230        use unindent::Unindent as _;
1231
1232        let text = r#"
1233            fn outer() {}
1234
1235            mod module {
1236                fn inner() {}
1237            }"#
1238        .unindent();
1239
1240        let theme = SyntaxTheme::new(vec![
1241            ("mod.body".to_string(), Color::red().into()),
1242            ("fn.name".to_string(), Color::blue().into()),
1243        ]);
1244        let language = Arc::new(
1245            Language::new(
1246                LanguageConfig {
1247                    name: "Test".into(),
1248                    path_suffixes: vec![".test".to_string()],
1249                    ..Default::default()
1250                },
1251                Some(tree_sitter_rust::language()),
1252            )
1253            .with_highlights_query(
1254                r#"
1255                (mod_item name: (identifier) body: _ @mod.body)
1256                (function_item name: (identifier) @fn.name)
1257                "#,
1258            )
1259            .unwrap(),
1260        );
1261        language.set_theme(&theme);
1262        cx.update(|cx| {
1263            let mut settings = Settings::test(cx);
1264            settings.editor_defaults.tab_size = Some(2.try_into().unwrap());
1265            cx.set_global(settings);
1266        });
1267
1268        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1269        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1270        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1271
1272        let font_cache = cx.font_cache();
1273        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1274        let font_id = font_cache
1275            .select_font(family_id, &Default::default())
1276            .unwrap();
1277        let font_size = 14.0;
1278
1279        let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1280        assert_eq!(
1281            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1282            vec![
1283                ("fn ".to_string(), None),
1284                ("outer".to_string(), Some(Color::blue())),
1285                ("() {}\n\nmod module ".to_string(), None),
1286                ("{\n    fn ".to_string(), Some(Color::red())),
1287                ("inner".to_string(), Some(Color::blue())),
1288                ("() {}\n}".to_string(), Some(Color::red())),
1289            ]
1290        );
1291        assert_eq!(
1292            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1293            vec![
1294                ("    fn ".to_string(), Some(Color::red())),
1295                ("inner".to_string(), Some(Color::blue())),
1296                ("() {}\n}".to_string(), Some(Color::red())),
1297            ]
1298        );
1299
1300        map.update(cx, |map, cx| {
1301            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1302        });
1303        assert_eq!(
1304            cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1305            vec![
1306                ("fn ".to_string(), None),
1307                ("out".to_string(), Some(Color::blue())),
1308                ("".to_string(), None),
1309                ("  fn ".to_string(), Some(Color::red())),
1310                ("inner".to_string(), Some(Color::blue())),
1311                ("() {}\n}".to_string(), Some(Color::red())),
1312            ]
1313        );
1314    }
1315
1316    #[gpui::test]
1317    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1318        use unindent::Unindent as _;
1319
1320        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1321
1322        let text = r#"
1323            fn outer() {}
1324
1325            mod module {
1326                fn inner() {}
1327            }"#
1328        .unindent();
1329
1330        let theme = SyntaxTheme::new(vec![
1331            ("mod.body".to_string(), Color::red().into()),
1332            ("fn.name".to_string(), Color::blue().into()),
1333        ]);
1334        let language = Arc::new(
1335            Language::new(
1336                LanguageConfig {
1337                    name: "Test".into(),
1338                    path_suffixes: vec![".test".to_string()],
1339                    ..Default::default()
1340                },
1341                Some(tree_sitter_rust::language()),
1342            )
1343            .with_highlights_query(
1344                r#"
1345                (mod_item name: (identifier) body: _ @mod.body)
1346                (function_item name: (identifier) @fn.name)
1347                "#,
1348            )
1349            .unwrap(),
1350        );
1351        language.set_theme(&theme);
1352
1353        cx.update(|cx| cx.set_global(Settings::test(cx)));
1354
1355        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1356        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1357        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1358
1359        let font_cache = cx.font_cache();
1360
1361        let family_id = font_cache.load_family(&["Courier"]).unwrap();
1362        let font_id = font_cache
1363            .select_font(family_id, &Default::default())
1364            .unwrap();
1365        let font_size = 16.0;
1366
1367        let map =
1368            cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, Some(40.0), 1, 1, cx));
1369        assert_eq!(
1370            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1371            [
1372                ("fn \n".to_string(), None),
1373                ("oute\nr".to_string(), Some(Color::blue())),
1374                ("() \n{}\n\n".to_string(), None),
1375            ]
1376        );
1377        assert_eq!(
1378            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1379            [("{}\n\n".to_string(), None)]
1380        );
1381
1382        map.update(cx, |map, cx| {
1383            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1384        });
1385        assert_eq!(
1386            cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1387            [
1388                ("out".to_string(), Some(Color::blue())),
1389                ("\n".to_string(), None),
1390                ("  \nfn ".to_string(), Some(Color::red())),
1391                ("i\n".to_string(), Some(Color::blue()))
1392            ]
1393        );
1394    }
1395
1396    #[gpui::test]
1397    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1398        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1399
1400        cx.update(|cx| cx.set_global(Settings::test(cx)));
1401        let theme = SyntaxTheme::new(vec![
1402            ("operator".to_string(), Color::red().into()),
1403            ("string".to_string(), Color::green().into()),
1404        ]);
1405        let language = Arc::new(
1406            Language::new(
1407                LanguageConfig {
1408                    name: "Test".into(),
1409                    path_suffixes: vec![".test".to_string()],
1410                    ..Default::default()
1411                },
1412                Some(tree_sitter_rust::language()),
1413            )
1414            .with_highlights_query(
1415                r#"
1416                ":" @operator
1417                (string_literal) @string
1418                "#,
1419            )
1420            .unwrap(),
1421        );
1422        language.set_theme(&theme);
1423
1424        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
1425
1426        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
1427        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1428
1429        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1430        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1431
1432        let font_cache = cx.font_cache();
1433        let family_id = font_cache.load_family(&["Courier"]).unwrap();
1434        let font_id = font_cache
1435            .select_font(family_id, &Default::default())
1436            .unwrap();
1437        let font_size = 16.0;
1438        let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1439
1440        enum MyType {}
1441
1442        let style = HighlightStyle {
1443            color: Some(Color::blue()),
1444            ..Default::default()
1445        };
1446
1447        map.update(cx, |map, _cx| {
1448            map.highlight_text(
1449                TypeId::of::<MyType>(),
1450                highlighted_ranges
1451                    .into_iter()
1452                    .map(|range| {
1453                        buffer_snapshot.anchor_before(range.start)
1454                            ..buffer_snapshot.anchor_before(range.end)
1455                    })
1456                    .collect(),
1457                style,
1458            );
1459        });
1460
1461        assert_eq!(
1462            cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1463            [
1464                ("const ".to_string(), None, None),
1465                ("a".to_string(), None, Some(Color::blue())),
1466                (":".to_string(), Some(Color::red()), None),
1467                (" B = ".to_string(), None, None),
1468                ("\"c ".to_string(), Some(Color::green()), None),
1469                ("d".to_string(), Some(Color::green()), Some(Color::blue())),
1470                ("\"".to_string(), Some(Color::green()), None),
1471            ]
1472        );
1473    }
1474
1475    #[gpui::test]
1476    fn test_clip_point(cx: &mut gpui::MutableAppContext) {
1477        cx.set_global(Settings::test(cx));
1478        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::MutableAppContext) {
1479            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1480
1481            match bias {
1482                Bias::Left => {
1483                    if shift_right {
1484                        *markers[1].column_mut() += 1;
1485                    }
1486
1487                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1488                }
1489                Bias::Right => {
1490                    if shift_right {
1491                        *markers[0].column_mut() += 1;
1492                    }
1493
1494                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1495                }
1496            };
1497        }
1498
1499        use Bias::{Left, Right};
1500        assert("ˇˇα", false, Left, cx);
1501        assert("ˇˇα", true, Left, cx);
1502        assert("ˇˇα", false, Right, cx);
1503        assert("ˇαˇ", true, Right, cx);
1504        assert("ˇˇ✋", false, Left, cx);
1505        assert("ˇˇ✋", true, Left, cx);
1506        assert("ˇˇ✋", false, Right, cx);
1507        assert("ˇ✋ˇ", true, Right, cx);
1508        assert("ˇˇ🍐", false, Left, cx);
1509        assert("ˇˇ🍐", true, Left, cx);
1510        assert("ˇˇ🍐", false, Right, cx);
1511        assert("ˇ🍐ˇ", true, Right, cx);
1512        assert("ˇˇ\t", false, Left, cx);
1513        assert("ˇˇ\t", true, Left, cx);
1514        assert("ˇˇ\t", false, Right, cx);
1515        assert("ˇ\tˇ", true, Right, cx);
1516        assert(" ˇˇ\t", false, Left, cx);
1517        assert(" ˇˇ\t", true, Left, cx);
1518        assert(" ˇˇ\t", false, Right, cx);
1519        assert(" ˇ\tˇ", true, Right, cx);
1520        assert("   ˇˇ\t", false, Left, cx);
1521        assert("   ˇˇ\t", false, Right, cx);
1522    }
1523
1524    #[gpui::test]
1525    fn test_clip_at_line_ends(cx: &mut gpui::MutableAppContext) {
1526        cx.set_global(Settings::test(cx));
1527
1528        fn assert(text: &str, cx: &mut gpui::MutableAppContext) {
1529            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1530            unmarked_snapshot.clip_at_line_ends = true;
1531            assert_eq!(
1532                unmarked_snapshot.clip_point(markers[1], Bias::Left),
1533                markers[0]
1534            );
1535        }
1536
1537        assert("ˇˇ", cx);
1538        assert("ˇaˇ", cx);
1539        assert("aˇbˇ", cx);
1540        assert("aˇαˇ", cx);
1541    }
1542
1543    #[gpui::test]
1544    fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1545        cx.set_global(Settings::test(cx));
1546        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
1547        let buffer = MultiBuffer::build_simple(text, cx);
1548        let font_cache = cx.font_cache();
1549        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1550        let font_id = font_cache
1551            .select_font(family_id, &Default::default())
1552            .unwrap();
1553        let font_size = 14.0;
1554
1555        let map =
1556            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1557        let map = map.update(cx, |map, cx| map.snapshot(cx));
1558        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
1559        assert_eq!(
1560            map.text_chunks(0).collect::<String>(),
1561            "✅       α\nβ   \n🏀β      γ"
1562        );
1563        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \n🏀β      γ");
1564        assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β      γ");
1565
1566        let point = Point::new(0, "\t\t".len() as u32);
1567        let display_point = DisplayPoint::new(0, "".len() as u32);
1568        assert_eq!(point.to_display_point(&map), display_point);
1569        assert_eq!(display_point.to_point(&map), point);
1570
1571        let point = Point::new(1, "β\t".len() as u32);
1572        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1573        assert_eq!(point.to_display_point(&map), display_point);
1574        assert_eq!(display_point.to_point(&map), point,);
1575
1576        let point = Point::new(2, "🏀β\t\t".len() as u32);
1577        let display_point = DisplayPoint::new(2, "🏀β      ".len() as u32);
1578        assert_eq!(point.to_display_point(&map), display_point);
1579        assert_eq!(display_point.to_point(&map), point,);
1580
1581        // Display points inside of expanded tabs
1582        assert_eq!(
1583            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1584            Point::new(0, "\t".len() as u32),
1585        );
1586        assert_eq!(
1587            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1588            Point::new(0, "".len() as u32),
1589        );
1590
1591        // Clipping display points inside of multi-byte characters
1592        assert_eq!(
1593            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Left),
1594            DisplayPoint::new(0, 0)
1595        );
1596        assert_eq!(
1597            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Bias::Right),
1598            DisplayPoint::new(0, "".len() as u32)
1599        );
1600    }
1601
1602    #[gpui::test]
1603    fn test_max_point(cx: &mut gpui::MutableAppContext) {
1604        cx.set_global(Settings::test(cx));
1605        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1606        let font_cache = cx.font_cache();
1607        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1608        let font_id = font_cache
1609            .select_font(family_id, &Default::default())
1610            .unwrap();
1611        let font_size = 14.0;
1612        let map =
1613            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1614        assert_eq!(
1615            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1616            DisplayPoint::new(1, 11)
1617        )
1618    }
1619
1620    #[test]
1621    fn test_find_internal() {
1622        assert("This is a ˇtest of find internal", "test");
1623        assert("Some text ˇaˇaˇaa with repeated characters", "aa");
1624
1625        fn assert(marked_text: &str, target: &str) {
1626            let (text, expected_offsets) = marked_text_offsets(marked_text);
1627
1628            let chars = text
1629                .chars()
1630                .enumerate()
1631                .map(|(index, ch)| (ch, DisplayPoint::new(0, index as u32)));
1632            let target = target.chars();
1633
1634            assert_eq!(
1635                expected_offsets
1636                    .into_iter()
1637                    .map(|offset| offset as u32)
1638                    .collect::<Vec<_>>(),
1639                DisplaySnapshot::find_internal(chars, target.collect(), |_, _| true)
1640                    .map(|point| point.column())
1641                    .collect::<Vec<_>>()
1642            )
1643        }
1644    }
1645
1646    fn syntax_chunks<'a>(
1647        rows: Range<u32>,
1648        map: &ModelHandle<DisplayMap>,
1649        theme: &'a SyntaxTheme,
1650        cx: &mut MutableAppContext,
1651    ) -> Vec<(String, Option<Color>)> {
1652        chunks(rows, map, theme, cx)
1653            .into_iter()
1654            .map(|(text, color, _)| (text, color))
1655            .collect()
1656    }
1657
1658    fn chunks<'a>(
1659        rows: Range<u32>,
1660        map: &ModelHandle<DisplayMap>,
1661        theme: &'a SyntaxTheme,
1662        cx: &mut MutableAppContext,
1663    ) -> Vec<(String, Option<Color>, Option<Color>)> {
1664        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1665        let mut chunks: Vec<(String, Option<Color>, Option<Color>)> = Vec::new();
1666        for chunk in snapshot.chunks(rows, true) {
1667            let syntax_color = chunk
1668                .syntax_highlight_id
1669                .and_then(|id| id.style(theme)?.color);
1670            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1671            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1672                if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1673                    last_chunk.push_str(chunk.text);
1674                    continue;
1675                }
1676            }
1677            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1678        }
1679        chunks
1680    }
1681}