wrap_map.rs

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