wrap_map.rs

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