display_map.rs

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