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