wrap_map.rs

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