display_map.rs

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