wrap_map.rs

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