wrap_map.rs

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