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