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