display_map.rs

   1mod block_map;
   2mod fold_map;
   3mod tab_map;
   4mod wrap_map;
   5
   6use block_map::{BlockMap, BlockPoint};
   7use fold_map::{FoldMap, ToFoldPoint as _};
   8use gpui::{fonts::FontId, ElementBox, Entity, ModelContext, ModelHandle};
   9use language::{
  10    multi_buffer::{Anchor, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint},
  11    Point, Subscription as BufferSubscription,
  12};
  13use std::{
  14    collections::{HashMap, HashSet},
  15    ops::Range,
  16};
  17use sum_tree::Bias;
  18use tab_map::TabMap;
  19use theme::SyntaxTheme;
  20use wrap_map::WrapMap;
  21
  22pub use block_map::{
  23    AlignedBlock, BlockBufferRows as DisplayBufferRows, BlockChunks as DisplayChunks, BlockContext,
  24    BlockDisposition, BlockId, BlockProperties,
  25};
  26
  27pub trait ToDisplayPoint {
  28    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
  29}
  30
  31pub struct DisplayMap {
  32    buffer: ModelHandle<MultiBuffer>,
  33    buffer_subscription: BufferSubscription,
  34    fold_map: FoldMap,
  35    tab_map: TabMap,
  36    wrap_map: ModelHandle<WrapMap>,
  37    block_map: BlockMap,
  38}
  39
  40impl Entity for DisplayMap {
  41    type Event = ();
  42}
  43
  44impl DisplayMap {
  45    pub fn new(
  46        buffer: ModelHandle<MultiBuffer>,
  47        tab_size: usize,
  48        font_id: FontId,
  49        font_size: f32,
  50        wrap_width: Option<f32>,
  51        cx: &mut ModelContext<Self>,
  52    ) -> Self {
  53        let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
  54        let (fold_map, snapshot) = FoldMap::new(buffer.read(cx).snapshot(cx));
  55        let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
  56        let (wrap_map, snapshot) = WrapMap::new(snapshot, font_id, font_size, wrap_width, cx);
  57        let block_map = BlockMap::new(buffer.clone(), snapshot);
  58        cx.observe(&wrap_map, |_, _, cx| cx.notify()).detach();
  59        DisplayMap {
  60            buffer,
  61            buffer_subscription,
  62            fold_map,
  63            tab_map,
  64            wrap_map,
  65            block_map,
  66        }
  67    }
  68
  69    pub fn snapshot(&self, cx: &mut ModelContext<Self>) -> DisplaySnapshot {
  70        let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
  71        let edits = self.buffer_subscription.consume().into_inner();
  72        let (folds_snapshot, edits) = self.fold_map.read(buffer_snapshot, edits);
  73        let (tabs_snapshot, edits) = self.tab_map.sync(folds_snapshot.clone(), edits);
  74        let (wraps_snapshot, edits) = self
  75            .wrap_map
  76            .update(cx, |map, cx| map.sync(tabs_snapshot.clone(), edits, cx));
  77        let blocks_snapshot = self.block_map.read(wraps_snapshot.clone(), edits, cx);
  78
  79        DisplaySnapshot {
  80            buffer_snapshot: self.buffer.read(cx).snapshot(cx),
  81            folds_snapshot,
  82            tabs_snapshot,
  83            wraps_snapshot,
  84            blocks_snapshot,
  85        }
  86    }
  87
  88    pub fn fold<T: ToOffset>(
  89        &mut self,
  90        ranges: impl IntoIterator<Item = Range<T>>,
  91        cx: &mut ModelContext<Self>,
  92    ) {
  93        let snapshot = self.buffer.read(cx).snapshot(cx);
  94        let edits = self.buffer_subscription.consume().into_inner();
  95        let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
  96        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
  97        let (snapshot, edits) = self
  98            .wrap_map
  99            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 100        self.block_map.read(snapshot, edits, cx);
 101        let (snapshot, edits) = fold_map.fold(ranges);
 102        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 103        let (snapshot, edits) = self
 104            .wrap_map
 105            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 106        self.block_map.read(snapshot, edits, cx);
 107    }
 108
 109    pub fn unfold<T: ToOffset>(
 110        &mut self,
 111        ranges: impl IntoIterator<Item = Range<T>>,
 112        cx: &mut ModelContext<Self>,
 113    ) {
 114        let snapshot = self.buffer.read(cx).snapshot(cx);
 115        let edits = self.buffer_subscription.consume().into_inner();
 116        let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
 117        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 118        let (snapshot, edits) = self
 119            .wrap_map
 120            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 121        self.block_map.read(snapshot, edits, cx);
 122        let (snapshot, edits) = fold_map.unfold(ranges);
 123        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 124        let (snapshot, edits) = self
 125            .wrap_map
 126            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 127        self.block_map.read(snapshot, edits, cx);
 128    }
 129
 130    pub fn insert_blocks<P>(
 131        &mut self,
 132        blocks: impl IntoIterator<Item = BlockProperties<P>>,
 133        cx: &mut ModelContext<Self>,
 134    ) -> Vec<BlockId>
 135    where
 136        P: ToOffset + Clone,
 137    {
 138        let snapshot = self.buffer.read(cx).snapshot(cx);
 139        let edits = self.buffer_subscription.consume().into_inner();
 140        let (snapshot, edits) = self.fold_map.read(snapshot, edits);
 141        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 142        let (snapshot, edits) = self
 143            .wrap_map
 144            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 145        let mut block_map = self.block_map.write(snapshot, edits, cx);
 146        block_map.insert(blocks, cx)
 147    }
 148
 149    pub fn replace_blocks<F>(&mut self, styles: HashMap<BlockId, F>)
 150    where
 151        F: 'static + Fn(&BlockContext) -> ElementBox,
 152    {
 153        self.block_map.replace(styles);
 154    }
 155
 156    pub fn remove_blocks(&mut self, ids: HashSet<BlockId>, cx: &mut ModelContext<Self>) {
 157        let snapshot = self.buffer.read(cx).snapshot(cx);
 158        let edits = self.buffer_subscription.consume().into_inner();
 159        let (snapshot, edits) = self.fold_map.read(snapshot, edits);
 160        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 161        let (snapshot, edits) = self
 162            .wrap_map
 163            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 164        let mut block_map = self.block_map.write(snapshot, edits, cx);
 165        block_map.remove(ids, cx);
 166    }
 167
 168    pub fn set_font(&self, font_id: FontId, font_size: f32, cx: &mut ModelContext<Self>) {
 169        self.wrap_map
 170            .update(cx, |map, cx| map.set_font(font_id, font_size, cx));
 171    }
 172
 173    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut ModelContext<Self>) -> bool {
 174        self.wrap_map
 175            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 176    }
 177
 178    #[cfg(test)]
 179    pub fn is_rewrapping(&self, cx: &gpui::AppContext) -> bool {
 180        self.wrap_map.read(cx).is_rewrapping()
 181    }
 182}
 183
 184pub struct DisplaySnapshot {
 185    pub buffer_snapshot: MultiBufferSnapshot,
 186    folds_snapshot: fold_map::FoldSnapshot,
 187    tabs_snapshot: tab_map::TabSnapshot,
 188    wraps_snapshot: wrap_map::WrapSnapshot,
 189    blocks_snapshot: block_map::BlockSnapshot,
 190}
 191
 192impl DisplaySnapshot {
 193    #[cfg(test)]
 194    pub fn fold_count(&self) -> usize {
 195        self.folds_snapshot.fold_count()
 196    }
 197
 198    pub fn is_empty(&self) -> bool {
 199        self.buffer_snapshot.len() == 0
 200    }
 201
 202    pub fn buffer_rows<'a>(&'a self, start_row: u32) -> DisplayBufferRows<'a> {
 203        self.blocks_snapshot.buffer_rows(start_row)
 204    }
 205
 206    pub fn buffer_row_count(&self) -> u32 {
 207        self.buffer_snapshot.max_point().row + 1
 208    }
 209
 210    pub fn prev_row_boundary(&self, mut display_point: DisplayPoint) -> (DisplayPoint, Point) {
 211        loop {
 212            *display_point.column_mut() = 0;
 213            let mut point = display_point.to_point(self);
 214            point.column = 0;
 215            let next_display_point = self.point_to_display_point(point, Bias::Left);
 216            if next_display_point == display_point {
 217                return (display_point, point);
 218            }
 219            display_point = next_display_point;
 220        }
 221    }
 222
 223    pub fn next_row_boundary(&self, mut display_point: DisplayPoint) -> (DisplayPoint, Point) {
 224        loop {
 225            *display_point.column_mut() = self.line_len(display_point.row());
 226            let mut point = display_point.to_point(self);
 227            point.column = self.buffer_snapshot.line_len(point.row);
 228            let next_display_point = self.point_to_display_point(point, Bias::Right);
 229            if next_display_point == display_point {
 230                return (display_point, point);
 231            }
 232            display_point = next_display_point;
 233        }
 234    }
 235
 236    fn point_to_display_point(&self, point: Point, bias: Bias) -> DisplayPoint {
 237        DisplayPoint(
 238            self.blocks_snapshot.to_block_point(
 239                self.wraps_snapshot.from_tab_point(
 240                    self.tabs_snapshot
 241                        .to_tab_point(point.to_fold_point(&self.folds_snapshot, bias)),
 242                ),
 243            ),
 244        )
 245    }
 246
 247    fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {
 248        let unblocked_point = self.blocks_snapshot.to_wrap_point(point.0);
 249        let unwrapped_point = self.wraps_snapshot.to_tab_point(unblocked_point);
 250        let unexpanded_point = self.tabs_snapshot.to_fold_point(unwrapped_point, bias).0;
 251        unexpanded_point.to_buffer_point(&self.folds_snapshot)
 252    }
 253
 254    pub fn max_point(&self) -> DisplayPoint {
 255        DisplayPoint(self.blocks_snapshot.max_point())
 256    }
 257
 258    pub fn text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
 259        self.blocks_snapshot
 260            .chunks(display_row..self.max_point().row() + 1, None)
 261            .map(|h| h.text)
 262    }
 263
 264    pub fn chunks<'a>(
 265        &'a self,
 266        display_rows: Range<u32>,
 267        theme: Option<&'a SyntaxTheme>,
 268    ) -> DisplayChunks<'a> {
 269        self.blocks_snapshot.chunks(display_rows, theme)
 270    }
 271
 272    pub fn chars_at<'a>(&'a self, point: DisplayPoint) -> impl Iterator<Item = char> + 'a {
 273        let mut column = 0;
 274        let mut chars = self.text_chunks(point.row()).flat_map(str::chars);
 275        while column < point.column() {
 276            if let Some(c) = chars.next() {
 277                column += c.len_utf8() as u32;
 278            } else {
 279                break;
 280            }
 281        }
 282        chars
 283    }
 284
 285    pub fn column_to_chars(&self, display_row: u32, target: u32) -> u32 {
 286        let mut count = 0;
 287        let mut column = 0;
 288        for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
 289            if column >= target {
 290                break;
 291            }
 292            count += 1;
 293            column += c.len_utf8() as u32;
 294        }
 295        count
 296    }
 297
 298    pub fn column_from_chars(&self, display_row: u32, char_count: u32) -> u32 {
 299        let mut count = 0;
 300        let mut column = 0;
 301        for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
 302            if c == '\n' || count >= char_count {
 303                break;
 304            }
 305            count += 1;
 306            column += c.len_utf8() as u32;
 307        }
 308        column
 309    }
 310
 311    pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
 312        DisplayPoint(self.blocks_snapshot.clip_point(point.0, bias))
 313    }
 314
 315    pub fn folds_in_range<'a, T>(
 316        &'a self,
 317        range: Range<T>,
 318    ) -> impl Iterator<Item = &'a Range<Anchor>>
 319    where
 320        T: ToOffset,
 321    {
 322        self.folds_snapshot.folds_in_range(range)
 323    }
 324
 325    pub fn blocks_in_range<'a>(
 326        &'a self,
 327        rows: Range<u32>,
 328    ) -> impl Iterator<Item = (u32, &'a AlignedBlock)> {
 329        self.blocks_snapshot.blocks_in_range(rows)
 330    }
 331
 332    pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
 333        self.folds_snapshot.intersects_fold(offset)
 334    }
 335
 336    pub fn is_line_folded(&self, display_row: u32) -> bool {
 337        let block_point = BlockPoint(Point::new(display_row, 0));
 338        let wrap_point = self.blocks_snapshot.to_wrap_point(block_point);
 339        let tab_point = self.wraps_snapshot.to_tab_point(wrap_point);
 340        self.folds_snapshot.is_line_folded(tab_point.row())
 341    }
 342
 343    pub fn is_block_line(&self, display_row: u32) -> bool {
 344        self.blocks_snapshot.is_block_line(display_row)
 345    }
 346
 347    pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
 348        let wrap_row = self
 349            .blocks_snapshot
 350            .to_wrap_point(BlockPoint::new(display_row, 0))
 351            .row();
 352        self.wraps_snapshot.soft_wrap_indent(wrap_row)
 353    }
 354
 355    pub fn text(&self) -> String {
 356        self.text_chunks(0).collect()
 357    }
 358
 359    pub fn line(&self, display_row: u32) -> String {
 360        let mut result = String::new();
 361        for chunk in self.text_chunks(display_row) {
 362            if let Some(ix) = chunk.find('\n') {
 363                result.push_str(&chunk[0..ix]);
 364                break;
 365            } else {
 366                result.push_str(chunk);
 367            }
 368        }
 369        result
 370    }
 371
 372    pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
 373        let mut indent = 0;
 374        let mut is_blank = true;
 375        for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
 376            if c == ' ' {
 377                indent += 1;
 378            } else {
 379                is_blank = c == '\n';
 380                break;
 381            }
 382        }
 383        (indent, is_blank)
 384    }
 385
 386    pub fn line_len(&self, row: u32) -> u32 {
 387        self.blocks_snapshot.line_len(row)
 388    }
 389
 390    pub fn longest_row(&self) -> u32 {
 391        self.blocks_snapshot.longest_row()
 392    }
 393}
 394
 395#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 396pub struct DisplayPoint(BlockPoint);
 397
 398impl DisplayPoint {
 399    pub fn new(row: u32, column: u32) -> Self {
 400        Self(BlockPoint(Point::new(row, column)))
 401    }
 402
 403    pub fn zero() -> Self {
 404        Self::new(0, 0)
 405    }
 406
 407    #[cfg(test)]
 408    pub fn is_zero(&self) -> bool {
 409        self.0.is_zero()
 410    }
 411
 412    pub fn row(self) -> u32 {
 413        self.0.row
 414    }
 415
 416    pub fn column(self) -> u32 {
 417        self.0.column
 418    }
 419
 420    pub fn row_mut(&mut self) -> &mut u32 {
 421        &mut self.0.row
 422    }
 423
 424    pub fn column_mut(&mut self) -> &mut u32 {
 425        &mut self.0.column
 426    }
 427
 428    pub fn to_point(self, map: &DisplaySnapshot) -> Point {
 429        map.display_point_to_point(self, Bias::Left)
 430    }
 431
 432    pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
 433        let unblocked_point = map.blocks_snapshot.to_wrap_point(self.0);
 434        let unwrapped_point = map.wraps_snapshot.to_tab_point(unblocked_point);
 435        let unexpanded_point = map.tabs_snapshot.to_fold_point(unwrapped_point, bias).0;
 436        unexpanded_point.to_buffer_offset(&map.folds_snapshot)
 437    }
 438}
 439
 440impl ToDisplayPoint for usize {
 441    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 442        map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
 443    }
 444}
 445
 446impl ToDisplayPoint for Point {
 447    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 448        map.point_to_display_point(*self, Bias::Left)
 449    }
 450}
 451
 452impl ToDisplayPoint for Anchor {
 453    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 454        self.to_point(&map.buffer_snapshot).to_display_point(map)
 455    }
 456}
 457
 458#[cfg(test)]
 459mod tests {
 460    use super::*;
 461    use crate::{movement, test::*};
 462    use gpui::{color::Color, MutableAppContext};
 463    use language::{Buffer, Language, LanguageConfig, RandomCharIter, SelectionGoal};
 464    use rand::{prelude::StdRng, Rng};
 465    use std::{env, sync::Arc};
 466    use theme::SyntaxTheme;
 467    use util::test::sample_text;
 468    use Bias::*;
 469
 470    #[gpui::test(iterations = 100)]
 471    async fn test_random(mut cx: gpui::TestAppContext, mut rng: StdRng) {
 472        cx.foreground().set_block_on_ticks(0..=50);
 473        cx.foreground().forbid_parking();
 474        let operations = env::var("OPERATIONS")
 475            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
 476            .unwrap_or(10);
 477
 478        let font_cache = cx.font_cache().clone();
 479        let tab_size = rng.gen_range(1..=4);
 480        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 481        let font_id = font_cache
 482            .select_font(family_id, &Default::default())
 483            .unwrap();
 484        let font_size = 14.0;
 485        let max_wrap_width = 300.0;
 486        let mut wrap_width = if rng.gen_bool(0.1) {
 487            None
 488        } else {
 489            Some(rng.gen_range(0.0..=max_wrap_width))
 490        };
 491
 492        log::info!("tab size: {}", tab_size);
 493        log::info!("wrap width: {:?}", wrap_width);
 494
 495        let buffer = cx.update(|cx| {
 496            let len = rng.gen_range(0..10);
 497            let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
 498            MultiBuffer::build_simple(&text, cx)
 499        });
 500
 501        let map = cx.add_model(|cx| {
 502            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
 503        });
 504        let (_observer, notifications) = Observer::new(&map, &mut cx);
 505        let mut fold_count = 0;
 506
 507        for _i in 0..operations {
 508            match rng.gen_range(0..100) {
 509                0..=19 => {
 510                    wrap_width = if rng.gen_bool(0.2) {
 511                        None
 512                    } else {
 513                        Some(rng.gen_range(0.0..=max_wrap_width))
 514                    };
 515                    log::info!("setting wrap width to {:?}", wrap_width);
 516                    map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
 517                }
 518                20..=80 => {
 519                    let mut ranges = Vec::new();
 520                    for _ in 0..rng.gen_range(1..=3) {
 521                        buffer.read_with(&cx, |buffer, _| {
 522                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
 523                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
 524                            ranges.push(start..end);
 525                        });
 526                    }
 527
 528                    if rng.gen() && fold_count > 0 {
 529                        log::info!("unfolding ranges: {:?}", ranges);
 530                        map.update(&mut cx, |map, cx| {
 531                            map.unfold(ranges, cx);
 532                        });
 533                    } else {
 534                        log::info!("folding ranges: {:?}", ranges);
 535                        map.update(&mut cx, |map, cx| {
 536                            map.fold(ranges, cx);
 537                        });
 538                    }
 539                }
 540                _ => {
 541                    buffer.update(&mut cx, |buffer, cx| buffer.randomly_edit(&mut rng, 5, cx));
 542                }
 543            }
 544
 545            if map.read_with(&cx, |map, cx| map.is_rewrapping(cx)) {
 546                notifications.recv().await.unwrap();
 547            }
 548
 549            let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
 550            fold_count = snapshot.fold_count();
 551            log::info!("buffer text: {:?}", buffer.read_with(&cx, |b, _| b.text()));
 552            log::info!("display text: {:?}", snapshot.text());
 553
 554            // Line boundaries
 555            for _ in 0..5 {
 556                let row = rng.gen_range(0..=snapshot.max_point().row());
 557                let column = rng.gen_range(0..=snapshot.line_len(row));
 558                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
 559
 560                let (prev_display_bound, prev_buffer_bound) = snapshot.prev_row_boundary(point);
 561                let (next_display_bound, next_buffer_bound) = snapshot.next_row_boundary(point);
 562
 563                assert!(prev_display_bound <= point);
 564                assert!(next_display_bound >= point);
 565                assert_eq!(prev_buffer_bound.column, 0);
 566                assert_eq!(prev_display_bound.column(), 0);
 567                if next_display_bound < snapshot.max_point() {
 568                    assert_eq!(
 569                        buffer.read_with(&cx, |buffer, _| buffer
 570                            .as_snapshot()
 571                            .chars_at(next_buffer_bound)
 572                            .next()),
 573                        Some('\n')
 574                    )
 575                }
 576
 577                assert_eq!(
 578                    prev_display_bound,
 579                    prev_buffer_bound.to_display_point(&snapshot),
 580                    "row boundary before {:?}. reported buffer row boundary: {:?}",
 581                    point,
 582                    prev_buffer_bound
 583                );
 584                assert_eq!(
 585                    next_display_bound,
 586                    next_buffer_bound.to_display_point(&snapshot),
 587                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
 588                    point,
 589                    next_buffer_bound
 590                );
 591                assert_eq!(
 592                    prev_buffer_bound,
 593                    prev_display_bound.to_point(&snapshot),
 594                    "row boundary before {:?}. reported display row boundary: {:?}",
 595                    point,
 596                    prev_display_bound
 597                );
 598                assert_eq!(
 599                    next_buffer_bound,
 600                    next_display_bound.to_point(&snapshot),
 601                    "row boundary after {:?}. reported display row boundary: {:?}",
 602                    point,
 603                    next_display_bound
 604                );
 605            }
 606
 607            // Movement
 608            for _ in 0..5 {
 609                let row = rng.gen_range(0..=snapshot.max_point().row());
 610                let column = rng.gen_range(0..=snapshot.line_len(row));
 611                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
 612
 613                log::info!("Moving from point {:?}", point);
 614
 615                let moved_right = movement::right(&snapshot, point).unwrap();
 616                log::info!("Right {:?}", moved_right);
 617                if point < snapshot.max_point() {
 618                    assert!(moved_right > point);
 619                    if point.column() == snapshot.line_len(point.row())
 620                        || snapshot.soft_wrap_indent(point.row()).is_some()
 621                            && point.column() == snapshot.line_len(point.row()) - 1
 622                    {
 623                        assert!(moved_right.row() > point.row());
 624                    }
 625                } else {
 626                    assert_eq!(moved_right, point);
 627                }
 628
 629                let moved_left = movement::left(&snapshot, point).unwrap();
 630                log::info!("Left {:?}", moved_left);
 631                if !point.is_zero() {
 632                    assert!(moved_left < point);
 633                    if point.column() == 0 {
 634                        assert!(moved_left.row() < point.row());
 635                    }
 636                } else {
 637                    assert!(moved_left.is_zero());
 638                }
 639            }
 640        }
 641    }
 642
 643    #[gpui::test(retries = 5)]
 644    fn test_soft_wraps(cx: &mut MutableAppContext) {
 645        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
 646        cx.foreground().forbid_parking();
 647
 648        let font_cache = cx.font_cache();
 649
 650        let tab_size = 4;
 651        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 652        let font_id = font_cache
 653            .select_font(family_id, &Default::default())
 654            .unwrap();
 655        let font_size = 12.0;
 656        let wrap_width = Some(64.);
 657
 658        let text = "one two three four five\nsix seven eight";
 659        let buffer = MultiBuffer::build_simple(text, cx);
 660        let map = cx.add_model(|cx| {
 661            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
 662        });
 663
 664        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 665        assert_eq!(
 666            snapshot.text_chunks(0).collect::<String>(),
 667            "one two \nthree four \nfive\nsix seven \neight"
 668        );
 669        assert_eq!(
 670            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
 671            DisplayPoint::new(0, 7)
 672        );
 673        assert_eq!(
 674            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
 675            DisplayPoint::new(1, 0)
 676        );
 677        assert_eq!(
 678            movement::right(&snapshot, DisplayPoint::new(0, 7)).unwrap(),
 679            DisplayPoint::new(1, 0)
 680        );
 681        assert_eq!(
 682            movement::left(&snapshot, DisplayPoint::new(1, 0)).unwrap(),
 683            DisplayPoint::new(0, 7)
 684        );
 685        assert_eq!(
 686            movement::up(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None).unwrap(),
 687            (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
 688        );
 689        assert_eq!(
 690            movement::down(
 691                &snapshot,
 692                DisplayPoint::new(0, 7),
 693                SelectionGoal::Column(10)
 694            )
 695            .unwrap(),
 696            (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
 697        );
 698        assert_eq!(
 699            movement::down(
 700                &snapshot,
 701                DisplayPoint::new(1, 10),
 702                SelectionGoal::Column(10)
 703            )
 704            .unwrap(),
 705            (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
 706        );
 707
 708        buffer.update(cx, |buffer, cx| {
 709            let ix = buffer.text().find("seven").unwrap();
 710            buffer.edit(vec![ix..ix], "and ", cx);
 711        });
 712
 713        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 714        assert_eq!(
 715            snapshot.text_chunks(1).collect::<String>(),
 716            "three four \nfive\nsix and \nseven eight"
 717        );
 718
 719        // Re-wrap on font size changes
 720        map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
 721
 722        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 723        assert_eq!(
 724            snapshot.text_chunks(1).collect::<String>(),
 725            "three \nfour five\nsix and \nseven \neight"
 726        )
 727    }
 728
 729    #[gpui::test]
 730    fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
 731        let text = sample_text(6, 6, 'a');
 732        let buffer = MultiBuffer::build_simple(&text, cx);
 733        let tab_size = 4;
 734        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
 735        let font_id = cx
 736            .font_cache()
 737            .select_font(family_id, &Default::default())
 738            .unwrap();
 739        let font_size = 14.0;
 740        let map = cx.add_model(|cx| {
 741            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
 742        });
 743        buffer.update(cx, |buffer, cx| {
 744            buffer.edit(
 745                vec![
 746                    Point::new(1, 0)..Point::new(1, 0),
 747                    Point::new(1, 1)..Point::new(1, 1),
 748                    Point::new(2, 1)..Point::new(2, 1),
 749                ],
 750                "\t",
 751                cx,
 752            )
 753        });
 754
 755        assert_eq!(
 756            map.update(cx, |map, cx| map.snapshot(cx))
 757                .text_chunks(1)
 758                .collect::<String>()
 759                .lines()
 760                .next(),
 761            Some("    b   bbbbb")
 762        );
 763        assert_eq!(
 764            map.update(cx, |map, cx| map.snapshot(cx))
 765                .text_chunks(2)
 766                .collect::<String>()
 767                .lines()
 768                .next(),
 769            Some("c   ccccc")
 770        );
 771    }
 772
 773    #[gpui::test]
 774    async fn test_chunks(mut cx: gpui::TestAppContext) {
 775        use unindent::Unindent as _;
 776
 777        let text = r#"
 778            fn outer() {}
 779
 780            mod module {
 781                fn inner() {}
 782            }"#
 783        .unindent();
 784
 785        let theme = SyntaxTheme::new(vec![
 786            ("mod.body".to_string(), Color::red().into()),
 787            ("fn.name".to_string(), Color::blue().into()),
 788        ]);
 789        let lang = Arc::new(
 790            Language::new(
 791                LanguageConfig {
 792                    name: "Test".to_string(),
 793                    path_suffixes: vec![".test".to_string()],
 794                    ..Default::default()
 795                },
 796                Some(tree_sitter_rust::language()),
 797            )
 798            .with_highlights_query(
 799                r#"
 800                (mod_item name: (identifier) body: _ @mod.body)
 801                (function_item name: (identifier) @fn.name)
 802                "#,
 803            )
 804            .unwrap(),
 805        );
 806        lang.set_theme(&theme);
 807
 808        let buffer =
 809            cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
 810        buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
 811        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 812
 813        let tab_size = 2;
 814        let font_cache = cx.font_cache();
 815        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 816        let font_id = font_cache
 817            .select_font(family_id, &Default::default())
 818            .unwrap();
 819        let font_size = 14.0;
 820
 821        let map =
 822            cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
 823        assert_eq!(
 824            cx.update(|cx| chunks(0..5, &map, &theme, cx)),
 825            vec![
 826                ("fn ".to_string(), None),
 827                ("outer".to_string(), Some(Color::blue())),
 828                ("() {}\n\nmod module ".to_string(), None),
 829                ("{\n    fn ".to_string(), Some(Color::red())),
 830                ("inner".to_string(), Some(Color::blue())),
 831                ("() {}\n}".to_string(), Some(Color::red())),
 832            ]
 833        );
 834        assert_eq!(
 835            cx.update(|cx| chunks(3..5, &map, &theme, cx)),
 836            vec![
 837                ("    fn ".to_string(), Some(Color::red())),
 838                ("inner".to_string(), Some(Color::blue())),
 839                ("() {}\n}".to_string(), Some(Color::red())),
 840            ]
 841        );
 842
 843        map.update(&mut cx, |map, cx| {
 844            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
 845        });
 846        assert_eq!(
 847            cx.update(|cx| chunks(0..2, &map, &theme, cx)),
 848            vec![
 849                ("fn ".to_string(), None),
 850                ("out".to_string(), Some(Color::blue())),
 851                ("".to_string(), None),
 852                ("  fn ".to_string(), Some(Color::red())),
 853                ("inner".to_string(), Some(Color::blue())),
 854                ("() {}\n}".to_string(), Some(Color::red())),
 855            ]
 856        );
 857    }
 858
 859    #[gpui::test]
 860    async fn test_chunks_with_soft_wrapping(mut cx: gpui::TestAppContext) {
 861        use unindent::Unindent as _;
 862
 863        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
 864
 865        let text = r#"
 866            fn outer() {}
 867
 868            mod module {
 869                fn inner() {}
 870            }"#
 871        .unindent();
 872
 873        let theme = SyntaxTheme::new(vec![
 874            ("mod.body".to_string(), Color::red().into()),
 875            ("fn.name".to_string(), Color::blue().into()),
 876        ]);
 877        let lang = Arc::new(
 878            Language::new(
 879                LanguageConfig {
 880                    name: "Test".to_string(),
 881                    path_suffixes: vec![".test".to_string()],
 882                    ..Default::default()
 883                },
 884                Some(tree_sitter_rust::language()),
 885            )
 886            .with_highlights_query(
 887                r#"
 888                (mod_item name: (identifier) body: _ @mod.body)
 889                (function_item name: (identifier) @fn.name)
 890                "#,
 891            )
 892            .unwrap(),
 893        );
 894        lang.set_theme(&theme);
 895
 896        let buffer =
 897            cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
 898        buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
 899        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 900
 901        let font_cache = cx.font_cache();
 902
 903        let tab_size = 4;
 904        let family_id = font_cache.load_family(&["Courier"]).unwrap();
 905        let font_id = font_cache
 906            .select_font(family_id, &Default::default())
 907            .unwrap();
 908        let font_size = 16.0;
 909
 910        let map = cx
 911            .add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, Some(40.0), cx));
 912        assert_eq!(
 913            cx.update(|cx| chunks(0..5, &map, &theme, cx)),
 914            [
 915                ("fn \n".to_string(), None),
 916                ("oute\nr".to_string(), Some(Color::blue())),
 917                ("() \n{}\n\n".to_string(), None),
 918            ]
 919        );
 920        assert_eq!(
 921            cx.update(|cx| chunks(3..5, &map, &theme, cx)),
 922            [("{}\n\n".to_string(), None)]
 923        );
 924
 925        map.update(&mut cx, |map, cx| {
 926            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
 927        });
 928        assert_eq!(
 929            cx.update(|cx| chunks(1..4, &map, &theme, cx)),
 930            [
 931                ("out".to_string(), Some(Color::blue())),
 932                ("\n".to_string(), None),
 933                ("  \nfn ".to_string(), Some(Color::red())),
 934                ("i\n".to_string(), Some(Color::blue()))
 935            ]
 936        );
 937    }
 938
 939    #[gpui::test]
 940    fn test_clip_point(cx: &mut gpui::MutableAppContext) {
 941        use Bias::{Left, Right};
 942
 943        let text = "\n'a', 'α',\t'✋',\t'❎', '🍐'\n";
 944        let display_text = "\n'a', 'α',   '✋',    '❎', '🍐'\n";
 945        let buffer = MultiBuffer::build_simple(text, cx);
 946
 947        let tab_size = 4;
 948        let font_cache = cx.font_cache();
 949        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 950        let font_id = font_cache
 951            .select_font(family_id, &Default::default())
 952            .unwrap();
 953        let font_size = 14.0;
 954        let map = cx.add_model(|cx| {
 955            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
 956        });
 957        let map = map.update(cx, |map, cx| map.snapshot(cx));
 958
 959        assert_eq!(map.text(), display_text);
 960        for (input_column, bias, output_column) in vec![
 961            ("'a', '".len(), Left, "'a', '".len()),
 962            ("'a', '".len() + 1, Left, "'a', '".len()),
 963            ("'a', '".len() + 1, Right, "'a', 'α".len()),
 964            ("'a', 'α', ".len(), Left, "'a', 'α',".len()),
 965            ("'a', 'α', ".len(), Right, "'a', 'α',   ".len()),
 966            ("'a', 'α',   '".len() + 1, Left, "'a', 'α',   '".len()),
 967            ("'a', 'α',   '".len() + 1, Right, "'a', 'α',   '✋".len()),
 968            ("'a', 'α',   '✋',".len(), Right, "'a', 'α',   '✋',".len()),
 969            ("'a', 'α',   '✋', ".len(), Left, "'a', 'α',   '✋',".len()),
 970            (
 971                "'a', 'α',   '✋', ".len(),
 972                Right,
 973                "'a', 'α',   '✋',    ".len(),
 974            ),
 975        ] {
 976            assert_eq!(
 977                map.clip_point(DisplayPoint::new(1, input_column as u32), bias),
 978                DisplayPoint::new(1, output_column as u32),
 979                "clip_point(({}, {}))",
 980                1,
 981                input_column,
 982            );
 983        }
 984    }
 985
 986    #[gpui::test]
 987    fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
 988        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
 989        let buffer = MultiBuffer::build_simple(text, cx);
 990        let tab_size = 4;
 991        let font_cache = cx.font_cache();
 992        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 993        let font_id = font_cache
 994            .select_font(family_id, &Default::default())
 995            .unwrap();
 996        let font_size = 14.0;
 997
 998        let map = cx.add_model(|cx| {
 999            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1000        });
1001        let map = map.update(cx, |map, cx| map.snapshot(cx));
1002        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
1003        assert_eq!(
1004            map.text_chunks(0).collect::<String>(),
1005            "✅       α\nβ   \n🏀β      γ"
1006        );
1007        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \n🏀β      γ");
1008        assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β      γ");
1009
1010        let point = Point::new(0, "\t\t".len() as u32);
1011        let display_point = DisplayPoint::new(0, "".len() as u32);
1012        assert_eq!(point.to_display_point(&map), display_point);
1013        assert_eq!(display_point.to_point(&map), point);
1014
1015        let point = Point::new(1, "β\t".len() as u32);
1016        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1017        assert_eq!(point.to_display_point(&map), display_point);
1018        assert_eq!(display_point.to_point(&map), point,);
1019
1020        let point = Point::new(2, "🏀β\t\t".len() as u32);
1021        let display_point = DisplayPoint::new(2, "🏀β      ".len() as u32);
1022        assert_eq!(point.to_display_point(&map), display_point);
1023        assert_eq!(display_point.to_point(&map), point,);
1024
1025        // Display points inside of expanded tabs
1026        assert_eq!(
1027            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1028            Point::new(0, "\t".len() as u32),
1029        );
1030        assert_eq!(
1031            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1032            Point::new(0, "".len() as u32),
1033        );
1034
1035        // Clipping display points inside of multi-byte characters
1036        assert_eq!(
1037            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Left),
1038            DisplayPoint::new(0, 0)
1039        );
1040        assert_eq!(
1041            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Bias::Right),
1042            DisplayPoint::new(0, "".len() as u32)
1043        );
1044    }
1045
1046    #[gpui::test]
1047    fn test_max_point(cx: &mut gpui::MutableAppContext) {
1048        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1049        let tab_size = 4;
1050        let font_cache = cx.font_cache();
1051        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1052        let font_id = font_cache
1053            .select_font(family_id, &Default::default())
1054            .unwrap();
1055        let font_size = 14.0;
1056        let map = cx.add_model(|cx| {
1057            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1058        });
1059        assert_eq!(
1060            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1061            DisplayPoint::new(1, 11)
1062        )
1063    }
1064
1065    fn chunks<'a>(
1066        rows: Range<u32>,
1067        map: &ModelHandle<DisplayMap>,
1068        theme: &'a SyntaxTheme,
1069        cx: &mut MutableAppContext,
1070    ) -> Vec<(String, Option<Color>)> {
1071        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1072        let mut chunks: Vec<(String, Option<Color>)> = Vec::new();
1073        for chunk in snapshot.chunks(rows, Some(theme)) {
1074            let color = chunk.highlight_style.map(|s| s.color);
1075            if let Some((last_chunk, last_color)) = chunks.last_mut() {
1076                if color == *last_color {
1077                    last_chunk.push_str(chunk.text);
1078                } else {
1079                    chunks.push((chunk.text.to_string(), color));
1080                }
1081            } else {
1082                chunks.push((chunk.text.to_string(), color));
1083            }
1084        }
1085        chunks
1086    }
1087}