wrap_map.rs

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