display_map.rs

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