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