display_map.rs

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