wrap_map.rs

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