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