display_map.rs

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