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