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::{BlockStyle, 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<'a>(&'a self, start_row: u32, cx: Option<&'a AppContext>) -> BufferRows<'a> {
 176        self.blocks_snapshot.buffer_rows(start_row, cx)
 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 420pub enum DisplayRow {
 421    Buffer(u32),
 422    Block(BlockId, Option<BlockStyle>),
 423    Wrap,
 424}
 425
 426#[cfg(test)]
 427mod tests {
 428    use super::*;
 429    use crate::{movement, test::*};
 430    use gpui::{color::Color, MutableAppContext};
 431    use language::{Language, LanguageConfig, RandomCharIter, SelectionGoal};
 432    use rand::{prelude::StdRng, Rng};
 433    use std::{env, sync::Arc};
 434    use theme::SyntaxTheme;
 435    use Bias::*;
 436
 437    #[gpui::test(iterations = 100)]
 438    async fn test_random(mut cx: gpui::TestAppContext, mut rng: StdRng) {
 439        cx.foreground().set_block_on_ticks(0..=50);
 440        cx.foreground().forbid_parking();
 441        let operations = env::var("OPERATIONS")
 442            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
 443            .unwrap_or(10);
 444
 445        let font_cache = cx.font_cache().clone();
 446        let tab_size = rng.gen_range(1..=4);
 447        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 448        let font_id = font_cache
 449            .select_font(family_id, &Default::default())
 450            .unwrap();
 451        let font_size = 14.0;
 452        let max_wrap_width = 300.0;
 453        let mut wrap_width = if rng.gen_bool(0.1) {
 454            None
 455        } else {
 456            Some(rng.gen_range(0.0..=max_wrap_width))
 457        };
 458
 459        log::info!("tab size: {}", tab_size);
 460        log::info!("wrap width: {:?}", wrap_width);
 461
 462        let buffer = cx.add_model(|cx| {
 463            let len = rng.gen_range(0..10);
 464            let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
 465            Buffer::new(0, text, cx)
 466        });
 467
 468        let map = cx.add_model(|cx| {
 469            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
 470        });
 471        let (_observer, notifications) = Observer::new(&map, &mut cx);
 472        let mut fold_count = 0;
 473
 474        for _i in 0..operations {
 475            match rng.gen_range(0..100) {
 476                0..=19 => {
 477                    wrap_width = if rng.gen_bool(0.2) {
 478                        None
 479                    } else {
 480                        Some(rng.gen_range(0.0..=max_wrap_width))
 481                    };
 482                    log::info!("setting wrap width to {:?}", wrap_width);
 483                    map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
 484                }
 485                20..=80 => {
 486                    let mut ranges = Vec::new();
 487                    for _ in 0..rng.gen_range(1..=3) {
 488                        buffer.read_with(&cx, |buffer, _| {
 489                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
 490                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
 491                            ranges.push(start..end);
 492                        });
 493                    }
 494
 495                    if rng.gen() && fold_count > 0 {
 496                        log::info!("unfolding ranges: {:?}", ranges);
 497                        map.update(&mut cx, |map, cx| {
 498                            map.unfold(ranges, cx);
 499                        });
 500                    } else {
 501                        log::info!("folding ranges: {:?}", ranges);
 502                        map.update(&mut cx, |map, cx| {
 503                            map.fold(ranges, cx);
 504                        });
 505                    }
 506                }
 507                _ => {
 508                    buffer.update(&mut cx, |buffer, _| buffer.randomly_edit(&mut rng, 5));
 509                }
 510            }
 511
 512            if map.read_with(&cx, |map, cx| map.is_rewrapping(cx)) {
 513                notifications.recv().await.unwrap();
 514            }
 515
 516            let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
 517            fold_count = snapshot.fold_count();
 518            log::info!("buffer text: {:?}", buffer.read_with(&cx, |b, _| b.text()));
 519            log::info!("display text: {:?}", snapshot.text());
 520
 521            // Line boundaries
 522            for _ in 0..5 {
 523                let row = rng.gen_range(0..=snapshot.max_point().row());
 524                let column = rng.gen_range(0..=snapshot.line_len(row));
 525                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
 526
 527                let (prev_display_bound, prev_buffer_bound) = snapshot.prev_row_boundary(point);
 528                let (next_display_bound, next_buffer_bound) = snapshot.next_row_boundary(point);
 529
 530                assert!(prev_display_bound <= point);
 531                assert!(next_display_bound >= point);
 532                assert_eq!(prev_buffer_bound.column, 0);
 533                assert_eq!(prev_display_bound.column(), 0);
 534                if next_display_bound < snapshot.max_point() {
 535                    assert_eq!(
 536                        buffer
 537                            .read_with(&cx, |buffer, _| buffer.chars_at(next_buffer_bound).next()),
 538                        Some('\n')
 539                    )
 540                }
 541
 542                assert_eq!(
 543                    prev_display_bound,
 544                    prev_buffer_bound.to_display_point(&snapshot),
 545                    "row boundary before {:?}. reported buffer row boundary: {:?}",
 546                    point,
 547                    prev_buffer_bound
 548                );
 549                assert_eq!(
 550                    next_display_bound,
 551                    next_buffer_bound.to_display_point(&snapshot),
 552                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
 553                    point,
 554                    next_buffer_bound
 555                );
 556                assert_eq!(
 557                    prev_buffer_bound,
 558                    prev_display_bound.to_point(&snapshot),
 559                    "row boundary before {:?}. reported display row boundary: {:?}",
 560                    point,
 561                    prev_display_bound
 562                );
 563                assert_eq!(
 564                    next_buffer_bound,
 565                    next_display_bound.to_point(&snapshot),
 566                    "row boundary after {:?}. reported display row boundary: {:?}",
 567                    point,
 568                    next_display_bound
 569                );
 570            }
 571
 572            // Movement
 573            for _ in 0..5 {
 574                let row = rng.gen_range(0..=snapshot.max_point().row());
 575                let column = rng.gen_range(0..=snapshot.line_len(row));
 576                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
 577
 578                log::info!("Moving from point {:?}", point);
 579
 580                let moved_right = movement::right(&snapshot, point).unwrap();
 581                log::info!("Right {:?}", moved_right);
 582                if point < snapshot.max_point() {
 583                    assert!(moved_right > point);
 584                    if point.column() == snapshot.line_len(point.row())
 585                        || snapshot.soft_wrap_indent(point.row()).is_some()
 586                            && point.column() == snapshot.line_len(point.row()) - 1
 587                    {
 588                        assert!(moved_right.row() > point.row());
 589                    }
 590                } else {
 591                    assert_eq!(moved_right, point);
 592                }
 593
 594                let moved_left = movement::left(&snapshot, point).unwrap();
 595                log::info!("Left {:?}", moved_left);
 596                if !point.is_zero() {
 597                    assert!(moved_left < point);
 598                    if point.column() == 0 {
 599                        assert!(moved_left.row() < point.row());
 600                    }
 601                } else {
 602                    assert!(moved_left.is_zero());
 603                }
 604            }
 605        }
 606    }
 607
 608    #[gpui::test]
 609    fn test_soft_wraps(cx: &mut MutableAppContext) {
 610        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
 611        cx.foreground().forbid_parking();
 612
 613        let font_cache = cx.font_cache();
 614
 615        let tab_size = 4;
 616        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 617        let font_id = font_cache
 618            .select_font(family_id, &Default::default())
 619            .unwrap();
 620        let font_size = 12.0;
 621        let wrap_width = Some(64.);
 622
 623        let text = "one two three four five\nsix seven eight";
 624        let buffer = cx.add_model(|cx| Buffer::new(0, text.to_string(), cx));
 625        let map = cx.add_model(|cx| {
 626            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
 627        });
 628
 629        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 630        assert_eq!(
 631            snapshot.text_chunks(0).collect::<String>(),
 632            "one two \nthree four \nfive\nsix seven \neight"
 633        );
 634        assert_eq!(
 635            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
 636            DisplayPoint::new(0, 7)
 637        );
 638        assert_eq!(
 639            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
 640            DisplayPoint::new(1, 0)
 641        );
 642        assert_eq!(
 643            movement::right(&snapshot, DisplayPoint::new(0, 7)).unwrap(),
 644            DisplayPoint::new(1, 0)
 645        );
 646        assert_eq!(
 647            movement::left(&snapshot, DisplayPoint::new(1, 0)).unwrap(),
 648            DisplayPoint::new(0, 7)
 649        );
 650        assert_eq!(
 651            movement::up(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None).unwrap(),
 652            (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
 653        );
 654        assert_eq!(
 655            movement::down(
 656                &snapshot,
 657                DisplayPoint::new(0, 7),
 658                SelectionGoal::Column(10)
 659            )
 660            .unwrap(),
 661            (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
 662        );
 663        assert_eq!(
 664            movement::down(
 665                &snapshot,
 666                DisplayPoint::new(1, 10),
 667                SelectionGoal::Column(10)
 668            )
 669            .unwrap(),
 670            (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
 671        );
 672
 673        buffer.update(cx, |buffer, cx| {
 674            let ix = buffer.text().find("seven").unwrap();
 675            buffer.edit(vec![ix..ix], "and ", cx);
 676        });
 677
 678        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 679        assert_eq!(
 680            snapshot.text_chunks(1).collect::<String>(),
 681            "three four \nfive\nsix and \nseven eight"
 682        );
 683
 684        // Re-wrap on font size changes
 685        map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
 686
 687        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 688        assert_eq!(
 689            snapshot.text_chunks(1).collect::<String>(),
 690            "three \nfour five\nsix and \nseven \neight"
 691        )
 692    }
 693
 694    #[gpui::test]
 695    fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
 696        let text = sample_text(6, 6);
 697        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
 698        let tab_size = 4;
 699        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
 700        let font_id = cx
 701            .font_cache()
 702            .select_font(family_id, &Default::default())
 703            .unwrap();
 704        let font_size = 14.0;
 705        let map = cx.add_model(|cx| {
 706            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
 707        });
 708        buffer.update(cx, |buffer, cx| {
 709            buffer.edit(
 710                vec![
 711                    Point::new(1, 0)..Point::new(1, 0),
 712                    Point::new(1, 1)..Point::new(1, 1),
 713                    Point::new(2, 1)..Point::new(2, 1),
 714                ],
 715                "\t",
 716                cx,
 717            )
 718        });
 719
 720        assert_eq!(
 721            map.update(cx, |map, cx| map.snapshot(cx))
 722                .text_chunks(1)
 723                .collect::<String>()
 724                .lines()
 725                .next(),
 726            Some("    b   bbbbb")
 727        );
 728        assert_eq!(
 729            map.update(cx, |map, cx| map.snapshot(cx))
 730                .text_chunks(2)
 731                .collect::<String>()
 732                .lines()
 733                .next(),
 734            Some("c   ccccc")
 735        );
 736    }
 737
 738    #[gpui::test]
 739    async fn test_chunks(mut cx: gpui::TestAppContext) {
 740        use unindent::Unindent as _;
 741
 742        let text = r#"
 743            fn outer() {}
 744
 745            mod module {
 746                fn inner() {}
 747            }"#
 748        .unindent();
 749
 750        let theme = SyntaxTheme::new(vec![
 751            ("mod.body".to_string(), Color::red().into()),
 752            ("fn.name".to_string(), Color::blue().into()),
 753        ]);
 754        let lang = Arc::new(
 755            Language::new(
 756                LanguageConfig {
 757                    name: "Test".to_string(),
 758                    path_suffixes: vec![".test".to_string()],
 759                    ..Default::default()
 760                },
 761                tree_sitter_rust::language(),
 762            )
 763            .with_highlights_query(
 764                r#"
 765                (mod_item name: (identifier) body: _ @mod.body)
 766                (function_item name: (identifier) @fn.name)
 767                "#,
 768            )
 769            .unwrap(),
 770        );
 771        lang.set_theme(&theme);
 772
 773        let buffer =
 774            cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
 775        buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
 776
 777        let tab_size = 2;
 778        let font_cache = cx.font_cache();
 779        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 780        let font_id = font_cache
 781            .select_font(family_id, &Default::default())
 782            .unwrap();
 783        let font_size = 14.0;
 784
 785        let map =
 786            cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
 787        assert_eq!(
 788            cx.update(|cx| chunks(0..5, &map, &theme, cx)),
 789            vec![
 790                ("fn ".to_string(), None),
 791                ("outer".to_string(), Some(Color::blue())),
 792                ("() {}\n\nmod module ".to_string(), None),
 793                ("{\n    fn ".to_string(), Some(Color::red())),
 794                ("inner".to_string(), Some(Color::blue())),
 795                ("() {}\n}".to_string(), Some(Color::red())),
 796            ]
 797        );
 798        assert_eq!(
 799            cx.update(|cx| chunks(3..5, &map, &theme, cx)),
 800            vec![
 801                ("    fn ".to_string(), Some(Color::red())),
 802                ("inner".to_string(), Some(Color::blue())),
 803                ("() {}\n}".to_string(), Some(Color::red())),
 804            ]
 805        );
 806
 807        map.update(&mut cx, |map, cx| {
 808            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
 809        });
 810        assert_eq!(
 811            cx.update(|cx| chunks(0..2, &map, &theme, cx)),
 812            vec![
 813                ("fn ".to_string(), None),
 814                ("out".to_string(), Some(Color::blue())),
 815                ("".to_string(), None),
 816                ("  fn ".to_string(), Some(Color::red())),
 817                ("inner".to_string(), Some(Color::blue())),
 818                ("() {}\n}".to_string(), Some(Color::red())),
 819            ]
 820        );
 821    }
 822
 823    #[gpui::test]
 824    async fn test_chunks_with_soft_wrapping(mut cx: gpui::TestAppContext) {
 825        use unindent::Unindent as _;
 826
 827        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
 828
 829        let text = r#"
 830            fn outer() {}
 831
 832            mod module {
 833                fn inner() {}
 834            }"#
 835        .unindent();
 836
 837        let theme = SyntaxTheme::new(vec![
 838            ("mod.body".to_string(), Color::red().into()),
 839            ("fn.name".to_string(), Color::blue().into()),
 840        ]);
 841        let lang = Arc::new(
 842            Language::new(
 843                LanguageConfig {
 844                    name: "Test".to_string(),
 845                    path_suffixes: vec![".test".to_string()],
 846                    ..Default::default()
 847                },
 848                tree_sitter_rust::language(),
 849            )
 850            .with_highlights_query(
 851                r#"
 852                (mod_item name: (identifier) body: _ @mod.body)
 853                (function_item name: (identifier) @fn.name)
 854                "#,
 855            )
 856            .unwrap(),
 857        );
 858        lang.set_theme(&theme);
 859
 860        let buffer =
 861            cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
 862        buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
 863
 864        let font_cache = cx.font_cache();
 865
 866        let tab_size = 4;
 867        let family_id = font_cache.load_family(&["Courier"]).unwrap();
 868        let font_id = font_cache
 869            .select_font(family_id, &Default::default())
 870            .unwrap();
 871        let font_size = 16.0;
 872
 873        let map = cx
 874            .add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, Some(40.0), cx));
 875        assert_eq!(
 876            cx.update(|cx| chunks(0..5, &map, &theme, cx)),
 877            [
 878                ("fn \n".to_string(), None),
 879                ("oute\nr".to_string(), Some(Color::blue())),
 880                ("() \n{}\n\n".to_string(), None),
 881            ]
 882        );
 883        assert_eq!(
 884            cx.update(|cx| chunks(3..5, &map, &theme, cx)),
 885            [("{}\n\n".to_string(), None)]
 886        );
 887
 888        map.update(&mut cx, |map, cx| {
 889            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
 890        });
 891        assert_eq!(
 892            cx.update(|cx| chunks(1..4, &map, &theme, cx)),
 893            [
 894                ("out".to_string(), Some(Color::blue())),
 895                ("\n".to_string(), None),
 896                ("  \nfn ".to_string(), Some(Color::red())),
 897                ("i\n".to_string(), Some(Color::blue()))
 898            ]
 899        );
 900    }
 901
 902    #[gpui::test]
 903    fn test_clip_point(cx: &mut gpui::MutableAppContext) {
 904        use Bias::{Left, Right};
 905
 906        let text = "\n'a', 'α',\t'✋',\t'❎', '🍐'\n";
 907        let display_text = "\n'a', 'α',   '✋',    '❎', '🍐'\n";
 908        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
 909
 910        let tab_size = 4;
 911        let font_cache = cx.font_cache();
 912        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 913        let font_id = font_cache
 914            .select_font(family_id, &Default::default())
 915            .unwrap();
 916        let font_size = 14.0;
 917        let map = cx.add_model(|cx| {
 918            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
 919        });
 920        let map = map.update(cx, |map, cx| map.snapshot(cx));
 921
 922        assert_eq!(map.text(), display_text);
 923        for (input_column, bias, output_column) in vec![
 924            ("'a', '".len(), Left, "'a', '".len()),
 925            ("'a', '".len() + 1, Left, "'a', '".len()),
 926            ("'a', '".len() + 1, Right, "'a', 'α".len()),
 927            ("'a', 'α', ".len(), Left, "'a', 'α',".len()),
 928            ("'a', 'α', ".len(), Right, "'a', 'α',   ".len()),
 929            ("'a', 'α',   '".len() + 1, Left, "'a', 'α',   '".len()),
 930            ("'a', 'α',   '".len() + 1, Right, "'a', 'α',   '✋".len()),
 931            ("'a', 'α',   '✋',".len(), Right, "'a', 'α',   '✋',".len()),
 932            ("'a', 'α',   '✋', ".len(), Left, "'a', 'α',   '✋',".len()),
 933            (
 934                "'a', 'α',   '✋', ".len(),
 935                Right,
 936                "'a', 'α',   '✋',    ".len(),
 937            ),
 938        ] {
 939            assert_eq!(
 940                map.clip_point(DisplayPoint::new(1, input_column as u32), bias),
 941                DisplayPoint::new(1, output_column as u32),
 942                "clip_point(({}, {}))",
 943                1,
 944                input_column,
 945            );
 946        }
 947    }
 948
 949    #[gpui::test]
 950    fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
 951        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
 952        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
 953        let tab_size = 4;
 954        let font_cache = cx.font_cache();
 955        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 956        let font_id = font_cache
 957            .select_font(family_id, &Default::default())
 958            .unwrap();
 959        let font_size = 14.0;
 960
 961        let map = cx.add_model(|cx| {
 962            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
 963        });
 964        let map = map.update(cx, |map, cx| map.snapshot(cx));
 965        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
 966        assert_eq!(
 967            map.text_chunks(0).collect::<String>(),
 968            "✅       α\nβ   \n🏀β      γ"
 969        );
 970        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \n🏀β      γ");
 971        assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β      γ");
 972
 973        let point = Point::new(0, "\t\t".len() as u32);
 974        let display_point = DisplayPoint::new(0, "".len() as u32);
 975        assert_eq!(point.to_display_point(&map), display_point);
 976        assert_eq!(display_point.to_point(&map), point);
 977
 978        let point = Point::new(1, "β\t".len() as u32);
 979        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
 980        assert_eq!(point.to_display_point(&map), display_point);
 981        assert_eq!(display_point.to_point(&map), point,);
 982
 983        let point = Point::new(2, "🏀β\t\t".len() as u32);
 984        let display_point = DisplayPoint::new(2, "🏀β      ".len() as u32);
 985        assert_eq!(point.to_display_point(&map), display_point);
 986        assert_eq!(display_point.to_point(&map), point,);
 987
 988        // Display points inside of expanded tabs
 989        assert_eq!(
 990            DisplayPoint::new(0, "".len() as u32).to_point(&map),
 991            Point::new(0, "\t".len() as u32),
 992        );
 993        assert_eq!(
 994            DisplayPoint::new(0, "".len() as u32).to_point(&map),
 995            Point::new(0, "".len() as u32),
 996        );
 997
 998        // Clipping display points inside of multi-byte characters
 999        assert_eq!(
1000            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Left),
1001            DisplayPoint::new(0, 0)
1002        );
1003        assert_eq!(
1004            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Bias::Right),
1005            DisplayPoint::new(0, "".len() as u32)
1006        );
1007    }
1008
1009    #[gpui::test]
1010    fn test_max_point(cx: &mut gpui::MutableAppContext) {
1011        let buffer = cx.add_model(|cx| Buffer::new(0, "aaa\n\t\tbbb", cx));
1012        let tab_size = 4;
1013        let font_cache = cx.font_cache();
1014        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1015        let font_id = font_cache
1016            .select_font(family_id, &Default::default())
1017            .unwrap();
1018        let font_size = 14.0;
1019        let map = cx.add_model(|cx| {
1020            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1021        });
1022        assert_eq!(
1023            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1024            DisplayPoint::new(1, 11)
1025        )
1026    }
1027
1028    fn chunks<'a>(
1029        rows: Range<u32>,
1030        map: &ModelHandle<DisplayMap>,
1031        theme: &'a SyntaxTheme,
1032        cx: &mut MutableAppContext,
1033    ) -> Vec<(String, Option<Color>)> {
1034        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1035        let mut chunks: Vec<(String, Option<Color>)> = Vec::new();
1036        for chunk in snapshot.chunks(rows, Some(theme), cx) {
1037            let color = chunk.highlight_style.map(|s| s.color);
1038            if let Some((last_chunk, last_color)) = chunks.last_mut() {
1039                if color == *last_color {
1040                    last_chunk.push_str(chunk.text);
1041                } else {
1042                    chunks.push((chunk.text.to_string(), color));
1043                }
1044            } else {
1045                chunks.push((chunk.text.to_string(), color));
1046            }
1047        }
1048        chunks
1049    }
1050}