Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T03:30:39.639Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

wrap_map.rs

1759 lines · 67.7 KB · rust
1use super::{
2    Highlights,
3    dimensions::RowDelta,
4    fold_map::{Chunk, FoldRows},
5    tab_map::{self, TabEdit, TabPoint, TabSnapshot},
6};
7
8use futures_lite::future::yield_now;
9use gpui::{App, AppContext as _, Context, Entity, Font, LineWrapper, Pixels, Task};
10use language::{LanguageAwareStyling, Point};
11use multi_buffer::RowInfo;
12use std::{cmp, collections::VecDeque, mem, ops::Range, sync::LazyLock, time::Duration};
13use sum_tree::{Bias, Cursor, Dimensions, SumTree};
14use text::Patch;
15
16pub use super::tab_map::TextSummary;
17pub type WrapEdit = text::Edit<WrapRow>;
18pub type WrapPatch = text::Patch<WrapRow>;
19
20#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
21pub struct WrapRow(pub u32);
22
23const WRAP_YIELD_ROW_INTERVAL: usize = 100;
24
25impl_for_row_types! {
26    WrapRow => RowDelta
27}
28
29/// Handles soft wrapping of text.
30///
31/// See the [`display_map` module documentation](crate::display_map) for more information.
32pub struct WrapMap {
33    snapshot: WrapSnapshot,
34    pending_edits: VecDeque<(TabSnapshot, Vec<TabEdit>)>,
35    interpolated_edits: WrapPatch,
36    edits_since_sync: WrapPatch,
37    wrap_width: Option<Pixels>,
38    background_task: Option<Task<()>>,
39    font_with_size: (Font, Pixels),
40}
41
42#[derive(Clone)]
43pub struct WrapSnapshot {
44    pub(super) tab_snapshot: TabSnapshot,
45    transforms: SumTree<Transform>,
46    interpolated: bool,
47}
48
49impl std::ops::Deref for WrapSnapshot {
50    type Target = TabSnapshot;
51
52    fn deref(&self) -> &Self::Target {
53        &self.tab_snapshot
54    }
55}
56
57#[derive(Clone, Debug, Default, Eq, PartialEq)]
58struct Transform {
59    summary: TransformSummary,
60    display_text: Option<&'static str>,
61}
62
63#[derive(Clone, Debug, Default, Eq, PartialEq)]
64struct TransformSummary {
65    input: TextSummary,
66    output: TextSummary,
67}
68
69impl TransformSummary {
70    fn has_wraps(&self) -> bool {
71        self.input.lines != self.output.lines
72    }
73}
74
75#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
76pub struct WrapPoint(pub Point);
77
78pub struct WrapChunks<'a> {
79    input_chunks: tab_map::TabChunks<'a>,
80    input_chunk: Chunk<'a>,
81    output_position: WrapPoint,
82    max_output_row: WrapRow,
83    transforms: Cursor<'a, 'static, Transform, Dimensions<WrapPoint, TabPoint>>,
84    snapshot: &'a WrapSnapshot,
85}
86
87#[derive(Clone)]
88pub struct WrapRows<'a> {
89    input_buffer_rows: FoldRows<'a>,
90    input_buffer_row: RowInfo,
91    output_row: WrapRow,
92    soft_wrapped: bool,
93    max_output_row: WrapRow,
94    transforms: Cursor<'a, 'static, Transform, Dimensions<WrapPoint, TabPoint>>,
95}
96
97impl WrapRows<'_> {
98    #[ztracing::instrument(skip_all)]
99    pub(crate) fn seek(&mut self, start_row: WrapRow) {
100        self.transforms
101            .seek(&WrapPoint::new(start_row, 0), Bias::Left);
102        let mut input_row = self.transforms.start().1.row();
103        if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
104            input_row += (start_row - self.transforms.start().0.row()).0;
105        }
106        self.soft_wrapped = self.transforms.item().is_some_and(|t| !t.is_isomorphic());
107        self.input_buffer_rows.seek(input_row);
108        self.input_buffer_row = self.input_buffer_rows.next().unwrap();
109        self.output_row = start_row;
110    }
111}
112
113impl WrapMap {
114    #[ztracing::instrument(skip_all)]
115    pub fn new(
116        tab_snapshot: TabSnapshot,
117        font: Font,
118        font_size: Pixels,
119        wrap_width: Option<Pixels>,
120        cx: &mut App,
121    ) -> (Entity<Self>, WrapSnapshot) {
122        let handle = cx.new(|cx| {
123            let mut this = Self {
124                font_with_size: (font, font_size),
125                wrap_width: None,
126                pending_edits: Default::default(),
127                interpolated_edits: Default::default(),
128                edits_since_sync: Default::default(),
129                snapshot: WrapSnapshot::new(tab_snapshot),
130                background_task: None,
131            };
132            this.set_wrap_width(wrap_width, cx);
133            mem::take(&mut this.edits_since_sync);
134            this
135        });
136        let snapshot = handle.read(cx).snapshot.clone();
137        (handle, snapshot)
138    }
139
140    #[cfg(test)]
141    pub fn is_rewrapping(&self) -> bool {
142        self.background_task.is_some()
143    }
144
145    #[ztracing::instrument(skip_all)]
146    pub fn sync(
147        &mut self,
148        tab_snapshot: TabSnapshot,
149        edits: Vec<TabEdit>,
150        cx: &mut Context<Self>,
151    ) -> (WrapSnapshot, WrapPatch) {
152        if self.wrap_width.is_some() {
153            self.pending_edits.push_back((tab_snapshot, edits));
154            self.flush_edits(cx);
155        } else {
156            self.edits_since_sync = self
157                .edits_since_sync
158                .compose(self.snapshot.interpolate(tab_snapshot, &edits));
159            self.snapshot.interpolated = false;
160        }
161
162        (self.snapshot.clone(), mem::take(&mut self.edits_since_sync))
163    }
164
165    #[ztracing::instrument(skip_all)]
166    pub fn set_font_with_size(
167        &mut self,
168        font: Font,
169        font_size: Pixels,
170        cx: &mut Context<Self>,
171    ) -> bool {
172        let font_with_size = (font, font_size);
173
174        if font_with_size == self.font_with_size {
175            false
176        } else {
177            self.font_with_size = font_with_size;
178            self.rewrap(cx);
179            true
180        }
181    }
182
183    #[ztracing::instrument(skip_all)]
184    pub fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut Context<Self>) -> bool {
185        if wrap_width == self.wrap_width {
186            return false;
187        }
188
189        self.wrap_width = wrap_width;
190        self.rewrap(cx);
191        true
192    }
193
194    #[ztracing::instrument(skip_all)]
195    fn rewrap(&mut self, cx: &mut Context<Self>) {
196        self.background_task.take();
197        self.interpolated_edits.clear();
198        self.pending_edits.clear();
199
200        if let Some(wrap_width) = self.wrap_width {
201            let mut new_snapshot = self.snapshot.clone();
202
203            let text_system = cx.text_system();
204            let (font, font_size) = self.font_with_size.clone();
205            let mut line_wrapper = text_system.line_wrapper(font, font_size);
206            let tab_snapshot = new_snapshot.tab_snapshot.clone();
207            let total_rows = tab_snapshot.max_point().row() as usize + 1;
208            let range = TabPoint::zero()..tab_snapshot.max_point();
209            let tab_edits = [TabEdit {
210                old: range.clone(),
211                new: range,
212            }];
213
214            if total_rows < WRAP_YIELD_ROW_INTERVAL {
215                let edits = gpui::block_on(new_snapshot.update(
216                    tab_snapshot,
217                    &tab_edits,
218                    wrap_width,
219                    &mut line_wrapper,
220                ));
221                self.snapshot = new_snapshot;
222                self.edits_since_sync = self.edits_since_sync.compose(&edits);
223            } else {
224                let task = cx.background_spawn(async move {
225                    let edits = new_snapshot
226                        .update(tab_snapshot, &tab_edits, wrap_width, &mut line_wrapper)
227                        .await;
228                    (new_snapshot, edits)
229                });
230
231                match cx
232                    .foreground_executor()
233                    .block_with_timeout(Duration::from_millis(5), task)
234                {
235                    Ok((snapshot, edits)) => {
236                        self.snapshot = snapshot;
237                        self.edits_since_sync = self.edits_since_sync.compose(&edits);
238                    }
239                    Err(wrap_task) => {
240                        self.background_task = Some(cx.spawn(async move |this, cx| {
241                            let (snapshot, edits) = wrap_task.await;
242                            this.update(cx, |this, cx| {
243                                this.snapshot = snapshot;
244                                this.edits_since_sync = this
245                                    .edits_since_sync
246                                    .compose(mem::take(&mut this.interpolated_edits).invert())
247                                    .compose(&edits);
248                                this.background_task = None;
249                                this.flush_edits(cx);
250                                cx.notify();
251                            })
252                            .ok();
253                        }));
254                    }
255                }
256            }
257        } else {
258            let old_rows = self.snapshot.transforms.summary().output.lines.row + 1;
259            self.snapshot.transforms = SumTree::default();
260            let summary = self.snapshot.tab_snapshot.text_summary();
261            if !summary.lines.is_zero() {
262                self.snapshot
263                    .transforms
264                    .push(Transform::isomorphic(summary), ());
265            }
266            let new_rows = self.snapshot.transforms.summary().output.lines.row + 1;
267            self.snapshot.interpolated = false;
268            self.edits_since_sync = self.edits_since_sync.compose(Patch::new(vec![WrapEdit {
269                old: WrapRow(0)..WrapRow(old_rows),
270                new: WrapRow(0)..WrapRow(new_rows),
271            }]));
272        }
273    }
274
275    #[ztracing::instrument(skip_all)]
276    fn flush_edits(&mut self, cx: &mut Context<Self>) {
277        if !self.snapshot.interpolated {
278            let mut to_remove_len = 0;
279            for (tab_snapshot, _) in &self.pending_edits {
280                if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
281                    to_remove_len += 1;
282                } else {
283                    break;
284                }
285            }
286            self.pending_edits.drain(..to_remove_len);
287        }
288
289        if self.pending_edits.is_empty() {
290            return;
291        }
292
293        if let Some(wrap_width) = self.wrap_width
294            && self.background_task.is_none()
295        {
296            let mut pending_edits = self.pending_edits.clone();
297            let mut snapshot = self.snapshot.clone();
298            let text_system = cx.text_system().clone();
299            let (font, font_size) = self.font_with_size.clone();
300            let mut line_wrapper = text_system.line_wrapper(font, font_size);
301
302            if pending_edits.len() == 1
303                && let Some((_, tab_edits)) = pending_edits.back()
304                && let [edit] = &**tab_edits
305                && ((edit.new.end.row().saturating_sub(edit.new.start.row()) + 1) as usize)
306                    < WRAP_YIELD_ROW_INTERVAL
307                && let Some((tab_snapshot, tab_edits)) = pending_edits.pop_back()
308            {
309                let wrap_edits = gpui::block_on(snapshot.update(
310                    tab_snapshot,
311                    &tab_edits,
312                    wrap_width,
313                    &mut line_wrapper,
314                ));
315                self.snapshot = snapshot;
316                self.edits_since_sync = self.edits_since_sync.compose(&wrap_edits);
317            } else {
318                let update_task = cx.background_spawn(async move {
319                    let mut edits = Patch::default();
320                    for (tab_snapshot, tab_edits) in pending_edits {
321                        let wrap_edits = snapshot
322                            .update(tab_snapshot, &tab_edits, wrap_width, &mut line_wrapper)
323                            .await;
324                        edits = edits.compose(&wrap_edits);
325                    }
326                    (snapshot, edits)
327                });
328
329                match cx
330                    .foreground_executor()
331                    .block_with_timeout(Duration::from_millis(1), update_task)
332                {
333                    Ok((snapshot, output_edits)) => {
334                        self.snapshot = snapshot;
335                        self.edits_since_sync = self.edits_since_sync.compose(&output_edits);
336                    }
337                    Err(update_task) => {
338                        self.background_task = Some(cx.spawn(async move |this, cx| {
339                            let (snapshot, edits) = update_task.await;
340                            this.update(cx, |this, cx| {
341                                this.snapshot = snapshot;
342                                this.edits_since_sync = this
343                                    .edits_since_sync
344                                    .compose(mem::take(&mut this.interpolated_edits).invert())
345                                    .compose(&edits);
346                                this.background_task = None;
347                                this.flush_edits(cx);
348                                cx.notify();
349                            })
350                            .ok();
351                        }));
352                    }
353                }
354            }
355        }
356
357        let was_interpolated = self.snapshot.interpolated;
358        let mut to_remove_len = 0;
359        for (tab_snapshot, edits) in &self.pending_edits {
360            if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
361                to_remove_len += 1;
362            } else {
363                let interpolated_edits = self.snapshot.interpolate(tab_snapshot.clone(), edits);
364                self.edits_since_sync = self.edits_since_sync.compose(&interpolated_edits);
365                self.interpolated_edits = self.interpolated_edits.compose(&interpolated_edits);
366            }
367        }
368
369        if !was_interpolated {
370            self.pending_edits.drain(..to_remove_len);
371        }
372    }
373}
374
375impl WrapSnapshot {
376    #[ztracing::instrument(skip_all)]
377    fn new(tab_snapshot: TabSnapshot) -> Self {
378        let mut transforms = SumTree::default();
379        let extent = tab_snapshot.text_summary();
380        if !extent.lines.is_zero() {
381            transforms.push(Transform::isomorphic(extent), ());
382        }
383        Self {
384            transforms,
385            tab_snapshot,
386            interpolated: true,
387        }
388    }
389
390    #[ztracing::instrument(skip_all)]
391    fn interpolate(&mut self, new_tab_snapshot: TabSnapshot, tab_edits: &[TabEdit]) -> WrapPatch {
392        let mut new_transforms;
393        if tab_edits.is_empty() {
394            new_transforms = self.transforms.clone();
395        } else if !self.transforms.summary().has_wraps()
396            && !new_tab_snapshot.text_summary().lines.is_zero()
397        {
398            // Fast path: without existing wraps, interpolation is a passthrough over the new tab snapshot.
399            new_transforms = SumTree::default();
400            new_transforms.push(Transform::isomorphic(new_tab_snapshot.text_summary()), ());
401        } else {
402            let mut old_cursor = self.transforms.cursor::<TabPoint>(());
403
404            let mut tab_edits_iter = tab_edits.iter().peekable();
405            new_transforms =
406                old_cursor.slice(&tab_edits_iter.peek().unwrap().old.start, Bias::Right);
407
408            while let Some(edit) = tab_edits_iter.next() {
409                if edit.new.start > TabPoint::from(new_transforms.summary().input.lines) {
410                    let summary = new_tab_snapshot.text_summary_for_range(
411                        TabPoint::from(new_transforms.summary().input.lines)..edit.new.start,
412                    );
413                    new_transforms.push_or_extend(Transform::isomorphic(summary));
414                }
415
416                if !edit.new.is_empty() {
417                    new_transforms.push_or_extend(Transform::isomorphic(
418                        new_tab_snapshot.text_summary_for_range(edit.new.clone()),
419                    ));
420                }
421
422                old_cursor.seek_forward(&edit.old.end, Bias::Right);
423                if let Some(next_edit) = tab_edits_iter.peek() {
424                    if next_edit.old.start > old_cursor.end() {
425                        if old_cursor.end() > edit.old.end {
426                            let summary = self
427                                .tab_snapshot
428                                .text_summary_for_range(edit.old.end..old_cursor.end());
429                            new_transforms.push_or_extend(Transform::isomorphic(summary));
430                        }
431
432                        old_cursor.next();
433                        new_transforms
434                            .append(old_cursor.slice(&next_edit.old.start, Bias::Right), ());
435                    }
436                } else {
437                    if old_cursor.end() > edit.old.end {
438                        let summary = self
439                            .tab_snapshot
440                            .text_summary_for_range(edit.old.end..old_cursor.end());
441                        new_transforms.push_or_extend(Transform::isomorphic(summary));
442                    }
443                    old_cursor.next();
444                    new_transforms.append(old_cursor.suffix(), ());
445                }
446            }
447        }
448
449        let old_snapshot = mem::replace(
450            self,
451            WrapSnapshot {
452                tab_snapshot: new_tab_snapshot,
453                transforms: new_transforms,
454                interpolated: true,
455            },
456        );
457        self.check_invariants();
458        old_snapshot.compute_edits(tab_edits, self)
459    }
460
461    #[ztracing::instrument(skip_all)]
462    async fn update(
463        &mut self,
464        new_tab_snapshot: TabSnapshot,
465        tab_edits: &[TabEdit],
466        wrap_width: Pixels,
467        line_wrapper: &mut LineWrapper,
468    ) -> WrapPatch {
469        #[derive(Debug)]
470        struct RowEdit {
471            old_rows: Range<u32>,
472            new_rows: Range<u32>,
473        }
474
475        let mut tab_edits_iter = tab_edits.iter().peekable();
476        let mut row_edits = Vec::with_capacity(tab_edits.len());
477        while let Some(edit) = tab_edits_iter.next() {
478            let mut row_edit = RowEdit {
479                old_rows: edit.old.start.row()..edit.old.end.row() + 1,
480                new_rows: edit.new.start.row()..edit.new.end.row() + 1,
481            };
482
483            while let Some(next_edit) = tab_edits_iter.peek() {
484                if next_edit.old.start.row() <= row_edit.old_rows.end {
485                    row_edit.old_rows.end =
486                        cmp::max(row_edit.old_rows.end, next_edit.old.end.row() + 1);
487                    row_edit.new_rows.end =
488                        cmp::max(row_edit.new_rows.end, next_edit.new.end.row() + 1);
489                    tab_edits_iter.next();
490                } else {
491                    break;
492                }
493            }
494
495            row_edits.push(row_edit);
496        }
497
498        let mut new_transforms;
499        if row_edits.is_empty() {
500            new_transforms = self.transforms.clone();
501        } else {
502            let mut row_edits = row_edits.into_iter().peekable();
503            let mut old_cursor = self.transforms.cursor::<TabPoint>(());
504
505            new_transforms = old_cursor.slice(
506                &TabPoint::new(row_edits.peek().unwrap().old_rows.start, 0),
507                Bias::Right,
508            );
509
510            while let Some(edit) = row_edits.next() {
511                if edit.new_rows.start > new_transforms.summary().input.lines.row {
512                    let summary = new_tab_snapshot.text_summary_for_range(
513                        TabPoint(new_transforms.summary().input.lines)
514                            ..TabPoint::new(edit.new_rows.start, 0),
515                    );
516                    new_transforms.push_or_extend(Transform::isomorphic(summary));
517                }
518
519                let mut line = String::new();
520                let mut line_fragments = Vec::new();
521                let mut remaining = None;
522                let mut chunks = new_tab_snapshot.chunks(
523                    TabPoint::new(edit.new_rows.start, 0)..new_tab_snapshot.max_point(),
524                    LanguageAwareStyling {
525                        tree_sitter: false,
526                        diagnostics: false,
527                    },
528                    Highlights::default(),
529                );
530                let mut edit_transforms = Vec::<Transform>::new();
531                for (i, _) in (edit.new_rows.start..edit.new_rows.end).enumerate() {
532                    while let Some(chunk) = remaining.take().or_else(|| chunks.next()) {
533                        if let Some(ix) = chunk.text.find('\n') {
534                            let (prefix, suffix) = chunk.text.split_at(ix + 1);
535                            line_fragments.push(gpui::LineFragment::text(prefix));
536                            line.push_str(prefix);
537                            remaining = Some(Chunk {
538                                text: suffix,
539                                ..chunk
540                            });
541                            break;
542                        } else {
543                            if let Some(width) =
544                                chunk.renderer.as_ref().and_then(|r| r.measured_width)
545                            {
546                                line_fragments
547                                    .push(gpui::LineFragment::element(width, chunk.text.len()));
548                            } else {
549                                line_fragments.push(gpui::LineFragment::text(chunk.text));
550                            }
551                            line.push_str(chunk.text);
552                        }
553                    }
554
555                    if line.is_empty() {
556                        break;
557                    }
558
559                    let mut prev_boundary_ix = 0;
560                    for boundary in line_wrapper.wrap_line(&line_fragments, wrap_width) {
561                        let wrapped = &line[prev_boundary_ix..boundary.ix];
562                        push_isomorphic(&mut edit_transforms, TextSummary::from(wrapped));
563                        edit_transforms.push(Transform::wrap(boundary.next_indent));
564                        prev_boundary_ix = boundary.ix;
565                    }
566
567                    if prev_boundary_ix < line.len() {
568                        push_isomorphic(
569                            &mut edit_transforms,
570                            TextSummary::from(&line[prev_boundary_ix..]),
571                        );
572                    }
573
574                    line.clear();
575                    line_fragments.clear();
576                    if i % WRAP_YIELD_ROW_INTERVAL == WRAP_YIELD_ROW_INTERVAL - 1 {
577                        yield_now().await;
578                    }
579                }
580
581                let mut edit_transforms = edit_transforms.into_iter();
582                if let Some(transform) = edit_transforms.next() {
583                    new_transforms.push_or_extend(transform);
584                }
585                new_transforms.extend(edit_transforms, ());
586
587                old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right);
588                if let Some(next_edit) = row_edits.peek() {
589                    if next_edit.old_rows.start > old_cursor.end().row() {
590                        if old_cursor.end() > TabPoint::new(edit.old_rows.end, 0) {
591                            let summary = self.tab_snapshot.text_summary_for_range(
592                                TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(),
593                            );
594                            new_transforms.push_or_extend(Transform::isomorphic(summary));
595                        }
596                        old_cursor.next();
597                        new_transforms.append(
598                            old_cursor
599                                .slice(&TabPoint::new(next_edit.old_rows.start, 0), Bias::Right),
600                            (),
601                        );
602                    }
603                    yield_now().await;
604                } else {
605                    if old_cursor.end() > TabPoint::new(edit.old_rows.end, 0) {
606                        let summary = self.tab_snapshot.text_summary_for_range(
607                            TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(),
608                        );
609                        new_transforms.push_or_extend(Transform::isomorphic(summary));
610                    }
611                    old_cursor.next();
612                    new_transforms.append(old_cursor.suffix(), ());
613                }
614            }
615        }
616
617        let old_snapshot = mem::replace(
618            self,
619            WrapSnapshot {
620                tab_snapshot: new_tab_snapshot,
621                transforms: new_transforms,
622                interpolated: false,
623            },
624        );
625        self.check_invariants();
626        old_snapshot.compute_edits(tab_edits, self)
627    }
628
629    #[ztracing::instrument(skip_all)]
630    fn compute_edits(&self, tab_edits: &[TabEdit], new_snapshot: &WrapSnapshot) -> WrapPatch {
631        let mut wrap_edits = Vec::with_capacity(tab_edits.len());
632        let mut old_cursor = self.transforms.cursor::<TransformSummary>(());
633        let mut new_cursor = new_snapshot.transforms.cursor::<TransformSummary>(());
634        for mut tab_edit in tab_edits.iter().cloned() {
635            tab_edit.old.start.0.column = 0;
636            tab_edit.old.end.0 += Point::new(1, 0);
637            tab_edit.new.start.0.column = 0;
638            tab_edit.new.end.0 += Point::new(1, 0);
639
640            old_cursor.seek(&tab_edit.old.start, Bias::Right);
641            let mut old_start = old_cursor.start().output.lines;
642            old_start += tab_edit.old.start.0 - old_cursor.start().input.lines;
643
644            old_cursor.seek_forward(&tab_edit.old.end, Bias::Right);
645            let mut old_end = old_cursor.start().output.lines;
646            old_end += tab_edit.old.end.0 - old_cursor.start().input.lines;
647
648            new_cursor.seek(&tab_edit.new.start, Bias::Right);
649            let mut new_start = new_cursor.start().output.lines;
650            new_start += tab_edit.new.start.0 - new_cursor.start().input.lines;
651
652            new_cursor.seek_forward(&tab_edit.new.end, Bias::Right);
653            let mut new_end = new_cursor.start().output.lines;
654            new_end += tab_edit.new.end.0 - new_cursor.start().input.lines;
655
656            wrap_edits.push(WrapEdit {
657                old: WrapRow(old_start.row)..WrapRow(old_end.row),
658                new: WrapRow(new_start.row)..WrapRow(new_end.row),
659            });
660        }
661
662        wrap_edits = consolidate_wrap_edits(wrap_edits);
663        Patch::new(wrap_edits)
664    }
665
666    #[ztracing::instrument(skip_all)]
667    pub(crate) fn chunks<'a>(
668        &'a self,
669        rows: Range<WrapRow>,
670        language_aware: LanguageAwareStyling,
671        highlights: Highlights<'a>,
672    ) -> WrapChunks<'a> {
673        let output_start = WrapPoint::new(rows.start, 0);
674        let output_end = WrapPoint::new(rows.end, 0);
675        let mut transforms = self
676            .transforms
677            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
678        transforms.seek(&output_start, Bias::Right);
679        let mut input_start = TabPoint(transforms.start().1.0);
680        if transforms.item().is_some_and(|t| t.is_isomorphic()) {
681            input_start.0 += output_start.0 - transforms.start().0.0;
682        }
683        let input_end = self.to_tab_point(output_end);
684        let max_point = self.tab_snapshot.max_point();
685        let input_start = input_start.min(max_point);
686        let input_end = input_end.min(max_point);
687        WrapChunks {
688            input_chunks: self.tab_snapshot.chunks(
689                input_start..input_end,
690                language_aware,
691                highlights,
692            ),
693            input_chunk: Default::default(),
694            output_position: output_start,
695            max_output_row: rows.end,
696            transforms,
697            snapshot: self,
698        }
699    }
700
701    #[ztracing::instrument(skip_all)]
702    pub fn max_point(&self) -> WrapPoint {
703        WrapPoint(self.transforms.summary().output.lines)
704    }
705
706    #[ztracing::instrument(skip_all)]
707    pub fn line_len(&self, row: WrapRow) -> u32 {
708        let (start, _, item) = self.transforms.find::<Dimensions<WrapPoint, TabPoint>, _>(
709            (),
710            &WrapPoint::new(row + WrapRow(1), 0),
711            Bias::Left,
712        );
713        if item.is_some_and(|transform| transform.is_isomorphic()) {
714            let overshoot = row - start.0.row();
715            let tab_row = start.1.row() + overshoot.0;
716            let tab_line_len = self.tab_snapshot.line_len(tab_row);
717            if overshoot.0 == 0 {
718                start.0.column() + (tab_line_len - start.1.column())
719            } else {
720                tab_line_len
721            }
722        } else {
723            start.0.column()
724        }
725    }
726
727    #[ztracing::instrument(skip_all, fields(rows))]
728    pub fn text_summary_for_range(&self, rows: Range<WrapRow>) -> TextSummary {
729        let mut summary = TextSummary::default();
730
731        let start = WrapPoint::new(rows.start, 0);
732        let end = WrapPoint::new(rows.end, 0);
733
734        let mut cursor = self
735            .transforms
736            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
737        cursor.seek(&start, Bias::Right);
738        if let Some(transform) = cursor.item() {
739            let start_in_transform = start.0 - cursor.start().0.0;
740            let end_in_transform = cmp::min(end, cursor.end().0).0 - cursor.start().0.0;
741            if transform.is_isomorphic() {
742                let tab_start = TabPoint(cursor.start().1.0 + start_in_transform);
743                let tab_end = TabPoint(cursor.start().1.0 + end_in_transform);
744                summary += &self.tab_snapshot.text_summary_for_range(tab_start..tab_end);
745            } else {
746                debug_assert_eq!(start_in_transform.row, end_in_transform.row);
747                let indent_len = end_in_transform.column - start_in_transform.column;
748                summary += &TextSummary {
749                    lines: Point::new(0, indent_len),
750                    first_line_chars: indent_len,
751                    last_line_chars: indent_len,
752                    longest_row: 0,
753                    longest_row_chars: indent_len,
754                };
755            }
756
757            cursor.next();
758        }
759
760        if rows.end > cursor.start().0.row() {
761            summary += &cursor
762                .summary::<_, TransformSummary>(&WrapPoint::new(rows.end, 0), Bias::Right)
763                .output;
764
765            if let Some(transform) = cursor.item() {
766                let end_in_transform = end.0 - cursor.start().0.0;
767                if transform.is_isomorphic() {
768                    let char_start = cursor.start().1;
769                    let char_end = TabPoint(char_start.0 + end_in_transform);
770                    summary += &self
771                        .tab_snapshot
772                        .text_summary_for_range(char_start..char_end);
773                } else {
774                    debug_assert_eq!(end_in_transform, Point::new(1, 0));
775                    summary += &TextSummary {
776                        lines: Point::new(1, 0),
777                        first_line_chars: 0,
778                        last_line_chars: 0,
779                        longest_row: 0,
780                        longest_row_chars: 0,
781                    };
782                }
783            }
784        }
785
786        summary
787    }
788
789    #[ztracing::instrument(skip_all)]
790    pub fn soft_wrap_indent(&self, row: WrapRow) -> Option<u32> {
791        let (.., item) = self.transforms.find::<WrapPoint, _>(
792            (),
793            &WrapPoint::new(row + WrapRow(1), 0),
794            Bias::Right,
795        );
796        item.and_then(|transform| {
797            if transform.is_isomorphic() {
798                None
799            } else {
800                Some(transform.summary.output.lines.column)
801            }
802        })
803    }
804
805    #[ztracing::instrument(skip_all)]
806    pub fn longest_row(&self) -> u32 {
807        self.transforms.summary().output.longest_row
808    }
809
810    #[ztracing::instrument(skip_all)]
811    pub fn row_infos(&self, start_row: WrapRow) -> WrapRows<'_> {
812        let mut transforms = self
813            .transforms
814            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
815        transforms.seek(&WrapPoint::new(start_row, 0), Bias::Left);
816        let mut input_row = transforms.start().1.row();
817        if transforms.item().is_some_and(|t| t.is_isomorphic()) {
818            input_row += (start_row - transforms.start().0.row()).0;
819        }
820        let soft_wrapped = transforms.item().is_some_and(|t| !t.is_isomorphic());
821        let mut input_buffer_rows = self.tab_snapshot.rows(input_row);
822        let input_buffer_row = input_buffer_rows.next().unwrap();
823        WrapRows {
824            transforms,
825            input_buffer_row,
826            input_buffer_rows,
827            output_row: start_row,
828            soft_wrapped,
829            max_output_row: self.max_point().row(),
830        }
831    }
832
833    #[ztracing::instrument(skip_all)]
834    pub fn to_tab_point(&self, point: WrapPoint) -> TabPoint {
835        let (start, _, item) =
836            self.transforms
837                .find::<Dimensions<WrapPoint, TabPoint>, _>((), &point, Bias::Right);
838        let mut tab_point = start.1.0;
839        if item.is_some_and(|t| t.is_isomorphic()) {
840            tab_point += point.0 - start.0.0;
841        }
842        TabPoint(tab_point)
843    }
844
845    #[ztracing::instrument(skip_all)]
846    pub fn to_point(&self, point: WrapPoint, bias: Bias) -> Point {
847        self.tab_snapshot
848            .tab_point_to_point(self.to_tab_point(point), bias)
849    }
850
851    #[ztracing::instrument(skip_all)]
852    pub fn make_wrap_point(&self, point: Point, bias: Bias) -> WrapPoint {
853        self.tab_point_to_wrap_point(self.tab_snapshot.point_to_tab_point(point, bias))
854    }
855
856    #[ztracing::instrument(skip_all)]
857    pub fn tab_point_to_wrap_point(&self, point: TabPoint) -> WrapPoint {
858        let (start, ..) =
859            self.transforms
860                .find::<Dimensions<TabPoint, WrapPoint>, _>((), &point, Bias::Right);
861        WrapPoint(start.1.0 + (point.0 - start.0.0))
862    }
863
864    #[ztracing::instrument(skip_all)]
865    pub fn wrap_point_cursor(&self) -> WrapPointCursor<'_> {
866        WrapPointCursor {
867            cursor: self
868                .transforms
869                .cursor::<Dimensions<TabPoint, WrapPoint>>(()),
870        }
871    }
872
873    #[ztracing::instrument(skip_all)]
874    pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
875        if bias == Bias::Left {
876            let (start, _, item) = self
877                .transforms
878                .find::<WrapPoint, _>((), &point, Bias::Right);
879            if item.is_some_and(|t| !t.is_isomorphic()) {
880                point = start;
881                *point.column_mut() -= 1;
882            }
883        }
884
885        self.tab_point_to_wrap_point(self.tab_snapshot.clip_point(self.to_tab_point(point), bias))
886    }
887
888    /// Try to find a TabRow start that is also a WrapRow start
889    /// Every TabRow start is a WrapRow start
890    #[ztracing::instrument(skip_all, fields(point=?point))]
891    pub fn prev_row_boundary(&self, point: WrapPoint) -> WrapRow {
892        if self.transforms.is_empty() {
893            return WrapRow(0);
894        }
895
896        let point = WrapPoint::new(point.row(), 0);
897
898        let mut cursor = self
899            .transforms
900            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
901
902        cursor.seek(&point, Bias::Right);
903        if cursor.item().is_none() {
904            cursor.prev();
905        }
906
907        //                          real newline     fake          fake
908        // text:      helloworldasldlfjasd\njdlasfalsk\naskdjfasdkfj\n
909        // dimensions v       v           v            v            v
910        // transforms |-------|-----NW----|-----W------|-----W------|
911        // cursor    ^        ^^^^^^^^^^^^^                          ^
912        //                               (^)           ^^^^^^^^^^^^^^
913        // point:                                            ^
914        // point(col_zero):                           (^)
915
916        while let Some(transform) = cursor.item() {
917            if transform.is_isomorphic() {
918                // this transform only has real linefeeds
919                let tab_summary = &transform.summary.input;
920                // is the wrap just before the end of the transform a tab row?
921                // thats only if this transform has at least one newline
922                //
923                // "this wrap row is a tab row" <=> self.to_tab_point(WrapPoint::new(wrap_row, 0)).column() == 0
924
925                // Note on comparison:
926                // We have code that relies on this to be row > 1
927                // It should work with row >= 1 but it does not :(
928                //
929                // That means that if every line is wrapped we walk back all the
930                // way to the start. Which invalidates the entire state triggering
931                // a full re-render.
932                if tab_summary.lines.row > 1 {
933                    let wrap_point_at_end = cursor.end().0.row();
934                    return cmp::min(wrap_point_at_end - RowDelta(1), point.row());
935                } else if cursor.start().1.column() == 0 {
936                    return cmp::min(cursor.end().0.row(), point.row());
937                }
938            }
939
940            cursor.prev();
941        }
942
943        WrapRow(0)
944    }
945
946    #[ztracing::instrument(skip_all)]
947    pub fn next_row_boundary(&self, mut point: WrapPoint) -> Option<WrapRow> {
948        point.0 += Point::new(1, 0);
949
950        let mut cursor = self
951            .transforms
952            .cursor::<Dimensions<WrapPoint, TabPoint>>(());
953        cursor.seek(&point, Bias::Right);
954        while let Some(transform) = cursor.item() {
955            if transform.is_isomorphic() && cursor.start().1.column() == 0 {
956                return Some(cmp::max(cursor.start().0.row(), point.row()));
957            } else {
958                cursor.next();
959            }
960        }
961
962        None
963    }
964
965    #[cfg(test)]
966    pub fn text(&self) -> String {
967        self.text_chunks(WrapRow(0)).collect()
968    }
969
970    #[cfg(test)]
971    pub fn text_chunks(&self, wrap_row: WrapRow) -> impl Iterator<Item = &str> {
972        self.chunks(
973            wrap_row..self.max_point().row() + WrapRow(1),
974            LanguageAwareStyling {
975                tree_sitter: false,
976                diagnostics: false,
977            },
978            Highlights::default(),
979        )
980        .map(|h| h.text)
981    }
982
983    #[ztracing::instrument(skip_all)]
984    fn check_invariants(&self) {
985        #[cfg(test)]
986        {
987            assert_eq!(
988                TabPoint::from(self.transforms.summary().input.lines),
989                self.tab_snapshot.max_point()
990            );
991
992            {
993                let mut transforms = self.transforms.cursor::<()>(()).peekable();
994                while let Some(transform) = transforms.next() {
995                    if let Some(next_transform) = transforms.peek() {
996                        assert!(transform.is_isomorphic() != next_transform.is_isomorphic());
997                    }
998                }
999            }
1000
1001            let text = language::Rope::from(self.text().as_str());
1002            let mut input_buffer_rows = self.tab_snapshot.rows(0);
1003            let mut expected_buffer_rows = Vec::new();
1004            let mut prev_tab_row = 0;
1005            for display_row in 0..=self.max_point().row().0 {
1006                let display_row = WrapRow(display_row);
1007                let tab_point = self.to_tab_point(WrapPoint::new(display_row, 0));
1008                if tab_point.row() == prev_tab_row && display_row != WrapRow(0) {
1009                    expected_buffer_rows.push(None);
1010                } else {
1011                    expected_buffer_rows.push(input_buffer_rows.next().unwrap().buffer_row);
1012                }
1013
1014                prev_tab_row = tab_point.row();
1015                assert_eq!(self.line_len(display_row), text.line_len(display_row.0));
1016            }
1017
1018            for start_display_row in 0..expected_buffer_rows.len() {
1019                assert_eq!(
1020                    self.row_infos(WrapRow(start_display_row as u32))
1021                        .map(|row_info| row_info.buffer_row)
1022                        .collect::<Vec<_>>(),
1023                    &expected_buffer_rows[start_display_row..],
1024                    "invalid buffer_rows({}..)",
1025                    start_display_row
1026                );
1027            }
1028        }
1029    }
1030}
1031
1032pub struct WrapPointCursor<'transforms> {
1033    cursor: Cursor<'transforms, 'static, Transform, Dimensions<TabPoint, WrapPoint>>,
1034}
1035
1036impl WrapPointCursor<'_> {
1037    /// Resets the cursor to the start so it can seek backward again.
1038    pub fn reset(&mut self) {
1039        self.cursor.reset();
1040    }
1041
1042    #[ztracing::instrument(skip_all)]
1043    pub fn map(&mut self, point: TabPoint) -> WrapPoint {
1044        let cursor = &mut self.cursor;
1045        if cursor.did_seek() {
1046            cursor.seek_forward(&point, Bias::Right);
1047        } else {
1048            cursor.seek(&point, Bias::Right);
1049        }
1050        WrapPoint(cursor.start().1.0 + (point.0 - cursor.start().0.0))
1051    }
1052}
1053
1054impl WrapChunks<'_> {
1055    #[ztracing::instrument(skip_all)]
1056    pub(crate) fn seek(&mut self, rows: Range<WrapRow>) {
1057        let output_start = WrapPoint::new(rows.start, 0);
1058        let output_end = WrapPoint::new(rows.end, 0);
1059        self.transforms.seek(&output_start, Bias::Right);
1060        let mut input_start = TabPoint(self.transforms.start().1.0);
1061        if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
1062            input_start.0 += output_start.0 - self.transforms.start().0.0;
1063        }
1064        let input_end = self.snapshot.to_tab_point(output_end);
1065        let max_point = self.snapshot.tab_snapshot.max_point();
1066        let input_start = input_start.min(max_point);
1067        let input_end = input_end.min(max_point);
1068        self.input_chunks.seek(input_start..input_end);
1069        self.input_chunk = Chunk::default();
1070        self.output_position = output_start;
1071        self.max_output_row = rows.end;
1072    }
1073}
1074
1075impl<'a> Iterator for WrapChunks<'a> {
1076    type Item = Chunk<'a>;
1077
1078    #[ztracing::instrument(skip_all)]
1079    fn next(&mut self) -> Option<Self::Item> {
1080        if self.output_position.row() >= self.max_output_row {
1081            return None;
1082        }
1083
1084        let transform = self.transforms.item()?;
1085        if let Some(display_text) = transform.display_text {
1086            let mut start_ix = 0;
1087            let mut end_ix = display_text.len();
1088            let mut summary = transform.summary.output.lines;
1089
1090            if self.output_position > self.transforms.start().0 {
1091                // Exclude newline starting prior to the desired row.
1092                start_ix = 1;
1093                summary.row = 0;
1094            } else if self.output_position.row() + WrapRow(1) >= self.max_output_row {
1095                // Exclude soft indentation ending after the desired row.
1096                end_ix = 1;
1097                summary.column = 0;
1098            }
1099
1100            self.output_position.0 += summary;
1101            self.transforms.next();
1102            return Some(Chunk {
1103                text: &display_text[start_ix..end_ix],
1104                ..Default::default()
1105            });
1106        }
1107
1108        if self.input_chunk.text.is_empty() {
1109            self.input_chunk = self.input_chunks.next()?;
1110        }
1111
1112        let mut input_len = 0;
1113        let transform_end = self.transforms.end().0;
1114        for c in self.input_chunk.text.chars() {
1115            let char_len = c.len_utf8();
1116            input_len += char_len;
1117            if c == '\n' {
1118                *self.output_position.row_mut() += 1;
1119                *self.output_position.column_mut() = 0;
1120            } else {
1121                *self.output_position.column_mut() += char_len as u32;
1122            }
1123
1124            if self.output_position >= transform_end {
1125                self.transforms.next();
1126                break;
1127            }
1128        }
1129
1130        let (prefix, suffix) = self.input_chunk.text.split_at(input_len);
1131
1132        let mask = 1u128.unbounded_shl(input_len as u32).wrapping_sub(1);
1133        let chars = self.input_chunk.chars & mask;
1134        let tabs = self.input_chunk.tabs & mask;
1135        let newlines = self.input_chunk.newlines & mask;
1136        self.input_chunk.tabs = self.input_chunk.tabs.unbounded_shr(input_len as u32);
1137        self.input_chunk.chars = self.input_chunk.chars.unbounded_shr(input_len as u32);
1138        self.input_chunk.newlines = self.input_chunk.newlines.unbounded_shr(input_len as u32);
1139
1140        self.input_chunk.text = suffix;
1141        Some(Chunk {
1142            text: prefix,
1143            chars,
1144            tabs,
1145            newlines,
1146            ..self.input_chunk.clone()
1147        })
1148    }
1149}
1150
1151impl Iterator for WrapRows<'_> {
1152    type Item = RowInfo;
1153
1154    #[ztracing::instrument(skip_all)]
1155    fn next(&mut self) -> Option<Self::Item> {
1156        if self.output_row > self.max_output_row {
1157            return None;
1158        }
1159
1160        let buffer_row = self.input_buffer_row;
1161        let soft_wrapped = self.soft_wrapped;
1162        let diff_status = self.input_buffer_row.diff_status;
1163
1164        self.output_row += WrapRow(1);
1165        self.transforms
1166            .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left);
1167        if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
1168            self.input_buffer_row = self.input_buffer_rows.next().unwrap();
1169            self.soft_wrapped = false;
1170        } else {
1171            self.soft_wrapped = true;
1172        }
1173
1174        Some(if soft_wrapped {
1175            RowInfo {
1176                buffer_id: None,
1177                buffer_row: None,
1178                multibuffer_row: None,
1179                diff_status,
1180                expand_info: None,
1181                wrapped_buffer_row: buffer_row.buffer_row,
1182            }
1183        } else {
1184            buffer_row
1185        })
1186    }
1187}
1188
1189impl Transform {
1190    #[ztracing::instrument(skip_all)]
1191    fn isomorphic(summary: TextSummary) -> Self {
1192        #[cfg(test)]
1193        assert!(!summary.lines.is_zero());
1194
1195        Self {
1196            summary: TransformSummary {
1197                input: summary.clone(),
1198                output: summary,
1199            },
1200            display_text: None,
1201        }
1202    }
1203
1204    #[ztracing::instrument(skip_all)]
1205    fn wrap(indent: u32) -> Self {
1206        static WRAP_TEXT: LazyLock<String> = LazyLock::new(|| {
1207            let mut wrap_text = String::new();
1208            wrap_text.push('\n');
1209            wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
1210            wrap_text
1211        });
1212
1213        Self {
1214            summary: TransformSummary {
1215                input: TextSummary::default(),
1216                output: TextSummary {
1217                    lines: Point::new(1, indent),
1218                    first_line_chars: 0,
1219                    last_line_chars: indent,
1220                    longest_row: 1,
1221                    longest_row_chars: indent,
1222                },
1223            },
1224            display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
1225        }
1226    }
1227
1228    fn is_isomorphic(&self) -> bool {
1229        self.display_text.is_none()
1230    }
1231}
1232
1233impl sum_tree::Item for Transform {
1234    type Summary = TransformSummary;
1235
1236    fn summary(&self, _cx: ()) -> Self::Summary {
1237        self.summary.clone()
1238    }
1239}
1240
1241fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
1242    if let Some(last_transform) = transforms.last_mut()
1243        && last_transform.is_isomorphic()
1244    {
1245        last_transform.summary.input += &summary;
1246        last_transform.summary.output += &summary;
1247        return;
1248    }
1249    transforms.push(Transform::isomorphic(summary));
1250}
1251
1252trait SumTreeExt {
1253    fn push_or_extend(&mut self, transform: Transform);
1254}
1255
1256impl SumTreeExt for SumTree<Transform> {
1257    #[ztracing::instrument(skip_all)]
1258    fn push_or_extend(&mut self, transform: Transform) {
1259        let mut transform = Some(transform);
1260        self.update_last(
1261            |last_transform| {
1262                if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
1263                    let transform = transform.take().unwrap();
1264                    last_transform.summary.input += &transform.summary.input;
1265                    last_transform.summary.output += &transform.summary.output;
1266                }
1267            },
1268            (),
1269        );
1270
1271        if let Some(transform) = transform {
1272            self.push(transform, ());
1273        }
1274    }
1275}
1276
1277impl WrapPoint {
1278    pub fn new(row: WrapRow, column: u32) -> Self {
1279        Self(Point::new(row.0, column))
1280    }
1281
1282    pub fn row(self) -> WrapRow {
1283        WrapRow(self.0.row)
1284    }
1285
1286    pub fn row_mut(&mut self) -> &mut u32 {
1287        &mut self.0.row
1288    }
1289
1290    pub fn column(self) -> u32 {
1291        self.0.column
1292    }
1293
1294    pub fn column_mut(&mut self) -> &mut u32 {
1295        &mut self.0.column
1296    }
1297}
1298
1299impl sum_tree::ContextLessSummary for TransformSummary {
1300    fn zero() -> Self {
1301        Default::default()
1302    }
1303
1304    fn add_summary(&mut self, other: &Self) {
1305        self.input += &other.input;
1306        self.output += &other.output;
1307    }
1308}
1309
1310impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
1311    fn zero(_cx: ()) -> Self {
1312        Default::default()
1313    }
1314
1315    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1316        self.0 += summary.input.lines;
1317    }
1318}
1319
1320impl sum_tree::SeekTarget<'_, TransformSummary, TransformSummary> for TabPoint {
1321    #[ztracing::instrument(skip_all)]
1322    fn cmp(&self, cursor_location: &TransformSummary, _: ()) -> std::cmp::Ordering {
1323        Ord::cmp(&self.0, &cursor_location.input.lines)
1324    }
1325}
1326
1327impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
1328    fn zero(_cx: ()) -> Self {
1329        Default::default()
1330    }
1331
1332    fn add_summary(&mut self, summary: &'a TransformSummary, _: ()) {
1333        self.0 += summary.output.lines;
1334    }
1335}
1336
1337fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
1338    let _old_alloc_ptr = edits.as_ptr();
1339    let mut wrap_edits = edits.into_iter();
1340
1341    if let Some(mut first_edit) = wrap_edits.next() {
1342        // This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
1343        #[allow(clippy::filter_map_identity)]
1344        let mut v: Vec<_> = wrap_edits
1345            .scan(&mut first_edit, |prev_edit, edit| {
1346                if prev_edit.old.end >= edit.old.start {
1347                    prev_edit.old.end = edit.old.end;
1348                    prev_edit.new.end = edit.new.end;
1349                    Some(None) // Skip this edit, it's merged
1350                } else {
1351                    let prev = std::mem::replace(*prev_edit, edit);
1352                    Some(Some(prev)) // Yield the previous edit
1353                }
1354            })
1355            .filter_map(|x| x)
1356            .collect();
1357        v.push(first_edit.clone());
1358        debug_assert_eq!(v.as_ptr(), _old_alloc_ptr, "Wrap edits were reallocated");
1359        v
1360    } else {
1361        vec![]
1362    }
1363}
1364
1365#[cfg(test)]
1366mod tests {
1367    use super::*;
1368    use crate::{
1369        MultiBuffer,
1370        display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
1371        test::test_font,
1372    };
1373    use futures::stream::StreamExt;
1374    use gpui::{LineFragment, px, test::observe};
1375    use rand::prelude::*;
1376    use settings::SettingsStore;
1377    use std::{cmp, env, num::NonZeroU32};
1378    use text::Rope;
1379    use theme::LoadThemes;
1380
1381    #[gpui::test]
1382    async fn test_prev_row_boundary(cx: &mut gpui::TestAppContext) {
1383        init_test(cx);
1384
1385        fn test_wrap_snapshot(
1386            text: &str,
1387            soft_wrap_every: usize, // font size multiple
1388            cx: &mut gpui::TestAppContext,
1389        ) -> WrapSnapshot {
1390            let text_system = cx.read(|cx| cx.text_system().clone());
1391            let tab_size = 4.try_into().unwrap();
1392            let font = test_font();
1393            let _font_id = text_system.resolve_font(&font);
1394            let font_size = px(14.0);
1395            // this is very much an estimate to try and get the wrapping to
1396            // occur at `soft_wrap_every` we check that it pans out for every test case
1397            let soft_wrapping = Some(font_size * soft_wrap_every * 0.6);
1398
1399            let buffer = cx.new(|cx| language::Buffer::local(text, cx));
1400            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1401            let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1402            let (_inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
1403            let (_fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
1404            let (mut tab_map, _) = TabMap::new(fold_snapshot, tab_size);
1405            let tabs_snapshot = tab_map.set_max_expansion_column(32);
1406            let (_wrap_map, wrap_snapshot) =
1407                cx.update(|cx| WrapMap::new(tabs_snapshot, font, font_size, soft_wrapping, cx));
1408
1409            wrap_snapshot
1410        }
1411
1412        // These two should pass but dont, see the comparison note in
1413        // prev_row_boundary about why.
1414        //
1415        // //                                      0123  4567  wrap_rows
1416        // let wrap_snapshot = test_wrap_snapshot("1234\n5678", 1, cx);
1417        // assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8");
1418        // let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1419        // assert_eq!(row.0, 3);
1420
1421        // //                                      012  345  678  wrap_rows
1422        // let wrap_snapshot = test_wrap_snapshot("123\n456\n789", 1, cx);
1423        // assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8\n9");
1424        // let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1425        // assert_eq!(row.0, 5);
1426
1427        //                                      012345678  wrap_rows
1428        let wrap_snapshot = test_wrap_snapshot("123456789", 1, cx);
1429        assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8\n9");
1430        let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1431        assert_eq!(row.0, 0);
1432
1433        //                                      111  2222    44  wrap_rows
1434        let wrap_snapshot = test_wrap_snapshot("123\n4567\n\n89", 4, cx);
1435        assert_eq!(wrap_snapshot.text(), "123\n4567\n\n89");
1436        let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1437        assert_eq!(row.0, 2);
1438
1439        //                                      11  2223   wrap_rows
1440        let wrap_snapshot = test_wrap_snapshot("12\n3456\n\n", 3, cx);
1441        assert_eq!(wrap_snapshot.text(), "12\n345\n6\n\n");
1442        let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
1443        assert_eq!(row.0, 3);
1444    }
1445
1446    #[gpui::test(iterations = 100)]
1447    async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1448        // todo this test is flaky
1449        init_test(cx);
1450
1451        cx.background_executor.set_block_on_ticks(0..=50);
1452        let operations = env::var("OPERATIONS")
1453            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1454            .unwrap_or(10);
1455
1456        let text_system = cx.read(|cx| cx.text_system().clone());
1457        let mut wrap_width = if rng.random_bool(0.1) {
1458            None
1459        } else {
1460            Some(px(rng.random_range(0.0..=1000.0)))
1461        };
1462        let tab_size = NonZeroU32::new(rng.random_range(1..=4)).unwrap();
1463
1464        let font = test_font();
1465        let _font_id = text_system.resolve_font(&font);
1466        let font_size = px(14.0);
1467
1468        log::info!("Tab size: {}", tab_size);
1469        log::info!("Wrap width: {:?}", wrap_width);
1470
1471        let buffer = cx.update(|cx| {
1472            if rng.random() {
1473                MultiBuffer::build_random(&mut rng, cx)
1474            } else {
1475                let len = rng.random_range(0..10);
1476                let text = util::RandomCharIter::new(&mut rng)
1477                    .take(len)
1478                    .collect::<String>();
1479                MultiBuffer::build_simple(&text, cx)
1480            }
1481        });
1482        let mut buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1483        log::info!("Buffer text: {:?}", buffer_snapshot.text());
1484        let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1485        log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1486        let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot.clone());
1487        log::info!("FoldMap text: {:?}", fold_snapshot.text());
1488        let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
1489        let tabs_snapshot = tab_map.set_max_expansion_column(32);
1490        log::info!("TabMap text: {:?}", tabs_snapshot.text());
1491
1492        let mut line_wrapper = text_system.line_wrapper(font.clone(), font_size);
1493        let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1494
1495        let (wrap_map, _) =
1496            cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font, font_size, wrap_width, cx));
1497        let mut notifications = observe(&wrap_map, cx);
1498
1499        if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1500            notifications.next().await.unwrap();
1501        }
1502
1503        let (initial_snapshot, _) = wrap_map.update(cx, |map, cx| {
1504            assert!(!map.is_rewrapping());
1505            map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1506        });
1507
1508        let actual_text = initial_snapshot.text();
1509        assert_eq!(
1510            actual_text,
1511            expected_text,
1512            "unwrapped text is: {:?}",
1513            tabs_snapshot.text()
1514        );
1515        log::info!("Wrapped text: {:?}", actual_text);
1516
1517        let mut next_inlay_id = 0;
1518        let mut edits = Vec::new();
1519        for _i in 0..operations {
1520            log::info!("{} ==============================================", _i);
1521
1522            let mut buffer_edits = Vec::new();
1523            match rng.random_range(0..=100) {
1524                0..=19 => {
1525                    wrap_width = if rng.random_bool(0.2) {
1526                        None
1527                    } else {
1528                        Some(px(rng.random_range(0.0..=1000.0)))
1529                    };
1530                    log::info!("Setting wrap width to {:?}", wrap_width);
1531                    wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1532                }
1533                20..=39 => {
1534                    for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1535                        let (tabs_snapshot, tab_edits) =
1536                            tab_map.sync(fold_snapshot, fold_edits, tab_size);
1537                        let (mut snapshot, wrap_edits) =
1538                            wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1539                        snapshot.check_invariants();
1540                        snapshot.verify_chunks(&mut rng);
1541                        edits.push((snapshot, wrap_edits));
1542                    }
1543                }
1544                40..=59 => {
1545                    let (inlay_snapshot, inlay_edits) =
1546                        inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1547                    let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1548                    let (tabs_snapshot, tab_edits) =
1549                        tab_map.sync(fold_snapshot, fold_edits, tab_size);
1550                    let (mut snapshot, wrap_edits) =
1551                        wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1552                    snapshot.check_invariants();
1553                    snapshot.verify_chunks(&mut rng);
1554                    edits.push((snapshot, wrap_edits));
1555                }
1556                _ => {
1557                    buffer.update(cx, |buffer, cx| {
1558                        let subscription = buffer.subscribe();
1559                        let edit_count = rng.random_range(1..=5);
1560                        buffer.randomly_mutate(&mut rng, edit_count, cx);
1561                        buffer_snapshot = buffer.snapshot(cx);
1562                        buffer_edits.extend(subscription.consume());
1563                    });
1564                }
1565            }
1566
1567            log::info!("Buffer text: {:?}", buffer_snapshot.text());
1568            let (inlay_snapshot, inlay_edits) =
1569                inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1570            log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1571            let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1572            log::info!("FoldMap text: {:?}", fold_snapshot.text());
1573            let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
1574            log::info!("TabMap text: {:?}", tabs_snapshot.text());
1575
1576            let expected_text = wrap_text(&tabs_snapshot, wrap_width, &mut line_wrapper);
1577            let (mut snapshot, wrap_edits) =
1578                wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot.clone(), tab_edits, cx));
1579            snapshot.check_invariants();
1580            snapshot.verify_chunks(&mut rng);
1581            edits.push((snapshot, wrap_edits));
1582
1583            if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) && rng.random_bool(0.4) {
1584                log::info!("Waiting for wrapping to finish");
1585                while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1586                    notifications.next().await.unwrap();
1587                }
1588                wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1589            }
1590
1591            if !wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1592                let (mut wrapped_snapshot, wrap_edits) = wrap_map.update(cx, |map, cx| {
1593                    map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1594                });
1595                let actual_text = wrapped_snapshot.text();
1596                let actual_longest_row = wrapped_snapshot.longest_row();
1597                log::info!("Wrapping finished: {:?}", actual_text);
1598                wrapped_snapshot.check_invariants();
1599                wrapped_snapshot.verify_chunks(&mut rng);
1600                edits.push((wrapped_snapshot.clone(), wrap_edits));
1601                assert_eq!(
1602                    actual_text,
1603                    expected_text,
1604                    "unwrapped text is: {:?}",
1605                    tabs_snapshot.text()
1606                );
1607
1608                let mut summary = TextSummary::default();
1609                for (ix, item) in wrapped_snapshot
1610                    .transforms
1611                    .items(())
1612                    .into_iter()
1613                    .enumerate()
1614                {
1615                    summary += &item.summary.output;
1616                    log::info!("{} summary: {:?}", ix, item.summary.output,);
1617                }
1618
1619                if tab_size.get() == 1
1620                    || !wrapped_snapshot
1621                        .tab_snapshot
1622                        .fold_snapshot
1623                        .text()
1624                        .contains('\t')
1625                {
1626                    let mut expected_longest_rows = Vec::new();
1627                    let mut longest_line_len = -1;
1628                    for (row, line) in expected_text.split('\n').enumerate() {
1629                        let line_char_count = line.chars().count() as isize;
1630                        if line_char_count > longest_line_len {
1631                            expected_longest_rows.clear();
1632                            longest_line_len = line_char_count;
1633                        }
1634                        if line_char_count >= longest_line_len {
1635                            expected_longest_rows.push(row as u32);
1636                        }
1637                    }
1638
1639                    assert!(
1640                        expected_longest_rows.contains(&actual_longest_row),
1641                        "incorrect longest row {}. expected {:?} with length {}",
1642                        actual_longest_row,
1643                        expected_longest_rows,
1644                        longest_line_len,
1645                    )
1646                }
1647            }
1648        }
1649
1650        let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1651        for (snapshot, patch) in edits {
1652            let snapshot_text = Rope::from(snapshot.text().as_str());
1653            for edit in &patch {
1654                let old_start = initial_text.point_to_offset(Point::new(edit.new.start.0, 0));
1655                let old_end = initial_text.point_to_offset(cmp::min(
1656                    Point::new(edit.new.start.0 + (edit.old.end - edit.old.start).0, 0),
1657                    initial_text.max_point(),
1658                ));
1659                let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start.0, 0));
1660                let new_end = snapshot_text.point_to_offset(cmp::min(
1661                    Point::new(edit.new.end.0, 0),
1662                    snapshot_text.max_point(),
1663                ));
1664                let new_text = snapshot_text
1665                    .chunks_in_range(new_start..new_end)
1666                    .collect::<String>();
1667
1668                initial_text.replace(old_start..old_end, &new_text);
1669            }
1670            assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1671        }
1672
1673        if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1674            log::info!("Waiting for wrapping to finish");
1675            while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1676                notifications.next().await.unwrap();
1677            }
1678        }
1679        wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1680    }
1681
1682    fn init_test(cx: &mut gpui::TestAppContext) {
1683        cx.update(|cx| {
1684            let settings = SettingsStore::test(cx);
1685            cx.set_global(settings);
1686            theme_settings::init(LoadThemes::JustBase, cx);
1687        });
1688    }
1689
1690    fn wrap_text(
1691        tab_snapshot: &TabSnapshot,
1692        wrap_width: Option<Pixels>,
1693        line_wrapper: &mut LineWrapper,
1694    ) -> String {
1695        if let Some(wrap_width) = wrap_width {
1696            let mut wrapped_text = String::new();
1697            for (row, line) in tab_snapshot.text().split('\n').enumerate() {
1698                if row > 0 {
1699                    wrapped_text.push('\n');
1700                }
1701
1702                let mut prev_ix = 0;
1703                for boundary in line_wrapper.wrap_line(&[LineFragment::text(line)], wrap_width) {
1704                    wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1705                    wrapped_text.push('\n');
1706                    wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1707                    prev_ix = boundary.ix;
1708                }
1709                wrapped_text.push_str(&line[prev_ix..]);
1710            }
1711
1712            wrapped_text
1713        } else {
1714            tab_snapshot.text()
1715        }
1716    }
1717
1718    impl WrapSnapshot {
1719        fn verify_chunks(&mut self, rng: &mut impl Rng) {
1720            for _ in 0..5 {
1721                let mut end_row = rng.random_range(0..=self.max_point().row().0);
1722                let start_row = rng.random_range(0..=end_row);
1723                end_row += 1;
1724
1725                let mut expected_text = self.text_chunks(WrapRow(start_row)).collect::<String>();
1726                if expected_text.ends_with('\n') {
1727                    expected_text.push('\n');
1728                }
1729                let mut expected_text = expected_text
1730                    .lines()
1731                    .take((end_row - start_row) as usize)
1732                    .collect::<Vec<_>>()
1733                    .join("\n");
1734                if end_row <= self.max_point().row().0 {
1735                    expected_text.push('\n');
1736                }
1737
1738                let actual_text = self
1739                    .chunks(
1740                        WrapRow(start_row)..WrapRow(end_row),
1741                        LanguageAwareStyling {
1742                            tree_sitter: true,
1743                            diagnostics: true,
1744                        },
1745                        Highlights::default(),
1746                    )
1747                    .map(|c| c.text)
1748                    .collect::<String>();
1749                assert_eq!(
1750                    expected_text,
1751                    actual_text,
1752                    "chunks != highlighted_chunks for rows {:?}",
1753                    start_row..end_row
1754                );
1755            }
1756        }
1757    }
1758}
1759
Served at tenant.openagents/omega Member data and write actions are omitted.