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, 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        cursor.seek(&point, Bias::Right);
 855        if cursor.item().is_none() {
 856            cursor.prev();
 857        }
 858
 859        while let Some(transform) = cursor.item() {
 860            if transform.is_isomorphic() && cursor.start().1.column() == 0 {
 861                return cmp::min(cursor.end().0.row(), point.row());
 862            } else {
 863                cursor.prev();
 864            }
 865        }
 866
 867        unreachable!()
 868    }
 869
 870    #[ztracing::instrument(skip_all)]
 871    pub fn next_row_boundary(&self, mut point: WrapPoint) -> Option<WrapRow> {
 872        point.0 += Point::new(1, 0);
 873
 874        let mut cursor = self
 875            .transforms
 876            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
 877        cursor.seek(&point, Bias::Right);
 878        while let Some(transform) = cursor.item() {
 879            if transform.is_isomorphic() && cursor.start().1.column() == 0 {
 880                return Some(cmp::max(cursor.start().0.row(), point.row()));
 881            } else {
 882                cursor.next();
 883            }
 884        }
 885
 886        None
 887    }
 888
 889    #[cfg(test)]
 890    #[ztracing::instrument(skip_all)]
 891    pub fn text(&self) -> String {
 892        self.text_chunks(WrapRow(0)).collect()
 893    }
 894
 895    #[cfg(test)]
 896    #[ztracing::instrument(skip_all)]
 897    pub fn text_chunks(&self, wrap_row: WrapRow) -> impl Iterator<Item = &str> {
 898        self.chunks(
 899            wrap_row..self.max_point().row() + WrapRow(1),
 900            false,
 901            Highlights::default(),
 902        )
 903        .map(|h| h.text)
 904    }
 905
 906    #[ztracing::instrument(skip_all)]
 907    fn check_invariants(&self) {
 908        #[cfg(test)]
 909        {
 910            assert_eq!(
 911                TabPoint::from(self.transforms.summary().input.lines),
 912                self.tab_snapshot.max_point()
 913            );
 914
 915            {
 916                let mut transforms = self.transforms.cursor::<()>(()).peekable();
 917                while let Some(transform) = transforms.next() {
 918                    if let Some(next_transform) = transforms.peek() {
 919                        assert!(transform.is_isomorphic() != next_transform.is_isomorphic());
 920                    }
 921                }
 922            }
 923
 924            let text = language::Rope::from(self.text().as_str());
 925            let mut input_buffer_rows = self.tab_snapshot.rows(0);
 926            let mut expected_buffer_rows = Vec::new();
 927            let mut prev_tab_row = 0;
 928            for display_row in 0..=self.max_point().row().0 {
 929                let display_row = WrapRow(display_row);
 930                let tab_point = self.to_tab_point(WrapPoint::new(display_row, 0));
 931                if tab_point.row() == prev_tab_row && display_row != WrapRow(0) {
 932                    expected_buffer_rows.push(None);
 933                } else {
 934                    expected_buffer_rows.push(input_buffer_rows.next().unwrap().buffer_row);
 935                }
 936
 937                prev_tab_row = tab_point.row();
 938                assert_eq!(self.line_len(display_row), text.line_len(display_row.0));
 939            }
 940
 941            for start_display_row in 0..expected_buffer_rows.len() {
 942                assert_eq!(
 943                    self.row_infos(WrapRow(start_display_row as u32))
 944                        .map(|row_info| row_info.buffer_row)
 945                        .collect::<Vec<_>>(),
 946                    &expected_buffer_rows[start_display_row..],
 947                    "invalid buffer_rows({}..)",
 948                    start_display_row
 949                );
 950            }
 951        }
 952    }
 953}
 954
 955pub struct WrapPointCursor<'transforms> {
 956    cursor: Cursor<'transforms, 'static, Transform, Dimensions<TabPoint, WrapPoint>>,
 957}
 958
 959impl WrapPointCursor<'_> {
 960    #[ztracing::instrument(skip_all)]
 961    pub fn map(&mut self, point: TabPoint) -> WrapPoint {
 962        let cursor = &mut self.cursor;
 963        if cursor.did_seek() {
 964            cursor.seek_forward(&point, Bias::Right);
 965        } else {
 966            cursor.seek(&point, Bias::Right);
 967        }
 968        WrapPoint(cursor.start().1.0 + (point.0 - cursor.start().0.0))
 969    }
 970}
 971
 972impl WrapChunks<'_> {
 973    #[ztracing::instrument(skip_all)]
 974    pub(crate) fn seek(&mut self, rows: Range<WrapRow>) {
 975        let output_start = WrapPoint::new(rows.start, 0);
 976        let output_end = WrapPoint::new(rows.end, 0);
 977        self.transforms.seek(&output_start, Bias::Right);
 978        let mut input_start = TabPoint(self.transforms.start().1.0);
 979        if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
 980            input_start.0 += output_start.0 - self.transforms.start().0.0;
 981        }
 982        let input_end = self.snapshot.to_tab_point(output_end);
 983        let max_point = self.snapshot.tab_snapshot.max_point();
 984        let input_start = input_start.min(max_point);
 985        let input_end = input_end.min(max_point);
 986        self.input_chunks.seek(input_start..input_end);
 987        self.input_chunk = Chunk::default();
 988        self.output_position = output_start;
 989        self.max_output_row = rows.end;
 990    }
 991}
 992
 993impl<'a> Iterator for WrapChunks<'a> {
 994    type Item = Chunk<'a>;
 995
 996    #[ztracing::instrument(skip_all)]
 997    fn next(&mut self) -> Option<Self::Item> {
 998        if self.output_position.row() >= self.max_output_row {
 999            return None;
1000        }
1001
1002        let transform = self.transforms.item()?;
1003        if let Some(display_text) = transform.display_text {
1004            let mut start_ix = 0;
1005            let mut end_ix = display_text.len();
1006            let mut summary = transform.summary.output.lines;
1007
1008            if self.output_position > self.transforms.start().0 {
1009                // Exclude newline starting prior to the desired row.
1010                start_ix = 1;
1011                summary.row = 0;
1012            } else if self.output_position.row() + WrapRow(1) >= self.max_output_row {
1013                // Exclude soft indentation ending after the desired row.
1014                end_ix = 1;
1015                summary.column = 0;
1016            }
1017
1018            self.output_position.0 += summary;
1019            self.transforms.next();
1020            return Some(Chunk {
1021                text: &display_text[start_ix..end_ix],
1022                ..Default::default()
1023            });
1024        }
1025
1026        if self.input_chunk.text.is_empty() {
1027            self.input_chunk = self.input_chunks.next()?;
1028        }
1029
1030        let mut input_len = 0;
1031        let transform_end = self.transforms.end().0;
1032        for c in self.input_chunk.text.chars() {
1033            let char_len = c.len_utf8();
1034            input_len += char_len;
1035            if c == '\n' {
1036                *self.output_position.row_mut() += 1;
1037                *self.output_position.column_mut() = 0;
1038            } else {
1039                *self.output_position.column_mut() += char_len as u32;
1040            }
1041
1042            if self.output_position >= transform_end {
1043                self.transforms.next();
1044                break;
1045            }
1046        }
1047
1048        let (prefix, suffix) = self.input_chunk.text.split_at(input_len);
1049
1050        let mask = 1u128.unbounded_shl(input_len as u32).wrapping_sub(1);
1051        let chars = self.input_chunk.chars & mask;
1052        let tabs = self.input_chunk.tabs & mask;
1053        self.input_chunk.tabs = self.input_chunk.tabs.unbounded_shr(input_len as u32);
1054        self.input_chunk.chars = self.input_chunk.chars.unbounded_shr(input_len as u32);
1055
1056        self.input_chunk.text = suffix;
1057        Some(Chunk {
1058            text: prefix,
1059            chars,
1060            tabs,
1061            ..self.input_chunk.clone()
1062        })
1063    }
1064}
1065
1066impl Iterator for WrapRows<'_> {
1067    type Item = RowInfo;
1068
1069    #[ztracing::instrument(skip_all)]
1070    fn next(&mut self) -> Option<Self::Item> {
1071        if self.output_row > self.max_output_row {
1072            return None;
1073        }
1074
1075        let buffer_row = self.input_buffer_row;
1076        let soft_wrapped = self.soft_wrapped;
1077        let diff_status = self.input_buffer_row.diff_status;
1078
1079        self.output_row += WrapRow(1);
1080        self.transforms
1081            .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left);
1082        if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
1083            self.input_buffer_row = self.input_buffer_rows.next().unwrap();
1084            self.soft_wrapped = false;
1085        } else {
1086            self.soft_wrapped = true;
1087        }
1088
1089        Some(if soft_wrapped {
1090            RowInfo {
1091                buffer_id: None,
1092                buffer_row: None,
1093                base_text_row: None,
1094                multibuffer_row: None,
1095                diff_status,
1096                expand_info: None,
1097                wrapped_buffer_row: buffer_row.buffer_row,
1098            }
1099        } else {
1100            buffer_row
1101        })
1102    }
1103}
1104
1105impl Transform {
1106    #[ztracing::instrument(skip_all)]
1107    fn isomorphic(summary: TextSummary) -> Self {
1108        #[cfg(test)]
1109        assert!(!summary.lines.is_zero());
1110
1111        Self {
1112            summary: TransformSummary {
1113                input: summary.clone(),
1114                output: summary,
1115            },
1116            display_text: None,
1117        }
1118    }
1119
1120    #[ztracing::instrument(skip_all)]
1121    fn wrap(indent: u32) -> Self {
1122        static WRAP_TEXT: LazyLock<String> = LazyLock::new(|| {
1123            let mut wrap_text = String::new();
1124            wrap_text.push('\n');
1125            wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
1126            wrap_text
1127        });
1128
1129        Self {
1130            summary: TransformSummary {
1131                input: TextSummary::default(),
1132                output: TextSummary {
1133                    lines: Point::new(1, indent),
1134                    first_line_chars: 0,
1135                    last_line_chars: indent,
1136                    longest_row: 1,
1137                    longest_row_chars: indent,
1138                },
1139            },
1140            display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
1141        }
1142    }
1143
1144    fn is_isomorphic(&self) -> bool {
1145        self.display_text.is_none()
1146    }
1147}
1148
1149impl sum_tree::Item for Transform {
1150    type Summary = TransformSummary;
1151
1152    fn summary(&self, _cx: ()) -> Self::Summary {
1153        self.summary.clone()
1154    }
1155}
1156
1157fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
1158    if let Some(last_transform) = transforms.last_mut()
1159        && last_transform.is_isomorphic()
1160    {
1161        last_transform.summary.input += &summary;
1162        last_transform.summary.output += &summary;
1163        return;
1164    }
1165    transforms.push(Transform::isomorphic(summary));
1166}
1167
1168trait SumTreeExt {
1169    fn push_or_extend(&mut self, transform: Transform);
1170}
1171
1172impl SumTreeExt for SumTree<Transform> {
1173    #[ztracing::instrument(skip_all)]
1174    fn push_or_extend(&mut self, transform: Transform) {
1175        let mut transform = Some(transform);
1176        self.update_last(
1177            |last_transform| {
1178                if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
1179                    let transform = transform.take().unwrap();
1180                    last_transform.summary.input += &transform.summary.input;
1181                    last_transform.summary.output += &transform.summary.output;
1182                }
1183            },
1184            (),
1185        );
1186
1187        if let Some(transform) = transform {
1188            self.push(transform, ());
1189        }
1190    }
1191}
1192
1193impl WrapPoint {
1194    pub fn new(row: WrapRow, column: u32) -> Self {
1195        Self(Point::new(row.0, column))
1196    }
1197
1198    pub fn row(self) -> WrapRow {
1199        WrapRow(self.0.row)
1200    }
1201
1202    pub fn row_mut(&mut self) -> &mut u32 {
1203        &mut self.0.row
1204    }
1205
1206    pub fn column(self) -> u32 {
1207        self.0.column
1208    }
1209
1210    pub fn column_mut(&mut self) -> &mut u32 {
1211        &mut self.0.column
1212    }
1213}
1214
1215impl sum_tree::ContextLessSummary for TransformSummary {
1216    fn zero() -> Self {
1217        Default::default()
1218    }
1219
1220    fn add_summary(&mut self, other: &Self) {
1221        self.input += &other.input;
1222        self.output += &other.output;
1223    }
1224}
1225
1226impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
1227    fn zero(_cx: ()) -> Self {
1228        Default::default()
1229    }
1230
1231    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1232        self.0 += summary.input.lines;
1233    }
1234}
1235
1236impl sum_tree::SeekTarget<'_, TransformSummary, TransformSummary> for TabPoint {
1237    #[ztracing::instrument(skip_all)]
1238    fn cmp(&self, cursor_location: &TransformSummary, _: ()) -> std::cmp::Ordering {
1239        Ord::cmp(&self.0, &cursor_location.input.lines)
1240    }
1241}
1242
1243impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
1244    fn zero(_cx: ()) -> Self {
1245        Default::default()
1246    }
1247
1248    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1249        self.0 += summary.output.lines;
1250    }
1251}
1252
1253fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
1254    let _old_alloc_ptr = edits.as_ptr();
1255    let mut wrap_edits = edits.into_iter();
1256
1257    if let Some(mut first_edit) = wrap_edits.next() {
1258        // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1259        #[allow(clippy::filter_map_identity)]
1260        let mut v: Vec<_> = wrap_edits
1261            .scan(&mut first_edit, |prev_edit, edit| {
1262                if prev_edit.old.end >= edit.old.start {
1263                    prev_edit.old.end = edit.old.end;
1264                    prev_edit.new.end = edit.new.end;
1265                    Some(None) // Skip this edit, it's merged
1266                } else {
1267                    let prev = std::mem::replace(*prev_edit, edit);
1268                    Some(Some(prev)) // Yield the previous edit
1269                }
1270            })
1271            .filter_map(|x| x)
1272            .collect();
1273        v.push(first_edit.clone());
1274        debug_assert_eq!(v.as_ptr(), _old_alloc_ptr, "Wrap edits were reallocated");
1275        v
1276    } else {
1277        vec![]
1278    }
1279}
1280
1281#[cfg(test)]
1282mod tests {
1283    use super::*;
1284    use crate::{
1285        MultiBuffer,
1286        display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
1287        test::test_font,
1288    };
1289    use gpui::{LineFragment, px, test::observe};
1290    use rand::prelude::*;
1291    use settings::SettingsStore;
1292    use smol::stream::StreamExt;
1293    use std::{cmp, env, num::NonZeroU32};
1294    use text::Rope;
1295    use theme::LoadThemes;
1296
1297    #[gpui::test(iterations = 100)]
1298    async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1299        // todo this test is flaky
1300        init_test(cx);
1301
1302        cx.background_executor.set_block_on_ticks(0..=50);
1303        let operations = env::var("OPERATIONS")
1304            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1305            .unwrap_or(10);
1306
1307        let text_system = cx.read(|cx| cx.text_system().clone());
1308        let mut wrap_width = if rng.random_bool(0.1) {
1309            None
1310        } else {
1311            Some(px(rng.random_range(0.0..=1000.0)))
1312        };
1313        let tab_size = NonZeroU32::new(rng.random_range(1..=4)).unwrap();
1314
1315        let font = test_font();
1316        let _font_id = text_system.resolve_font(&font);
1317        let font_size = px(14.0);
1318
1319        log::info!("Tab size: {}", tab_size);
1320        log::info!("Wrap width: {:?}", wrap_width);
1321
1322        let buffer = cx.update(|cx| {
1323            if rng.random() {
1324                MultiBuffer::build_random(&mut rng, cx)
1325            } else {
1326                let len = rng.random_range(0..10);
1327                let text = util::RandomCharIter::new(&mut rng)
1328                    .take(len)
1329                    .collect::<String>();
1330                MultiBuffer::build_simple(&text, cx)
1331            }
1332        });
1333        let mut buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1334        log::info!("Buffer text: {:?}", buffer_snapshot.text());
1335        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1336        log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1337        let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot.clone());
1338        log::info!("FoldMap text: {:?}", fold_snapshot.text());
1339        let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
1340        let tabs_snapshot = tab_map.set_max_expansion_column(32);
1341        log::info!("TabMap text: {:?}", tabs_snapshot.text());
1342
1343        let mut line_wrapper = text_system.line_wrapper(font.clone(), font_size);
1344        let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1345
1346        let (wrap_map, _) =
1347            cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font, font_size, wrap_width, cx));
1348        let mut notifications = observe(&wrap_map, cx);
1349
1350        if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1351            notifications.next().await.unwrap();
1352        }
1353
1354        let (initial_snapshot, _) = wrap_map.update(cx, |map, cx| {
1355            assert!(!map.is_rewrapping());
1356            map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1357        });
1358
1359        let actual_text = initial_snapshot.text();
1360        assert_eq!(
1361            actual_text,
1362            expected_text,
1363            "unwrapped text is: {:?}",
1364            tabs_snapshot.text()
1365        );
1366        log::info!("Wrapped text: {:?}", actual_text);
1367
1368        let mut next_inlay_id = 0;
1369        let mut edits = Vec::new();
1370        for _i in 0..operations {
1371            log::info!("{} ==============================================", _i);
1372
1373            let mut buffer_edits = Vec::new();
1374            match rng.random_range(0..=100) {
1375                0..=19 => {
1376                    wrap_width = if rng.random_bool(0.2) {
1377                        None
1378                    } else {
1379                        Some(px(rng.random_range(0.0..=1000.0)))
1380                    };
1381                    log::info!("Setting wrap width to {:?}", wrap_width);
1382                    wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1383                }
1384                20..=39 => {
1385                    for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1386                        let (tabs_snapshot, tab_edits) =
1387                            tab_map.sync(fold_snapshot, fold_edits, tab_size);
1388                        let (mut snapshot, wrap_edits) =
1389                            wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1390                        snapshot.check_invariants();
1391                        snapshot.verify_chunks(&mut rng);
1392                        edits.push((snapshot, wrap_edits));
1393                    }
1394                }
1395                40..=59 => {
1396                    let (inlay_snapshot, inlay_edits) =
1397                        inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1398                    let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1399                    let (tabs_snapshot, tab_edits) =
1400                        tab_map.sync(fold_snapshot, fold_edits, tab_size);
1401                    let (mut snapshot, wrap_edits) =
1402                        wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1403                    snapshot.check_invariants();
1404                    snapshot.verify_chunks(&mut rng);
1405                    edits.push((snapshot, wrap_edits));
1406                }
1407                _ => {
1408                    buffer.update(cx, |buffer, cx| {
1409                        let subscription = buffer.subscribe();
1410                        let edit_count = rng.random_range(1..=5);
1411                        buffer.randomly_mutate(&mut rng, edit_count, cx);
1412                        buffer_snapshot = buffer.snapshot(cx);
1413                        buffer_edits.extend(subscription.consume());
1414                    });
1415                }
1416            }
1417
1418            log::info!("Buffer text: {:?}", buffer_snapshot.text());
1419            let (inlay_snapshot, inlay_edits) =
1420                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1421            log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1422            let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1423            log::info!("FoldMap text: {:?}", fold_snapshot.text());
1424            let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
1425            log::info!("TabMap text: {:?}", tabs_snapshot.text());
1426
1427            let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1428            let (mut snapshot, wrap_edits) =
1429                wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot.clone(), tab_edits, cx));
1430            snapshot.check_invariants();
1431            snapshot.verify_chunks(&mut rng);
1432            edits.push((snapshot, wrap_edits));
1433
1434            if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) && rng.random_bool(0.4) {
1435                log::info!("Waiting for wrapping to finish");
1436                while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1437                    notifications.next().await.unwrap();
1438                }
1439                wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1440            }
1441
1442            if !wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1443                let (mut wrapped_snapshot, wrap_edits) = wrap_map.update(cx, |map, cx| {
1444                    map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1445                });
1446                let actual_text = wrapped_snapshot.text();
1447                let actual_longest_row = wrapped_snapshot.longest_row();
1448                log::info!("Wrapping finished: {:?}", actual_text);
1449                wrapped_snapshot.check_invariants();
1450                wrapped_snapshot.verify_chunks(&mut rng);
1451                edits.push((wrapped_snapshot.clone(), wrap_edits));
1452                assert_eq!(
1453                    actual_text,
1454                    expected_text,
1455                    "unwrapped text is: {:?}",
1456                    tabs_snapshot.text()
1457                );
1458
1459                let mut summary = TextSummary::default();
1460                for (ix, item) in wrapped_snapshot
1461                    .transforms
1462                    .items(())
1463                    .into_iter()
1464                    .enumerate()
1465                {
1466                    summary += &item.summary.output;
1467                    log::info!("{} summary: {:?}", ix, item.summary.output,);
1468                }
1469
1470                if tab_size.get() == 1
1471                    || !wrapped_snapshot
1472                        .tab_snapshot
1473                        .fold_snapshot
1474                        .text()
1475                        .contains('\t')
1476                {
1477                    let mut expected_longest_rows = Vec::new();
1478                    let mut longest_line_len = -1;
1479                    for (row, line) in expected_text.split('\n').enumerate() {
1480                        let line_char_count = line.chars().count() as isize;
1481                        if line_char_count > longest_line_len {
1482                            expected_longest_rows.clear();
1483                            longest_line_len = line_char_count;
1484                        }
1485                        if line_char_count >= longest_line_len {
1486                            expected_longest_rows.push(row as u32);
1487                        }
1488                    }
1489
1490                    assert!(
1491                        expected_longest_rows.contains(&actual_longest_row),
1492                        "incorrect longest row {}. expected {:?} with length {}",
1493                        actual_longest_row,
1494                        expected_longest_rows,
1495                        longest_line_len,
1496                    )
1497                }
1498            }
1499        }
1500
1501        let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1502        for (snapshot, patch) in edits {
1503            let snapshot_text = Rope::from(snapshot.text().as_str());
1504            for edit in &patch {
1505                let old_start = initial_text.point_to_offset(Point::new(edit.new.start.0, 0));
1506                let old_end = initial_text.point_to_offset(cmp::min(
1507                    Point::new(edit.new.start.0 + (edit.old.end - edit.old.start).0, 0),
1508                    initial_text.max_point(),
1509                ));
1510                let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start.0, 0));
1511                let new_end = snapshot_text.point_to_offset(cmp::min(
1512                    Point::new(edit.new.end.0, 0),
1513                    snapshot_text.max_point(),
1514                ));
1515                let new_text = snapshot_text
1516                    .chunks_in_range(new_start..new_end)
1517                    .collect::<String>();
1518
1519                initial_text.replace(old_start..old_end, &new_text);
1520            }
1521            assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1522        }
1523
1524        if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1525            log::info!("Waiting for wrapping to finish");
1526            while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1527                notifications.next().await.unwrap();
1528            }
1529        }
1530        wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1531    }
1532
1533    fn init_test(cx: &mut gpui::TestAppContext) {
1534        cx.update(|cx| {
1535            let settings = SettingsStore::test(cx);
1536            cx.set_global(settings);
1537            theme::init(LoadThemes::JustBase, cx);
1538        });
1539    }
1540
1541    fn wrap_text(
1542        tab_snapshot: &TabSnapshot,
1543        wrap_width: Option<Pixels>,
1544        line_wrapper: &mut LineWrapper,
1545    ) -> String {
1546        if let Some(wrap_width) = wrap_width {
1547            let mut wrapped_text = String::new();
1548            for (row, line) in tab_snapshot.text().split('\n').enumerate() {
1549                if row > 0 {
1550                    wrapped_text.push('\n');
1551                }
1552
1553                let mut prev_ix = 0;
1554                for boundary in line_wrapper.wrap_line(&[LineFragment::text(line)], wrap_width) {
1555                    wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1556                    wrapped_text.push('\n');
1557                    wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1558                    prev_ix = boundary.ix;
1559                }
1560                wrapped_text.push_str(&line[prev_ix..]);
1561            }
1562
1563            wrapped_text
1564        } else {
1565            tab_snapshot.text()
1566        }
1567    }
1568
1569    impl WrapSnapshot {
1570        fn verify_chunks(&mut self, rng: &mut impl Rng) {
1571            for _ in 0..5 {
1572                let mut end_row = rng.random_range(0..=self.max_point().row().0);
1573                let start_row = rng.random_range(0..=end_row);
1574                end_row += 1;
1575
1576                let mut expected_text = self.text_chunks(WrapRow(start_row)).collect::<String>();
1577                if expected_text.ends_with('\n') {
1578                    expected_text.push('\n');
1579                }
1580                let mut expected_text = expected_text
1581                    .lines()
1582                    .take((end_row - start_row) as usize)
1583                    .collect::<Vec<_>>()
1584                    .join("\n");
1585                if end_row <= self.max_point().row().0 {
1586                    expected_text.push('\n');
1587                }
1588
1589                let actual_text = self
1590                    .chunks(
1591                        WrapRow(start_row)..WrapRow(end_row),
1592                        true,
1593                        Highlights::default(),
1594                    )
1595                    .map(|c| c.text)
1596                    .collect::<String>();
1597                assert_eq!(
1598                    expected_text,
1599                    actual_text,
1600                    "chunks != highlighted_chunks for rows {:?}",
1601                    start_row..end_row
1602                );
1603            }
1604        }
1605    }
1606}