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