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    pub fn column_to_chars(&self, display_row: u32, target: u32) -> u32 {
 559        let mut count = 0;
 560        let mut column = 0;
 561        for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
 562            if column >= target {
 563                break;
 564            }
 565            count += 1;
 566            column += c.len_utf8() as u32;
 567        }
 568        count
 569    }
 570
 571    pub fn column_from_chars(&self, display_row: u32, char_count: u32) -> u32 {
 572        let mut column = 0;
 573
 574        for (count, (c, _)) in self.chars_at(DisplayPoint::new(display_row, 0)).enumerate() {
 575            if c == '\n' || count >= char_count as usize {
 576                break;
 577            }
 578            column += c.len_utf8() as u32;
 579        }
 580
 581        column
 582    }
 583
 584    pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
 585        let mut clipped = self.block_snapshot.clip_point(point.0, bias);
 586        if self.clip_at_line_ends {
 587            clipped = self.clip_at_line_end(DisplayPoint(clipped)).0
 588        }
 589        DisplayPoint(clipped)
 590    }
 591
 592    pub fn clip_at_line_end(&self, point: DisplayPoint) -> DisplayPoint {
 593        let mut point = point.0;
 594        if point.column == self.line_len(point.row) {
 595            point.column = point.column.saturating_sub(1);
 596            point = self.block_snapshot.clip_point(point, Bias::Left);
 597        }
 598        DisplayPoint(point)
 599    }
 600
 601    pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Range<Anchor>>
 602    where
 603        T: ToOffset,
 604    {
 605        self.fold_snapshot.folds_in_range(range)
 606    }
 607
 608    pub fn blocks_in_range(
 609        &self,
 610        rows: Range<u32>,
 611    ) -> impl Iterator<Item = (u32, &TransformBlock)> {
 612        self.block_snapshot.blocks_in_range(rows)
 613    }
 614
 615    pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
 616        self.fold_snapshot.intersects_fold(offset)
 617    }
 618
 619    pub fn is_line_folded(&self, buffer_row: u32) -> bool {
 620        self.fold_snapshot.is_line_folded(buffer_row)
 621    }
 622
 623    pub fn is_block_line(&self, display_row: u32) -> bool {
 624        self.block_snapshot.is_block_line(display_row)
 625    }
 626
 627    pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
 628        let wrap_row = self
 629            .block_snapshot
 630            .to_wrap_point(BlockPoint::new(display_row, 0))
 631            .row();
 632        self.wrap_snapshot.soft_wrap_indent(wrap_row)
 633    }
 634
 635    pub fn text(&self) -> String {
 636        self.text_chunks(0).collect()
 637    }
 638
 639    pub fn line(&self, display_row: u32) -> String {
 640        let mut result = String::new();
 641        for chunk in self.text_chunks(display_row) {
 642            if let Some(ix) = chunk.find('\n') {
 643                result.push_str(&chunk[0..ix]);
 644                break;
 645            } else {
 646                result.push_str(chunk);
 647            }
 648        }
 649        result
 650    }
 651
 652    pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
 653        let mut indent = 0;
 654        let mut is_blank = true;
 655        for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
 656            if c == ' ' {
 657                indent += 1;
 658            } else {
 659                is_blank = c == '\n';
 660                break;
 661            }
 662        }
 663        (indent, is_blank)
 664    }
 665
 666    pub fn line_indent_for_buffer_row(&self, buffer_row: u32) -> (u32, bool) {
 667        let (buffer, range) = self
 668            .buffer_snapshot
 669            .buffer_line_for_row(buffer_row)
 670            .unwrap();
 671
 672        let mut indent_size = 0;
 673        let mut is_blank = false;
 674        for c in buffer.chars_at(Point::new(range.start.row, 0)) {
 675            if c == ' ' || c == '\t' {
 676                indent_size += 1;
 677            } else {
 678                if c == '\n' {
 679                    is_blank = true;
 680                }
 681                break;
 682            }
 683        }
 684
 685        (indent_size, is_blank)
 686    }
 687
 688    pub fn line_len(&self, row: u32) -> u32 {
 689        self.block_snapshot.line_len(row)
 690    }
 691
 692    pub fn longest_row(&self) -> u32 {
 693        self.block_snapshot.longest_row()
 694    }
 695
 696    pub fn fold_for_line(self: &Self, buffer_row: u32) -> Option<FoldStatus> {
 697        if self.is_line_folded(buffer_row) {
 698            Some(FoldStatus::Folded)
 699        } else if self.is_foldable(buffer_row) {
 700            Some(FoldStatus::Foldable)
 701        } else {
 702            None
 703        }
 704    }
 705
 706    pub fn is_foldable(self: &Self, buffer_row: u32) -> bool {
 707        let max_row = self.buffer_snapshot.max_buffer_row();
 708        if buffer_row >= max_row {
 709            return false;
 710        }
 711
 712        let (indent_size, is_blank) = self.line_indent_for_buffer_row(buffer_row);
 713        if is_blank {
 714            return false;
 715        }
 716
 717        for next_row in (buffer_row + 1)..=max_row {
 718            let (next_indent_size, next_line_is_blank) = self.line_indent_for_buffer_row(next_row);
 719            if next_indent_size > indent_size {
 720                return true;
 721            } else if !next_line_is_blank {
 722                break;
 723            }
 724        }
 725
 726        false
 727    }
 728
 729    pub fn foldable_range(self: &Self, buffer_row: u32) -> Option<Range<Point>> {
 730        let start = Point::new(buffer_row, self.buffer_snapshot.line_len(buffer_row));
 731        if self.is_foldable(start.row) && !self.is_line_folded(start.row) {
 732            let (start_indent, _) = self.line_indent_for_buffer_row(buffer_row);
 733            let max_point = self.buffer_snapshot.max_point();
 734            let mut end = None;
 735
 736            for row in (buffer_row + 1)..=max_point.row {
 737                let (indent, is_blank) = self.line_indent_for_buffer_row(row);
 738                if !is_blank && indent <= start_indent {
 739                    let prev_row = row - 1;
 740                    end = Some(Point::new(
 741                        prev_row,
 742                        self.buffer_snapshot.line_len(prev_row),
 743                    ));
 744                    break;
 745                }
 746            }
 747            let end = end.unwrap_or(max_point);
 748            Some(start..end)
 749        } else {
 750            None
 751        }
 752    }
 753
 754    #[cfg(any(test, feature = "test-support"))]
 755    pub fn highlight_ranges<Tag: ?Sized + 'static>(
 756        &self,
 757    ) -> Option<Arc<(HighlightStyle, Vec<DocumentRange>)>> {
 758        let type_id = TypeId::of::<Tag>();
 759        self.text_highlights.get(&Some(type_id)).cloned()
 760    }
 761}
 762
 763#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
 764pub struct DisplayPoint(BlockPoint);
 765
 766impl Debug for DisplayPoint {
 767    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 768        f.write_fmt(format_args!(
 769            "DisplayPoint({}, {})",
 770            self.row(),
 771            self.column()
 772        ))
 773    }
 774}
 775
 776impl DisplayPoint {
 777    pub fn new(row: u32, column: u32) -> Self {
 778        Self(BlockPoint(Point::new(row, column)))
 779    }
 780
 781    pub fn zero() -> Self {
 782        Self::new(0, 0)
 783    }
 784
 785    pub fn is_zero(&self) -> bool {
 786        self.0.is_zero()
 787    }
 788
 789    pub fn row(self) -> u32 {
 790        self.0.row
 791    }
 792
 793    pub fn column(self) -> u32 {
 794        self.0.column
 795    }
 796
 797    pub fn row_mut(&mut self) -> &mut u32 {
 798        &mut self.0.row
 799    }
 800
 801    pub fn column_mut(&mut self) -> &mut u32 {
 802        &mut self.0.column
 803    }
 804
 805    pub fn to_point(self, map: &DisplaySnapshot) -> Point {
 806        map.display_point_to_point(self, Bias::Left)
 807    }
 808
 809    pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
 810        let wrap_point = map.block_snapshot.to_wrap_point(self.0);
 811        let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
 812        let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
 813        let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
 814        map.inlay_snapshot
 815            .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
 816    }
 817}
 818
 819impl ToDisplayPoint for usize {
 820    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 821        map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
 822    }
 823}
 824
 825impl ToDisplayPoint for OffsetUtf16 {
 826    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 827        self.to_offset(&map.buffer_snapshot).to_display_point(map)
 828    }
 829}
 830
 831impl ToDisplayPoint for Point {
 832    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 833        map.point_to_display_point(*self, Bias::Left)
 834    }
 835}
 836
 837impl ToDisplayPoint for Anchor {
 838    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 839        self.to_point(&map.buffer_snapshot).to_display_point(map)
 840    }
 841}
 842
 843pub fn next_rows(display_row: u32, display_map: &DisplaySnapshot) -> impl Iterator<Item = u32> {
 844    let max_row = display_map.max_point().row();
 845    let start_row = display_row + 1;
 846    let mut current = None;
 847    std::iter::from_fn(move || {
 848        if current == None {
 849            current = Some(start_row);
 850        } else {
 851            current = Some(current.unwrap() + 1)
 852        }
 853        if current.unwrap() > max_row {
 854            None
 855        } else {
 856            current
 857        }
 858    })
 859}
 860
 861#[cfg(test)]
 862pub mod tests {
 863    use super::*;
 864    use crate::{movement, test::marked_display_snapshot};
 865    use gpui::{color::Color, elements::*, test::observe, AppContext};
 866    use language::{
 867        language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
 868        Buffer, Language, LanguageConfig, SelectionGoal,
 869    };
 870    use rand::{prelude::*, Rng};
 871    use settings::SettingsStore;
 872    use smol::stream::StreamExt;
 873    use std::{env, sync::Arc};
 874    use theme::SyntaxTheme;
 875    use util::test::{marked_text_ranges, sample_text};
 876    use Bias::*;
 877
 878    #[gpui::test(iterations = 100)]
 879    async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
 880        cx.foreground().set_block_on_ticks(0..=50);
 881        cx.foreground().forbid_parking();
 882        let operations = env::var("OPERATIONS")
 883            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
 884            .unwrap_or(10);
 885
 886        let font_cache = cx.font_cache().clone();
 887        let mut tab_size = rng.gen_range(1..=4);
 888        let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
 889        let excerpt_header_height = rng.gen_range(1..=5);
 890        let family_id = font_cache
 891            .load_family(&["Helvetica"], &Default::default())
 892            .unwrap();
 893        let font_id = font_cache
 894            .select_font(family_id, &Default::default())
 895            .unwrap();
 896        let font_size = 14.0;
 897        let max_wrap_width = 300.0;
 898        let mut wrap_width = if rng.gen_bool(0.1) {
 899            None
 900        } else {
 901            Some(rng.gen_range(0.0..=max_wrap_width))
 902        };
 903
 904        log::info!("tab size: {}", tab_size);
 905        log::info!("wrap width: {:?}", wrap_width);
 906
 907        cx.update(|cx| {
 908            init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
 909        });
 910
 911        let buffer = cx.update(|cx| {
 912            if rng.gen() {
 913                let len = rng.gen_range(0..10);
 914                let text = util::RandomCharIter::new(&mut rng)
 915                    .take(len)
 916                    .collect::<String>();
 917                MultiBuffer::build_simple(&text, cx)
 918            } else {
 919                MultiBuffer::build_random(&mut rng, cx)
 920            }
 921        });
 922
 923        let map = cx.add_model(|cx| {
 924            DisplayMap::new(
 925                buffer.clone(),
 926                font_id,
 927                font_size,
 928                wrap_width,
 929                buffer_start_excerpt_header_height,
 930                excerpt_header_height,
 931                cx,
 932            )
 933        });
 934        let mut notifications = observe(&map, cx);
 935        let mut fold_count = 0;
 936        let mut blocks = Vec::new();
 937
 938        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 939        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
 940        log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
 941        log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
 942        log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
 943        log::info!("block text: {:?}", snapshot.block_snapshot.text());
 944        log::info!("display text: {:?}", snapshot.text());
 945
 946        for _i in 0..operations {
 947            match rng.gen_range(0..100) {
 948                0..=19 => {
 949                    wrap_width = if rng.gen_bool(0.2) {
 950                        None
 951                    } else {
 952                        Some(rng.gen_range(0.0..=max_wrap_width))
 953                    };
 954                    log::info!("setting wrap width to {:?}", wrap_width);
 955                    map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
 956                }
 957                20..=29 => {
 958                    let mut tab_sizes = vec![1, 2, 3, 4];
 959                    tab_sizes.remove((tab_size - 1) as usize);
 960                    tab_size = *tab_sizes.choose(&mut rng).unwrap();
 961                    log::info!("setting tab size to {:?}", tab_size);
 962                    cx.update(|cx| {
 963                        cx.update_global::<SettingsStore, _, _>(|store, cx| {
 964                            store.update_user_settings::<AllLanguageSettings>(cx, |s| {
 965                                s.defaults.tab_size = NonZeroU32::new(tab_size);
 966                            });
 967                        });
 968                    });
 969                }
 970                30..=44 => {
 971                    map.update(cx, |map, cx| {
 972                        if rng.gen() || blocks.is_empty() {
 973                            let buffer = map.snapshot(cx).buffer_snapshot;
 974                            let block_properties = (0..rng.gen_range(1..=1))
 975                                .map(|_| {
 976                                    let position =
 977                                        buffer.anchor_after(buffer.clip_offset(
 978                                            rng.gen_range(0..=buffer.len()),
 979                                            Bias::Left,
 980                                        ));
 981
 982                                    let disposition = if rng.gen() {
 983                                        BlockDisposition::Above
 984                                    } else {
 985                                        BlockDisposition::Below
 986                                    };
 987                                    let height = rng.gen_range(1..5);
 988                                    log::info!(
 989                                        "inserting block {:?} {:?} with height {}",
 990                                        disposition,
 991                                        position.to_point(&buffer),
 992                                        height
 993                                    );
 994                                    BlockProperties {
 995                                        style: BlockStyle::Fixed,
 996                                        position,
 997                                        height,
 998                                        disposition,
 999                                        render: Arc::new(|_| Empty::new().into_any()),
1000                                    }
1001                                })
1002                                .collect::<Vec<_>>();
1003                            blocks.extend(map.insert_blocks(block_properties, cx));
1004                        } else {
1005                            blocks.shuffle(&mut rng);
1006                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1007                            let block_ids_to_remove = (0..remove_count)
1008                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1009                                .collect();
1010                            log::info!("removing block ids {:?}", block_ids_to_remove);
1011                            map.remove_blocks(block_ids_to_remove, cx);
1012                        }
1013                    });
1014                }
1015                45..=79 => {
1016                    let mut ranges = Vec::new();
1017                    for _ in 0..rng.gen_range(1..=3) {
1018                        buffer.read_with(cx, |buffer, cx| {
1019                            let buffer = buffer.read(cx);
1020                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1021                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1022                            ranges.push(start..end);
1023                        });
1024                    }
1025
1026                    if rng.gen() && fold_count > 0 {
1027                        log::info!("unfolding ranges: {:?}", ranges);
1028                        map.update(cx, |map, cx| {
1029                            map.unfold(ranges, true, cx);
1030                        });
1031                    } else {
1032                        log::info!("folding ranges: {:?}", ranges);
1033                        map.update(cx, |map, cx| {
1034                            map.fold(ranges, cx);
1035                        });
1036                    }
1037                }
1038                _ => {
1039                    buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1040                }
1041            }
1042
1043            if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1044                notifications.next().await.unwrap();
1045            }
1046
1047            let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1048            fold_count = snapshot.fold_count();
1049            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1050            log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1051            log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1052            log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1053            log::info!("block text: {:?}", snapshot.block_snapshot.text());
1054            log::info!("display text: {:?}", snapshot.text());
1055
1056            // Line boundaries
1057            let buffer = &snapshot.buffer_snapshot;
1058            for _ in 0..5 {
1059                let row = rng.gen_range(0..=buffer.max_point().row);
1060                let column = rng.gen_range(0..=buffer.line_len(row));
1061                let point = buffer.clip_point(Point::new(row, column), Left);
1062
1063                let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1064                let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1065
1066                assert!(prev_buffer_bound <= point);
1067                assert!(next_buffer_bound >= point);
1068                assert_eq!(prev_buffer_bound.column, 0);
1069                assert_eq!(prev_display_bound.column(), 0);
1070                if next_buffer_bound < buffer.max_point() {
1071                    assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1072                }
1073
1074                assert_eq!(
1075                    prev_display_bound,
1076                    prev_buffer_bound.to_display_point(&snapshot),
1077                    "row boundary before {:?}. reported buffer row boundary: {:?}",
1078                    point,
1079                    prev_buffer_bound
1080                );
1081                assert_eq!(
1082                    next_display_bound,
1083                    next_buffer_bound.to_display_point(&snapshot),
1084                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
1085                    point,
1086                    next_buffer_bound
1087                );
1088                assert_eq!(
1089                    prev_buffer_bound,
1090                    prev_display_bound.to_point(&snapshot),
1091                    "row boundary before {:?}. reported display row boundary: {:?}",
1092                    point,
1093                    prev_display_bound
1094                );
1095                assert_eq!(
1096                    next_buffer_bound,
1097                    next_display_bound.to_point(&snapshot),
1098                    "row boundary after {:?}. reported display row boundary: {:?}",
1099                    point,
1100                    next_display_bound
1101                );
1102            }
1103
1104            // Movement
1105            let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1106            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1107            for _ in 0..5 {
1108                let row = rng.gen_range(0..=snapshot.max_point().row());
1109                let column = rng.gen_range(0..=snapshot.line_len(row));
1110                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1111
1112                log::info!("Moving from point {:?}", point);
1113
1114                let moved_right = movement::right(&snapshot, point);
1115                log::info!("Right {:?}", moved_right);
1116                if point < max_point {
1117                    assert!(moved_right > point);
1118                    if point.column() == snapshot.line_len(point.row())
1119                        || snapshot.soft_wrap_indent(point.row()).is_some()
1120                            && point.column() == snapshot.line_len(point.row()) - 1
1121                    {
1122                        assert!(moved_right.row() > point.row());
1123                    }
1124                } else {
1125                    assert_eq!(moved_right, point);
1126                }
1127
1128                let moved_left = movement::left(&snapshot, point);
1129                log::info!("Left {:?}", moved_left);
1130                if point > min_point {
1131                    assert!(moved_left < point);
1132                    if point.column() == 0 {
1133                        assert!(moved_left.row() < point.row());
1134                    }
1135                } else {
1136                    assert_eq!(moved_left, point);
1137                }
1138            }
1139        }
1140    }
1141
1142    #[gpui::test(retries = 5)]
1143    fn test_soft_wraps(cx: &mut AppContext) {
1144        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1145        init_test(cx, |_| {});
1146
1147        let font_cache = cx.font_cache();
1148
1149        let family_id = font_cache
1150            .load_family(&["Helvetica"], &Default::default())
1151            .unwrap();
1152        let font_id = font_cache
1153            .select_font(family_id, &Default::default())
1154            .unwrap();
1155        let font_size = 12.0;
1156        let wrap_width = Some(64.);
1157
1158        let text = "one two three four five\nsix seven eight";
1159        let buffer = MultiBuffer::build_simple(text, cx);
1160        let map = cx.add_model(|cx| {
1161            DisplayMap::new(buffer.clone(), font_id, font_size, wrap_width, 1, 1, cx)
1162        });
1163
1164        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1165        assert_eq!(
1166            snapshot.text_chunks(0).collect::<String>(),
1167            "one two \nthree four \nfive\nsix seven \neight"
1168        );
1169        assert_eq!(
1170            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1171            DisplayPoint::new(0, 7)
1172        );
1173        assert_eq!(
1174            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1175            DisplayPoint::new(1, 0)
1176        );
1177        assert_eq!(
1178            movement::right(&snapshot, DisplayPoint::new(0, 7)),
1179            DisplayPoint::new(1, 0)
1180        );
1181        assert_eq!(
1182            movement::left(&snapshot, DisplayPoint::new(1, 0)),
1183            DisplayPoint::new(0, 7)
1184        );
1185        assert_eq!(
1186            movement::up(
1187                &snapshot,
1188                DisplayPoint::new(1, 10),
1189                SelectionGoal::None,
1190                false
1191            ),
1192            (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
1193        );
1194        assert_eq!(
1195            movement::down(
1196                &snapshot,
1197                DisplayPoint::new(0, 7),
1198                SelectionGoal::Column(10),
1199                false
1200            ),
1201            (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
1202        );
1203        assert_eq!(
1204            movement::down(
1205                &snapshot,
1206                DisplayPoint::new(1, 10),
1207                SelectionGoal::Column(10),
1208                false
1209            ),
1210            (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
1211        );
1212
1213        let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1214        buffer.update(cx, |buffer, cx| {
1215            buffer.edit([(ix..ix, "and ")], None, cx);
1216        });
1217
1218        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1219        assert_eq!(
1220            snapshot.text_chunks(1).collect::<String>(),
1221            "three four \nfive\nsix and \nseven eight"
1222        );
1223
1224        // Re-wrap on font size changes
1225        map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
1226
1227        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1228        assert_eq!(
1229            snapshot.text_chunks(1).collect::<String>(),
1230            "three \nfour five\nsix and \nseven \neight"
1231        )
1232    }
1233
1234    #[gpui::test]
1235    fn test_text_chunks(cx: &mut gpui::AppContext) {
1236        init_test(cx, |_| {});
1237
1238        let text = sample_text(6, 6, 'a');
1239        let buffer = MultiBuffer::build_simple(&text, cx);
1240        let family_id = cx
1241            .font_cache()
1242            .load_family(&["Helvetica"], &Default::default())
1243            .unwrap();
1244        let font_id = cx
1245            .font_cache()
1246            .select_font(family_id, &Default::default())
1247            .unwrap();
1248        let font_size = 14.0;
1249        let map =
1250            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1251
1252        buffer.update(cx, |buffer, cx| {
1253            buffer.edit(
1254                vec![
1255                    (Point::new(1, 0)..Point::new(1, 0), "\t"),
1256                    (Point::new(1, 1)..Point::new(1, 1), "\t"),
1257                    (Point::new(2, 1)..Point::new(2, 1), "\t"),
1258                ],
1259                None,
1260                cx,
1261            )
1262        });
1263
1264        assert_eq!(
1265            map.update(cx, |map, cx| map.snapshot(cx))
1266                .text_chunks(1)
1267                .collect::<String>()
1268                .lines()
1269                .next(),
1270            Some("    b   bbbbb")
1271        );
1272        assert_eq!(
1273            map.update(cx, |map, cx| map.snapshot(cx))
1274                .text_chunks(2)
1275                .collect::<String>()
1276                .lines()
1277                .next(),
1278            Some("c   ccccc")
1279        );
1280    }
1281
1282    #[gpui::test]
1283    async fn test_chunks(cx: &mut gpui::TestAppContext) {
1284        use unindent::Unindent as _;
1285
1286        let text = r#"
1287            fn outer() {}
1288
1289            mod module {
1290                fn inner() {}
1291            }"#
1292        .unindent();
1293
1294        let theme = SyntaxTheme::new(vec![
1295            ("mod.body".to_string(), Color::red().into()),
1296            ("fn.name".to_string(), Color::blue().into()),
1297        ]);
1298        let language = Arc::new(
1299            Language::new(
1300                LanguageConfig {
1301                    name: "Test".into(),
1302                    path_suffixes: vec![".test".to_string()],
1303                    ..Default::default()
1304                },
1305                Some(tree_sitter_rust::language()),
1306            )
1307            .with_highlights_query(
1308                r#"
1309                (mod_item name: (identifier) body: _ @mod.body)
1310                (function_item name: (identifier) @fn.name)
1311                "#,
1312            )
1313            .unwrap(),
1314        );
1315        language.set_theme(&theme);
1316
1317        cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1318
1319        let buffer = cx
1320            .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1321        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1322        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1323
1324        let font_cache = cx.font_cache();
1325        let family_id = font_cache
1326            .load_family(&["Helvetica"], &Default::default())
1327            .unwrap();
1328        let font_id = font_cache
1329            .select_font(family_id, &Default::default())
1330            .unwrap();
1331        let font_size = 14.0;
1332
1333        let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1334        assert_eq!(
1335            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1336            vec![
1337                ("fn ".to_string(), None),
1338                ("outer".to_string(), Some(Color::blue())),
1339                ("() {}\n\nmod module ".to_string(), None),
1340                ("{\n    fn ".to_string(), Some(Color::red())),
1341                ("inner".to_string(), Some(Color::blue())),
1342                ("() {}\n}".to_string(), Some(Color::red())),
1343            ]
1344        );
1345        assert_eq!(
1346            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1347            vec![
1348                ("    fn ".to_string(), Some(Color::red())),
1349                ("inner".to_string(), Some(Color::blue())),
1350                ("() {}\n}".to_string(), Some(Color::red())),
1351            ]
1352        );
1353
1354        map.update(cx, |map, cx| {
1355            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1356        });
1357        assert_eq!(
1358            cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1359            vec![
1360                ("fn ".to_string(), None),
1361                ("out".to_string(), Some(Color::blue())),
1362                ("⋯".to_string(), None),
1363                ("  fn ".to_string(), Some(Color::red())),
1364                ("inner".to_string(), Some(Color::blue())),
1365                ("() {}\n}".to_string(), Some(Color::red())),
1366            ]
1367        );
1368    }
1369
1370    #[gpui::test]
1371    async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1372        use unindent::Unindent as _;
1373
1374        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1375
1376        let text = r#"
1377            fn outer() {}
1378
1379            mod module {
1380                fn inner() {}
1381            }"#
1382        .unindent();
1383
1384        let theme = SyntaxTheme::new(vec![
1385            ("mod.body".to_string(), Color::red().into()),
1386            ("fn.name".to_string(), Color::blue().into()),
1387        ]);
1388        let language = Arc::new(
1389            Language::new(
1390                LanguageConfig {
1391                    name: "Test".into(),
1392                    path_suffixes: vec![".test".to_string()],
1393                    ..Default::default()
1394                },
1395                Some(tree_sitter_rust::language()),
1396            )
1397            .with_highlights_query(
1398                r#"
1399                (mod_item name: (identifier) body: _ @mod.body)
1400                (function_item name: (identifier) @fn.name)
1401                "#,
1402            )
1403            .unwrap(),
1404        );
1405        language.set_theme(&theme);
1406
1407        cx.update(|cx| init_test(cx, |_| {}));
1408
1409        let buffer = cx
1410            .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1411        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1412        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1413
1414        let font_cache = cx.font_cache();
1415
1416        let family_id = font_cache
1417            .load_family(&["Courier"], &Default::default())
1418            .unwrap();
1419        let font_id = font_cache
1420            .select_font(family_id, &Default::default())
1421            .unwrap();
1422        let font_size = 16.0;
1423
1424        let map =
1425            cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, Some(40.0), 1, 1, cx));
1426        assert_eq!(
1427            cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1428            [
1429                ("fn \n".to_string(), None),
1430                ("oute\nr".to_string(), Some(Color::blue())),
1431                ("() \n{}\n\n".to_string(), None),
1432            ]
1433        );
1434        assert_eq!(
1435            cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1436            [("{}\n\n".to_string(), None)]
1437        );
1438
1439        map.update(cx, |map, cx| {
1440            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1441        });
1442        assert_eq!(
1443            cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1444            [
1445                ("out".to_string(), Some(Color::blue())),
1446                ("⋯\n".to_string(), None),
1447                ("  \nfn ".to_string(), Some(Color::red())),
1448                ("i\n".to_string(), Some(Color::blue()))
1449            ]
1450        );
1451    }
1452
1453    #[gpui::test]
1454    async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1455        cx.update(|cx| init_test(cx, |_| {}));
1456
1457        let theme = SyntaxTheme::new(vec![
1458            ("operator".to_string(), Color::red().into()),
1459            ("string".to_string(), Color::green().into()),
1460        ]);
1461        let language = Arc::new(
1462            Language::new(
1463                LanguageConfig {
1464                    name: "Test".into(),
1465                    path_suffixes: vec![".test".to_string()],
1466                    ..Default::default()
1467                },
1468                Some(tree_sitter_rust::language()),
1469            )
1470            .with_highlights_query(
1471                r#"
1472                ":" @operator
1473                (string_literal) @string
1474                "#,
1475            )
1476            .unwrap(),
1477        );
1478        language.set_theme(&theme);
1479
1480        let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ Ā«aĀ»: B = "c Ā«dĀ»""#, false);
1481
1482        let buffer = cx
1483            .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1484        buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1485
1486        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1487        let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1488
1489        let font_cache = cx.font_cache();
1490        let family_id = font_cache
1491            .load_family(&["Courier"], &Default::default())
1492            .unwrap();
1493        let font_id = font_cache
1494            .select_font(family_id, &Default::default())
1495            .unwrap();
1496        let font_size = 16.0;
1497        let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1498
1499        enum MyType {}
1500
1501        let style = HighlightStyle {
1502            color: Some(Color::blue()),
1503            ..Default::default()
1504        };
1505
1506        map.update(cx, |map, _cx| {
1507            map.highlight_text(
1508                TypeId::of::<MyType>(),
1509                highlighted_ranges
1510                    .into_iter()
1511                    .map(|range| {
1512                        buffer_snapshot.anchor_before(range.start)
1513                            ..buffer_snapshot.anchor_before(range.end)
1514                    })
1515                    .collect(),
1516                style,
1517            );
1518        });
1519
1520        assert_eq!(
1521            cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1522            [
1523                ("const ".to_string(), None, None),
1524                ("a".to_string(), None, Some(Color::blue())),
1525                (":".to_string(), Some(Color::red()), None),
1526                (" B = ".to_string(), None, None),
1527                ("\"c ".to_string(), Some(Color::green()), None),
1528                ("d".to_string(), Some(Color::green()), Some(Color::blue())),
1529                ("\"".to_string(), Some(Color::green()), None),
1530            ]
1531        );
1532    }
1533
1534    #[gpui::test]
1535    fn test_clip_point(cx: &mut gpui::AppContext) {
1536        init_test(cx, |_| {});
1537
1538        fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1539            let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1540
1541            match bias {
1542                Bias::Left => {
1543                    if shift_right {
1544                        *markers[1].column_mut() += 1;
1545                    }
1546
1547                    assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1548                }
1549                Bias::Right => {
1550                    if shift_right {
1551                        *markers[0].column_mut() += 1;
1552                    }
1553
1554                    assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1555                }
1556            };
1557        }
1558
1559        use Bias::{Left, Right};
1560        assert("ˇˇα", false, Left, cx);
1561        assert("ˇˇα", true, Left, cx);
1562        assert("ˇˇα", false, Right, cx);
1563        assert("ˇαˇ", true, Right, cx);
1564        assert("Ė‡Ė‡āœ‹", false, Left, cx);
1565        assert("Ė‡Ė‡āœ‹", true, Left, cx);
1566        assert("Ė‡Ė‡āœ‹", false, Right, cx);
1567        assert("Ė‡āœ‹Ė‡", true, Right, cx);
1568        assert("Ė‡Ė‡šŸ", false, Left, cx);
1569        assert("Ė‡Ė‡šŸ", true, Left, cx);
1570        assert("Ė‡Ė‡šŸ", false, Right, cx);
1571        assert("Ė‡šŸĖ‡", true, Right, cx);
1572        assert("ˇˇ\t", false, Left, cx);
1573        assert("ˇˇ\t", true, Left, cx);
1574        assert("ˇˇ\t", false, Right, cx);
1575        assert("ˇ\tˇ", true, Right, cx);
1576        assert(" ˇˇ\t", false, Left, cx);
1577        assert(" ˇˇ\t", true, Left, cx);
1578        assert(" ˇˇ\t", false, Right, cx);
1579        assert(" ˇ\tˇ", true, Right, cx);
1580        assert("   ˇˇ\t", false, Left, cx);
1581        assert("   ˇˇ\t", false, Right, cx);
1582    }
1583
1584    #[gpui::test]
1585    fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1586        init_test(cx, |_| {});
1587
1588        fn assert(text: &str, cx: &mut gpui::AppContext) {
1589            let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1590            unmarked_snapshot.clip_at_line_ends = true;
1591            assert_eq!(
1592                unmarked_snapshot.clip_point(markers[1], Bias::Left),
1593                markers[0]
1594            );
1595        }
1596
1597        assert("ˇˇ", cx);
1598        assert("ˇaˇ", cx);
1599        assert("aˇbˇ", cx);
1600        assert("aˇαˇ", cx);
1601    }
1602
1603    #[gpui::test]
1604    fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1605        init_test(cx, |_| {});
1606
1607        let text = "āœ…\t\tα\nβ\t\nšŸ€Ī²\t\tγ";
1608        let buffer = MultiBuffer::build_simple(text, cx);
1609        let font_cache = cx.font_cache();
1610        let family_id = font_cache
1611            .load_family(&["Helvetica"], &Default::default())
1612            .unwrap();
1613        let font_id = font_cache
1614            .select_font(family_id, &Default::default())
1615            .unwrap();
1616        let font_size = 14.0;
1617
1618        let map =
1619            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1620        let map = map.update(cx, |map, cx| map.snapshot(cx));
1621        assert_eq!(map.text(), "āœ…       α\nβ   \nšŸ€Ī²      γ");
1622        assert_eq!(
1623            map.text_chunks(0).collect::<String>(),
1624            "āœ…       α\nβ   \nšŸ€Ī²      γ"
1625        );
1626        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \nšŸ€Ī²      γ");
1627        assert_eq!(map.text_chunks(2).collect::<String>(), "šŸ€Ī²      γ");
1628
1629        let point = Point::new(0, "āœ…\t\t".len() as u32);
1630        let display_point = DisplayPoint::new(0, "āœ…       ".len() as u32);
1631        assert_eq!(point.to_display_point(&map), display_point);
1632        assert_eq!(display_point.to_point(&map), point);
1633
1634        let point = Point::new(1, "β\t".len() as u32);
1635        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1636        assert_eq!(point.to_display_point(&map), display_point);
1637        assert_eq!(display_point.to_point(&map), point,);
1638
1639        let point = Point::new(2, "šŸ€Ī²\t\t".len() as u32);
1640        let display_point = DisplayPoint::new(2, "šŸ€Ī²      ".len() as u32);
1641        assert_eq!(point.to_display_point(&map), display_point);
1642        assert_eq!(display_point.to_point(&map), point,);
1643
1644        // Display points inside of expanded tabs
1645        assert_eq!(
1646            DisplayPoint::new(0, "āœ…      ".len() as u32).to_point(&map),
1647            Point::new(0, "āœ…\t".len() as u32),
1648        );
1649        assert_eq!(
1650            DisplayPoint::new(0, "āœ… ".len() as u32).to_point(&map),
1651            Point::new(0, "āœ…".len() as u32),
1652        );
1653
1654        // Clipping display points inside of multi-byte characters
1655        assert_eq!(
1656            map.clip_point(DisplayPoint::new(0, "āœ…".len() as u32 - 1), Left),
1657            DisplayPoint::new(0, 0)
1658        );
1659        assert_eq!(
1660            map.clip_point(DisplayPoint::new(0, "āœ…".len() as u32 - 1), Bias::Right),
1661            DisplayPoint::new(0, "āœ…".len() as u32)
1662        );
1663    }
1664
1665    #[gpui::test]
1666    fn test_max_point(cx: &mut gpui::AppContext) {
1667        init_test(cx, |_| {});
1668
1669        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", 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        let map =
1679            cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1680        assert_eq!(
1681            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1682            DisplayPoint::new(1, 11)
1683        )
1684    }
1685
1686    fn syntax_chunks<'a>(
1687        rows: Range<u32>,
1688        map: &ModelHandle<DisplayMap>,
1689        theme: &'a SyntaxTheme,
1690        cx: &mut AppContext,
1691    ) -> Vec<(String, Option<Color>)> {
1692        chunks(rows, map, theme, cx)
1693            .into_iter()
1694            .map(|(text, color, _)| (text, color))
1695            .collect()
1696    }
1697
1698    fn chunks<'a>(
1699        rows: Range<u32>,
1700        map: &ModelHandle<DisplayMap>,
1701        theme: &'a SyntaxTheme,
1702        cx: &mut AppContext,
1703    ) -> Vec<(String, Option<Color>, Option<Color>)> {
1704        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1705        let mut chunks: Vec<(String, Option<Color>, Option<Color>)> = Vec::new();
1706        for chunk in snapshot.chunks(rows, true, None, None) {
1707            let syntax_color = chunk
1708                .syntax_highlight_id
1709                .and_then(|id| id.style(theme)?.color);
1710            let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1711            if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1712                if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1713                    last_chunk.push_str(chunk.text);
1714                    continue;
1715                }
1716            }
1717            chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1718        }
1719        chunks
1720    }
1721
1722    fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
1723        cx.foreground().forbid_parking();
1724        cx.set_global(SettingsStore::test(cx));
1725        language::init(cx);
1726        cx.update_global::<SettingsStore, _, _>(|store, cx| {
1727            store.update_user_settings::<AllLanguageSettings>(cx, f);
1728        });
1729    }
1730}