display_map.rs

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