wrap_map.rs

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