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