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