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.build_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 cx.notify();
188 }
189 Err(wrap_task) => {
190 self.background_task = Some(cx.spawn(|this, mut cx| async move {
191 let (snapshot, edits) = wrap_task.await;
192 this.update(&mut cx, |this, cx| {
193 this.snapshot = snapshot;
194 this.edits_since_sync = this
195 .edits_since_sync
196 .compose(mem::take(&mut this.interpolated_edits).invert())
197 .compose(&edits);
198 this.background_task = None;
199 this.flush_edits(cx);
200 cx.notify();
201 });
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 }));
283 }
284 }
285 }
286 }
287
288 let was_interpolated = self.snapshot.interpolated;
289 let mut to_remove_len = 0;
290 for (tab_snapshot, edits) in &self.pending_edits {
291 if tab_snapshot.version <= self.snapshot.tab_snapshot.version {
292 to_remove_len += 1;
293 } else {
294 let interpolated_edits = self.snapshot.interpolate(tab_snapshot.clone(), edits);
295 self.edits_since_sync = self.edits_since_sync.compose(&interpolated_edits);
296 self.interpolated_edits = self.interpolated_edits.compose(&interpolated_edits);
297 }
298 }
299
300 if !was_interpolated {
301 self.pending_edits.drain(..to_remove_len);
302 }
303 }
304}
305
306impl WrapSnapshot {
307 fn new(tab_snapshot: TabSnapshot) -> Self {
308 let mut transforms = SumTree::new();
309 let extent = tab_snapshot.text_summary();
310 if !extent.lines.is_zero() {
311 transforms.push(Transform::isomorphic(extent), &());
312 }
313 Self {
314 transforms,
315 tab_snapshot,
316 interpolated: true,
317 }
318 }
319
320 pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
321 self.tab_snapshot.buffer_snapshot()
322 }
323
324 fn interpolate(&mut self, new_tab_snapshot: TabSnapshot, tab_edits: &[TabEdit]) -> Patch<u32> {
325 let mut new_transforms;
326 if tab_edits.is_empty() {
327 new_transforms = self.transforms.clone();
328 } else {
329 let mut old_cursor = self.transforms.cursor::<TabPoint>();
330
331 let mut tab_edits_iter = tab_edits.iter().peekable();
332 new_transforms =
333 old_cursor.slice(&tab_edits_iter.peek().unwrap().old.start, Bias::Right, &());
334
335 while let Some(edit) = tab_edits_iter.next() {
336 if edit.new.start > TabPoint::from(new_transforms.summary().input.lines) {
337 let summary = new_tab_snapshot.text_summary_for_range(
338 TabPoint::from(new_transforms.summary().input.lines)..edit.new.start,
339 );
340 new_transforms.push_or_extend(Transform::isomorphic(summary));
341 }
342
343 if !edit.new.is_empty() {
344 new_transforms.push_or_extend(Transform::isomorphic(
345 new_tab_snapshot.text_summary_for_range(edit.new.clone()),
346 ));
347 }
348
349 old_cursor.seek_forward(&edit.old.end, Bias::Right, &());
350 if let Some(next_edit) = tab_edits_iter.peek() {
351 if next_edit.old.start > old_cursor.end(&()) {
352 if old_cursor.end(&()) > edit.old.end {
353 let summary = self
354 .tab_snapshot
355 .text_summary_for_range(edit.old.end..old_cursor.end(&()));
356 new_transforms.push_or_extend(Transform::isomorphic(summary));
357 }
358
359 old_cursor.next(&());
360 new_transforms.append(
361 old_cursor.slice(&next_edit.old.start, Bias::Right, &()),
362 &(),
363 );
364 }
365 } else {
366 if old_cursor.end(&()) > edit.old.end {
367 let summary = self
368 .tab_snapshot
369 .text_summary_for_range(edit.old.end..old_cursor.end(&()));
370 new_transforms.push_or_extend(Transform::isomorphic(summary));
371 }
372 old_cursor.next(&());
373 new_transforms.append(old_cursor.suffix(&()), &());
374 }
375 }
376 }
377
378 let old_snapshot = mem::replace(
379 self,
380 WrapSnapshot {
381 tab_snapshot: new_tab_snapshot,
382 transforms: new_transforms,
383 interpolated: true,
384 },
385 );
386 self.check_invariants();
387 old_snapshot.compute_edits(tab_edits, self)
388 }
389
390 async fn update(
391 &mut self,
392 new_tab_snapshot: TabSnapshot,
393 tab_edits: &[TabEdit],
394 wrap_width: Pixels,
395 line_wrapper: &mut LineWrapper,
396 ) -> Patch<u32> {
397 #[derive(Debug)]
398 struct RowEdit {
399 old_rows: Range<u32>,
400 new_rows: Range<u32>,
401 }
402
403 let mut tab_edits_iter = tab_edits.iter().peekable();
404 let mut row_edits = Vec::new();
405 while let Some(edit) = tab_edits_iter.next() {
406 let mut row_edit = RowEdit {
407 old_rows: edit.old.start.row()..edit.old.end.row() + 1,
408 new_rows: edit.new.start.row()..edit.new.end.row() + 1,
409 };
410
411 while let Some(next_edit) = tab_edits_iter.peek() {
412 if next_edit.old.start.row() <= row_edit.old_rows.end {
413 row_edit.old_rows.end = next_edit.old.end.row() + 1;
414 row_edit.new_rows.end = next_edit.new.end.row() + 1;
415 tab_edits_iter.next();
416 } else {
417 break;
418 }
419 }
420
421 row_edits.push(row_edit);
422 }
423
424 let mut new_transforms;
425 if row_edits.is_empty() {
426 new_transforms = self.transforms.clone();
427 } else {
428 let mut row_edits = row_edits.into_iter().peekable();
429 let mut old_cursor = self.transforms.cursor::<TabPoint>();
430
431 new_transforms = old_cursor.slice(
432 &TabPoint::new(row_edits.peek().unwrap().old_rows.start, 0),
433 Bias::Right,
434 &(),
435 );
436
437 while let Some(edit) = row_edits.next() {
438 if edit.new_rows.start > new_transforms.summary().input.lines.row {
439 let summary = new_tab_snapshot.text_summary_for_range(
440 TabPoint(new_transforms.summary().input.lines)
441 ..TabPoint::new(edit.new_rows.start, 0),
442 );
443 new_transforms.push_or_extend(Transform::isomorphic(summary));
444 }
445
446 let mut line = String::new();
447 let mut remaining = None;
448 let mut chunks = new_tab_snapshot.chunks(
449 TabPoint::new(edit.new_rows.start, 0)..new_tab_snapshot.max_point(),
450 false,
451 Highlights::default(),
452 );
453 let mut edit_transforms = Vec::<Transform>::new();
454 for _ in edit.new_rows.start..edit.new_rows.end {
455 while let Some(chunk) =
456 remaining.take().or_else(|| chunks.next().map(|c| c.text))
457 {
458 if let Some(ix) = chunk.find('\n') {
459 line.push_str(&chunk[..ix + 1]);
460 remaining = Some(&chunk[ix + 1..]);
461 break;
462 } else {
463 line.push_str(chunk)
464 }
465 }
466
467 if line.is_empty() {
468 break;
469 }
470
471 let mut prev_boundary_ix = 0;
472 for boundary in line_wrapper.wrap_line(&line, wrap_width) {
473 let wrapped = &line[prev_boundary_ix..boundary.ix];
474 push_isomorphic(&mut edit_transforms, TextSummary::from(wrapped));
475 edit_transforms.push(Transform::wrap(boundary.next_indent));
476 prev_boundary_ix = boundary.ix;
477 }
478
479 if prev_boundary_ix < line.len() {
480 push_isomorphic(
481 &mut edit_transforms,
482 TextSummary::from(&line[prev_boundary_ix..]),
483 );
484 }
485
486 line.clear();
487 yield_now().await;
488 }
489
490 let mut edit_transforms = edit_transforms.into_iter();
491 if let Some(transform) = edit_transforms.next() {
492 new_transforms.push_or_extend(transform);
493 }
494 new_transforms.extend(edit_transforms, &());
495
496 old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right, &());
497 if let Some(next_edit) = row_edits.peek() {
498 if next_edit.old_rows.start > old_cursor.end(&()).row() {
499 if old_cursor.end(&()) > TabPoint::new(edit.old_rows.end, 0) {
500 let summary = self.tab_snapshot.text_summary_for_range(
501 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(&()),
502 );
503 new_transforms.push_or_extend(Transform::isomorphic(summary));
504 }
505 old_cursor.next(&());
506 new_transforms.append(
507 old_cursor.slice(
508 &TabPoint::new(next_edit.old_rows.start, 0),
509 Bias::Right,
510 &(),
511 ),
512 &(),
513 );
514 }
515 } else {
516 if old_cursor.end(&()) > TabPoint::new(edit.old_rows.end, 0) {
517 let summary = self.tab_snapshot.text_summary_for_range(
518 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(&()),
519 );
520 new_transforms.push_or_extend(Transform::isomorphic(summary));
521 }
522 old_cursor.next(&());
523 new_transforms.append(old_cursor.suffix(&()), &());
524 }
525 }
526 }
527
528 let old_snapshot = mem::replace(
529 self,
530 WrapSnapshot {
531 tab_snapshot: new_tab_snapshot,
532 transforms: new_transforms,
533 interpolated: false,
534 },
535 );
536 self.check_invariants();
537 old_snapshot.compute_edits(tab_edits, self)
538 }
539
540 fn compute_edits(&self, tab_edits: &[TabEdit], new_snapshot: &WrapSnapshot) -> Patch<u32> {
541 let mut wrap_edits = Vec::new();
542 let mut old_cursor = self.transforms.cursor::<TransformSummary>();
543 let mut new_cursor = new_snapshot.transforms.cursor::<TransformSummary>();
544 for mut tab_edit in tab_edits.iter().cloned() {
545 tab_edit.old.start.0.column = 0;
546 tab_edit.old.end.0 += Point::new(1, 0);
547 tab_edit.new.start.0.column = 0;
548 tab_edit.new.end.0 += Point::new(1, 0);
549
550 old_cursor.seek(&tab_edit.old.start, Bias::Right, &());
551 let mut old_start = old_cursor.start().output.lines;
552 old_start += tab_edit.old.start.0 - old_cursor.start().input.lines;
553
554 old_cursor.seek(&tab_edit.old.end, Bias::Right, &());
555 let mut old_end = old_cursor.start().output.lines;
556 old_end += tab_edit.old.end.0 - old_cursor.start().input.lines;
557
558 new_cursor.seek(&tab_edit.new.start, Bias::Right, &());
559 let mut new_start = new_cursor.start().output.lines;
560 new_start += tab_edit.new.start.0 - new_cursor.start().input.lines;
561
562 new_cursor.seek(&tab_edit.new.end, Bias::Right, &());
563 let mut new_end = new_cursor.start().output.lines;
564 new_end += tab_edit.new.end.0 - new_cursor.start().input.lines;
565
566 wrap_edits.push(WrapEdit {
567 old: old_start.row..old_end.row,
568 new: new_start.row..new_end.row,
569 });
570 }
571
572 consolidate_wrap_edits(&mut wrap_edits);
573 Patch::new(wrap_edits)
574 }
575
576 pub fn chunks<'a>(
577 &'a self,
578 rows: Range<u32>,
579 language_aware: bool,
580 highlights: Highlights<'a>,
581 ) -> WrapChunks<'a> {
582 let output_start = WrapPoint::new(rows.start, 0);
583 let output_end = WrapPoint::new(rows.end, 0);
584 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>();
585 transforms.seek(&output_start, Bias::Right, &());
586 let mut input_start = TabPoint(transforms.start().1 .0);
587 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
588 input_start.0 += output_start.0 - transforms.start().0 .0;
589 }
590 let input_end = self
591 .to_tab_point(output_end)
592 .min(self.tab_snapshot.max_point());
593 WrapChunks {
594 input_chunks: self.tab_snapshot.chunks(
595 input_start..input_end,
596 language_aware,
597 highlights,
598 ),
599 input_chunk: Default::default(),
600 output_position: output_start,
601 max_output_row: rows.end,
602 transforms,
603 }
604 }
605
606 pub fn max_point(&self) -> WrapPoint {
607 WrapPoint(self.transforms.summary().output.lines)
608 }
609
610 pub fn line_len(&self, row: u32) -> u32 {
611 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>();
612 cursor.seek(&WrapPoint::new(row + 1, 0), Bias::Left, &());
613 if cursor
614 .item()
615 .map_or(false, |transform| transform.is_isomorphic())
616 {
617 let overshoot = row - cursor.start().0.row();
618 let tab_row = cursor.start().1.row() + overshoot;
619 let tab_line_len = self.tab_snapshot.line_len(tab_row);
620 if overshoot == 0 {
621 cursor.start().0.column() + (tab_line_len - cursor.start().1.column())
622 } else {
623 tab_line_len
624 }
625 } else {
626 cursor.start().0.column()
627 }
628 }
629
630 pub fn soft_wrap_indent(&self, row: u32) -> Option<u32> {
631 let mut cursor = self.transforms.cursor::<WrapPoint>();
632 cursor.seek(&WrapPoint::new(row + 1, 0), Bias::Right, &());
633 cursor.item().and_then(|transform| {
634 if transform.is_isomorphic() {
635 None
636 } else {
637 Some(transform.summary.output.lines.column)
638 }
639 })
640 }
641
642 pub fn longest_row(&self) -> u32 {
643 self.transforms.summary().output.longest_row
644 }
645
646 pub fn buffer_rows(&self, start_row: u32) -> WrapBufferRows {
647 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>();
648 transforms.seek(&WrapPoint::new(start_row, 0), Bias::Left, &());
649 let mut input_row = transforms.start().1.row();
650 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
651 input_row += start_row - transforms.start().0.row();
652 }
653 let soft_wrapped = transforms.item().map_or(false, |t| !t.is_isomorphic());
654 let mut input_buffer_rows = self.tab_snapshot.buffer_rows(input_row);
655 let input_buffer_row = input_buffer_rows.next().unwrap();
656 WrapBufferRows {
657 transforms,
658 input_buffer_row,
659 input_buffer_rows,
660 output_row: start_row,
661 soft_wrapped,
662 max_output_row: self.max_point().row(),
663 }
664 }
665
666 pub fn to_tab_point(&self, point: WrapPoint) -> TabPoint {
667 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>();
668 cursor.seek(&point, Bias::Right, &());
669 let mut tab_point = cursor.start().1 .0;
670 if cursor.item().map_or(false, |t| t.is_isomorphic()) {
671 tab_point += point.0 - cursor.start().0 .0;
672 }
673 TabPoint(tab_point)
674 }
675
676 pub fn to_point(&self, point: WrapPoint, bias: Bias) -> Point {
677 self.tab_snapshot.to_point(self.to_tab_point(point), bias)
678 }
679
680 pub fn make_wrap_point(&self, point: Point, bias: Bias) -> WrapPoint {
681 self.tab_point_to_wrap_point(self.tab_snapshot.make_tab_point(point, bias))
682 }
683
684 pub fn tab_point_to_wrap_point(&self, point: TabPoint) -> WrapPoint {
685 let mut cursor = self.transforms.cursor::<(TabPoint, WrapPoint)>();
686 cursor.seek(&point, Bias::Right, &());
687 WrapPoint(cursor.start().1 .0 + (point.0 - cursor.start().0 .0))
688 }
689
690 pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
691 if bias == Bias::Left {
692 let mut cursor = self.transforms.cursor::<WrapPoint>();
693 cursor.seek(&point, Bias::Right, &());
694 if cursor.item().map_or(false, |t| !t.is_isomorphic()) {
695 point = *cursor.start();
696 *point.column_mut() -= 1;
697 }
698 }
699
700 self.tab_point_to_wrap_point(self.tab_snapshot.clip_point(self.to_tab_point(point), bias))
701 }
702
703 pub fn prev_row_boundary(&self, mut point: WrapPoint) -> u32 {
704 if self.transforms.is_empty() {
705 return 0;
706 }
707
708 *point.column_mut() = 0;
709
710 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>();
711 cursor.seek(&point, Bias::Right, &());
712 if cursor.item().is_none() {
713 cursor.prev(&());
714 }
715
716 while let Some(transform) = cursor.item() {
717 if transform.is_isomorphic() && cursor.start().1.column() == 0 {
718 return cmp::min(cursor.end(&()).0.row(), point.row());
719 } else {
720 cursor.prev(&());
721 }
722 }
723
724 unreachable!()
725 }
726
727 pub fn next_row_boundary(&self, mut point: WrapPoint) -> Option<u32> {
728 point.0 += Point::new(1, 0);
729
730 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>();
731 cursor.seek(&point, Bias::Right, &());
732 while let Some(transform) = cursor.item() {
733 if transform.is_isomorphic() && cursor.start().1.column() == 0 {
734 return Some(cmp::max(cursor.start().0.row(), point.row()));
735 } else {
736 cursor.next(&());
737 }
738 }
739
740 None
741 }
742
743 fn check_invariants(&self) {
744 // todo!()
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)]
1030// mod 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::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
1043// #[gpui::test(iterations = 100)]
1044// async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1045// init_test(cx);
1046
1047// cx.foreground().set_block_on_ticks(0..=50);
1048// let operations = env::var("OPERATIONS")
1049// .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1050// .unwrap_or(10);
1051
1052// let font_cache = cx.font_cache().clone();
1053// let font_system = cx.platform().fonts();
1054// let mut wrap_width = if rng.gen_bool(0.1) {
1055// None
1056// } else {
1057// Some(rng.gen_range(0.0..=1000.0))
1058// };
1059// let tab_size = NonZeroU32::new(rng.gen_range(1..=4)).unwrap();
1060// let family_id = font_cache
1061// .load_family(&["Helvetica"], &Default::default())
1062// .unwrap();
1063// let font_id = font_cache
1064// .select_font(family_id, &Default::default())
1065// .unwrap();
1066// let font_size = 14.0;
1067
1068// log::info!("Tab size: {}", tab_size);
1069// log::info!("Wrap width: {:?}", wrap_width);
1070
1071// let buffer = cx.update(|cx| {
1072// if rng.gen() {
1073// MultiBuffer::build_random(&mut rng, cx)
1074// } else {
1075// let len = rng.gen_range(0..10);
1076// let text = util::RandomCharIter::new(&mut rng)
1077// .take(len)
1078// .collect::<String>();
1079// MultiBuffer::build_simple(&text, cx)
1080// }
1081// });
1082// let mut buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1083// log::info!("Buffer text: {:?}", buffer_snapshot.text());
1084// let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1085// log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1086// let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot.clone());
1087// log::info!("FoldMap text: {:?}", fold_snapshot.text());
1088// let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
1089// let tabs_snapshot = tab_map.set_max_expansion_column(32);
1090// log::info!("TabMap text: {:?}", tabs_snapshot.text());
1091
1092// let mut line_wrapper = LineWrapper::new(font_id, font_size, font_system);
1093// let unwrapped_text = tabs_snapshot.text();
1094// let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1095
1096// let (wrap_map, _) =
1097// cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font_id, font_size, wrap_width, cx));
1098// let mut notifications = observe(&wrap_map, cx);
1099
1100// if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1101// notifications.next().await.unwrap();
1102// }
1103
1104// let (initial_snapshot, _) = wrap_map.update(cx, |map, cx| {
1105// assert!(!map.is_rewrapping());
1106// map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1107// });
1108
1109// let actual_text = initial_snapshot.text();
1110// assert_eq!(
1111// actual_text, expected_text,
1112// "unwrapped text is: {:?}",
1113// unwrapped_text
1114// );
1115// log::info!("Wrapped text: {:?}", actual_text);
1116
1117// let mut next_inlay_id = 0;
1118// let mut edits = Vec::new();
1119// for _i in 0..operations {
1120// log::info!("{} ==============================================", _i);
1121
1122// let mut buffer_edits = Vec::new();
1123// match rng.gen_range(0..=100) {
1124// 0..=19 => {
1125// wrap_width = if rng.gen_bool(0.2) {
1126// None
1127// } else {
1128// Some(rng.gen_range(0.0..=1000.0))
1129// };
1130// log::info!("Setting wrap width to {:?}", wrap_width);
1131// wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1132// }
1133// 20..=39 => {
1134// for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1135// let (tabs_snapshot, tab_edits) =
1136// tab_map.sync(fold_snapshot, fold_edits, tab_size);
1137// let (mut snapshot, wrap_edits) =
1138// wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1139// snapshot.check_invariants();
1140// snapshot.verify_chunks(&mut rng);
1141// edits.push((snapshot, wrap_edits));
1142// }
1143// }
1144// 40..=59 => {
1145// let (inlay_snapshot, inlay_edits) =
1146// inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
1147// let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1148// let (tabs_snapshot, tab_edits) =
1149// tab_map.sync(fold_snapshot, fold_edits, tab_size);
1150// let (mut snapshot, wrap_edits) =
1151// wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1152// snapshot.check_invariants();
1153// snapshot.verify_chunks(&mut rng);
1154// edits.push((snapshot, wrap_edits));
1155// }
1156// _ => {
1157// buffer.update(cx, |buffer, cx| {
1158// let subscription = buffer.subscribe();
1159// let edit_count = rng.gen_range(1..=5);
1160// buffer.randomly_mutate(&mut rng, edit_count, cx);
1161// buffer_snapshot = buffer.snapshot(cx);
1162// buffer_edits.extend(subscription.consume());
1163// });
1164// }
1165// }
1166
1167// log::info!("Buffer text: {:?}", buffer_snapshot.text());
1168// let (inlay_snapshot, inlay_edits) =
1169// inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1170// log::info!("InlayMap text: {:?}", inlay_snapshot.text());
1171// let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1172// log::info!("FoldMap text: {:?}", fold_snapshot.text());
1173// let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
1174// log::info!("TabMap text: {:?}", tabs_snapshot.text());
1175
1176// let unwrapped_text = tabs_snapshot.text();
1177// let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1178// let (mut snapshot, wrap_edits) =
1179// wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot.clone(), tab_edits, cx));
1180// snapshot.check_invariants();
1181// snapshot.verify_chunks(&mut rng);
1182// edits.push((snapshot, wrap_edits));
1183
1184// if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) && rng.gen_bool(0.4) {
1185// log::info!("Waiting for wrapping to finish");
1186// while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1187// notifications.next().await.unwrap();
1188// }
1189// wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1190// }
1191
1192// if !wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1193// let (mut wrapped_snapshot, wrap_edits) =
1194// wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, Vec::new(), cx));
1195// let actual_text = wrapped_snapshot.text();
1196// let actual_longest_row = wrapped_snapshot.longest_row();
1197// log::info!("Wrapping finished: {:?}", actual_text);
1198// wrapped_snapshot.check_invariants();
1199// wrapped_snapshot.verify_chunks(&mut rng);
1200// edits.push((wrapped_snapshot.clone(), wrap_edits));
1201// assert_eq!(
1202// actual_text, expected_text,
1203// "unwrapped text is: {:?}",
1204// unwrapped_text
1205// );
1206
1207// let mut summary = TextSummary::default();
1208// for (ix, item) in wrapped_snapshot
1209// .transforms
1210// .items(&())
1211// .into_iter()
1212// .enumerate()
1213// {
1214// summary += &item.summary.output;
1215// log::info!("{} summary: {:?}", ix, item.summary.output,);
1216// }
1217
1218// if tab_size.get() == 1
1219// || !wrapped_snapshot
1220// .tab_snapshot
1221// .fold_snapshot
1222// .text()
1223// .contains('\t')
1224// {
1225// let mut expected_longest_rows = Vec::new();
1226// let mut longest_line_len = -1;
1227// for (row, line) in expected_text.split('\n').enumerate() {
1228// let line_char_count = line.chars().count() as isize;
1229// if line_char_count > longest_line_len {
1230// expected_longest_rows.clear();
1231// longest_line_len = line_char_count;
1232// }
1233// if line_char_count >= longest_line_len {
1234// expected_longest_rows.push(row as u32);
1235// }
1236// }
1237
1238// assert!(
1239// expected_longest_rows.contains(&actual_longest_row),
1240// "incorrect longest row {}. expected {:?} with length {}",
1241// actual_longest_row,
1242// expected_longest_rows,
1243// longest_line_len,
1244// )
1245// }
1246// }
1247// }
1248
1249// let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1250// for (snapshot, patch) in edits {
1251// let snapshot_text = Rope::from(snapshot.text().as_str());
1252// for edit in &patch {
1253// let old_start = initial_text.point_to_offset(Point::new(edit.new.start, 0));
1254// let old_end = initial_text.point_to_offset(cmp::min(
1255// Point::new(edit.new.start + edit.old.len() as u32, 0),
1256// initial_text.max_point(),
1257// ));
1258// let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start, 0));
1259// let new_end = snapshot_text.point_to_offset(cmp::min(
1260// Point::new(edit.new.end, 0),
1261// snapshot_text.max_point(),
1262// ));
1263// let new_text = snapshot_text
1264// .chunks_in_range(new_start..new_end)
1265// .collect::<String>();
1266
1267// initial_text.replace(old_start..old_end, &new_text);
1268// }
1269// assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1270// }
1271
1272// if wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1273// log::info!("Waiting for wrapping to finish");
1274// while wrap_map.read_with(cx, |map, _| map.is_rewrapping()) {
1275// notifications.next().await.unwrap();
1276// }
1277// }
1278// wrap_map.read_with(cx, |map, _| assert!(map.pending_edits.is_empty()));
1279// }
1280
1281// fn init_test(cx: &mut gpui::TestAppContext) {
1282// cx.foreground().forbid_parking();
1283// cx.update(|cx| {
1284// cx.set_global(SettingsStore::test(cx));
1285// theme::init((), cx);
1286// });
1287// }
1288
1289// fn wrap_text(
1290// unwrapped_text: &str,
1291// wrap_width: Option<f32>,
1292// line_wrapper: &mut LineWrapper,
1293// ) -> String {
1294// if let Some(wrap_width) = wrap_width {
1295// let mut wrapped_text = String::new();
1296// for (row, line) in unwrapped_text.split('\n').enumerate() {
1297// if row > 0 {
1298// wrapped_text.push('\n')
1299// }
1300
1301// let mut prev_ix = 0;
1302// for boundary in line_wrapper.wrap_line(line, wrap_width) {
1303// wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1304// wrapped_text.push('\n');
1305// wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1306// prev_ix = boundary.ix;
1307// }
1308// wrapped_text.push_str(&line[prev_ix..]);
1309// }
1310// wrapped_text
1311// } else {
1312// unwrapped_text.to_string()
1313// }
1314// }
1315
1316// impl WrapSnapshot {
1317// pub fn text(&self) -> String {
1318// self.text_chunks(0).collect()
1319// }
1320
1321// pub fn text_chunks(&self, wrap_row: u32) -> impl Iterator<Item = &str> {
1322// self.chunks(
1323// wrap_row..self.max_point().row() + 1,
1324// false,
1325// Highlights::default(),
1326// )
1327// .map(|h| h.text)
1328// }
1329
1330// fn verify_chunks(&mut self, rng: &mut impl Rng) {
1331// for _ in 0..5 {
1332// let mut end_row = rng.gen_range(0..=self.max_point().row());
1333// let start_row = rng.gen_range(0..=end_row);
1334// end_row += 1;
1335
1336// let mut expected_text = self.text_chunks(start_row).collect::<String>();
1337// if expected_text.ends_with('\n') {
1338// expected_text.push('\n');
1339// }
1340// let mut expected_text = expected_text
1341// .lines()
1342// .take((end_row - start_row) as usize)
1343// .collect::<Vec<_>>()
1344// .join("\n");
1345// if end_row <= self.max_point().row() {
1346// expected_text.push('\n');
1347// }
1348
1349// let actual_text = self
1350// .chunks(start_row..end_row, true, Highlights::default())
1351// .map(|c| c.text)
1352// .collect::<String>();
1353// assert_eq!(
1354// expected_text,
1355// actual_text,
1356// "chunks != highlighted_chunks for rows {:?}",
1357// start_row..end_row
1358// );
1359// }
1360// }
1361// }
1362// }