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    pub fn is_zero(&self) -> bool {
 956        self.0.is_zero()
 957    }
 958}
 959
 960impl sum_tree::Summary for TransformSummary {
 961    type Context = ();
 962
 963    fn add_summary(&mut self, other: &Self, _: &()) {
 964        self.input += &other.input;
 965        self.output += &other.output;
 966    }
 967}
 968
 969impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
 970    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 971        self.0 += summary.input.lines;
 972    }
 973}
 974
 975impl<'a> sum_tree::SeekTarget<'a, TransformSummary, TransformSummary> for TabPoint {
 976    fn cmp(&self, cursor_location: &TransformSummary, _: &()) -> std::cmp::Ordering {
 977        Ord::cmp(&self.0, &cursor_location.input.lines)
 978    }
 979}
 980
 981impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
 982    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 983        self.0 += summary.output.lines;
 984    }
 985}
 986
 987fn consolidate_wrap_edits(edits: &mut Vec<WrapEdit>) {
 988    let mut i = 1;
 989    while i < edits.len() {
 990        let edit = edits[i].clone();
 991        let prev_edit = &mut edits[i - 1];
 992        if prev_edit.old.end >= edit.old.start {
 993            prev_edit.old.end = edit.old.end;
 994            prev_edit.new.end = edit.new.end;
 995            edits.remove(i);
 996            continue;
 997        }
 998        i += 1;
 999    }
1000}
1001
1002#[cfg(test)]
1003mod tests {
1004    use super::*;
1005    use crate::{
1006        display_map::{fold_map::FoldMap, tab_map::TabMap},
1007        MultiBuffer,
1008    };
1009    use gpui::test::observe;
1010    use language::RandomCharIter;
1011    use rand::prelude::*;
1012    use smol::stream::StreamExt;
1013    use std::{cmp, env};
1014    use text::Rope;
1015
1016    #[gpui::test(iterations = 100)]
1017    async fn test_random_wraps(mut cx: gpui::TestAppContext, mut rng: StdRng) {
1018        cx.foreground().set_block_on_ticks(0..=50);
1019        cx.foreground().forbid_parking();
1020        let operations = env::var("OPERATIONS")
1021            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1022            .unwrap_or(10);
1023
1024        let font_cache = cx.font_cache().clone();
1025        let font_system = cx.platform().fonts();
1026        let mut wrap_width = if rng.gen_bool(0.1) {
1027            None
1028        } else {
1029            Some(rng.gen_range(0.0..=1000.0))
1030        };
1031        let tab_size = rng.gen_range(1..=4);
1032        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1033        let font_id = font_cache
1034            .select_font(family_id, &Default::default())
1035            .unwrap();
1036        let font_size = 14.0;
1037
1038        log::info!("Tab size: {}", tab_size);
1039        log::info!("Wrap width: {:?}", wrap_width);
1040
1041        let buffer = cx.update(|cx| {
1042            if rng.gen() {
1043                MultiBuffer::build_random(&mut rng, cx)
1044            } else {
1045                let len = rng.gen_range(0..10);
1046                let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1047                MultiBuffer::build_simple(&text, cx)
1048            }
1049        });
1050        let mut buffer_snapshot = buffer.read_with(&cx, |buffer, cx| buffer.snapshot(cx));
1051        let (mut fold_map, folds_snapshot) = FoldMap::new(buffer_snapshot.clone());
1052        let (tab_map, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), tab_size);
1053        log::info!("Unwrapped text (no folds): {:?}", buffer_snapshot.text());
1054        log::info!(
1055            "Unwrapped text (unexpanded tabs): {:?}",
1056            folds_snapshot.text()
1057        );
1058        log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
1059
1060        let mut line_wrapper = LineWrapper::new(font_id, font_size, font_system);
1061        let unwrapped_text = tabs_snapshot.text();
1062        let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1063
1064        let (wrap_map, _) =
1065            cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font_id, font_size, wrap_width, cx));
1066        let mut notifications = observe(&wrap_map, &mut cx);
1067
1068        if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1069            notifications.next().await.unwrap();
1070        }
1071
1072        let (initial_snapshot, _) = wrap_map.update(&mut cx, |map, cx| {
1073            assert!(!map.is_rewrapping());
1074            map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1075        });
1076
1077        let actual_text = initial_snapshot.text();
1078        assert_eq!(
1079            actual_text, expected_text,
1080            "unwrapped text is: {:?}",
1081            unwrapped_text
1082        );
1083        log::info!("Wrapped text: {:?}", actual_text);
1084
1085        let mut edits = Vec::new();
1086        for _i in 0..operations {
1087            log::info!("{} ==============================================", _i);
1088
1089            let mut buffer_edits = Vec::new();
1090            match rng.gen_range(0..=100) {
1091                0..=19 => {
1092                    wrap_width = if rng.gen_bool(0.2) {
1093                        None
1094                    } else {
1095                        Some(rng.gen_range(0.0..=1000.0))
1096                    };
1097                    log::info!("Setting wrap width to {:?}", wrap_width);
1098                    wrap_map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1099                }
1100                20..=39 => {
1101                    for (folds_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1102                        let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1103                        let (mut snapshot, wrap_edits) = wrap_map
1104                            .update(&mut cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1105                        snapshot.check_invariants();
1106                        snapshot.verify_chunks(&mut rng);
1107                        edits.push((snapshot, wrap_edits));
1108                    }
1109                }
1110                _ => {
1111                    buffer.update(&mut cx, |buffer, cx| {
1112                        let subscription = buffer.subscribe();
1113                        let edit_count = rng.gen_range(1..=5);
1114                        buffer.randomly_edit(&mut rng, edit_count, cx);
1115                        buffer_snapshot = buffer.snapshot(cx);
1116                        buffer_edits.extend(subscription.consume());
1117                    });
1118                }
1119            }
1120
1121            log::info!("Unwrapped text (no folds): {:?}", buffer_snapshot.text());
1122            let (folds_snapshot, fold_edits) = fold_map.read(buffer_snapshot.clone(), buffer_edits);
1123            log::info!(
1124                "Unwrapped text (unexpanded tabs): {:?}",
1125                folds_snapshot.text()
1126            );
1127            let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1128            log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
1129
1130            let unwrapped_text = tabs_snapshot.text();
1131            let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1132            let (mut snapshot, wrap_edits) = wrap_map.update(&mut cx, |map, cx| {
1133                map.sync(tabs_snapshot.clone(), tab_edits, cx)
1134            });
1135            snapshot.check_invariants();
1136            snapshot.verify_chunks(&mut rng);
1137            edits.push((snapshot, wrap_edits));
1138
1139            if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) && rng.gen_bool(0.4) {
1140                log::info!("Waiting for wrapping to finish");
1141                while wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1142                    notifications.next().await.unwrap();
1143                }
1144                wrap_map.read_with(&cx, |map, _| assert!(map.pending_edits.is_empty()));
1145            }
1146
1147            if !wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1148                let (mut wrapped_snapshot, wrap_edits) =
1149                    wrap_map.update(&mut cx, |map, cx| map.sync(tabs_snapshot, Vec::new(), cx));
1150                let actual_text = wrapped_snapshot.text();
1151                let actual_longest_row = wrapped_snapshot.longest_row();
1152                log::info!("Wrapping finished: {:?}", actual_text);
1153                wrapped_snapshot.check_invariants();
1154                wrapped_snapshot.verify_chunks(&mut rng);
1155                edits.push((wrapped_snapshot.clone(), wrap_edits));
1156                assert_eq!(
1157                    actual_text, expected_text,
1158                    "unwrapped text is: {:?}",
1159                    unwrapped_text
1160                );
1161
1162                let mut summary = TextSummary::default();
1163                for (ix, item) in wrapped_snapshot
1164                    .transforms
1165                    .items(&())
1166                    .into_iter()
1167                    .enumerate()
1168                {
1169                    summary += &item.summary.output;
1170                    log::info!("{} summary: {:?}", ix, item.summary.output,);
1171                }
1172
1173                if tab_size == 1
1174                    || !wrapped_snapshot
1175                        .tab_snapshot
1176                        .fold_snapshot
1177                        .text()
1178                        .contains('\t')
1179                {
1180                    let mut expected_longest_rows = Vec::new();
1181                    let mut longest_line_len = -1;
1182                    for (row, line) in expected_text.split('\n').enumerate() {
1183                        let line_char_count = line.chars().count() as isize;
1184                        if line_char_count > longest_line_len {
1185                            expected_longest_rows.clear();
1186                            longest_line_len = line_char_count;
1187                        }
1188                        if line_char_count >= longest_line_len {
1189                            expected_longest_rows.push(row as u32);
1190                        }
1191                    }
1192
1193                    assert!(
1194                        expected_longest_rows.contains(&actual_longest_row),
1195                        "incorrect longest row {}. expected {:?} with length {}",
1196                        actual_longest_row,
1197                        expected_longest_rows,
1198                        longest_line_len,
1199                    )
1200                }
1201            }
1202        }
1203
1204        let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1205        for (snapshot, patch) in edits {
1206            let snapshot_text = Rope::from(snapshot.text().as_str());
1207            for edit in &patch {
1208                let old_start = initial_text.point_to_offset(Point::new(edit.new.start, 0));
1209                let old_end = initial_text.point_to_offset(cmp::min(
1210                    Point::new(edit.new.start + edit.old.len() as u32, 0),
1211                    initial_text.max_point(),
1212                ));
1213                let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start, 0));
1214                let new_end = snapshot_text.point_to_offset(cmp::min(
1215                    Point::new(edit.new.end, 0),
1216                    snapshot_text.max_point(),
1217                ));
1218                let new_text = snapshot_text
1219                    .chunks_in_range(new_start..new_end)
1220                    .collect::<String>();
1221
1222                initial_text.replace(old_start..old_end, &new_text);
1223            }
1224            assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1225        }
1226
1227        if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1228            log::info!("Waiting for wrapping to finish");
1229            while wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1230                notifications.next().await.unwrap();
1231            }
1232        }
1233        wrap_map.read_with(&cx, |map, _| assert!(map.pending_edits.is_empty()));
1234    }
1235
1236    fn wrap_text(
1237        unwrapped_text: &str,
1238        wrap_width: Option<f32>,
1239        line_wrapper: &mut LineWrapper,
1240    ) -> String {
1241        if let Some(wrap_width) = wrap_width {
1242            let mut wrapped_text = String::new();
1243            for (row, line) in unwrapped_text.split('\n').enumerate() {
1244                if row > 0 {
1245                    wrapped_text.push('\n')
1246                }
1247
1248                let mut prev_ix = 0;
1249                for boundary in line_wrapper.wrap_line(line, wrap_width) {
1250                    wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1251                    wrapped_text.push('\n');
1252                    wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1253                    prev_ix = boundary.ix;
1254                }
1255                wrapped_text.push_str(&line[prev_ix..]);
1256            }
1257            wrapped_text
1258        } else {
1259            unwrapped_text.to_string()
1260        }
1261    }
1262
1263    impl WrapSnapshot {
1264        pub fn text(&self) -> String {
1265            self.text_chunks(0).collect()
1266        }
1267
1268        fn verify_chunks(&mut self, rng: &mut impl Rng) {
1269            for _ in 0..5 {
1270                let mut end_row = rng.gen_range(0..=self.max_point().row());
1271                let start_row = rng.gen_range(0..=end_row);
1272                end_row += 1;
1273
1274                let mut expected_text = self.text_chunks(start_row).collect::<String>();
1275                if expected_text.ends_with("\n") {
1276                    expected_text.push('\n');
1277                }
1278                let mut expected_text = expected_text
1279                    .lines()
1280                    .take((end_row - start_row) as usize)
1281                    .collect::<Vec<_>>()
1282                    .join("\n");
1283                if end_row <= self.max_point().row() {
1284                    expected_text.push('\n');
1285                }
1286
1287                let actual_text = self
1288                    .chunks(start_row..end_row, true)
1289                    .map(|c| c.text)
1290                    .collect::<String>();
1291                assert_eq!(
1292                    expected_text,
1293                    actual_text,
1294                    "chunks != highlighted_chunks for rows {:?}",
1295                    start_row..end_row
1296                );
1297            }
1298        }
1299    }
1300}