display_map.rs

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