wrap_map.rs

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