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