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 multi_buffer::MultiBufferSnapshot;
   9use smol::future::yield_now;
  10use std::sync::LazyLock;
  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        wrap_edits = consolidate_wrap_edits(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        static WRAP_TEXT: LazyLock<String> = LazyLock::new(|| {
 891            let mut wrap_text = String::new();
 892            wrap_text.push('\n');
 893            wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
 894            wrap_text
 895        });
 896
 897        Self {
 898            summary: TransformSummary {
 899                input: TextSummary::default(),
 900                output: TextSummary {
 901                    lines: Point::new(1, indent),
 902                    first_line_chars: 0,
 903                    last_line_chars: indent,
 904                    longest_row: 1,
 905                    longest_row_chars: indent,
 906                },
 907            },
 908            display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
 909        }
 910    }
 911
 912    fn is_isomorphic(&self) -> bool {
 913        self.display_text.is_none()
 914    }
 915}
 916
 917impl sum_tree::Item for Transform {
 918    type Summary = TransformSummary;
 919
 920    fn summary(&self) -> Self::Summary {
 921        self.summary.clone()
 922    }
 923}
 924
 925fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
 926    if let Some(last_transform) = transforms.last_mut() {
 927        if last_transform.is_isomorphic() {
 928            last_transform.summary.input += &summary;
 929            last_transform.summary.output += &summary;
 930            return;
 931        }
 932    }
 933    transforms.push(Transform::isomorphic(summary));
 934}
 935
 936trait SumTreeExt {
 937    fn push_or_extend(&mut self, transform: Transform);
 938}
 939
 940impl SumTreeExt for SumTree<Transform> {
 941    fn push_or_extend(&mut self, transform: Transform) {
 942        let mut transform = Some(transform);
 943        self.update_last(
 944            |last_transform| {
 945                if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
 946                    let transform = transform.take().unwrap();
 947                    last_transform.summary.input += &transform.summary.input;
 948                    last_transform.summary.output += &transform.summary.output;
 949                }
 950            },
 951            &(),
 952        );
 953
 954        if let Some(transform) = transform {
 955            self.push(transform, &());
 956        }
 957    }
 958}
 959
 960impl WrapPoint {
 961    pub fn new(row: u32, column: u32) -> Self {
 962        Self(Point::new(row, column))
 963    }
 964
 965    pub fn row(self) -> u32 {
 966        self.0.row
 967    }
 968
 969    pub fn row_mut(&mut self) -> &mut u32 {
 970        &mut self.0.row
 971    }
 972
 973    pub fn column(self) -> u32 {
 974        self.0.column
 975    }
 976
 977    pub fn column_mut(&mut self) -> &mut u32 {
 978        &mut self.0.column
 979    }
 980}
 981
 982impl sum_tree::Summary for TransformSummary {
 983    type Context = ();
 984
 985    fn add_summary(&mut self, other: &Self, _: &()) {
 986        self.input += &other.input;
 987        self.output += &other.output;
 988    }
 989}
 990
 991impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
 992    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 993        self.0 += summary.input.lines;
 994    }
 995}
 996
 997impl<'a> sum_tree::SeekTarget<'a, TransformSummary, TransformSummary> for TabPoint {
 998    fn cmp(&self, cursor_location: &TransformSummary, _: &()) -> std::cmp::Ordering {
 999        Ord::cmp(&self.0, &cursor_location.input.lines)
1000    }
1001}
1002
1003impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
1004    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1005        self.0 += summary.output.lines;
1006    }
1007}
1008
1009fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
1010    let _old_alloc_ptr = edits.as_ptr();
1011    let mut wrap_edits = edits.into_iter();
1012
1013    if let Some(mut first_edit) = wrap_edits.next() {
1014        // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1015        #[allow(clippy::filter_map_identity)]
1016        let mut v: Vec<_> = wrap_edits
1017            .scan(&mut first_edit, |prev_edit, edit| {
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                    Some(None) // Skip this edit, it's merged
1022                } else {
1023                    let prev = std::mem::replace(*prev_edit, edit);
1024                    Some(Some(prev)) // Yield the previous edit
1025                }
1026            })
1027            .filter_map(|x| x)
1028            .collect();
1029        v.push(first_edit.clone());
1030        debug_assert_eq!(v.as_ptr(), _old_alloc_ptr, "Wrap edits were reallocated");
1031        v
1032    } else {
1033        vec![]
1034    }
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039    use super::*;
1040    use crate::{
1041        display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
1042        MultiBuffer,
1043    };
1044    use gpui::{font, px, test::observe};
1045    use rand::prelude::*;
1046    use settings::SettingsStore;
1047    use smol::stream::StreamExt;
1048    use std::{cmp, env, num::NonZeroU32};
1049    use text::Rope;
1050    use theme::LoadThemes;
1051
1052    #[gpui::test(iterations = 100)]
1053    async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1054        // todo this test is flaky
1055        init_test(cx);
1056
1057        cx.background_executor.set_block_on_ticks(0..=50);
1058        let operations = env::var("OPERATIONS")
1059            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1060            .unwrap_or(10);
1061
1062        let text_system = cx.read(|cx| cx.text_system().clone());
1063        let mut wrap_width = if rng.gen_bool(0.1) {
1064            None
1065        } else {
1066            Some(px(rng.gen_range(0.0..=1000.0)))
1067        };
1068        let tab_size = NonZeroU32::new(rng.gen_range(1..=4)).unwrap();
1069        let font = font("Helvetica");
1070        let _font_id = text_system.font_id(&font);
1071        let font_size = px(14.0);
1072
1073        log::info!("Tab size: {}", tab_size);
1074        log::info!("Wrap width: {:?}", wrap_width);
1075
1076        let buffer = cx.update(|cx| {
1077            if rng.gen() {
1078                MultiBuffer::build_random(&mut rng, cx)
1079            } else {
1080                let len = rng.gen_range(0..10);
1081                let text = util::RandomCharIter::new(&mut rng)
1082                    .take(len)
1083                    .collect::<String>();
1084                MultiBuffer::build_simple(&text, cx)
1085            }
1086        });
1087        let mut buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1088        log::info!("Buffer text: {:?}", buffer_snapshot.text());
1089        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1090        log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1091        let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot.clone());
1092        log::info!("FoldMap text: {:?}", fold_snapshot.text());
1093        let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
1094        let tabs_snapshot = tab_map.set_max_expansion_column(32);
1095        log::info!("TabMap text: {:?}", tabs_snapshot.text());
1096
1097        let mut line_wrapper = text_system.line_wrapper(font.clone(), font_size);
1098        let unwrapped_text = tabs_snapshot.text();
1099        let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1100
1101        let (wrap_map, _) =
1102            cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font, font_size, wrap_width, cx));
1103        let mut notifications = observe(&wrap_map, cx);
1104
1105        if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1106            notifications.next().await.unwrap();
1107        }
1108
1109        let (initial_snapshot, _) = wrap_map.update(cx, |map, cx| {
1110            assert!(!map.is_rewrapping());
1111            map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1112        });
1113
1114        let actual_text = initial_snapshot.text();
1115        assert_eq!(
1116            actual_text, expected_text,
1117            "unwrapped text is: {:?}",
1118            unwrapped_text
1119        );
1120        log::info!("Wrapped text: {:?}", actual_text);
1121
1122        let mut next_inlay_id = 0;
1123        let mut edits = Vec::new();
1124        for _i in 0..operations {
1125            log::info!("{} ==============================================", _i);
1126
1127            let mut buffer_edits = Vec::new();
1128            match rng.gen_range(0..=100) {
1129                0..=19 => {
1130                    wrap_width = if rng.gen_bool(0.2) {
1131                        None
1132                    } else {
1133                        Some(px(rng.gen_range(0.0..=1000.0)))
1134                    };
1135                    log::info!("Setting wrap width to {:?}", wrap_width);
1136                    wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1137                }
1138                20..=39 => {
1139                    for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1140                        let (tabs_snapshot, tab_edits) =
1141                            tab_map.sync(fold_snapshot, fold_edits, tab_size);
1142                        let (mut snapshot, wrap_edits) =
1143                            wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1144                        snapshot.check_invariants();
1145                        snapshot.verify_chunks(&mut rng);
1146                        edits.push((snapshot, wrap_edits));
1147                    }
1148                }
1149                40..=59 => {
1150                    let (inlay_snapshot, inlay_edits) =
1151                        inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1152                    let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1153                    let (tabs_snapshot, tab_edits) =
1154                        tab_map.sync(fold_snapshot, fold_edits, tab_size);
1155                    let (mut snapshot, wrap_edits) =
1156                        wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1157                    snapshot.check_invariants();
1158                    snapshot.verify_chunks(&mut rng);
1159                    edits.push((snapshot, wrap_edits));
1160                }
1161                _ => {
1162                    buffer.update(cx, |buffer, cx| {
1163                        let subscription = buffer.subscribe();
1164                        let edit_count = rng.gen_range(1..=5);
1165                        buffer.randomly_mutate(&mut rng, edit_count, cx);
1166                        buffer_snapshot = buffer.snapshot(cx);
1167                        buffer_edits.extend(subscription.consume());
1168                    });
1169                }
1170            }
1171
1172            log::info!("Buffer text: {:?}", buffer_snapshot.text());
1173            let (inlay_snapshot, inlay_edits) =
1174                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1175            log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1176            let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1177            log::info!("FoldMap text: {:?}", fold_snapshot.text());
1178            let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
1179            log::info!("TabMap text: {:?}", tabs_snapshot.text());
1180
1181            let unwrapped_text = tabs_snapshot.text();
1182            let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1183            let (mut snapshot, wrap_edits) =
1184                wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot.clone(), tab_edits, cx));
1185            snapshot.check_invariants();
1186            snapshot.verify_chunks(&mut rng);
1187            edits.push((snapshot, wrap_edits));
1188
1189            if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) && rng.gen_bool(0.4) {
1190                log::info!("Waiting for wrapping to finish");
1191                while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1192                    notifications.next().await.unwrap();
1193                }
1194                wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1195            }
1196
1197            if !wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1198                let (mut wrapped_snapshot, wrap_edits) =
1199                    wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, Vec::new(), cx));
1200                let actual_text = wrapped_snapshot.text();
1201                let actual_longest_row = wrapped_snapshot.longest_row();
1202                log::info!("Wrapping finished: {:?}", actual_text);
1203                wrapped_snapshot.check_invariants();
1204                wrapped_snapshot.verify_chunks(&mut rng);
1205                edits.push((wrapped_snapshot.clone(), wrap_edits));
1206                assert_eq!(
1207                    actual_text, expected_text,
1208                    "unwrapped text is: {:?}",
1209                    unwrapped_text
1210                );
1211
1212                let mut summary = TextSummary::default();
1213                for (ix, item) in wrapped_snapshot
1214                    .transforms
1215                    .items(&())
1216                    .into_iter()
1217                    .enumerate()
1218                {
1219                    summary += &item.summary.output;
1220                    log::info!("{} summary: {:?}", ix, item.summary.output,);
1221                }
1222
1223                if tab_size.get() == 1
1224                    || !wrapped_snapshot
1225                        .tab_snapshot
1226                        .fold_snapshot
1227                        .text()
1228                        .contains('\t')
1229                {
1230                    let mut expected_longest_rows = Vec::new();
1231                    let mut longest_line_len = -1;
1232                    for (row, line) in expected_text.split('\n').enumerate() {
1233                        let line_char_count = line.chars().count() as isize;
1234                        if line_char_count > longest_line_len {
1235                            expected_longest_rows.clear();
1236                            longest_line_len = line_char_count;
1237                        }
1238                        if line_char_count >= longest_line_len {
1239                            expected_longest_rows.push(row as u32);
1240                        }
1241                    }
1242
1243                    assert!(
1244                        expected_longest_rows.contains(&actual_longest_row),
1245                        "incorrect longest row {}. expected {:?} with length {}",
1246                        actual_longest_row,
1247                        expected_longest_rows,
1248                        longest_line_len,
1249                    )
1250                }
1251            }
1252        }
1253
1254        let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1255        for (snapshot, patch) in edits {
1256            let snapshot_text = Rope::from(snapshot.text().as_str());
1257            for edit in &patch {
1258                let old_start = initial_text.point_to_offset(Point::new(edit.new.start, 0));
1259                let old_end = initial_text.point_to_offset(cmp::min(
1260                    Point::new(edit.new.start + edit.old.len() as u32, 0),
1261                    initial_text.max_point(),
1262                ));
1263                let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start, 0));
1264                let new_end = snapshot_text.point_to_offset(cmp::min(
1265                    Point::new(edit.new.end, 0),
1266                    snapshot_text.max_point(),
1267                ));
1268                let new_text = snapshot_text
1269                    .chunks_in_range(new_start..new_end)
1270                    .collect::<String>();
1271
1272                initial_text.replace(old_start..old_end, &new_text);
1273            }
1274            assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1275        }
1276
1277        if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1278            log::info!("Waiting for wrapping to finish");
1279            while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1280                notifications.next().await.unwrap();
1281            }
1282        }
1283        wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1284    }
1285
1286    fn init_test(cx: &mut gpui::TestAppContext) {
1287        cx.update(|cx| {
1288            let settings = SettingsStore::test(cx);
1289            cx.set_global(settings);
1290            theme::init(LoadThemes::JustBase, cx);
1291        });
1292    }
1293
1294    fn wrap_text(
1295        unwrapped_text: &str,
1296        wrap_width: Option<Pixels>,
1297        line_wrapper: &mut LineWrapper,
1298    ) -> String {
1299        if let Some(wrap_width) = wrap_width {
1300            let mut wrapped_text = String::new();
1301            for (row, line) in unwrapped_text.split('\n').enumerate() {
1302                if row > 0 {
1303                    wrapped_text.push('\n')
1304                }
1305
1306                let mut prev_ix = 0;
1307                for boundary in line_wrapper.wrap_line(line, wrap_width) {
1308                    wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1309                    wrapped_text.push('\n');
1310                    wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1311                    prev_ix = boundary.ix;
1312                }
1313                wrapped_text.push_str(&line[prev_ix..]);
1314            }
1315            wrapped_text
1316        } else {
1317            unwrapped_text.to_string()
1318        }
1319    }
1320
1321    impl WrapSnapshot {
1322        pub fn text(&self) -> String {
1323            self.text_chunks(0).collect()
1324        }
1325
1326        pub fn text_chunks(&self, wrap_row: u32) -> impl Iterator<Item = &str> {
1327            self.chunks(
1328                wrap_row..self.max_point().row() + 1,
1329                false,
1330                Highlights::default(),
1331            )
1332            .map(|h| h.text)
1333        }
1334
1335        fn verify_chunks(&mut self, rng: &mut impl Rng) {
1336            for _ in 0..5 {
1337                let mut end_row = rng.gen_range(0..=self.max_point().row());
1338                let start_row = rng.gen_range(0..=end_row);
1339                end_row += 1;
1340
1341                let mut expected_text = self.text_chunks(start_row).collect::<String>();
1342                if expected_text.ends_with('\n') {
1343                    expected_text.push('\n');
1344                }
1345                let mut expected_text = expected_text
1346                    .lines()
1347                    .take((end_row - start_row) as usize)
1348                    .collect::<Vec<_>>()
1349                    .join("\n");
1350                if end_row <= self.max_point().row() {
1351                    expected_text.push('\n');
1352                }
1353
1354                let actual_text = self
1355                    .chunks(start_row..end_row, true, Highlights::default())
1356                    .map(|c| c.text)
1357                    .collect::<String>();
1358                assert_eq!(
1359                    expected_text,
1360                    actual_text,
1361                    "chunks != highlighted_chunks for rows {:?}",
1362                    start_row..end_row
1363                );
1364            }
1365        }
1366    }
1367}