wrap_map.rs

   1use super::{
   2    Highlights,
   3    dimensions::RowDelta,
   4    fold_map::{Chunk, FoldRows},
   5    tab_map::{self, TabEdit, TabPoint, TabSnapshot},
   6};
   7use gpui::{App, AppContext as _, Context, Entity, Font, LineWrapper, Pixels, Task};
   8use language::Point;
   9use multi_buffer::{MultiBufferSnapshot, RowInfo};
  10use smol::future::yield_now;
  11use std::{cmp, collections::VecDeque, mem, ops::Range, sync::LazyLock, time::Duration};
  12use sum_tree::{Bias, Cursor, Dimensions, SumTree};
  13use text::Patch;
  14
  15pub use super::tab_map::TextSummary;
  16pub type WrapEdit = text::Edit<WrapRow>;
  17pub type WrapPatch = text::Patch<WrapRow>;
  18
  19#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
  20pub struct WrapRow(pub u32);
  21
  22impl_for_row_types! {
  23    WrapRow => RowDelta
  24}
  25
  26/// Handles soft wrapping of text.
  27///
  28/// See the [`display_map` module documentation](crate::display_map) for more information.
  29pub struct WrapMap {
  30    snapshot: WrapSnapshot,
  31    pending_edits: VecDeque<(TabSnapshot, Vec<TabEdit>)>,
  32    interpolated_edits: WrapPatch,
  33    edits_since_sync: WrapPatch,
  34    wrap_width: Option<Pixels>,
  35    background_task: Option<Task<()>>,
  36    font_with_size: (Font, Pixels),
  37}
  38
  39#[derive(Clone)]
  40pub struct WrapSnapshot {
  41    pub(super) tab_snapshot: TabSnapshot,
  42    transforms: SumTree<Transform>,
  43    interpolated: bool,
  44}
  45
  46impl std::ops::Deref for WrapSnapshot {
  47    type Target = TabSnapshot;
  48
  49    fn deref(&self) -> &Self::Target {
  50        &self.tab_snapshot
  51    }
  52}
  53
  54#[derive(Clone, Debug, Default, Eq, PartialEq)]
  55struct Transform {
  56    summary: TransformSummary,
  57    display_text: Option<&'static str>,
  58}
  59
  60#[derive(Clone, Debug, Default, Eq, PartialEq)]
  61struct TransformSummary {
  62    input: TextSummary,
  63    output: TextSummary,
  64}
  65
  66#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
  67pub struct WrapPoint(pub Point);
  68
  69pub struct WrapChunks<'a> {
  70    input_chunks: tab_map::TabChunks<'a>,
  71    input_chunk: Chunk<'a>,
  72    output_position: WrapPoint,
  73    max_output_row: WrapRow,
  74    transforms: Cursor<'a, 'static, Transform, Dimensions<WrapPoint, TabPoint>>,
  75    snapshot: &'a WrapSnapshot,
  76}
  77
  78#[derive(Clone)]
  79pub struct WrapRows<'a> {
  80    input_buffer_rows: FoldRows<'a>,
  81    input_buffer_row: RowInfo,
  82    output_row: WrapRow,
  83    soft_wrapped: bool,
  84    max_output_row: WrapRow,
  85    transforms: Cursor<'a, 'static, Transform, Dimensions<WrapPoint, TabPoint>>,
  86}
  87
  88impl WrapRows<'_> {
  89    #[ztracing::instrument(skip_all)]
  90    pub(crate) fn seek(&mut self, start_row: WrapRow) {
  91        self.transforms
  92            .seek(&WrapPoint::new(start_row, 0), Bias::Left);
  93        let mut input_row = self.transforms.start().1.row();
  94        if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
  95            input_row += (start_row - self.transforms.start().0.row()).0;
  96        }
  97        self.soft_wrapped = self.transforms.item().is_some_and(|t| !t.is_isomorphic());
  98        self.input_buffer_rows.seek(input_row);
  99        self.input_buffer_row = self.input_buffer_rows.next().unwrap();
 100        self.output_row = start_row;
 101    }
 102}
 103
 104impl WrapMap {
 105    #[ztracing::instrument(skip_all)]
 106    pub fn new(
 107        tab_snapshot: TabSnapshot,
 108        font: Font,
 109        font_size: Pixels,
 110        wrap_width: Option<Pixels>,
 111        cx: &mut App,
 112    ) -> (Entity<Self>, WrapSnapshot) {
 113        let handle = cx.new(|cx| {
 114            let mut this = Self {
 115                font_with_size: (font, font_size),
 116                wrap_width: None,
 117                pending_edits: Default::default(),
 118                interpolated_edits: Default::default(),
 119                edits_since_sync: Default::default(),
 120                snapshot: WrapSnapshot::new(tab_snapshot),
 121                background_task: None,
 122            };
 123            this.set_wrap_width(wrap_width, cx);
 124            mem::take(&mut this.edits_since_sync);
 125            this
 126        });
 127        let snapshot = handle.read(cx).snapshot.clone();
 128        (handle, snapshot)
 129    }
 130
 131    #[cfg(test)]
 132    pub fn is_rewrapping(&self) -> bool {
 133        self.background_task.is_some()
 134    }
 135
 136    #[ztracing::instrument(skip_all)]
 137    pub fn sync(
 138        &mut self,
 139        tab_snapshot: TabSnapshot,
 140        edits: Vec<TabEdit>,
 141        cx: &mut Context<Self>,
 142    ) -> (WrapSnapshot, WrapPatch) {
 143        if self.wrap_width.is_some() {
 144            self.pending_edits.push_back((tab_snapshot, edits));
 145            self.flush_edits(cx);
 146        } else {
 147            self.edits_since_sync = self
 148                .edits_since_sync
 149                .compose(self.snapshot.interpolate(tab_snapshot, &edits));
 150            self.snapshot.interpolated = false;
 151        }
 152
 153        (self.snapshot.clone(), mem::take(&mut self.edits_since_sync))
 154    }
 155
 156    #[ztracing::instrument(skip_all)]
 157    pub fn set_font_with_size(
 158        &mut self,
 159        font: Font,
 160        font_size: Pixels,
 161        cx: &mut Context<Self>,
 162    ) -> bool {
 163        let font_with_size = (font, font_size);
 164
 165        if font_with_size == self.font_with_size {
 166            false
 167        } else {
 168            self.font_with_size = font_with_size;
 169            self.rewrap(cx);
 170            true
 171        }
 172    }
 173
 174    #[ztracing::instrument(skip_all)]
 175    pub fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut Context<Self>) -> bool {
 176        if wrap_width == self.wrap_width {
 177            return false;
 178        }
 179
 180        self.wrap_width = wrap_width;
 181        self.rewrap(cx);
 182        true
 183    }
 184
 185    #[ztracing::instrument(skip_all)]
 186    fn rewrap(&mut self, cx: &mut Context<Self>) {
 187        self.background_task.take();
 188        self.interpolated_edits.clear();
 189        self.pending_edits.clear();
 190
 191        if let Some(wrap_width) = self.wrap_width {
 192            let mut new_snapshot = self.snapshot.clone();
 193
 194            let text_system = cx.text_system().clone();
 195            let (font, font_size) = self.font_with_size.clone();
 196            let task = cx.background_spawn(async move {
 197                let mut line_wrapper = text_system.line_wrapper(font, font_size);
 198                let tab_snapshot = new_snapshot.tab_snapshot.clone();
 199                let range = TabPoint::zero()..tab_snapshot.max_point();
 200                let edits = new_snapshot
 201                    .update(
 202                        tab_snapshot,
 203                        &[TabEdit {
 204                            old: range.clone(),
 205                            new: range.clone(),
 206                        }],
 207                        wrap_width,
 208                        &mut line_wrapper,
 209                    )
 210                    .await;
 211                (new_snapshot, edits)
 212            });
 213
 214            match cx
 215                .background_executor()
 216                .block_with_timeout(Duration::from_millis(5), task)
 217            {
 218                Ok((snapshot, edits)) => {
 219                    self.snapshot = snapshot;
 220                    self.edits_since_sync = self.edits_since_sync.compose(&edits);
 221                }
 222                Err(wrap_task) => {
 223                    self.background_task = Some(cx.spawn(async move |this, cx| {
 224                        let (snapshot, edits) = wrap_task.await;
 225                        this.update(cx, |this, cx| {
 226                            this.snapshot = snapshot;
 227                            this.edits_since_sync = this
 228                                .edits_since_sync
 229                                .compose(mem::take(&mut this.interpolated_edits).invert())
 230                                .compose(&edits);
 231                            this.background_task = None;
 232                            this.flush_edits(cx);
 233                            cx.notify();
 234                        })
 235                        .ok();
 236                    }));
 237                }
 238            }
 239        } else {
 240            let old_rows = self.snapshot.transforms.summary().output.lines.row + 1;
 241            self.snapshot.transforms = SumTree::default();
 242            let summary = self.snapshot.tab_snapshot.text_summary();
 243            if !summary.lines.is_zero() {
 244                self.snapshot
 245                    .transforms
 246                    .push(Transform::isomorphic(summary), ());
 247            }
 248            let new_rows = self.snapshot.transforms.summary().output.lines.row + 1;
 249            self.snapshot.interpolated = false;
 250            self.edits_since_sync = self.edits_since_sync.compose(Patch::new(vec![WrapEdit {
 251                old: WrapRow(0)..WrapRow(old_rows),
 252                new: WrapRow(0)..WrapRow(new_rows),
 253            }]));
 254        }
 255    }
 256
 257    #[ztracing::instrument(skip_all)]
 258    fn flush_edits(&mut self, cx: &mut Context<Self>) {
 259        if !self.snapshot.interpolated {
 260            let mut to_remove_len = 0;
 261            for (tab_snapshot, _) in &self.pending_edits {
 262                if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
 263                    to_remove_len += 1;
 264                } else {
 265                    break;
 266                }
 267            }
 268            self.pending_edits.drain(..to_remove_len);
 269        }
 270
 271        if self.pending_edits.is_empty() {
 272            return;
 273        }
 274
 275        if let Some(wrap_width) = self.wrap_width
 276            && self.background_task.is_none()
 277        {
 278            let pending_edits = self.pending_edits.clone();
 279            let mut snapshot = self.snapshot.clone();
 280            let text_system = cx.text_system().clone();
 281            let (font, font_size) = self.font_with_size.clone();
 282            let update_task = cx.background_spawn(async move {
 283                let mut edits = Patch::default();
 284                let mut line_wrapper = text_system.line_wrapper(font, font_size);
 285                for (tab_snapshot, tab_edits) in pending_edits {
 286                    let wrap_edits = snapshot
 287                        .update(tab_snapshot, &tab_edits, wrap_width, &mut line_wrapper)
 288                        .await;
 289                    edits = edits.compose(&wrap_edits);
 290                }
 291                (snapshot, edits)
 292            });
 293
 294            match cx
 295                .background_executor()
 296                .block_with_timeout(Duration::from_millis(1), update_task)
 297            {
 298                Ok((snapshot, output_edits)) => {
 299                    self.snapshot = snapshot;
 300                    self.edits_since_sync = self.edits_since_sync.compose(&output_edits);
 301                }
 302                Err(update_task) => {
 303                    self.background_task = Some(cx.spawn(async move |this, cx| {
 304                        let (snapshot, edits) = update_task.await;
 305                        this.update(cx, |this, cx| {
 306                            this.snapshot = snapshot;
 307                            this.edits_since_sync = this
 308                                .edits_since_sync
 309                                .compose(mem::take(&mut this.interpolated_edits).invert())
 310                                .compose(&edits);
 311                            this.background_task = None;
 312                            this.flush_edits(cx);
 313                            cx.notify();
 314                        })
 315                        .ok();
 316                    }));
 317                }
 318            }
 319        }
 320
 321        let was_interpolated = self.snapshot.interpolated;
 322        let mut to_remove_len = 0;
 323        for (tab_snapshot, edits) in &self.pending_edits {
 324            if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
 325                to_remove_len += 1;
 326            } else {
 327                let interpolated_edits = self.snapshot.interpolate(tab_snapshot.clone(), edits);
 328                self.edits_since_sync = self.edits_since_sync.compose(&interpolated_edits);
 329                self.interpolated_edits = self.interpolated_edits.compose(&interpolated_edits);
 330            }
 331        }
 332
 333        if !was_interpolated {
 334            self.pending_edits.drain(..to_remove_len);
 335        }
 336    }
 337}
 338
 339impl WrapSnapshot {
 340    #[ztracing::instrument(skip_all)]
 341    fn new(tab_snapshot: TabSnapshot) -> Self {
 342        let mut transforms = SumTree::default();
 343        let extent = tab_snapshot.text_summary();
 344        if !extent.lines.is_zero() {
 345            transforms.push(Transform::isomorphic(extent), ());
 346        }
 347        Self {
 348            transforms,
 349            tab_snapshot,
 350            interpolated: true,
 351        }
 352    }
 353
 354    #[ztracing::instrument(skip_all)]
 355    pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
 356        self.tab_snapshot.buffer_snapshot()
 357    }
 358
 359    #[ztracing::instrument(skip_all)]
 360    fn interpolate(&mut self, new_tab_snapshot: TabSnapshot, tab_edits: &[TabEdit]) -> WrapPatch {
 361        let mut new_transforms;
 362        if tab_edits.is_empty() {
 363            new_transforms = self.transforms.clone();
 364        } else {
 365            let mut old_cursor = self.transforms.cursor::<TabPoint>(());
 366
 367            let mut tab_edits_iter = tab_edits.iter().peekable();
 368            new_transforms =
 369                old_cursor.slice(&tab_edits_iter.peek().unwrap().old.start, Bias::Right);
 370
 371            while let Some(edit) = tab_edits_iter.next() {
 372                if edit.new.start > TabPoint::from(new_transforms.summary().input.lines) {
 373                    let summary = new_tab_snapshot.text_summary_for_range(
 374                        TabPoint::from(new_transforms.summary().input.lines)..edit.new.start,
 375                    );
 376                    new_transforms.push_or_extend(Transform::isomorphic(summary));
 377                }
 378
 379                if !edit.new.is_empty() {
 380                    new_transforms.push_or_extend(Transform::isomorphic(
 381                        new_tab_snapshot.text_summary_for_range(edit.new.clone()),
 382                    ));
 383                }
 384
 385                old_cursor.seek_forward(&edit.old.end, Bias::Right);
 386                if let Some(next_edit) = tab_edits_iter.peek() {
 387                    if next_edit.old.start > old_cursor.end() {
 388                        if old_cursor.end() > edit.old.end {
 389                            let summary = self
 390                                .tab_snapshot
 391                                .text_summary_for_range(edit.old.end..old_cursor.end());
 392                            new_transforms.push_or_extend(Transform::isomorphic(summary));
 393                        }
 394
 395                        old_cursor.next();
 396                        new_transforms
 397                            .append(old_cursor.slice(&next_edit.old.start, Bias::Right), ());
 398                    }
 399                } else {
 400                    if old_cursor.end() > edit.old.end {
 401                        let summary = self
 402                            .tab_snapshot
 403                            .text_summary_for_range(edit.old.end..old_cursor.end());
 404                        new_transforms.push_or_extend(Transform::isomorphic(summary));
 405                    }
 406                    old_cursor.next();
 407                    new_transforms.append(old_cursor.suffix(), ());
 408                }
 409            }
 410        }
 411
 412        let old_snapshot = mem::replace(
 413            self,
 414            WrapSnapshot {
 415                tab_snapshot: new_tab_snapshot,
 416                transforms: new_transforms,
 417                interpolated: true,
 418            },
 419        );
 420        self.check_invariants();
 421        old_snapshot.compute_edits(tab_edits, self)
 422    }
 423
 424    #[ztracing::instrument(skip_all)]
 425    async fn update(
 426        &mut self,
 427        new_tab_snapshot: TabSnapshot,
 428        tab_edits: &[TabEdit],
 429        wrap_width: Pixels,
 430        line_wrapper: &mut LineWrapper,
 431    ) -> WrapPatch {
 432        #[derive(Debug)]
 433        struct RowEdit {
 434            old_rows: Range<u32>,
 435            new_rows: Range<u32>,
 436        }
 437
 438        let mut tab_edits_iter = tab_edits.iter().peekable();
 439        let mut row_edits = Vec::with_capacity(tab_edits.len());
 440        while let Some(edit) = tab_edits_iter.next() {
 441            let mut row_edit = RowEdit {
 442                old_rows: edit.old.start.row()..edit.old.end.row() + 1,
 443                new_rows: edit.new.start.row()..edit.new.end.row() + 1,
 444            };
 445
 446            while let Some(next_edit) = tab_edits_iter.peek() {
 447                if next_edit.old.start.row() <= row_edit.old_rows.end {
 448                    row_edit.old_rows.end = next_edit.old.end.row() + 1;
 449                    row_edit.new_rows.end = next_edit.new.end.row() + 1;
 450                    tab_edits_iter.next();
 451                } else {
 452                    break;
 453                }
 454            }
 455
 456            row_edits.push(row_edit);
 457        }
 458
 459        let mut new_transforms;
 460        if row_edits.is_empty() {
 461            new_transforms = self.transforms.clone();
 462        } else {
 463            let mut row_edits = row_edits.into_iter().peekable();
 464            let mut old_cursor = self.transforms.cursor::<TabPoint>(());
 465
 466            new_transforms = old_cursor.slice(
 467                &TabPoint::new(row_edits.peek().unwrap().old_rows.start, 0),
 468                Bias::Right,
 469            );
 470
 471            while let Some(edit) = row_edits.next() {
 472                if edit.new_rows.start > new_transforms.summary().input.lines.row {
 473                    let summary = new_tab_snapshot.text_summary_for_range(
 474                        TabPoint(new_transforms.summary().input.lines)
 475                            ..TabPoint::new(edit.new_rows.start, 0),
 476                    );
 477                    new_transforms.push_or_extend(Transform::isomorphic(summary));
 478                }
 479
 480                let mut line = String::new();
 481                let mut line_fragments = Vec::new();
 482                let mut remaining = None;
 483                let mut chunks = new_tab_snapshot.chunks(
 484                    TabPoint::new(edit.new_rows.start, 0)..new_tab_snapshot.max_point(),
 485                    false,
 486                    Highlights::default(),
 487                );
 488                let mut edit_transforms = Vec::<Transform>::new();
 489                for _ in edit.new_rows.start..edit.new_rows.end {
 490                    while let Some(chunk) = remaining.take().or_else(|| chunks.next()) {
 491                        if let Some(ix) = chunk.text.find('\n') {
 492                            let (prefix, suffix) = chunk.text.split_at(ix + 1);
 493                            line_fragments.push(gpui::LineFragment::text(prefix));
 494                            line.push_str(prefix);
 495                            remaining = Some(Chunk {
 496                                text: suffix,
 497                                ..chunk
 498                            });
 499                            break;
 500                        } else {
 501                            if let Some(width) =
 502                                chunk.renderer.as_ref().and_then(|r| r.measured_width)
 503                            {
 504                                line_fragments
 505                                    .push(gpui::LineFragment::element(width, chunk.text.len()));
 506                            } else {
 507                                line_fragments.push(gpui::LineFragment::text(chunk.text));
 508                            }
 509                            line.push_str(chunk.text);
 510                        }
 511                    }
 512
 513                    if line.is_empty() {
 514                        break;
 515                    }
 516
 517                    let mut prev_boundary_ix = 0;
 518                    for boundary in line_wrapper.wrap_line(&line_fragments, wrap_width) {
 519                        let wrapped = &line[prev_boundary_ix..boundary.ix];
 520                        push_isomorphic(&mut edit_transforms, TextSummary::from(wrapped));
 521                        edit_transforms.push(Transform::wrap(boundary.next_indent));
 522                        prev_boundary_ix = boundary.ix;
 523                    }
 524
 525                    if prev_boundary_ix < line.len() {
 526                        push_isomorphic(
 527                            &mut edit_transforms,
 528                            TextSummary::from(&line[prev_boundary_ix..]),
 529                        );
 530                    }
 531
 532                    line.clear();
 533                    line_fragments.clear();
 534                    yield_now().await;
 535                }
 536
 537                let mut edit_transforms = edit_transforms.into_iter();
 538                if let Some(transform) = edit_transforms.next() {
 539                    new_transforms.push_or_extend(transform);
 540                }
 541                new_transforms.extend(edit_transforms, ());
 542
 543                old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right);
 544                if let Some(next_edit) = row_edits.peek() {
 545                    if next_edit.old_rows.start > old_cursor.end().row() {
 546                        if old_cursor.end() > TabPoint::new(edit.old_rows.end, 0) {
 547                            let summary = self.tab_snapshot.text_summary_for_range(
 548                                TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(),
 549                            );
 550                            new_transforms.push_or_extend(Transform::isomorphic(summary));
 551                        }
 552                        old_cursor.next();
 553                        new_transforms.append(
 554                            old_cursor
 555                                .slice(&TabPoint::new(next_edit.old_rows.start, 0), Bias::Right),
 556                            (),
 557                        );
 558                    }
 559                } else {
 560                    if old_cursor.end() > TabPoint::new(edit.old_rows.end, 0) {
 561                        let summary = self.tab_snapshot.text_summary_for_range(
 562                            TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(),
 563                        );
 564                        new_transforms.push_or_extend(Transform::isomorphic(summary));
 565                    }
 566                    old_cursor.next();
 567                    new_transforms.append(old_cursor.suffix(), ());
 568                }
 569            }
 570        }
 571
 572        let old_snapshot = mem::replace(
 573            self,
 574            WrapSnapshot {
 575                tab_snapshot: new_tab_snapshot,
 576                transforms: new_transforms,
 577                interpolated: false,
 578            },
 579        );
 580        self.check_invariants();
 581        old_snapshot.compute_edits(tab_edits, self)
 582    }
 583
 584    #[ztracing::instrument(skip_all)]
 585    fn compute_edits(&self, tab_edits: &[TabEdit], new_snapshot: &WrapSnapshot) -> WrapPatch {
 586        let mut wrap_edits = Vec::with_capacity(tab_edits.len());
 587        let mut old_cursor = self.transforms.cursor::<TransformSummary>(());
 588        let mut new_cursor = new_snapshot.transforms.cursor::<TransformSummary>(());
 589        for mut tab_edit in tab_edits.iter().cloned() {
 590            tab_edit.old.start.0.column = 0;
 591            tab_edit.old.end.0 += Point::new(1, 0);
 592            tab_edit.new.start.0.column = 0;
 593            tab_edit.new.end.0 += Point::new(1, 0);
 594
 595            old_cursor.seek(&tab_edit.old.start, Bias::Right);
 596            let mut old_start = old_cursor.start().output.lines;
 597            old_start += tab_edit.old.start.0 - old_cursor.start().input.lines;
 598
 599            old_cursor.seek_forward(&tab_edit.old.end, Bias::Right);
 600            let mut old_end = old_cursor.start().output.lines;
 601            old_end += tab_edit.old.end.0 - old_cursor.start().input.lines;
 602
 603            new_cursor.seek(&tab_edit.new.start, Bias::Right);
 604            let mut new_start = new_cursor.start().output.lines;
 605            new_start += tab_edit.new.start.0 - new_cursor.start().input.lines;
 606
 607            new_cursor.seek_forward(&tab_edit.new.end, Bias::Right);
 608            let mut new_end = new_cursor.start().output.lines;
 609            new_end += tab_edit.new.end.0 - new_cursor.start().input.lines;
 610
 611            wrap_edits.push(WrapEdit {
 612                old: WrapRow(old_start.row)..WrapRow(old_end.row),
 613                new: WrapRow(new_start.row)..WrapRow(new_end.row),
 614            });
 615        }
 616
 617        wrap_edits = consolidate_wrap_edits(wrap_edits);
 618        Patch::new(wrap_edits)
 619    }
 620
 621    #[ztracing::instrument(skip_all)]
 622    pub(crate) fn chunks<'a>(
 623        &'a self,
 624        rows: Range<WrapRow>,
 625        language_aware: bool,
 626        highlights: Highlights<'a>,
 627    ) -> WrapChunks<'a> {
 628        let output_start = WrapPoint::new(rows.start, 0);
 629        let output_end = WrapPoint::new(rows.end, 0);
 630        let mut transforms = self
 631            .transforms
 632            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
 633        transforms.seek(&output_start, Bias::Right);
 634        let mut input_start = TabPoint(transforms.start().1.0);
 635        if transforms.item().is_some_and(|t| t.is_isomorphic()) {
 636            input_start.0 += output_start.0 - transforms.start().0.0;
 637        }
 638        let input_end = self.to_tab_point(output_end);
 639        let max_point = self.tab_snapshot.max_point();
 640        let input_start = input_start.min(max_point);
 641        let input_end = input_end.min(max_point);
 642        WrapChunks {
 643            input_chunks: self.tab_snapshot.chunks(
 644                input_start..input_end,
 645                language_aware,
 646                highlights,
 647            ),
 648            input_chunk: Default::default(),
 649            output_position: output_start,
 650            max_output_row: rows.end,
 651            transforms,
 652            snapshot: self,
 653        }
 654    }
 655
 656    #[ztracing::instrument(skip_all)]
 657    pub fn max_point(&self) -> WrapPoint {
 658        WrapPoint(self.transforms.summary().output.lines)
 659    }
 660
 661    #[ztracing::instrument(skip_all)]
 662    pub fn line_len(&self, row: WrapRow) -> u32 {
 663        let (start, _, item) = self.transforms.find::<Dimensions<WrapPoint, TabPoint>, _>(
 664            (),
 665            &WrapPoint::new(row + WrapRow(1), 0),
 666            Bias::Left,
 667        );
 668        if item.is_some_and(|transform| transform.is_isomorphic()) {
 669            let overshoot = row - start.0.row();
 670            let tab_row = start.1.row() + overshoot.0;
 671            let tab_line_len = self.tab_snapshot.line_len(tab_row);
 672            if overshoot.0 == 0 {
 673                start.0.column() + (tab_line_len - start.1.column())
 674            } else {
 675                tab_line_len
 676            }
 677        } else {
 678            start.0.column()
 679        }
 680    }
 681
 682    #[ztracing::instrument(skip_all, fields(rows))]
 683    pub fn text_summary_for_range(&self, rows: Range<WrapRow>) -> TextSummary {
 684        let mut summary = TextSummary::default();
 685
 686        let start = WrapPoint::new(rows.start, 0);
 687        let end = WrapPoint::new(rows.end, 0);
 688
 689        let mut cursor = self
 690            .transforms
 691            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
 692        cursor.seek(&start, Bias::Right);
 693        if let Some(transform) = cursor.item() {
 694            let start_in_transform = start.0 - cursor.start().0.0;
 695            let end_in_transform = cmp::min(end, cursor.end().0).0 - cursor.start().0.0;
 696            if transform.is_isomorphic() {
 697                let tab_start = TabPoint(cursor.start().1.0 + start_in_transform);
 698                let tab_end = TabPoint(cursor.start().1.0 + end_in_transform);
 699                summary += &self.tab_snapshot.text_summary_for_range(tab_start..tab_end);
 700            } else {
 701                debug_assert_eq!(start_in_transform.row, end_in_transform.row);
 702                let indent_len = end_in_transform.column - start_in_transform.column;
 703                summary += &TextSummary {
 704                    lines: Point::new(0, indent_len),
 705                    first_line_chars: indent_len,
 706                    last_line_chars: indent_len,
 707                    longest_row: 0,
 708                    longest_row_chars: indent_len,
 709                };
 710            }
 711
 712            cursor.next();
 713        }
 714
 715        if rows.end > cursor.start().0.row() {
 716            summary += &cursor
 717                .summary::<_, TransformSummary>(&WrapPoint::new(rows.end, 0), Bias::Right)
 718                .output;
 719
 720            if let Some(transform) = cursor.item() {
 721                let end_in_transform = end.0 - cursor.start().0.0;
 722                if transform.is_isomorphic() {
 723                    let char_start = cursor.start().1;
 724                    let char_end = TabPoint(char_start.0 + end_in_transform);
 725                    summary += &self
 726                        .tab_snapshot
 727                        .text_summary_for_range(char_start..char_end);
 728                } else {
 729                    debug_assert_eq!(end_in_transform, Point::new(1, 0));
 730                    summary += &TextSummary {
 731                        lines: Point::new(1, 0),
 732                        first_line_chars: 0,
 733                        last_line_chars: 0,
 734                        longest_row: 0,
 735                        longest_row_chars: 0,
 736                    };
 737                }
 738            }
 739        }
 740
 741        summary
 742    }
 743
 744    #[ztracing::instrument(skip_all)]
 745    pub fn soft_wrap_indent(&self, row: WrapRow) -> Option<u32> {
 746        let (.., item) = self.transforms.find::<WrapPoint, _>(
 747            (),
 748            &WrapPoint::new(row + WrapRow(1), 0),
 749            Bias::Right,
 750        );
 751        item.and_then(|transform| {
 752            if transform.is_isomorphic() {
 753                None
 754            } else {
 755                Some(transform.summary.output.lines.column)
 756            }
 757        })
 758    }
 759
 760    #[ztracing::instrument(skip_all)]
 761    pub fn longest_row(&self) -> u32 {
 762        self.transforms.summary().output.longest_row
 763    }
 764
 765    #[ztracing::instrument(skip_all)]
 766    pub fn row_infos(&self, start_row: WrapRow) -> WrapRows<'_> {
 767        let mut transforms = self
 768            .transforms
 769            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
 770        transforms.seek(&WrapPoint::new(start_row, 0), Bias::Left);
 771        let mut input_row = transforms.start().1.row();
 772        if transforms.item().is_some_and(|t| t.is_isomorphic()) {
 773            input_row += (start_row - transforms.start().0.row()).0;
 774        }
 775        let soft_wrapped = transforms.item().is_some_and(|t| !t.is_isomorphic());
 776        let mut input_buffer_rows = self.tab_snapshot.rows(input_row);
 777        let input_buffer_row = input_buffer_rows.next().unwrap();
 778        WrapRows {
 779            transforms,
 780            input_buffer_row,
 781            input_buffer_rows,
 782            output_row: start_row,
 783            soft_wrapped,
 784            max_output_row: self.max_point().row(),
 785        }
 786    }
 787
 788    #[ztracing::instrument(skip_all)]
 789    pub fn to_tab_point(&self, point: WrapPoint) -> TabPoint {
 790        let (start, _, item) =
 791            self.transforms
 792                .find::<Dimensions<WrapPoint, TabPoint>, _>((), &point, Bias::Right);
 793        let mut tab_point = start.1.0;
 794        if item.is_some_and(|t| t.is_isomorphic()) {
 795            tab_point += point.0 - start.0.0;
 796        }
 797        TabPoint(tab_point)
 798    }
 799
 800    #[ztracing::instrument(skip_all)]
 801    pub fn to_point(&self, point: WrapPoint, bias: Bias) -> Point {
 802        self.tab_snapshot
 803            .tab_point_to_point(self.to_tab_point(point), bias)
 804    }
 805
 806    #[ztracing::instrument(skip_all)]
 807    pub fn make_wrap_point(&self, point: Point, bias: Bias) -> WrapPoint {
 808        self.tab_point_to_wrap_point(self.tab_snapshot.point_to_tab_point(point, bias))
 809    }
 810
 811    #[ztracing::instrument(skip_all)]
 812    pub fn tab_point_to_wrap_point(&self, point: TabPoint) -> WrapPoint {
 813        let (start, ..) =
 814            self.transforms
 815                .find::<Dimensions<TabPoint, WrapPoint>, _>((), &point, Bias::Right);
 816        WrapPoint(start.1.0 + (point.0 - start.0.0))
 817    }
 818
 819    #[ztracing::instrument(skip_all)]
 820    pub fn wrap_point_cursor(&self) -> WrapPointCursor<'_> {
 821        WrapPointCursor {
 822            cursor: self
 823                .transforms
 824                .cursor::<Dimensions<TabPoint, WrapPoint>>(()),
 825        }
 826    }
 827
 828    #[ztracing::instrument(skip_all)]
 829    pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
 830        if bias == Bias::Left {
 831            let (start, _, item) = self
 832                .transforms
 833                .find::<WrapPoint, _>((), &point, Bias::Right);
 834            if item.is_some_and(|t| !t.is_isomorphic()) {
 835                point = start;
 836                *point.column_mut() -= 1;
 837            }
 838        }
 839
 840        self.tab_point_to_wrap_point(self.tab_snapshot.clip_point(self.to_tab_point(point), bias))
 841    }
 842
 843    #[ztracing::instrument(skip_all, fields(point=?point, ret))]
 844    pub fn prev_row_boundary(&self, mut point: WrapPoint) -> WrapRow {
 845        if self.transforms.is_empty() {
 846            return WrapRow(0);
 847        }
 848
 849        *point.column_mut() = 0;
 850
 851        let mut cursor = self
 852            .transforms
 853            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
 854        // start
 855        cursor.seek(&point, Bias::Right);
 856        // end
 857        if cursor.item().is_none() {
 858            cursor.prev();
 859        }
 860
 861        // start
 862        while let Some(transform) = cursor.item() {
 863            if transform.is_isomorphic() && cursor.start().1.column() == 0 {
 864                return cmp::min(cursor.end().0.row(), point.row());
 865            } else {
 866                cursor.prev();
 867            }
 868        }
 869        // end
 870
 871        unreachable!()
 872    }
 873
 874    #[ztracing::instrument(skip_all)]
 875    pub fn next_row_boundary(&self, mut point: WrapPoint) -> Option<WrapRow> {
 876        point.0 += Point::new(1, 0);
 877
 878        let mut cursor = self
 879            .transforms
 880            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
 881        cursor.seek(&point, Bias::Right);
 882        while let Some(transform) = cursor.item() {
 883            if transform.is_isomorphic() && cursor.start().1.column() == 0 {
 884                return Some(cmp::max(cursor.start().0.row(), point.row()));
 885            } else {
 886                cursor.next();
 887            }
 888        }
 889
 890        None
 891    }
 892
 893    #[cfg(test)]
 894    #[ztracing::instrument(skip_all)]
 895    pub fn text(&self) -> String {
 896        self.text_chunks(WrapRow(0)).collect()
 897    }
 898
 899    #[cfg(test)]
 900    #[ztracing::instrument(skip_all)]
 901    pub fn text_chunks(&self, wrap_row: WrapRow) -> impl Iterator<Item = &str> {
 902        self.chunks(
 903            wrap_row..self.max_point().row() + WrapRow(1),
 904            false,
 905            Highlights::default(),
 906        )
 907        .map(|h| h.text)
 908    }
 909
 910    #[ztracing::instrument(skip_all)]
 911    fn check_invariants(&self) {
 912        #[cfg(test)]
 913        {
 914            assert_eq!(
 915                TabPoint::from(self.transforms.summary().input.lines),
 916                self.tab_snapshot.max_point()
 917            );
 918
 919            {
 920                let mut transforms = self.transforms.cursor::<()>(()).peekable();
 921                while let Some(transform) = transforms.next() {
 922                    if let Some(next_transform) = transforms.peek() {
 923                        assert!(transform.is_isomorphic() != next_transform.is_isomorphic());
 924                    }
 925                }
 926            }
 927
 928            let text = language::Rope::from(self.text().as_str());
 929            let mut input_buffer_rows = self.tab_snapshot.rows(0);
 930            let mut expected_buffer_rows = Vec::new();
 931            let mut prev_tab_row = 0;
 932            for display_row in 0..=self.max_point().row().0 {
 933                let display_row = WrapRow(display_row);
 934                let tab_point = self.to_tab_point(WrapPoint::new(display_row, 0));
 935                if tab_point.row() == prev_tab_row && display_row != WrapRow(0) {
 936                    expected_buffer_rows.push(None);
 937                } else {
 938                    expected_buffer_rows.push(input_buffer_rows.next().unwrap().buffer_row);
 939                }
 940
 941                prev_tab_row = tab_point.row();
 942                assert_eq!(self.line_len(display_row), text.line_len(display_row.0));
 943            }
 944
 945            for start_display_row in 0..expected_buffer_rows.len() {
 946                assert_eq!(
 947                    self.row_infos(WrapRow(start_display_row as u32))
 948                        .map(|row_info| row_info.buffer_row)
 949                        .collect::<Vec<_>>(),
 950                    &expected_buffer_rows[start_display_row..],
 951                    "invalid buffer_rows({}..)",
 952                    start_display_row
 953                );
 954            }
 955        }
 956    }
 957}
 958
 959pub struct WrapPointCursor<'transforms> {
 960    cursor: Cursor<'transforms, 'static, Transform, Dimensions<TabPoint, WrapPoint>>,
 961}
 962
 963impl WrapPointCursor<'_> {
 964    #[ztracing::instrument(skip_all)]
 965    pub fn map(&mut self, point: TabPoint) -> WrapPoint {
 966        let cursor = &mut self.cursor;
 967        if cursor.did_seek() {
 968            cursor.seek_forward(&point, Bias::Right);
 969        } else {
 970            cursor.seek(&point, Bias::Right);
 971        }
 972        WrapPoint(cursor.start().1.0 + (point.0 - cursor.start().0.0))
 973    }
 974}
 975
 976impl WrapChunks<'_> {
 977    #[ztracing::instrument(skip_all)]
 978    pub(crate) fn seek(&mut self, rows: Range<WrapRow>) {
 979        let output_start = WrapPoint::new(rows.start, 0);
 980        let output_end = WrapPoint::new(rows.end, 0);
 981        self.transforms.seek(&output_start, Bias::Right);
 982        let mut input_start = TabPoint(self.transforms.start().1.0);
 983        if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
 984            input_start.0 += output_start.0 - self.transforms.start().0.0;
 985        }
 986        let input_end = self.snapshot.to_tab_point(output_end);
 987        let max_point = self.snapshot.tab_snapshot.max_point();
 988        let input_start = input_start.min(max_point);
 989        let input_end = input_end.min(max_point);
 990        self.input_chunks.seek(input_start..input_end);
 991        self.input_chunk = Chunk::default();
 992        self.output_position = output_start;
 993        self.max_output_row = rows.end;
 994    }
 995}
 996
 997impl<'a> Iterator for WrapChunks<'a> {
 998    type Item = Chunk<'a>;
 999
1000    #[ztracing::instrument(skip_all)]
1001    fn next(&mut self) -> Option<Self::Item> {
1002        if self.output_position.row() >= self.max_output_row {
1003            return None;
1004        }
1005
1006        let transform = self.transforms.item()?;
1007        if let Some(display_text) = transform.display_text {
1008            let mut start_ix = 0;
1009            let mut end_ix = display_text.len();
1010            let mut summary = transform.summary.output.lines;
1011
1012            if self.output_position > self.transforms.start().0 {
1013                // Exclude newline starting prior to the desired row.
1014                start_ix = 1;
1015                summary.row = 0;
1016            } else if self.output_position.row() + WrapRow(1) >= self.max_output_row {
1017                // Exclude soft indentation ending after the desired row.
1018                end_ix = 1;
1019                summary.column = 0;
1020            }
1021
1022            self.output_position.0 += summary;
1023            self.transforms.next();
1024            return Some(Chunk {
1025                text: &display_text[start_ix..end_ix],
1026                ..Default::default()
1027            });
1028        }
1029
1030        if self.input_chunk.text.is_empty() {
1031            self.input_chunk = self.input_chunks.next()?;
1032        }
1033
1034        let mut input_len = 0;
1035        let transform_end = self.transforms.end().0;
1036        for c in self.input_chunk.text.chars() {
1037            let char_len = c.len_utf8();
1038            input_len += char_len;
1039            if c == '\n' {
1040                *self.output_position.row_mut() += 1;
1041                *self.output_position.column_mut() = 0;
1042            } else {
1043                *self.output_position.column_mut() += char_len as u32;
1044            }
1045
1046            if self.output_position >= transform_end {
1047                self.transforms.next();
1048                break;
1049            }
1050        }
1051
1052        let (prefix, suffix) = self.input_chunk.text.split_at(input_len);
1053
1054        let mask = 1u128.unbounded_shl(input_len as u32).wrapping_sub(1);
1055        let chars = self.input_chunk.chars & mask;
1056        let tabs = self.input_chunk.tabs & mask;
1057        self.input_chunk.tabs = self.input_chunk.tabs.unbounded_shr(input_len as u32);
1058        self.input_chunk.chars = self.input_chunk.chars.unbounded_shr(input_len as u32);
1059
1060        self.input_chunk.text = suffix;
1061        Some(Chunk {
1062            text: prefix,
1063            chars,
1064            tabs,
1065            ..self.input_chunk.clone()
1066        })
1067    }
1068}
1069
1070impl Iterator for WrapRows<'_> {
1071    type Item = RowInfo;
1072
1073    #[ztracing::instrument(skip_all)]
1074    fn next(&mut self) -> Option<Self::Item> {
1075        if self.output_row > self.max_output_row {
1076            return None;
1077        }
1078
1079        let buffer_row = self.input_buffer_row;
1080        let soft_wrapped = self.soft_wrapped;
1081        let diff_status = self.input_buffer_row.diff_status;
1082
1083        self.output_row += WrapRow(1);
1084        self.transforms
1085            .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left);
1086        if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
1087            self.input_buffer_row = self.input_buffer_rows.next().unwrap();
1088            self.soft_wrapped = false;
1089        } else {
1090            self.soft_wrapped = true;
1091        }
1092
1093        Some(if soft_wrapped {
1094            RowInfo {
1095                buffer_id: None,
1096                buffer_row: None,
1097                base_text_row: None,
1098                multibuffer_row: None,
1099                diff_status,
1100                expand_info: None,
1101                wrapped_buffer_row: buffer_row.buffer_row,
1102            }
1103        } else {
1104            buffer_row
1105        })
1106    }
1107}
1108
1109impl Transform {
1110    #[ztracing::instrument(skip_all)]
1111    fn isomorphic(summary: TextSummary) -> Self {
1112        #[cfg(test)]
1113        assert!(!summary.lines.is_zero());
1114
1115        Self {
1116            summary: TransformSummary {
1117                input: summary.clone(),
1118                output: summary,
1119            },
1120            display_text: None,
1121        }
1122    }
1123
1124    #[ztracing::instrument(skip_all)]
1125    fn wrap(indent: u32) -> Self {
1126        static WRAP_TEXT: LazyLock<String> = LazyLock::new(|| {
1127            let mut wrap_text = String::new();
1128            wrap_text.push('\n');
1129            wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
1130            wrap_text
1131        });
1132
1133        Self {
1134            summary: TransformSummary {
1135                input: TextSummary::default(),
1136                output: TextSummary {
1137                    lines: Point::new(1, indent),
1138                    first_line_chars: 0,
1139                    last_line_chars: indent,
1140                    longest_row: 1,
1141                    longest_row_chars: indent,
1142                },
1143            },
1144            display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
1145        }
1146    }
1147
1148    fn is_isomorphic(&self) -> bool {
1149        self.display_text.is_none()
1150    }
1151}
1152
1153impl sum_tree::Item for Transform {
1154    type Summary = TransformSummary;
1155
1156    fn summary(&self, _cx: ()) -> Self::Summary {
1157        self.summary.clone()
1158    }
1159}
1160
1161fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
1162    if let Some(last_transform) = transforms.last_mut()
1163        && last_transform.is_isomorphic()
1164    {
1165        last_transform.summary.input += &summary;
1166        last_transform.summary.output += &summary;
1167        return;
1168    }
1169    transforms.push(Transform::isomorphic(summary));
1170}
1171
1172trait SumTreeExt {
1173    fn push_or_extend(&mut self, transform: Transform);
1174}
1175
1176impl SumTreeExt for SumTree<Transform> {
1177    #[ztracing::instrument(skip_all)]
1178    fn push_or_extend(&mut self, transform: Transform) {
1179        let mut transform = Some(transform);
1180        self.update_last(
1181            |last_transform| {
1182                if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
1183                    let transform = transform.take().unwrap();
1184                    last_transform.summary.input += &transform.summary.input;
1185                    last_transform.summary.output += &transform.summary.output;
1186                }
1187            },
1188            (),
1189        );
1190
1191        if let Some(transform) = transform {
1192            self.push(transform, ());
1193        }
1194    }
1195}
1196
1197impl WrapPoint {
1198    pub fn new(row: WrapRow, column: u32) -> Self {
1199        Self(Point::new(row.0, column))
1200    }
1201
1202    pub fn row(self) -> WrapRow {
1203        WrapRow(self.0.row)
1204    }
1205
1206    pub fn row_mut(&mut self) -> &mut u32 {
1207        &mut self.0.row
1208    }
1209
1210    pub fn column(self) -> u32 {
1211        self.0.column
1212    }
1213
1214    pub fn column_mut(&mut self) -> &mut u32 {
1215        &mut self.0.column
1216    }
1217}
1218
1219impl sum_tree::ContextLessSummary for TransformSummary {
1220    fn zero() -> Self {
1221        Default::default()
1222    }
1223
1224    fn add_summary(&mut self, other: &Self) {
1225        self.input += &other.input;
1226        self.output += &other.output;
1227    }
1228}
1229
1230impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
1231    fn zero(_cx: ()) -> Self {
1232        Default::default()
1233    }
1234
1235    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1236        self.0 += summary.input.lines;
1237    }
1238}
1239
1240impl sum_tree::SeekTarget<'_, TransformSummary, TransformSummary> for TabPoint {
1241    #[ztracing::instrument(skip_all)]
1242    fn cmp(&self, cursor_location: &TransformSummary, _: ()) -> std::cmp::Ordering {
1243        Ord::cmp(&self.0, &cursor_location.input.lines)
1244    }
1245}
1246
1247impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
1248    fn zero(_cx: ()) -> Self {
1249        Default::default()
1250    }
1251
1252    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1253        self.0 += summary.output.lines;
1254    }
1255}
1256
1257fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
1258    let _old_alloc_ptr = edits.as_ptr();
1259    let mut wrap_edits = edits.into_iter();
1260
1261    if let Some(mut first_edit) = wrap_edits.next() {
1262        // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1263        #[allow(clippy::filter_map_identity)]
1264        let mut v: Vec<_> = wrap_edits
1265            .scan(&mut first_edit, |prev_edit, edit| {
1266                if prev_edit.old.end >= edit.old.start {
1267                    prev_edit.old.end = edit.old.end;
1268                    prev_edit.new.end = edit.new.end;
1269                    Some(None) // Skip this edit, it's merged
1270                } else {
1271                    let prev = std::mem::replace(*prev_edit, edit);
1272                    Some(Some(prev)) // Yield the previous edit
1273                }
1274            })
1275            .filter_map(|x| x)
1276            .collect();
1277        v.push(first_edit.clone());
1278        debug_assert_eq!(v.as_ptr(), _old_alloc_ptr, "Wrap edits were reallocated");
1279        v
1280    } else {
1281        vec![]
1282    }
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287    use super::*;
1288    use crate::{
1289        MultiBuffer,
1290        display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
1291        test::test_font,
1292    };
1293    use gpui::{LineFragment, px, test::observe};
1294    use rand::prelude::*;
1295    use settings::SettingsStore;
1296    use smol::stream::StreamExt;
1297    use std::{cmp, env, num::NonZeroU32};
1298    use text::Rope;
1299    use theme::LoadThemes;
1300
1301    #[gpui::test(iterations = 100)]
1302    async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1303        // todo this test is flaky
1304        init_test(cx);
1305
1306        cx.background_executor.set_block_on_ticks(0..=50);
1307        let operations = env::var("OPERATIONS")
1308            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1309            .unwrap_or(10);
1310
1311        let text_system = cx.read(|cx| cx.text_system().clone());
1312        let mut wrap_width = if rng.random_bool(0.1) {
1313            None
1314        } else {
1315            Some(px(rng.random_range(0.0..=1000.0)))
1316        };
1317        let tab_size = NonZeroU32::new(rng.random_range(1..=4)).unwrap();
1318
1319        let font = test_font();
1320        let _font_id = text_system.resolve_font(&font);
1321        let font_size = px(14.0);
1322
1323        log::info!("Tab size: {}", tab_size);
1324        log::info!("Wrap width: {:?}", wrap_width);
1325
1326        let buffer = cx.update(|cx| {
1327            if rng.random() {
1328                MultiBuffer::build_random(&mut rng, cx)
1329            } else {
1330                let len = rng.random_range(0..10);
1331                let text = util::RandomCharIter::new(&mut rng)
1332                    .take(len)
1333                    .collect::<String>();
1334                MultiBuffer::build_simple(&text, cx)
1335            }
1336        });
1337        let mut buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1338        log::info!("Buffer text: {:?}", buffer_snapshot.text());
1339        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1340        log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1341        let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot.clone());
1342        log::info!("FoldMap text: {:?}", fold_snapshot.text());
1343        let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
1344        let tabs_snapshot = tab_map.set_max_expansion_column(32);
1345        log::info!("TabMap text: {:?}", tabs_snapshot.text());
1346
1347        let mut line_wrapper = text_system.line_wrapper(font.clone(), font_size);
1348        let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1349
1350        let (wrap_map, _) =
1351            cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font, font_size, wrap_width, cx));
1352        let mut notifications = observe(&wrap_map, cx);
1353
1354        if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1355            notifications.next().await.unwrap();
1356        }
1357
1358        let (initial_snapshot, _) = wrap_map.update(cx, |map, cx| {
1359            assert!(!map.is_rewrapping());
1360            map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1361        });
1362
1363        let actual_text = initial_snapshot.text();
1364        assert_eq!(
1365            actual_text,
1366            expected_text,
1367            "unwrapped text is: {:?}",
1368            tabs_snapshot.text()
1369        );
1370        log::info!("Wrapped text: {:?}", actual_text);
1371
1372        let mut next_inlay_id = 0;
1373        let mut edits = Vec::new();
1374        for _i in 0..operations {
1375            log::info!("{} ==============================================", _i);
1376
1377            let mut buffer_edits = Vec::new();
1378            match rng.random_range(0..=100) {
1379                0..=19 => {
1380                    wrap_width = if rng.random_bool(0.2) {
1381                        None
1382                    } else {
1383                        Some(px(rng.random_range(0.0..=1000.0)))
1384                    };
1385                    log::info!("Setting wrap width to {:?}", wrap_width);
1386                    wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1387                }
1388                20..=39 => {
1389                    for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1390                        let (tabs_snapshot, tab_edits) =
1391                            tab_map.sync(fold_snapshot, fold_edits, tab_size);
1392                        let (mut snapshot, wrap_edits) =
1393                            wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1394                        snapshot.check_invariants();
1395                        snapshot.verify_chunks(&mut rng);
1396                        edits.push((snapshot, wrap_edits));
1397                    }
1398                }
1399                40..=59 => {
1400                    let (inlay_snapshot, inlay_edits) =
1401                        inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1402                    let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1403                    let (tabs_snapshot, tab_edits) =
1404                        tab_map.sync(fold_snapshot, fold_edits, tab_size);
1405                    let (mut snapshot, wrap_edits) =
1406                        wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1407                    snapshot.check_invariants();
1408                    snapshot.verify_chunks(&mut rng);
1409                    edits.push((snapshot, wrap_edits));
1410                }
1411                _ => {
1412                    buffer.update(cx, |buffer, cx| {
1413                        let subscription = buffer.subscribe();
1414                        let edit_count = rng.random_range(1..=5);
1415                        buffer.randomly_mutate(&mut rng, edit_count, cx);
1416                        buffer_snapshot = buffer.snapshot(cx);
1417                        buffer_edits.extend(subscription.consume());
1418                    });
1419                }
1420            }
1421
1422            log::info!("Buffer text: {:?}", buffer_snapshot.text());
1423            let (inlay_snapshot, inlay_edits) =
1424                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1425            log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1426            let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1427            log::info!("FoldMap text: {:?}", fold_snapshot.text());
1428            let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
1429            log::info!("TabMap text: {:?}", tabs_snapshot.text());
1430
1431            let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1432            let (mut snapshot, wrap_edits) =
1433                wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot.clone(), tab_edits, cx));
1434            snapshot.check_invariants();
1435            snapshot.verify_chunks(&mut rng);
1436            edits.push((snapshot, wrap_edits));
1437
1438            if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) && rng.random_bool(0.4) {
1439                log::info!("Waiting for wrapping to finish");
1440                while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1441                    notifications.next().await.unwrap();
1442                }
1443                wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1444            }
1445
1446            if !wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1447                let (mut wrapped_snapshot, wrap_edits) = wrap_map.update(cx, |map, cx| {
1448                    map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1449                });
1450                let actual_text = wrapped_snapshot.text();
1451                let actual_longest_row = wrapped_snapshot.longest_row();
1452                log::info!("Wrapping finished: {:?}", actual_text);
1453                wrapped_snapshot.check_invariants();
1454                wrapped_snapshot.verify_chunks(&mut rng);
1455                edits.push((wrapped_snapshot.clone(), wrap_edits));
1456                assert_eq!(
1457                    actual_text,
1458                    expected_text,
1459                    "unwrapped text is: {:?}",
1460                    tabs_snapshot.text()
1461                );
1462
1463                let mut summary = TextSummary::default();
1464                for (ix, item) in wrapped_snapshot
1465                    .transforms
1466                    .items(())
1467                    .into_iter()
1468                    .enumerate()
1469                {
1470                    summary += &item.summary.output;
1471                    log::info!("{} summary: {:?}", ix, item.summary.output,);
1472                }
1473
1474                if tab_size.get() == 1
1475                    || !wrapped_snapshot
1476                        .tab_snapshot
1477                        .fold_snapshot
1478                        .text()
1479                        .contains('\t')
1480                {
1481                    let mut expected_longest_rows = Vec::new();
1482                    let mut longest_line_len = -1;
1483                    for (row, line) in expected_text.split('\n').enumerate() {
1484                        let line_char_count = line.chars().count() as isize;
1485                        if line_char_count > longest_line_len {
1486                            expected_longest_rows.clear();
1487                            longest_line_len = line_char_count;
1488                        }
1489                        if line_char_count >= longest_line_len {
1490                            expected_longest_rows.push(row as u32);
1491                        }
1492                    }
1493
1494                    assert!(
1495                        expected_longest_rows.contains(&actual_longest_row),
1496                        "incorrect longest row {}. expected {:?} with length {}",
1497                        actual_longest_row,
1498                        expected_longest_rows,
1499                        longest_line_len,
1500                    )
1501                }
1502            }
1503        }
1504
1505        let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1506        for (snapshot, patch) in edits {
1507            let snapshot_text = Rope::from(snapshot.text().as_str());
1508            for edit in &patch {
1509                let old_start = initial_text.point_to_offset(Point::new(edit.new.start.0, 0));
1510                let old_end = initial_text.point_to_offset(cmp::min(
1511                    Point::new(edit.new.start.0 + (edit.old.end - edit.old.start).0, 0),
1512                    initial_text.max_point(),
1513                ));
1514                let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start.0, 0));
1515                let new_end = snapshot_text.point_to_offset(cmp::min(
1516                    Point::new(edit.new.end.0, 0),
1517                    snapshot_text.max_point(),
1518                ));
1519                let new_text = snapshot_text
1520                    .chunks_in_range(new_start..new_end)
1521                    .collect::<String>();
1522
1523                initial_text.replace(old_start..old_end, &new_text);
1524            }
1525            assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1526        }
1527
1528        if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1529            log::info!("Waiting for wrapping to finish");
1530            while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1531                notifications.next().await.unwrap();
1532            }
1533        }
1534        wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1535    }
1536
1537    fn init_test(cx: &mut gpui::TestAppContext) {
1538        cx.update(|cx| {
1539            let settings = SettingsStore::test(cx);
1540            cx.set_global(settings);
1541            theme::init(LoadThemes::JustBase, cx);
1542        });
1543    }
1544
1545    fn wrap_text(
1546        tab_snapshot: &TabSnapshot,
1547        wrap_width: Option<Pixels>,
1548        line_wrapper: &mut LineWrapper,
1549    ) -> String {
1550        if let Some(wrap_width) = wrap_width {
1551            let mut wrapped_text = String::new();
1552            for (row, line) in tab_snapshot.text().split('\n').enumerate() {
1553                if row > 0 {
1554                    wrapped_text.push('\n');
1555                }
1556
1557                let mut prev_ix = 0;
1558                for boundary in line_wrapper.wrap_line(&[LineFragment::text(line)], wrap_width) {
1559                    wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1560                    wrapped_text.push('\n');
1561                    wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1562                    prev_ix = boundary.ix;
1563                }
1564                wrapped_text.push_str(&line[prev_ix..]);
1565            }
1566
1567            wrapped_text
1568        } else {
1569            tab_snapshot.text()
1570        }
1571    }
1572
1573    impl WrapSnapshot {
1574        fn verify_chunks(&mut self, rng: &mut impl Rng) {
1575            for _ in 0..5 {
1576                let mut end_row = rng.random_range(0..=self.max_point().row().0);
1577                let start_row = rng.random_range(0..=end_row);
1578                end_row += 1;
1579
1580                let mut expected_text = self.text_chunks(WrapRow(start_row)).collect::<String>();
1581                if expected_text.ends_with('\n') {
1582                    expected_text.push('\n');
1583                }
1584                let mut expected_text = expected_text
1585                    .lines()
1586                    .take((end_row - start_row) as usize)
1587                    .collect::<Vec<_>>()
1588                    .join("\n");
1589                if end_row <= self.max_point().row().0 {
1590                    expected_text.push('\n');
1591                }
1592
1593                let actual_text = self
1594                    .chunks(
1595                        WrapRow(start_row)..WrapRow(end_row),
1596                        true,
1597                        Highlights::default(),
1598                    )
1599                    .map(|c| c.text)
1600                    .collect::<String>();
1601                assert_eq!(
1602                    expected_text,
1603                    actual_text,
1604                    "chunks != highlighted_chunks for rows {:?}",
1605                    start_row..end_row
1606                );
1607            }
1608        }
1609    }
1610}