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