display_map.rs

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