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