1use super::*;
2use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
3use gpui::{App, TestAppContext};
4use indoc::indoc;
5use language::{Buffer, Rope};
6use parking_lot::RwLock;
7use rand::prelude::*;
8use settings::SettingsStore;
9use std::env;
10use util::test::sample_text;
11
12#[ctor::ctor]
13fn init_logger() {
14 if std::env::var("RUST_LOG").is_ok() {
15 env_logger::init();
16 }
17}
18
19#[gpui::test]
20fn test_empty_singleton(cx: &mut App) {
21 let buffer = cx.new(|cx| Buffer::local("", cx));
22 let buffer_id = buffer.read(cx).remote_id();
23 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
24 let snapshot = multibuffer.read(cx).snapshot(cx);
25 assert_eq!(snapshot.text(), "");
26 assert_eq!(
27 snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>(),
28 [RowInfo {
29 buffer_id: Some(buffer_id),
30 buffer_row: Some(0),
31 multibuffer_row: Some(MultiBufferRow(0)),
32 diff_status: None
33 }]
34 );
35}
36
37#[gpui::test]
38fn test_singleton(cx: &mut App) {
39 let buffer = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
40 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
41
42 let snapshot = multibuffer.read(cx).snapshot(cx);
43 assert_eq!(snapshot.text(), buffer.read(cx).text());
44
45 assert_eq!(
46 snapshot
47 .row_infos(MultiBufferRow(0))
48 .map(|info| info.buffer_row)
49 .collect::<Vec<_>>(),
50 (0..buffer.read(cx).row_count())
51 .map(Some)
52 .collect::<Vec<_>>()
53 );
54 assert_consistent_line_numbers(&snapshot);
55
56 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
57 let snapshot = multibuffer.read(cx).snapshot(cx);
58
59 assert_eq!(snapshot.text(), buffer.read(cx).text());
60 assert_eq!(
61 snapshot
62 .row_infos(MultiBufferRow(0))
63 .map(|info| info.buffer_row)
64 .collect::<Vec<_>>(),
65 (0..buffer.read(cx).row_count())
66 .map(Some)
67 .collect::<Vec<_>>()
68 );
69 assert_consistent_line_numbers(&snapshot);
70}
71
72#[gpui::test]
73fn test_remote(cx: &mut App) {
74 let host_buffer = cx.new(|cx| Buffer::local("a", cx));
75 let guest_buffer = cx.new(|cx| {
76 let state = host_buffer.read(cx).to_proto(cx);
77 let ops = cx
78 .background_executor()
79 .block(host_buffer.read(cx).serialize_ops(None, cx));
80 let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
81 buffer.apply_ops(
82 ops.into_iter()
83 .map(|op| language::proto::deserialize_operation(op).unwrap()),
84 cx,
85 );
86 buffer
87 });
88 let multibuffer = cx.new(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
89 let snapshot = multibuffer.read(cx).snapshot(cx);
90 assert_eq!(snapshot.text(), "a");
91
92 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
93 let snapshot = multibuffer.read(cx).snapshot(cx);
94 assert_eq!(snapshot.text(), "ab");
95
96 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
97 let snapshot = multibuffer.read(cx).snapshot(cx);
98 assert_eq!(snapshot.text(), "abc");
99}
100
101#[gpui::test]
102fn test_excerpt_boundaries_and_clipping(cx: &mut App) {
103 let buffer_1 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
104 let buffer_2 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
105 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
106
107 let events = Arc::new(RwLock::new(Vec::<Event>::new()));
108 multibuffer.update(cx, |_, cx| {
109 let events = events.clone();
110 cx.subscribe(&multibuffer, move |_, _, event, _| {
111 if let Event::Edited { .. } = event {
112 events.write().push(event.clone())
113 }
114 })
115 .detach();
116 });
117
118 let subscription = multibuffer.update(cx, |multibuffer, cx| {
119 let subscription = multibuffer.subscribe();
120 multibuffer.push_excerpts(
121 buffer_1.clone(),
122 [ExcerptRange {
123 context: Point::new(1, 2)..Point::new(2, 5),
124 primary: None,
125 }],
126 cx,
127 );
128 assert_eq!(
129 subscription.consume().into_inner(),
130 [Edit {
131 old: 0..0,
132 new: 0..10
133 }]
134 );
135
136 multibuffer.push_excerpts(
137 buffer_1.clone(),
138 [ExcerptRange {
139 context: Point::new(3, 3)..Point::new(4, 4),
140 primary: None,
141 }],
142 cx,
143 );
144 multibuffer.push_excerpts(
145 buffer_2.clone(),
146 [ExcerptRange {
147 context: Point::new(3, 1)..Point::new(3, 3),
148 primary: None,
149 }],
150 cx,
151 );
152 assert_eq!(
153 subscription.consume().into_inner(),
154 [Edit {
155 old: 10..10,
156 new: 10..22
157 }]
158 );
159
160 subscription
161 });
162
163 // Adding excerpts emits an edited event.
164 assert_eq!(
165 events.read().as_slice(),
166 &[
167 Event::Edited {
168 singleton_buffer_edited: false,
169 edited_buffer: None,
170 },
171 Event::Edited {
172 singleton_buffer_edited: false,
173 edited_buffer: None,
174 },
175 Event::Edited {
176 singleton_buffer_edited: false,
177 edited_buffer: None,
178 }
179 ]
180 );
181
182 let snapshot = multibuffer.read(cx).snapshot(cx);
183 assert_eq!(
184 snapshot.text(),
185 indoc!(
186 "
187 bbbb
188 ccccc
189 ddd
190 eeee
191 jj"
192 ),
193 );
194 assert_eq!(
195 snapshot
196 .row_infos(MultiBufferRow(0))
197 .map(|info| info.buffer_row)
198 .collect::<Vec<_>>(),
199 [Some(1), Some(2), Some(3), Some(4), Some(3)]
200 );
201 assert_eq!(
202 snapshot
203 .row_infos(MultiBufferRow(2))
204 .map(|info| info.buffer_row)
205 .collect::<Vec<_>>(),
206 [Some(3), Some(4), Some(3)]
207 );
208 assert_eq!(
209 snapshot
210 .row_infos(MultiBufferRow(4))
211 .map(|info| info.buffer_row)
212 .collect::<Vec<_>>(),
213 [Some(3)]
214 );
215 assert_eq!(
216 snapshot
217 .row_infos(MultiBufferRow(5))
218 .map(|info| info.buffer_row)
219 .collect::<Vec<_>>(),
220 []
221 );
222
223 assert_eq!(
224 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
225 &[
226 (MultiBufferRow(0), "bbbb\nccccc".to_string(), true),
227 (MultiBufferRow(2), "ddd\neeee".to_string(), false),
228 (MultiBufferRow(4), "jj".to_string(), true),
229 ]
230 );
231 assert_eq!(
232 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
233 &[(MultiBufferRow(0), "bbbb\nccccc".to_string(), true)]
234 );
235 assert_eq!(
236 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
237 &[]
238 );
239 assert_eq!(
240 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
241 &[]
242 );
243 assert_eq!(
244 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
245 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
246 );
247 assert_eq!(
248 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
249 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
250 );
251 assert_eq!(
252 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
253 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
254 );
255 assert_eq!(
256 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
257 &[(MultiBufferRow(4), "jj".to_string(), true)]
258 );
259 assert_eq!(
260 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
261 &[]
262 );
263
264 buffer_1.update(cx, |buffer, cx| {
265 let text = "\n";
266 buffer.edit(
267 [
268 (Point::new(0, 0)..Point::new(0, 0), text),
269 (Point::new(2, 1)..Point::new(2, 3), text),
270 ],
271 None,
272 cx,
273 );
274 });
275
276 let snapshot = multibuffer.read(cx).snapshot(cx);
277 assert_eq!(
278 snapshot.text(),
279 concat!(
280 "bbbb\n", // Preserve newlines
281 "c\n", //
282 "cc\n", //
283 "ddd\n", //
284 "eeee\n", //
285 "jj" //
286 )
287 );
288
289 assert_eq!(
290 subscription.consume().into_inner(),
291 [Edit {
292 old: 6..8,
293 new: 6..7
294 }]
295 );
296
297 let snapshot = multibuffer.read(cx).snapshot(cx);
298 assert_eq!(
299 snapshot.clip_point(Point::new(0, 5), Bias::Left),
300 Point::new(0, 4)
301 );
302 assert_eq!(
303 snapshot.clip_point(Point::new(0, 5), Bias::Right),
304 Point::new(0, 4)
305 );
306 assert_eq!(
307 snapshot.clip_point(Point::new(5, 1), Bias::Right),
308 Point::new(5, 1)
309 );
310 assert_eq!(
311 snapshot.clip_point(Point::new(5, 2), Bias::Right),
312 Point::new(5, 2)
313 );
314 assert_eq!(
315 snapshot.clip_point(Point::new(5, 3), Bias::Right),
316 Point::new(5, 2)
317 );
318
319 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
320 let (buffer_2_excerpt_id, _) =
321 multibuffer.excerpts_for_buffer(buffer_2.read(cx).remote_id(), cx)[0].clone();
322 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
323 multibuffer.snapshot(cx)
324 });
325
326 assert_eq!(
327 snapshot.text(),
328 concat!(
329 "bbbb\n", // Preserve newlines
330 "c\n", //
331 "cc\n", //
332 "ddd\n", //
333 "eeee", //
334 )
335 );
336
337 fn boundaries_in_range(
338 range: Range<Point>,
339 snapshot: &MultiBufferSnapshot,
340 ) -> Vec<(MultiBufferRow, String, bool)> {
341 snapshot
342 .excerpt_boundaries_in_range(range)
343 .filter_map(|boundary| {
344 let starts_new_buffer = boundary.starts_new_buffer();
345 boundary.next.map(|next| {
346 (
347 boundary.row,
348 next.buffer
349 .text_for_range(next.range.context)
350 .collect::<String>(),
351 starts_new_buffer,
352 )
353 })
354 })
355 .collect::<Vec<_>>()
356 }
357}
358
359#[gpui::test]
360fn test_diff_boundary_anchors(cx: &mut TestAppContext) {
361 let base_text = "one\ntwo\nthree\n";
362 let text = "one\nthree\n";
363 let buffer = cx.new(|cx| Buffer::local(text, cx));
364 let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
365 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
366 multibuffer.update(cx, |multibuffer, cx| multibuffer.add_diff(diff, cx));
367
368 let (before, after) = multibuffer.update(cx, |multibuffer, cx| {
369 let before = multibuffer.snapshot(cx).anchor_before(Point::new(1, 0));
370 let after = multibuffer.snapshot(cx).anchor_after(Point::new(1, 0));
371 multibuffer.set_all_diff_hunks_expanded(cx);
372 (before, after)
373 });
374 cx.run_until_parked();
375
376 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
377 let actual_text = snapshot.text();
378 let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
379 let actual_diff = format_diff(&actual_text, &actual_row_infos, &Default::default(), None);
380 pretty_assertions::assert_eq!(
381 actual_diff,
382 indoc! {
383 " one
384 - two
385 three
386 "
387 },
388 );
389
390 multibuffer.update(cx, |multibuffer, cx| {
391 let snapshot = multibuffer.snapshot(cx);
392 assert_eq!(before.to_point(&snapshot), Point::new(1, 0));
393 assert_eq!(after.to_point(&snapshot), Point::new(2, 0));
394 assert_eq!(
395 vec![Point::new(1, 0), Point::new(2, 0),],
396 snapshot.summaries_for_anchors::<Point, _>(&[before, after]),
397 )
398 })
399}
400
401#[gpui::test]
402fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
403 let base_text = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n";
404 let text = "one\nfour\nseven\n";
405 let buffer = cx.new(|cx| Buffer::local(text, cx));
406 let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
407 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
408 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
409 (multibuffer.snapshot(cx), multibuffer.subscribe())
410 });
411
412 multibuffer.update(cx, |multibuffer, cx| {
413 multibuffer.add_diff(diff, cx);
414 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
415 });
416
417 assert_new_snapshot(
418 &multibuffer,
419 &mut snapshot,
420 &mut subscription,
421 cx,
422 indoc! {
423 " one
424 - two
425 - three
426 four
427 - five
428 - six
429 seven
430 - eight
431 "
432 },
433 );
434
435 assert_eq!(
436 snapshot
437 .diff_hunks_in_range(Point::new(1, 0)..Point::MAX)
438 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
439 .collect::<Vec<_>>(),
440 vec![1..3, 4..6, 7..8]
441 );
442
443 assert_eq!(
444 snapshot
445 .diff_hunk_before(Point::new(1, 1))
446 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0),
447 None,
448 );
449 assert_eq!(
450 snapshot
451 .diff_hunk_before(Point::new(7, 0))
452 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0),
453 Some(4..6)
454 );
455 assert_eq!(
456 snapshot
457 .diff_hunk_before(Point::new(4, 0))
458 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0),
459 Some(1..3)
460 );
461
462 multibuffer.update(cx, |multibuffer, cx| {
463 multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
464 });
465
466 assert_new_snapshot(
467 &multibuffer,
468 &mut snapshot,
469 &mut subscription,
470 cx,
471 indoc! {
472 "
473 one
474 four
475 seven
476 "
477 },
478 );
479
480 assert_eq!(
481 snapshot
482 .diff_hunk_before(Point::new(2, 0))
483 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0),
484 Some(1..1),
485 );
486 assert_eq!(
487 snapshot
488 .diff_hunk_before(Point::new(4, 0))
489 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0),
490 Some(2..2)
491 );
492}
493
494#[gpui::test]
495fn test_editing_text_in_diff_hunks(cx: &mut TestAppContext) {
496 let base_text = "one\ntwo\nfour\nfive\nsix\nseven\n";
497 let text = "one\ntwo\nTHREE\nfour\nfive\nseven\n";
498 let buffer = cx.new(|cx| Buffer::local(text, cx));
499 let diff = cx.new(|cx| BufferDiff::new_with_base_text(&base_text, &buffer, cx));
500 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
501
502 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
503 multibuffer.add_diff(diff.clone(), cx);
504 (multibuffer.snapshot(cx), multibuffer.subscribe())
505 });
506
507 cx.executor().run_until_parked();
508 multibuffer.update(cx, |multibuffer, cx| {
509 multibuffer.set_all_diff_hunks_expanded(cx);
510 });
511
512 assert_new_snapshot(
513 &multibuffer,
514 &mut snapshot,
515 &mut subscription,
516 cx,
517 indoc! {
518 "
519 one
520 two
521 + THREE
522 four
523 five
524 - six
525 seven
526 "
527 },
528 );
529
530 // Insert a newline within an insertion hunk
531 multibuffer.update(cx, |multibuffer, cx| {
532 multibuffer.edit([(Point::new(2, 0)..Point::new(2, 0), "__\n__")], None, cx);
533 });
534 assert_new_snapshot(
535 &multibuffer,
536 &mut snapshot,
537 &mut subscription,
538 cx,
539 indoc! {
540 "
541 one
542 two
543 + __
544 + __THREE
545 four
546 five
547 - six
548 seven
549 "
550 },
551 );
552
553 // Delete the newline before a deleted hunk.
554 multibuffer.update(cx, |multibuffer, cx| {
555 multibuffer.edit([(Point::new(5, 4)..Point::new(6, 0), "")], None, cx);
556 });
557 assert_new_snapshot(
558 &multibuffer,
559 &mut snapshot,
560 &mut subscription,
561 cx,
562 indoc! {
563 "
564 one
565 two
566 + __
567 + __THREE
568 four
569 fiveseven
570 "
571 },
572 );
573
574 multibuffer.update(cx, |multibuffer, cx| multibuffer.undo(cx));
575 assert_new_snapshot(
576 &multibuffer,
577 &mut snapshot,
578 &mut subscription,
579 cx,
580 indoc! {
581 "
582 one
583 two
584 + __
585 + __THREE
586 four
587 five
588 - six
589 seven
590 "
591 },
592 );
593
594 // Cannot (yet) insert at the beginning of a deleted hunk.
595 // (because it would put the newline in the wrong place)
596 multibuffer.update(cx, |multibuffer, cx| {
597 multibuffer.edit([(Point::new(6, 0)..Point::new(6, 0), "\n")], None, cx);
598 });
599 assert_new_snapshot(
600 &multibuffer,
601 &mut snapshot,
602 &mut subscription,
603 cx,
604 indoc! {
605 "
606 one
607 two
608 + __
609 + __THREE
610 four
611 five
612 - six
613 seven
614 "
615 },
616 );
617
618 // Replace a range that ends in a deleted hunk.
619 multibuffer.update(cx, |multibuffer, cx| {
620 multibuffer.edit([(Point::new(5, 2)..Point::new(6, 2), "fty-")], None, cx);
621 });
622 assert_new_snapshot(
623 &multibuffer,
624 &mut snapshot,
625 &mut subscription,
626 cx,
627 indoc! {
628 "
629 one
630 two
631 + __
632 + __THREE
633 four
634 fifty-seven
635 "
636 },
637 );
638}
639
640#[gpui::test]
641fn test_excerpt_events(cx: &mut App) {
642 let buffer_1 = cx.new(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
643 let buffer_2 = cx.new(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
644
645 let leader_multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
646 let follower_multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
647 let follower_edit_event_count = Arc::new(RwLock::new(0));
648
649 follower_multibuffer.update(cx, |_, cx| {
650 let follower_edit_event_count = follower_edit_event_count.clone();
651 cx.subscribe(
652 &leader_multibuffer,
653 move |follower, _, event, cx| match event.clone() {
654 Event::ExcerptsAdded {
655 buffer,
656 predecessor,
657 excerpts,
658 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
659 Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
660 Event::Edited { .. } => {
661 *follower_edit_event_count.write() += 1;
662 }
663 _ => {}
664 },
665 )
666 .detach();
667 });
668
669 leader_multibuffer.update(cx, |leader, cx| {
670 leader.push_excerpts(
671 buffer_1.clone(),
672 [
673 ExcerptRange {
674 context: 0..8,
675 primary: None,
676 },
677 ExcerptRange {
678 context: 12..16,
679 primary: None,
680 },
681 ],
682 cx,
683 );
684 leader.insert_excerpts_after(
685 leader.excerpt_ids()[0],
686 buffer_2.clone(),
687 [
688 ExcerptRange {
689 context: 0..5,
690 primary: None,
691 },
692 ExcerptRange {
693 context: 10..15,
694 primary: None,
695 },
696 ],
697 cx,
698 )
699 });
700 assert_eq!(
701 leader_multibuffer.read(cx).snapshot(cx).text(),
702 follower_multibuffer.read(cx).snapshot(cx).text(),
703 );
704 assert_eq!(*follower_edit_event_count.read(), 2);
705
706 leader_multibuffer.update(cx, |leader, cx| {
707 let excerpt_ids = leader.excerpt_ids();
708 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
709 });
710 assert_eq!(
711 leader_multibuffer.read(cx).snapshot(cx).text(),
712 follower_multibuffer.read(cx).snapshot(cx).text(),
713 );
714 assert_eq!(*follower_edit_event_count.read(), 3);
715
716 // Removing an empty set of excerpts is a noop.
717 leader_multibuffer.update(cx, |leader, cx| {
718 leader.remove_excerpts([], cx);
719 });
720 assert_eq!(
721 leader_multibuffer.read(cx).snapshot(cx).text(),
722 follower_multibuffer.read(cx).snapshot(cx).text(),
723 );
724 assert_eq!(*follower_edit_event_count.read(), 3);
725
726 // Adding an empty set of excerpts is a noop.
727 leader_multibuffer.update(cx, |leader, cx| {
728 leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
729 });
730 assert_eq!(
731 leader_multibuffer.read(cx).snapshot(cx).text(),
732 follower_multibuffer.read(cx).snapshot(cx).text(),
733 );
734 assert_eq!(*follower_edit_event_count.read(), 3);
735
736 leader_multibuffer.update(cx, |leader, cx| {
737 leader.clear(cx);
738 });
739 assert_eq!(
740 leader_multibuffer.read(cx).snapshot(cx).text(),
741 follower_multibuffer.read(cx).snapshot(cx).text(),
742 );
743 assert_eq!(*follower_edit_event_count.read(), 4);
744}
745
746#[gpui::test]
747fn test_expand_excerpts(cx: &mut App) {
748 let buffer = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
749 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
750
751 multibuffer.update(cx, |multibuffer, cx| {
752 multibuffer.push_excerpts_with_context_lines(
753 buffer.clone(),
754 vec![
755 // Note that in this test, this first excerpt
756 // does not contain a new line
757 Point::new(3, 2)..Point::new(3, 3),
758 Point::new(7, 1)..Point::new(7, 3),
759 Point::new(15, 0)..Point::new(15, 0),
760 ],
761 1,
762 cx,
763 )
764 });
765
766 let snapshot = multibuffer.read(cx).snapshot(cx);
767
768 assert_eq!(
769 snapshot.text(),
770 concat!(
771 "ccc\n", //
772 "ddd\n", //
773 "eee", //
774 "\n", // End of excerpt
775 "ggg\n", //
776 "hhh\n", //
777 "iii", //
778 "\n", // End of excerpt
779 "ooo\n", //
780 "ppp\n", //
781 "qqq", // End of excerpt
782 )
783 );
784 drop(snapshot);
785
786 multibuffer.update(cx, |multibuffer, cx| {
787 multibuffer.expand_excerpts(
788 multibuffer.excerpt_ids(),
789 1,
790 ExpandExcerptDirection::UpAndDown,
791 cx,
792 )
793 });
794
795 let snapshot = multibuffer.read(cx).snapshot(cx);
796
797 // Expanding context lines causes the line containing 'fff' to appear in two different excerpts.
798 // We don't attempt to merge them, because removing the excerpt could create inconsistency with other layers
799 // that are tracking excerpt ids.
800 assert_eq!(
801 snapshot.text(),
802 concat!(
803 "bbb\n", //
804 "ccc\n", //
805 "ddd\n", //
806 "eee\n", //
807 "fff\n", // End of excerpt
808 "fff\n", //
809 "ggg\n", //
810 "hhh\n", //
811 "iii\n", //
812 "jjj\n", // End of excerpt
813 "nnn\n", //
814 "ooo\n", //
815 "ppp\n", //
816 "qqq\n", //
817 "rrr", // End of excerpt
818 )
819 );
820}
821
822#[gpui::test]
823fn test_push_excerpts_with_context_lines(cx: &mut App) {
824 let buffer = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
825 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
826 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
827 multibuffer.push_excerpts_with_context_lines(
828 buffer.clone(),
829 vec![
830 // Note that in this test, this first excerpt
831 // does contain a new line
832 Point::new(3, 2)..Point::new(4, 2),
833 Point::new(7, 1)..Point::new(7, 3),
834 Point::new(15, 0)..Point::new(15, 0),
835 ],
836 2,
837 cx,
838 )
839 });
840
841 let snapshot = multibuffer.read(cx).snapshot(cx);
842 assert_eq!(
843 snapshot.text(),
844 concat!(
845 "bbb\n", // Preserve newlines
846 "ccc\n", //
847 "ddd\n", //
848 "eee\n", //
849 "fff\n", //
850 "ggg\n", //
851 "hhh\n", //
852 "iii\n", //
853 "jjj\n", //
854 "nnn\n", //
855 "ooo\n", //
856 "ppp\n", //
857 "qqq\n", //
858 "rrr", //
859 )
860 );
861
862 assert_eq!(
863 anchor_ranges
864 .iter()
865 .map(|range| range.to_point(&snapshot))
866 .collect::<Vec<_>>(),
867 vec![
868 Point::new(2, 2)..Point::new(3, 2),
869 Point::new(6, 1)..Point::new(6, 3),
870 Point::new(11, 0)..Point::new(11, 0)
871 ]
872 );
873}
874
875#[gpui::test(iterations = 100)]
876async fn test_push_multiple_excerpts_with_context_lines(cx: &mut TestAppContext) {
877 let buffer_1 = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
878 let buffer_2 = cx.new(|cx| Buffer::local(sample_text(15, 4, 'a'), cx));
879 let snapshot_1 = buffer_1.update(cx, |buffer, _| buffer.snapshot());
880 let snapshot_2 = buffer_2.update(cx, |buffer, _| buffer.snapshot());
881 let ranges_1 = vec![
882 snapshot_1.anchor_before(Point::new(3, 2))..snapshot_1.anchor_before(Point::new(4, 2)),
883 snapshot_1.anchor_before(Point::new(7, 1))..snapshot_1.anchor_before(Point::new(7, 3)),
884 snapshot_1.anchor_before(Point::new(15, 0))..snapshot_1.anchor_before(Point::new(15, 0)),
885 ];
886 let ranges_2 = vec![
887 snapshot_2.anchor_before(Point::new(2, 1))..snapshot_2.anchor_before(Point::new(3, 1)),
888 snapshot_2.anchor_before(Point::new(10, 0))..snapshot_2.anchor_before(Point::new(10, 2)),
889 ];
890
891 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
892 let anchor_ranges = multibuffer
893 .update(cx, |multibuffer, cx| {
894 multibuffer.push_multiple_excerpts_with_context_lines(
895 vec![(buffer_1.clone(), ranges_1), (buffer_2.clone(), ranges_2)],
896 2,
897 cx,
898 )
899 })
900 .await;
901
902 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
903 assert_eq!(
904 snapshot.text(),
905 concat!(
906 "bbb\n", // buffer_1
907 "ccc\n", //
908 "ddd\n", // <-- excerpt 1
909 "eee\n", // <-- excerpt 1
910 "fff\n", //
911 "ggg\n", //
912 "hhh\n", // <-- excerpt 2
913 "iii\n", //
914 "jjj\n", //
915 //
916 "nnn\n", //
917 "ooo\n", //
918 "ppp\n", // <-- excerpt 3
919 "qqq\n", //
920 "rrr\n", //
921 //
922 "aaaa\n", // buffer 2
923 "bbbb\n", //
924 "cccc\n", // <-- excerpt 4
925 "dddd\n", // <-- excerpt 4
926 "eeee\n", //
927 "ffff\n", //
928 //
929 "iiii\n", //
930 "jjjj\n", //
931 "kkkk\n", // <-- excerpt 5
932 "llll\n", //
933 "mmmm", //
934 )
935 );
936
937 assert_eq!(
938 anchor_ranges
939 .iter()
940 .map(|range| range.to_point(&snapshot))
941 .collect::<Vec<_>>(),
942 vec![
943 Point::new(2, 2)..Point::new(3, 2),
944 Point::new(6, 1)..Point::new(6, 3),
945 Point::new(11, 0)..Point::new(11, 0),
946 Point::new(16, 1)..Point::new(17, 1),
947 Point::new(22, 0)..Point::new(22, 2)
948 ]
949 );
950}
951
952#[gpui::test]
953fn test_empty_multibuffer(cx: &mut App) {
954 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
955
956 let snapshot = multibuffer.read(cx).snapshot(cx);
957 assert_eq!(snapshot.text(), "");
958 assert_eq!(
959 snapshot
960 .row_infos(MultiBufferRow(0))
961 .map(|info| info.buffer_row)
962 .collect::<Vec<_>>(),
963 &[Some(0)]
964 );
965 assert_eq!(
966 snapshot
967 .row_infos(MultiBufferRow(1))
968 .map(|info| info.buffer_row)
969 .collect::<Vec<_>>(),
970 &[]
971 );
972}
973
974#[gpui::test]
975fn test_empty_diff_excerpt(cx: &mut TestAppContext) {
976 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
977 let buffer = cx.new(|cx| Buffer::local("", cx));
978 let base_text = "a\nb\nc";
979
980 let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
981 multibuffer.update(cx, |multibuffer, cx| {
982 multibuffer.push_excerpts(
983 buffer.clone(),
984 [ExcerptRange {
985 context: 0..0,
986 primary: None,
987 }],
988 cx,
989 );
990 multibuffer.set_all_diff_hunks_expanded(cx);
991 multibuffer.add_diff(diff.clone(), cx);
992 });
993 cx.run_until_parked();
994
995 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
996 assert_eq!(snapshot.text(), "a\nb\nc\n");
997
998 let hunk = snapshot
999 .diff_hunks_in_range(Point::new(1, 1)..Point::new(1, 1))
1000 .next()
1001 .unwrap();
1002
1003 assert_eq!(hunk.diff_base_byte_range.start, 0);
1004
1005 let buf2 = cx.new(|cx| Buffer::local("X", cx));
1006 multibuffer.update(cx, |multibuffer, cx| {
1007 multibuffer.push_excerpts(
1008 buf2,
1009 [ExcerptRange {
1010 context: 0..1,
1011 primary: None,
1012 }],
1013 cx,
1014 );
1015 });
1016
1017 buffer.update(cx, |buffer, cx| {
1018 buffer.edit([(0..0, "a\nb\nc")], None, cx);
1019 diff.update(cx, |diff, cx| {
1020 diff.recalculate_diff_sync(buffer.snapshot().text, cx);
1021 });
1022 assert_eq!(buffer.text(), "a\nb\nc")
1023 });
1024 cx.run_until_parked();
1025
1026 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
1027 assert_eq!(snapshot.text(), "a\nb\nc\nX");
1028
1029 buffer.update(cx, |buffer, cx| {
1030 buffer.undo(cx);
1031 diff.update(cx, |diff, cx| {
1032 diff.recalculate_diff_sync(buffer.snapshot().text, cx);
1033 });
1034 assert_eq!(buffer.text(), "")
1035 });
1036 cx.run_until_parked();
1037
1038 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
1039 assert_eq!(snapshot.text(), "a\nb\nc\n\nX");
1040}
1041
1042#[gpui::test]
1043fn test_singleton_multibuffer_anchors(cx: &mut App) {
1044 let buffer = cx.new(|cx| Buffer::local("abcd", cx));
1045 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
1046 let old_snapshot = multibuffer.read(cx).snapshot(cx);
1047 buffer.update(cx, |buffer, cx| {
1048 buffer.edit([(0..0, "X")], None, cx);
1049 buffer.edit([(5..5, "Y")], None, cx);
1050 });
1051 let new_snapshot = multibuffer.read(cx).snapshot(cx);
1052
1053 assert_eq!(old_snapshot.text(), "abcd");
1054 assert_eq!(new_snapshot.text(), "XabcdY");
1055
1056 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
1057 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
1058 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
1059 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
1060}
1061
1062#[gpui::test]
1063fn test_multibuffer_anchors(cx: &mut App) {
1064 let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
1065 let buffer_2 = cx.new(|cx| Buffer::local("efghi", cx));
1066 let multibuffer = cx.new(|cx| {
1067 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1068 multibuffer.push_excerpts(
1069 buffer_1.clone(),
1070 [ExcerptRange {
1071 context: 0..4,
1072 primary: None,
1073 }],
1074 cx,
1075 );
1076 multibuffer.push_excerpts(
1077 buffer_2.clone(),
1078 [ExcerptRange {
1079 context: 0..5,
1080 primary: None,
1081 }],
1082 cx,
1083 );
1084 multibuffer
1085 });
1086 let old_snapshot = multibuffer.read(cx).snapshot(cx);
1087
1088 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
1089 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
1090 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
1091 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
1092 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
1093 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
1094
1095 buffer_1.update(cx, |buffer, cx| {
1096 buffer.edit([(0..0, "W")], None, cx);
1097 buffer.edit([(5..5, "X")], None, cx);
1098 });
1099 buffer_2.update(cx, |buffer, cx| {
1100 buffer.edit([(0..0, "Y")], None, cx);
1101 buffer.edit([(6..6, "Z")], None, cx);
1102 });
1103 let new_snapshot = multibuffer.read(cx).snapshot(cx);
1104
1105 assert_eq!(old_snapshot.text(), "abcd\nefghi");
1106 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
1107
1108 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
1109 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
1110 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
1111 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
1112 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
1113 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
1114 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
1115 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
1116 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
1117 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
1118}
1119
1120#[gpui::test]
1121fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut App) {
1122 let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
1123 let buffer_2 = cx.new(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
1124 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1125
1126 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
1127 // Add an excerpt from buffer 1 that spans this new insertion.
1128 buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
1129 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
1130 multibuffer
1131 .push_excerpts(
1132 buffer_1.clone(),
1133 [ExcerptRange {
1134 context: 0..7,
1135 primary: None,
1136 }],
1137 cx,
1138 )
1139 .pop()
1140 .unwrap()
1141 });
1142
1143 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
1144 assert_eq!(snapshot_1.text(), "abcd123");
1145
1146 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
1147 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
1148 multibuffer.remove_excerpts([excerpt_id_1], cx);
1149 let mut ids = multibuffer
1150 .push_excerpts(
1151 buffer_2.clone(),
1152 [
1153 ExcerptRange {
1154 context: 0..4,
1155 primary: None,
1156 },
1157 ExcerptRange {
1158 context: 6..10,
1159 primary: None,
1160 },
1161 ExcerptRange {
1162 context: 12..16,
1163 primary: None,
1164 },
1165 ],
1166 cx,
1167 )
1168 .into_iter();
1169 (ids.next().unwrap(), ids.next().unwrap())
1170 });
1171 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
1172 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
1173
1174 // The old excerpt id doesn't get reused.
1175 assert_ne!(excerpt_id_2, excerpt_id_1);
1176
1177 // Resolve some anchors from the previous snapshot in the new snapshot.
1178 // The current excerpts are from a different buffer, so we don't attempt to
1179 // resolve the old text anchor in the new buffer.
1180 assert_eq!(
1181 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
1182 0
1183 );
1184 assert_eq!(
1185 snapshot_2.summaries_for_anchors::<usize, _>(&[
1186 snapshot_1.anchor_before(2),
1187 snapshot_1.anchor_after(3)
1188 ]),
1189 vec![0, 0]
1190 );
1191
1192 // Refresh anchors from the old snapshot. The return value indicates that both
1193 // anchors lost their original excerpt.
1194 let refresh =
1195 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
1196 assert_eq!(
1197 refresh,
1198 &[
1199 (0, snapshot_2.anchor_before(0), false),
1200 (1, snapshot_2.anchor_after(0), false),
1201 ]
1202 );
1203
1204 // Replace the middle excerpt with a smaller excerpt in buffer 2,
1205 // that intersects the old excerpt.
1206 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
1207 multibuffer.remove_excerpts([excerpt_id_3], cx);
1208 multibuffer
1209 .insert_excerpts_after(
1210 excerpt_id_2,
1211 buffer_2.clone(),
1212 [ExcerptRange {
1213 context: 5..8,
1214 primary: None,
1215 }],
1216 cx,
1217 )
1218 .pop()
1219 .unwrap()
1220 });
1221
1222 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
1223 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
1224 assert_ne!(excerpt_id_5, excerpt_id_3);
1225
1226 // Resolve some anchors from the previous snapshot in the new snapshot.
1227 // The third anchor can't be resolved, since its excerpt has been removed,
1228 // so it resolves to the same position as its predecessor.
1229 let anchors = [
1230 snapshot_2.anchor_before(0),
1231 snapshot_2.anchor_after(2),
1232 snapshot_2.anchor_after(6),
1233 snapshot_2.anchor_after(14),
1234 ];
1235 assert_eq!(
1236 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
1237 &[0, 2, 9, 13]
1238 );
1239
1240 let new_anchors = snapshot_3.refresh_anchors(&anchors);
1241 assert_eq!(
1242 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
1243 &[(0, true), (1, true), (2, true), (3, true)]
1244 );
1245 assert_eq!(
1246 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
1247 &[0, 2, 7, 13]
1248 );
1249}
1250
1251#[gpui::test]
1252fn test_basic_diff_hunks(cx: &mut TestAppContext) {
1253 let text = indoc!(
1254 "
1255 ZERO
1256 one
1257 TWO
1258 three
1259 six
1260 "
1261 );
1262 let base_text = indoc!(
1263 "
1264 one
1265 two
1266 three
1267 four
1268 five
1269 six
1270 "
1271 );
1272
1273 let buffer = cx.new(|cx| Buffer::local(text, cx));
1274 let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
1275 cx.run_until_parked();
1276
1277 let multibuffer = cx.new(|cx| {
1278 let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1279 multibuffer.add_diff(diff.clone(), cx);
1280 multibuffer
1281 });
1282
1283 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1284 (multibuffer.snapshot(cx), multibuffer.subscribe())
1285 });
1286 assert_eq!(
1287 snapshot.text(),
1288 indoc!(
1289 "
1290 ZERO
1291 one
1292 TWO
1293 three
1294 six
1295 "
1296 ),
1297 );
1298
1299 multibuffer.update(cx, |multibuffer, cx| {
1300 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1301 });
1302
1303 assert_new_snapshot(
1304 &multibuffer,
1305 &mut snapshot,
1306 &mut subscription,
1307 cx,
1308 indoc!(
1309 "
1310 + ZERO
1311 one
1312 - two
1313 + TWO
1314 three
1315 - four
1316 - five
1317 six
1318 "
1319 ),
1320 );
1321
1322 assert_eq!(
1323 snapshot
1324 .row_infos(MultiBufferRow(0))
1325 .map(|info| (info.buffer_row, info.diff_status))
1326 .collect::<Vec<_>>(),
1327 vec![
1328 (Some(0), Some(DiffHunkStatus::added_none())),
1329 (Some(1), None),
1330 (Some(1), Some(DiffHunkStatus::deleted_none())),
1331 (Some(2), Some(DiffHunkStatus::added_none())),
1332 (Some(3), None),
1333 (Some(3), Some(DiffHunkStatus::deleted_none())),
1334 (Some(4), Some(DiffHunkStatus::deleted_none())),
1335 (Some(4), None),
1336 (Some(5), None)
1337 ]
1338 );
1339
1340 assert_chunks_in_ranges(&snapshot);
1341 assert_consistent_line_numbers(&snapshot);
1342 assert_position_translation(&snapshot);
1343 assert_line_indents(&snapshot);
1344
1345 multibuffer.update(cx, |multibuffer, cx| {
1346 multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
1347 });
1348 assert_new_snapshot(
1349 &multibuffer,
1350 &mut snapshot,
1351 &mut subscription,
1352 cx,
1353 indoc!(
1354 "
1355 ZERO
1356 one
1357 TWO
1358 three
1359 six
1360 "
1361 ),
1362 );
1363
1364 assert_chunks_in_ranges(&snapshot);
1365 assert_consistent_line_numbers(&snapshot);
1366 assert_position_translation(&snapshot);
1367 assert_line_indents(&snapshot);
1368
1369 // Expand the first diff hunk
1370 multibuffer.update(cx, |multibuffer, cx| {
1371 let position = multibuffer.read(cx).anchor_before(Point::new(2, 2));
1372 multibuffer.expand_diff_hunks(vec![position..position], cx)
1373 });
1374 assert_new_snapshot(
1375 &multibuffer,
1376 &mut snapshot,
1377 &mut subscription,
1378 cx,
1379 indoc!(
1380 "
1381 ZERO
1382 one
1383 - two
1384 + TWO
1385 three
1386 six
1387 "
1388 ),
1389 );
1390
1391 // Expand the second diff hunk
1392 multibuffer.update(cx, |multibuffer, cx| {
1393 let start = multibuffer.read(cx).anchor_before(Point::new(4, 0));
1394 let end = multibuffer.read(cx).anchor_before(Point::new(5, 0));
1395 multibuffer.expand_diff_hunks(vec![start..end], cx)
1396 });
1397 assert_new_snapshot(
1398 &multibuffer,
1399 &mut snapshot,
1400 &mut subscription,
1401 cx,
1402 indoc!(
1403 "
1404 ZERO
1405 one
1406 - two
1407 + TWO
1408 three
1409 - four
1410 - five
1411 six
1412 "
1413 ),
1414 );
1415
1416 assert_chunks_in_ranges(&snapshot);
1417 assert_consistent_line_numbers(&snapshot);
1418 assert_position_translation(&snapshot);
1419 assert_line_indents(&snapshot);
1420
1421 // Edit the buffer before the first hunk
1422 buffer.update(cx, |buffer, cx| {
1423 buffer.edit_via_marked_text(
1424 indoc!(
1425 "
1426 ZERO
1427 one« hundred
1428 thousand»
1429 TWO
1430 three
1431 six
1432 "
1433 ),
1434 None,
1435 cx,
1436 );
1437 });
1438 assert_new_snapshot(
1439 &multibuffer,
1440 &mut snapshot,
1441 &mut subscription,
1442 cx,
1443 indoc!(
1444 "
1445 ZERO
1446 one hundred
1447 thousand
1448 - two
1449 + TWO
1450 three
1451 - four
1452 - five
1453 six
1454 "
1455 ),
1456 );
1457
1458 assert_chunks_in_ranges(&snapshot);
1459 assert_consistent_line_numbers(&snapshot);
1460 assert_position_translation(&snapshot);
1461 assert_line_indents(&snapshot);
1462
1463 // Recalculate the diff, changing the first diff hunk.
1464 diff.update(cx, |diff, cx| {
1465 diff.recalculate_diff_sync(buffer.read(cx).text_snapshot(), cx);
1466 });
1467 cx.run_until_parked();
1468 assert_new_snapshot(
1469 &multibuffer,
1470 &mut snapshot,
1471 &mut subscription,
1472 cx,
1473 indoc!(
1474 "
1475 ZERO
1476 one hundred
1477 thousand
1478 TWO
1479 three
1480 - four
1481 - five
1482 six
1483 "
1484 ),
1485 );
1486
1487 assert_eq!(
1488 snapshot
1489 .diff_hunks_in_range(0..snapshot.len())
1490 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
1491 .collect::<Vec<_>>(),
1492 &[0..4, 5..7]
1493 );
1494}
1495
1496#[gpui::test]
1497fn test_repeatedly_expand_a_diff_hunk(cx: &mut TestAppContext) {
1498 let text = indoc!(
1499 "
1500 one
1501 TWO
1502 THREE
1503 four
1504 FIVE
1505 six
1506 "
1507 );
1508 let base_text = indoc!(
1509 "
1510 one
1511 four
1512 six
1513 "
1514 );
1515
1516 let buffer = cx.new(|cx| Buffer::local(text, cx));
1517 let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
1518 cx.run_until_parked();
1519
1520 let multibuffer = cx.new(|cx| {
1521 let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1522 multibuffer.add_diff(diff.clone(), cx);
1523 multibuffer
1524 });
1525
1526 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1527 (multibuffer.snapshot(cx), multibuffer.subscribe())
1528 });
1529
1530 multibuffer.update(cx, |multibuffer, cx| {
1531 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1532 });
1533
1534 assert_new_snapshot(
1535 &multibuffer,
1536 &mut snapshot,
1537 &mut subscription,
1538 cx,
1539 indoc!(
1540 "
1541 one
1542 + TWO
1543 + THREE
1544 four
1545 + FIVE
1546 six
1547 "
1548 ),
1549 );
1550
1551 // Regression test: expanding diff hunks that are already expanded should not change anything.
1552 multibuffer.update(cx, |multibuffer, cx| {
1553 multibuffer.expand_diff_hunks(
1554 vec![
1555 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_before(Point::new(2, 0)),
1556 ],
1557 cx,
1558 );
1559 });
1560
1561 assert_new_snapshot(
1562 &multibuffer,
1563 &mut snapshot,
1564 &mut subscription,
1565 cx,
1566 indoc!(
1567 "
1568 one
1569 + TWO
1570 + THREE
1571 four
1572 + FIVE
1573 six
1574 "
1575 ),
1576 );
1577}
1578
1579#[gpui::test]
1580fn test_set_excerpts_for_buffer_ordering(cx: &mut TestAppContext) {
1581 let buf1 = cx.new(|cx| {
1582 Buffer::local(
1583 indoc! {
1584 "zero
1585 one
1586 two
1587 two.five
1588 three
1589 four
1590 five
1591 six
1592 seven
1593 eight
1594 nine
1595 ten
1596 eleven
1597 ",
1598 },
1599 cx,
1600 )
1601 });
1602 let path1: PathKey = PathKey::namespaced("0", Path::new("/").into());
1603
1604 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1605 multibuffer.update(cx, |multibuffer, cx| {
1606 multibuffer.set_excerpts_for_path(
1607 path1.clone(),
1608 buf1.clone(),
1609 vec![
1610 Point::row_range(1..2),
1611 Point::row_range(6..7),
1612 Point::row_range(11..12),
1613 ],
1614 1,
1615 cx,
1616 );
1617 });
1618
1619 assert_excerpts_match(
1620 &multibuffer,
1621 cx,
1622 indoc! {
1623 "-----
1624 zero
1625 one
1626 two
1627 two.five
1628 -----
1629 four
1630 five
1631 six
1632 seven
1633 -----
1634 nine
1635 ten
1636 eleven
1637 "
1638 },
1639 );
1640
1641 buf1.update(cx, |buffer, cx| buffer.edit([(0..5, "")], None, cx));
1642
1643 multibuffer.update(cx, |multibuffer, cx| {
1644 multibuffer.set_excerpts_for_path(
1645 path1.clone(),
1646 buf1.clone(),
1647 vec![
1648 Point::row_range(0..2),
1649 Point::row_range(5..6),
1650 Point::row_range(10..11),
1651 ],
1652 1,
1653 cx,
1654 );
1655 });
1656
1657 assert_excerpts_match(
1658 &multibuffer,
1659 cx,
1660 indoc! {
1661 "-----
1662 one
1663 two
1664 two.five
1665 three
1666 -----
1667 four
1668 five
1669 six
1670 seven
1671 -----
1672 nine
1673 ten
1674 eleven
1675 "
1676 },
1677 );
1678}
1679
1680#[gpui::test]
1681fn test_set_excerpts_for_buffer(cx: &mut TestAppContext) {
1682 let buf1 = cx.new(|cx| {
1683 Buffer::local(
1684 indoc! {
1685 "zero
1686 one
1687 two
1688 three
1689 four
1690 five
1691 six
1692 seven
1693 ",
1694 },
1695 cx,
1696 )
1697 });
1698 let path1: PathKey = PathKey::namespaced("0", Path::new("/").into());
1699 let buf2 = cx.new(|cx| {
1700 Buffer::local(
1701 indoc! {
1702 "000
1703 111
1704 222
1705 333
1706 444
1707 555
1708 666
1709 777
1710 888
1711 999
1712 "
1713 },
1714 cx,
1715 )
1716 });
1717 let path2 = PathKey::namespaced("x", Path::new("/").into());
1718
1719 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1720 multibuffer.update(cx, |multibuffer, cx| {
1721 multibuffer.set_excerpts_for_path(
1722 path1.clone(),
1723 buf1.clone(),
1724 vec![Point::row_range(0..1)],
1725 2,
1726 cx,
1727 );
1728 });
1729
1730 assert_excerpts_match(
1731 &multibuffer,
1732 cx,
1733 indoc! {
1734 "-----
1735 zero
1736 one
1737 two
1738 three
1739 "
1740 },
1741 );
1742
1743 multibuffer.update(cx, |multibuffer, cx| {
1744 multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1745 });
1746
1747 assert_excerpts_match(&multibuffer, cx, "");
1748
1749 multibuffer.update(cx, |multibuffer, cx| {
1750 multibuffer.set_excerpts_for_path(
1751 path1.clone(),
1752 buf1.clone(),
1753 vec![Point::row_range(0..1), Point::row_range(7..8)],
1754 2,
1755 cx,
1756 );
1757 });
1758
1759 assert_excerpts_match(
1760 &multibuffer,
1761 cx,
1762 indoc! {"-----
1763 zero
1764 one
1765 two
1766 three
1767 -----
1768 five
1769 six
1770 seven
1771 "},
1772 );
1773
1774 multibuffer.update(cx, |multibuffer, cx| {
1775 multibuffer.set_excerpts_for_path(
1776 path1.clone(),
1777 buf1.clone(),
1778 vec![Point::row_range(0..1), Point::row_range(5..6)],
1779 2,
1780 cx,
1781 );
1782 });
1783
1784 assert_excerpts_match(
1785 &multibuffer,
1786 cx,
1787 indoc! {"-----
1788 zero
1789 one
1790 two
1791 three
1792 four
1793 five
1794 six
1795 seven
1796 "},
1797 );
1798
1799 multibuffer.update(cx, |multibuffer, cx| {
1800 multibuffer.set_excerpts_for_path(
1801 path2.clone(),
1802 buf2.clone(),
1803 vec![Point::row_range(2..3)],
1804 2,
1805 cx,
1806 );
1807 });
1808
1809 assert_excerpts_match(
1810 &multibuffer,
1811 cx,
1812 indoc! {"-----
1813 zero
1814 one
1815 two
1816 three
1817 four
1818 five
1819 six
1820 seven
1821 -----
1822 000
1823 111
1824 222
1825 333
1826 444
1827 555
1828 "},
1829 );
1830
1831 multibuffer.update(cx, |multibuffer, cx| {
1832 multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1833 });
1834
1835 multibuffer.update(cx, |multibuffer, cx| {
1836 multibuffer.set_excerpts_for_path(
1837 path1.clone(),
1838 buf1.clone(),
1839 vec![Point::row_range(3..4)],
1840 2,
1841 cx,
1842 );
1843 });
1844
1845 assert_excerpts_match(
1846 &multibuffer,
1847 cx,
1848 indoc! {"-----
1849 one
1850 two
1851 three
1852 four
1853 five
1854 six
1855 -----
1856 000
1857 111
1858 222
1859 333
1860 444
1861 555
1862 "},
1863 );
1864
1865 multibuffer.update(cx, |multibuffer, cx| {
1866 multibuffer.set_excerpts_for_path(
1867 path1.clone(),
1868 buf1.clone(),
1869 vec![Point::row_range(3..4)],
1870 2,
1871 cx,
1872 );
1873 });
1874}
1875
1876#[gpui::test]
1877fn test_diff_hunks_with_multiple_excerpts(cx: &mut TestAppContext) {
1878 let base_text_1 = indoc!(
1879 "
1880 one
1881 two
1882 three
1883 four
1884 five
1885 six
1886 "
1887 );
1888 let text_1 = indoc!(
1889 "
1890 ZERO
1891 one
1892 TWO
1893 three
1894 six
1895 "
1896 );
1897 let base_text_2 = indoc!(
1898 "
1899 seven
1900 eight
1901 nine
1902 ten
1903 eleven
1904 twelve
1905 "
1906 );
1907 let text_2 = indoc!(
1908 "
1909 eight
1910 nine
1911 eleven
1912 THIRTEEN
1913 FOURTEEN
1914 "
1915 );
1916
1917 let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
1918 let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
1919 let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_1, &buffer_1, cx));
1920 let diff_2 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_2, &buffer_2, cx));
1921 cx.run_until_parked();
1922
1923 let multibuffer = cx.new(|cx| {
1924 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1925 multibuffer.push_excerpts(
1926 buffer_1.clone(),
1927 [ExcerptRange {
1928 context: text::Anchor::MIN..text::Anchor::MAX,
1929 primary: None,
1930 }],
1931 cx,
1932 );
1933 multibuffer.push_excerpts(
1934 buffer_2.clone(),
1935 [ExcerptRange {
1936 context: text::Anchor::MIN..text::Anchor::MAX,
1937 primary: None,
1938 }],
1939 cx,
1940 );
1941 multibuffer.add_diff(diff_1.clone(), cx);
1942 multibuffer.add_diff(diff_2.clone(), cx);
1943 multibuffer
1944 });
1945
1946 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1947 (multibuffer.snapshot(cx), multibuffer.subscribe())
1948 });
1949 assert_eq!(
1950 snapshot.text(),
1951 indoc!(
1952 "
1953 ZERO
1954 one
1955 TWO
1956 three
1957 six
1958
1959 eight
1960 nine
1961 eleven
1962 THIRTEEN
1963 FOURTEEN
1964 "
1965 ),
1966 );
1967
1968 multibuffer.update(cx, |multibuffer, cx| {
1969 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1970 });
1971
1972 assert_new_snapshot(
1973 &multibuffer,
1974 &mut snapshot,
1975 &mut subscription,
1976 cx,
1977 indoc!(
1978 "
1979 + ZERO
1980 one
1981 - two
1982 + TWO
1983 three
1984 - four
1985 - five
1986 six
1987
1988 - seven
1989 eight
1990 nine
1991 - ten
1992 eleven
1993 - twelve
1994 + THIRTEEN
1995 + FOURTEEN
1996 "
1997 ),
1998 );
1999
2000 let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
2001 let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
2002 let base_id_1 = diff_1.read_with(cx, |diff, _| diff.base_text().as_ref().unwrap().remote_id());
2003 let base_id_2 = diff_2.read_with(cx, |diff, _| diff.base_text().as_ref().unwrap().remote_id());
2004
2005 let buffer_lines = (0..=snapshot.max_row().0)
2006 .map(|row| {
2007 let (buffer, range) = snapshot.buffer_line_for_row(MultiBufferRow(row))?;
2008 Some((
2009 buffer.remote_id(),
2010 buffer.text_for_range(range).collect::<String>(),
2011 ))
2012 })
2013 .collect::<Vec<_>>();
2014 pretty_assertions::assert_eq!(
2015 buffer_lines,
2016 [
2017 Some((id_1, "ZERO".into())),
2018 Some((id_1, "one".into())),
2019 Some((base_id_1, "two".into())),
2020 Some((id_1, "TWO".into())),
2021 Some((id_1, " three".into())),
2022 Some((base_id_1, "four".into())),
2023 Some((base_id_1, "five".into())),
2024 Some((id_1, "six".into())),
2025 Some((id_1, "".into())),
2026 Some((base_id_2, "seven".into())),
2027 Some((id_2, " eight".into())),
2028 Some((id_2, "nine".into())),
2029 Some((base_id_2, "ten".into())),
2030 Some((id_2, "eleven".into())),
2031 Some((base_id_2, "twelve".into())),
2032 Some((id_2, "THIRTEEN".into())),
2033 Some((id_2, "FOURTEEN".into())),
2034 Some((id_2, "".into())),
2035 ]
2036 );
2037
2038 assert_position_translation(&snapshot);
2039 assert_line_indents(&snapshot);
2040
2041 assert_eq!(
2042 snapshot
2043 .diff_hunks_in_range(0..snapshot.len())
2044 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
2045 .collect::<Vec<_>>(),
2046 &[0..1, 2..4, 5..7, 9..10, 12..13, 14..17]
2047 );
2048
2049 buffer_2.update(cx, |buffer, cx| {
2050 buffer.edit_via_marked_text(
2051 indoc!(
2052 "
2053 eight
2054 «»eleven
2055 THIRTEEN
2056 FOURTEEN
2057 "
2058 ),
2059 None,
2060 cx,
2061 );
2062 });
2063
2064 assert_new_snapshot(
2065 &multibuffer,
2066 &mut snapshot,
2067 &mut subscription,
2068 cx,
2069 indoc!(
2070 "
2071 + ZERO
2072 one
2073 - two
2074 + TWO
2075 three
2076 - four
2077 - five
2078 six
2079
2080 - seven
2081 eight
2082 eleven
2083 - twelve
2084 + THIRTEEN
2085 + FOURTEEN
2086 "
2087 ),
2088 );
2089
2090 assert_line_indents(&snapshot);
2091}
2092
2093/// A naive implementation of a multi-buffer that does not maintain
2094/// any derived state, used for comparison in a randomized test.
2095#[derive(Default)]
2096struct ReferenceMultibuffer {
2097 excerpts: Vec<ReferenceExcerpt>,
2098 diffs: HashMap<BufferId, Entity<BufferDiff>>,
2099}
2100
2101#[derive(Debug)]
2102struct ReferenceExcerpt {
2103 id: ExcerptId,
2104 buffer: Entity<Buffer>,
2105 range: Range<text::Anchor>,
2106 expanded_diff_hunks: Vec<text::Anchor>,
2107}
2108
2109#[derive(Debug)]
2110struct ReferenceRegion {
2111 buffer_id: Option<BufferId>,
2112 range: Range<usize>,
2113 buffer_start: Option<Point>,
2114 status: Option<DiffHunkStatus>,
2115}
2116
2117impl ReferenceMultibuffer {
2118 fn expand_excerpts(&mut self, excerpts: &HashSet<ExcerptId>, line_count: u32, cx: &App) {
2119 if line_count == 0 {
2120 return;
2121 }
2122
2123 for id in excerpts {
2124 let excerpt = self.excerpts.iter_mut().find(|e| e.id == *id).unwrap();
2125 let snapshot = excerpt.buffer.read(cx).snapshot();
2126 let mut point_range = excerpt.range.to_point(&snapshot);
2127 point_range.start = Point::new(point_range.start.row.saturating_sub(line_count), 0);
2128 point_range.end =
2129 snapshot.clip_point(Point::new(point_range.end.row + line_count, 0), Bias::Left);
2130 point_range.end.column = snapshot.line_len(point_range.end.row);
2131 excerpt.range =
2132 snapshot.anchor_before(point_range.start)..snapshot.anchor_after(point_range.end);
2133 }
2134 }
2135
2136 fn remove_excerpt(&mut self, id: ExcerptId, cx: &App) {
2137 let ix = self
2138 .excerpts
2139 .iter()
2140 .position(|excerpt| excerpt.id == id)
2141 .unwrap();
2142 let excerpt = self.excerpts.remove(ix);
2143 let buffer = excerpt.buffer.read(cx);
2144 log::info!(
2145 "Removing excerpt {}: {:?}",
2146 ix,
2147 buffer
2148 .text_for_range(excerpt.range.to_offset(buffer))
2149 .collect::<String>(),
2150 );
2151 }
2152
2153 fn insert_excerpt_after(
2154 &mut self,
2155 prev_id: ExcerptId,
2156 new_excerpt_id: ExcerptId,
2157 (buffer_handle, anchor_range): (Entity<Buffer>, Range<text::Anchor>),
2158 ) {
2159 let excerpt_ix = if prev_id == ExcerptId::max() {
2160 self.excerpts.len()
2161 } else {
2162 self.excerpts
2163 .iter()
2164 .position(|excerpt| excerpt.id == prev_id)
2165 .unwrap()
2166 + 1
2167 };
2168 self.excerpts.insert(
2169 excerpt_ix,
2170 ReferenceExcerpt {
2171 id: new_excerpt_id,
2172 buffer: buffer_handle,
2173 range: anchor_range,
2174 expanded_diff_hunks: Vec::new(),
2175 },
2176 );
2177 }
2178
2179 fn expand_diff_hunks(&mut self, excerpt_id: ExcerptId, range: Range<text::Anchor>, cx: &App) {
2180 let excerpt = self
2181 .excerpts
2182 .iter_mut()
2183 .find(|e| e.id == excerpt_id)
2184 .unwrap();
2185 let buffer = excerpt.buffer.read(cx).snapshot();
2186 let buffer_id = buffer.remote_id();
2187 let Some(diff) = self.diffs.get(&buffer_id) else {
2188 return;
2189 };
2190 let excerpt_range = excerpt.range.to_offset(&buffer);
2191 for hunk in diff.read(cx).hunks_intersecting_range(range, &buffer, cx) {
2192 let hunk_range = hunk.buffer_range.to_offset(&buffer);
2193 if hunk_range.start < excerpt_range.start || hunk_range.start > excerpt_range.end {
2194 continue;
2195 }
2196 if let Err(ix) = excerpt
2197 .expanded_diff_hunks
2198 .binary_search_by(|anchor| anchor.cmp(&hunk.buffer_range.start, &buffer))
2199 {
2200 log::info!(
2201 "expanding diff hunk {:?}. excerpt:{:?}, excerpt range:{:?}",
2202 hunk_range,
2203 excerpt_id,
2204 excerpt_range
2205 );
2206 excerpt
2207 .expanded_diff_hunks
2208 .insert(ix, hunk.buffer_range.start);
2209 } else {
2210 log::trace!("hunk {hunk_range:?} already expanded in excerpt {excerpt_id:?}");
2211 }
2212 }
2213 }
2214
2215 fn expected_content(&self, cx: &App) -> (String, Vec<RowInfo>, HashSet<MultiBufferRow>) {
2216 let mut text = String::new();
2217 let mut regions = Vec::<ReferenceRegion>::new();
2218 let mut excerpt_boundary_rows = HashSet::default();
2219 for excerpt in &self.excerpts {
2220 excerpt_boundary_rows.insert(MultiBufferRow(text.matches('\n').count() as u32));
2221 let buffer = excerpt.buffer.read(cx);
2222 let buffer_range = excerpt.range.to_offset(buffer);
2223 let diff = self.diffs.get(&buffer.remote_id()).unwrap().read(cx);
2224 // let diff = diff.snapshot.clone();
2225 let base_buffer = diff.base_text().unwrap();
2226
2227 let mut offset = buffer_range.start;
2228 let mut hunks = diff
2229 .hunks_intersecting_range(excerpt.range.clone(), buffer, cx)
2230 .peekable();
2231
2232 while let Some(hunk) = hunks.next() {
2233 // Ignore hunks that are outside the excerpt range.
2234 let mut hunk_range = hunk.buffer_range.to_offset(buffer);
2235
2236 hunk_range.end = hunk_range.end.min(buffer_range.end);
2237 if hunk_range.start > buffer_range.end || hunk_range.start < buffer_range.start {
2238 log::trace!("skipping hunk outside excerpt range");
2239 continue;
2240 }
2241
2242 if !excerpt.expanded_diff_hunks.iter().any(|expanded_anchor| {
2243 expanded_anchor.to_offset(&buffer).max(buffer_range.start)
2244 == hunk_range.start.max(buffer_range.start)
2245 }) {
2246 log::trace!("skipping a hunk that's not marked as expanded");
2247 continue;
2248 }
2249
2250 if !hunk.buffer_range.start.is_valid(&buffer) {
2251 log::trace!("skipping hunk with deleted start: {:?}", hunk.row_range);
2252 continue;
2253 }
2254
2255 if hunk_range.start >= offset {
2256 // Add the buffer text before the hunk
2257 let len = text.len();
2258 text.extend(buffer.text_for_range(offset..hunk_range.start));
2259 regions.push(ReferenceRegion {
2260 buffer_id: Some(buffer.remote_id()),
2261 range: len..text.len(),
2262 buffer_start: Some(buffer.offset_to_point(offset)),
2263 status: None,
2264 });
2265
2266 // Add the deleted text for the hunk.
2267 if !hunk.diff_base_byte_range.is_empty() {
2268 let mut base_text = base_buffer
2269 .text_for_range(hunk.diff_base_byte_range.clone())
2270 .collect::<String>();
2271 if !base_text.ends_with('\n') {
2272 base_text.push('\n');
2273 }
2274 let len = text.len();
2275 text.push_str(&base_text);
2276 regions.push(ReferenceRegion {
2277 buffer_id: Some(base_buffer.remote_id()),
2278 range: len..text.len(),
2279 buffer_start: Some(
2280 base_buffer.offset_to_point(hunk.diff_base_byte_range.start),
2281 ),
2282 status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2283 });
2284 }
2285
2286 offset = hunk_range.start;
2287 }
2288
2289 // Add the inserted text for the hunk.
2290 if hunk_range.end > offset {
2291 let len = text.len();
2292 text.extend(buffer.text_for_range(offset..hunk_range.end));
2293 regions.push(ReferenceRegion {
2294 buffer_id: Some(buffer.remote_id()),
2295 range: len..text.len(),
2296 buffer_start: Some(buffer.offset_to_point(offset)),
2297 status: Some(DiffHunkStatus::added(hunk.secondary_status)),
2298 });
2299 offset = hunk_range.end;
2300 }
2301 }
2302
2303 // Add the buffer text for the rest of the excerpt.
2304 let len = text.len();
2305 text.extend(buffer.text_for_range(offset..buffer_range.end));
2306 text.push('\n');
2307 regions.push(ReferenceRegion {
2308 buffer_id: Some(buffer.remote_id()),
2309 range: len..text.len(),
2310 buffer_start: Some(buffer.offset_to_point(offset)),
2311 status: None,
2312 });
2313 }
2314
2315 // Remove final trailing newline.
2316 if self.excerpts.is_empty() {
2317 regions.push(ReferenceRegion {
2318 buffer_id: None,
2319 range: 0..1,
2320 buffer_start: Some(Point::new(0, 0)),
2321 status: None,
2322 });
2323 } else {
2324 text.pop();
2325 }
2326
2327 // Retrieve the row info using the region that contains
2328 // the start of each multi-buffer line.
2329 let mut ix = 0;
2330 let row_infos = text
2331 .split('\n')
2332 .map(|line| {
2333 let row_info = regions
2334 .iter()
2335 .find(|region| region.range.contains(&ix))
2336 .map_or(RowInfo::default(), |region| {
2337 let buffer_row = region.buffer_start.map(|start_point| {
2338 start_point.row
2339 + text[region.range.start..ix].matches('\n').count() as u32
2340 });
2341 RowInfo {
2342 buffer_id: region.buffer_id,
2343 diff_status: region.status,
2344 buffer_row,
2345 multibuffer_row: Some(MultiBufferRow(
2346 text[..ix].matches('\n').count() as u32
2347 )),
2348 }
2349 });
2350 ix += line.len() + 1;
2351 row_info
2352 })
2353 .collect();
2354
2355 (text, row_infos, excerpt_boundary_rows)
2356 }
2357
2358 fn diffs_updated(&mut self, cx: &App) {
2359 for excerpt in &mut self.excerpts {
2360 let buffer = excerpt.buffer.read(cx).snapshot();
2361 let excerpt_range = excerpt.range.to_offset(&buffer);
2362 let buffer_id = buffer.remote_id();
2363 let diff = self.diffs.get(&buffer_id).unwrap().read(cx);
2364 let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer, cx).peekable();
2365 excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2366 if !hunk_anchor.is_valid(&buffer) {
2367 return false;
2368 }
2369 while let Some(hunk) = hunks.peek() {
2370 match hunk.buffer_range.start.cmp(&hunk_anchor, &buffer) {
2371 cmp::Ordering::Less => {
2372 hunks.next();
2373 }
2374 cmp::Ordering::Equal => {
2375 let hunk_range = hunk.buffer_range.to_offset(&buffer);
2376 return hunk_range.end >= excerpt_range.start
2377 && hunk_range.start <= excerpt_range.end;
2378 }
2379 cmp::Ordering::Greater => break,
2380 }
2381 }
2382 false
2383 });
2384 }
2385 }
2386
2387 fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2388 let buffer_id = diff.read(cx).buffer_id;
2389 self.diffs.insert(buffer_id, diff);
2390 }
2391}
2392
2393#[gpui::test(iterations = 100)]
2394async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
2395 let operations = env::var("OPERATIONS")
2396 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2397 .unwrap_or(10);
2398
2399 let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2400 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2401 let mut reference = ReferenceMultibuffer::default();
2402 let mut anchors = Vec::new();
2403 let mut old_versions = Vec::new();
2404 let mut needs_diff_calculation = false;
2405
2406 for _ in 0..operations {
2407 match rng.gen_range(0..100) {
2408 0..=14 if !buffers.is_empty() => {
2409 let buffer = buffers.choose(&mut rng).unwrap();
2410 buffer.update(cx, |buf, cx| {
2411 let edit_count = rng.gen_range(1..5);
2412 buf.randomly_edit(&mut rng, edit_count, cx);
2413 log::info!("buffer text:\n{}", buf.text());
2414 needs_diff_calculation = true;
2415 });
2416 cx.update(|cx| reference.diffs_updated(cx));
2417 }
2418 15..=19 if !reference.excerpts.is_empty() => {
2419 multibuffer.update(cx, |multibuffer, cx| {
2420 let ids = multibuffer.excerpt_ids();
2421 let mut excerpts = HashSet::default();
2422 for _ in 0..rng.gen_range(0..ids.len()) {
2423 excerpts.extend(ids.choose(&mut rng).copied());
2424 }
2425
2426 let line_count = rng.gen_range(0..5);
2427
2428 let excerpt_ixs = excerpts
2429 .iter()
2430 .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2431 .collect::<Vec<_>>();
2432 log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2433 multibuffer.expand_excerpts(
2434 excerpts.iter().cloned(),
2435 line_count,
2436 ExpandExcerptDirection::UpAndDown,
2437 cx,
2438 );
2439
2440 reference.expand_excerpts(&excerpts, line_count, cx);
2441 });
2442 }
2443 20..=29 if !reference.excerpts.is_empty() => {
2444 let mut ids_to_remove = vec![];
2445 for _ in 0..rng.gen_range(1..=3) {
2446 let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2447 break;
2448 };
2449 let id = excerpt.id;
2450 cx.update(|cx| reference.remove_excerpt(id, cx));
2451 ids_to_remove.push(id);
2452 }
2453 let snapshot =
2454 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2455 ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2456 drop(snapshot);
2457 multibuffer.update(cx, |multibuffer, cx| {
2458 multibuffer.remove_excerpts(ids_to_remove, cx)
2459 });
2460 }
2461 30..=39 if !reference.excerpts.is_empty() => {
2462 let multibuffer =
2463 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2464 let offset =
2465 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
2466 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
2467 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2468 anchors.push(multibuffer.anchor_at(offset, bias));
2469 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2470 }
2471 40..=44 if !anchors.is_empty() => {
2472 let multibuffer =
2473 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2474 let prev_len = anchors.len();
2475 anchors = multibuffer
2476 .refresh_anchors(&anchors)
2477 .into_iter()
2478 .map(|a| a.1)
2479 .collect();
2480
2481 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2482 // overshoot its boundaries.
2483 assert_eq!(anchors.len(), prev_len);
2484 for anchor in &anchors {
2485 if anchor.excerpt_id == ExcerptId::min()
2486 || anchor.excerpt_id == ExcerptId::max()
2487 {
2488 continue;
2489 }
2490
2491 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2492 assert_eq!(excerpt.id, anchor.excerpt_id);
2493 assert!(excerpt.contains(anchor));
2494 }
2495 }
2496 45..=55 if !reference.excerpts.is_empty() => {
2497 multibuffer.update(cx, |multibuffer, cx| {
2498 let snapshot = multibuffer.snapshot(cx);
2499 let excerpt_ix = rng.gen_range(0..reference.excerpts.len());
2500 let excerpt = &reference.excerpts[excerpt_ix];
2501 let start = excerpt.range.start;
2502 let end = excerpt.range.end;
2503 let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2504 ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2505
2506 log::info!(
2507 "expanding diff hunks in range {:?} (excerpt id {:?}) index {excerpt_ix:?})",
2508 range.to_offset(&snapshot),
2509 excerpt.id
2510 );
2511 reference.expand_diff_hunks(excerpt.id, start..end, cx);
2512 multibuffer.expand_diff_hunks(vec![range], cx);
2513 });
2514 }
2515 56..=85 if needs_diff_calculation => {
2516 multibuffer.update(cx, |multibuffer, cx| {
2517 for buffer in multibuffer.all_buffers() {
2518 let snapshot = buffer.read(cx).snapshot();
2519 let _ = multibuffer.diff_for(snapshot.remote_id()).unwrap().update(
2520 cx,
2521 |diff, cx| {
2522 log::info!(
2523 "recalculating diff for buffer {:?}",
2524 snapshot.remote_id(),
2525 );
2526 diff.recalculate_diff_sync(snapshot.text, cx);
2527 },
2528 );
2529 }
2530 reference.diffs_updated(cx);
2531 needs_diff_calculation = false;
2532 });
2533 }
2534 _ => {
2535 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2536 let base_text = util::RandomCharIter::new(&mut rng)
2537 .take(256)
2538 .collect::<String>();
2539
2540 let buffer = cx.new(|cx| Buffer::local(base_text.clone(), cx));
2541 let diff = cx.new(|cx| BufferDiff::new_with_base_text(&base_text, &buffer, cx));
2542
2543 multibuffer.update(cx, |multibuffer, cx| {
2544 reference.add_diff(diff.clone(), cx);
2545 multibuffer.add_diff(diff, cx)
2546 });
2547 buffers.push(buffer);
2548 buffers.last().unwrap()
2549 } else {
2550 buffers.choose(&mut rng).unwrap()
2551 };
2552
2553 let prev_excerpt_ix = rng.gen_range(0..=reference.excerpts.len());
2554 let prev_excerpt_id = reference
2555 .excerpts
2556 .get(prev_excerpt_ix)
2557 .map_or(ExcerptId::max(), |e| e.id);
2558 let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
2559
2560 let (range, anchor_range) = buffer_handle.read_with(cx, |buffer, _| {
2561 let end_row = rng.gen_range(0..=buffer.max_point().row);
2562 let start_row = rng.gen_range(0..=end_row);
2563 let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
2564 let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
2565 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2566
2567 log::info!(
2568 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2569 excerpt_ix,
2570 reference.excerpts.len(),
2571 buffer.remote_id(),
2572 buffer.text(),
2573 start_ix..end_ix,
2574 &buffer.text()[start_ix..end_ix]
2575 );
2576
2577 (start_ix..end_ix, anchor_range)
2578 });
2579
2580 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
2581 multibuffer
2582 .insert_excerpts_after(
2583 prev_excerpt_id,
2584 buffer_handle.clone(),
2585 [ExcerptRange {
2586 context: range,
2587 primary: None,
2588 }],
2589 cx,
2590 )
2591 .pop()
2592 .unwrap()
2593 });
2594
2595 reference.insert_excerpt_after(
2596 prev_excerpt_id,
2597 excerpt_id,
2598 (buffer_handle.clone(), anchor_range),
2599 );
2600 }
2601 }
2602
2603 if rng.gen_bool(0.3) {
2604 multibuffer.update(cx, |multibuffer, cx| {
2605 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
2606 })
2607 }
2608
2609 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2610 let actual_text = snapshot.text();
2611 let actual_boundary_rows = snapshot
2612 .excerpt_boundaries_in_range(0..)
2613 .filter_map(|b| if b.next.is_some() { Some(b.row) } else { None })
2614 .collect::<HashSet<_>>();
2615 let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
2616
2617 let (expected_text, expected_row_infos, expected_boundary_rows) =
2618 cx.update(|cx| reference.expected_content(cx));
2619
2620 let has_diff = actual_row_infos
2621 .iter()
2622 .any(|info| info.diff_status.is_some())
2623 || expected_row_infos
2624 .iter()
2625 .any(|info| info.diff_status.is_some());
2626 let actual_diff = format_diff(
2627 &actual_text,
2628 &actual_row_infos,
2629 &actual_boundary_rows,
2630 Some(has_diff),
2631 );
2632 let expected_diff = format_diff(
2633 &expected_text,
2634 &expected_row_infos,
2635 &expected_boundary_rows,
2636 Some(has_diff),
2637 );
2638
2639 log::info!("Multibuffer content:\n{}", actual_diff);
2640
2641 assert_eq!(
2642 actual_row_infos.len(),
2643 actual_text.split('\n').count(),
2644 "line count: {}",
2645 actual_text.split('\n').count()
2646 );
2647 pretty_assertions::assert_eq!(actual_diff, expected_diff);
2648 pretty_assertions::assert_eq!(actual_text, expected_text);
2649 pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
2650
2651 for _ in 0..5 {
2652 let start_row = rng.gen_range(0..=expected_row_infos.len());
2653 assert_eq!(
2654 snapshot
2655 .row_infos(MultiBufferRow(start_row as u32))
2656 .collect::<Vec<_>>(),
2657 &expected_row_infos[start_row..],
2658 "buffer_rows({})",
2659 start_row
2660 );
2661 }
2662
2663 assert_eq!(
2664 snapshot.widest_line_number(),
2665 expected_row_infos
2666 .into_iter()
2667 .filter_map(|info| {
2668 if info.diff_status.is_some_and(|status| status.is_deleted()) {
2669 None
2670 } else {
2671 info.buffer_row
2672 }
2673 })
2674 .max()
2675 .unwrap()
2676 + 1
2677 );
2678
2679 assert_consistent_line_numbers(&snapshot);
2680 assert_position_translation(&snapshot);
2681
2682 for (row, line) in expected_text.split('\n').enumerate() {
2683 assert_eq!(
2684 snapshot.line_len(MultiBufferRow(row as u32)),
2685 line.len() as u32,
2686 "line_len({}).",
2687 row
2688 );
2689 }
2690
2691 let text_rope = Rope::from(expected_text.as_str());
2692 for _ in 0..10 {
2693 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2694 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2695
2696 let text_for_range = snapshot
2697 .text_for_range(start_ix..end_ix)
2698 .collect::<String>();
2699 assert_eq!(
2700 text_for_range,
2701 &expected_text[start_ix..end_ix],
2702 "incorrect text for range {:?}",
2703 start_ix..end_ix
2704 );
2705
2706 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
2707 assert_eq!(
2708 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
2709 expected_summary,
2710 "incorrect summary for range {:?}",
2711 start_ix..end_ix
2712 );
2713 }
2714
2715 // Anchor resolution
2716 let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
2717 assert_eq!(anchors.len(), summaries.len());
2718 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
2719 assert!(resolved_offset <= snapshot.len());
2720 assert_eq!(
2721 snapshot.summary_for_anchor::<usize>(anchor),
2722 resolved_offset,
2723 "anchor: {:?}",
2724 anchor
2725 );
2726 }
2727
2728 for _ in 0..10 {
2729 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2730 assert_eq!(
2731 snapshot.reversed_chars_at(end_ix).collect::<String>(),
2732 expected_text[..end_ix].chars().rev().collect::<String>(),
2733 );
2734 }
2735
2736 for _ in 0..10 {
2737 let end_ix = rng.gen_range(0..=text_rope.len());
2738 let start_ix = rng.gen_range(0..=end_ix);
2739 assert_eq!(
2740 snapshot
2741 .bytes_in_range(start_ix..end_ix)
2742 .flatten()
2743 .copied()
2744 .collect::<Vec<_>>(),
2745 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
2746 "bytes_in_range({:?})",
2747 start_ix..end_ix,
2748 );
2749 }
2750 }
2751
2752 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2753 for (old_snapshot, subscription) in old_versions {
2754 let edits = subscription.consume().into_inner();
2755
2756 log::info!(
2757 "applying subscription edits to old text: {:?}: {:?}",
2758 old_snapshot.text(),
2759 edits,
2760 );
2761
2762 let mut text = old_snapshot.text();
2763 for edit in edits {
2764 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
2765 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
2766 }
2767 assert_eq!(text.to_string(), snapshot.text());
2768 }
2769}
2770
2771#[gpui::test]
2772fn test_history(cx: &mut App) {
2773 let test_settings = SettingsStore::test(cx);
2774 cx.set_global(test_settings);
2775 let group_interval: Duration = Duration::from_millis(1);
2776 let buffer_1 = cx.new(|cx| {
2777 let mut buf = Buffer::local("1234", cx);
2778 buf.set_group_interval(group_interval);
2779 buf
2780 });
2781 let buffer_2 = cx.new(|cx| {
2782 let mut buf = Buffer::local("5678", cx);
2783 buf.set_group_interval(group_interval);
2784 buf
2785 });
2786 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2787 multibuffer.update(cx, |this, _| {
2788 this.history.group_interval = group_interval;
2789 });
2790 multibuffer.update(cx, |multibuffer, cx| {
2791 multibuffer.push_excerpts(
2792 buffer_1.clone(),
2793 [ExcerptRange {
2794 context: 0..buffer_1.read(cx).len(),
2795 primary: None,
2796 }],
2797 cx,
2798 );
2799 multibuffer.push_excerpts(
2800 buffer_2.clone(),
2801 [ExcerptRange {
2802 context: 0..buffer_2.read(cx).len(),
2803 primary: None,
2804 }],
2805 cx,
2806 );
2807 });
2808
2809 let mut now = Instant::now();
2810
2811 multibuffer.update(cx, |multibuffer, cx| {
2812 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
2813 multibuffer.edit(
2814 [
2815 (Point::new(0, 0)..Point::new(0, 0), "A"),
2816 (Point::new(1, 0)..Point::new(1, 0), "A"),
2817 ],
2818 None,
2819 cx,
2820 );
2821 multibuffer.edit(
2822 [
2823 (Point::new(0, 1)..Point::new(0, 1), "B"),
2824 (Point::new(1, 1)..Point::new(1, 1), "B"),
2825 ],
2826 None,
2827 cx,
2828 );
2829 multibuffer.end_transaction_at(now, cx);
2830 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2831
2832 // Verify edited ranges for transaction 1
2833 assert_eq!(
2834 multibuffer.edited_ranges_for_transaction(transaction_1, cx),
2835 &[
2836 Point::new(0, 0)..Point::new(0, 2),
2837 Point::new(1, 0)..Point::new(1, 2)
2838 ]
2839 );
2840
2841 // Edit buffer 1 through the multibuffer
2842 now += 2 * group_interval;
2843 multibuffer.start_transaction_at(now, cx);
2844 multibuffer.edit([(2..2, "C")], None, cx);
2845 multibuffer.end_transaction_at(now, cx);
2846 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2847
2848 // Edit buffer 1 independently
2849 buffer_1.update(cx, |buffer_1, cx| {
2850 buffer_1.start_transaction_at(now);
2851 buffer_1.edit([(3..3, "D")], None, cx);
2852 buffer_1.end_transaction_at(now, cx);
2853
2854 now += 2 * group_interval;
2855 buffer_1.start_transaction_at(now);
2856 buffer_1.edit([(4..4, "E")], None, cx);
2857 buffer_1.end_transaction_at(now, cx);
2858 });
2859 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
2860
2861 // An undo in the multibuffer undoes the multibuffer transaction
2862 // and also any individual buffer edits that have occurred since
2863 // that transaction.
2864 multibuffer.undo(cx);
2865 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2866
2867 multibuffer.undo(cx);
2868 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2869
2870 multibuffer.redo(cx);
2871 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2872
2873 multibuffer.redo(cx);
2874 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
2875
2876 // Undo buffer 2 independently.
2877 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
2878 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
2879
2880 // An undo in the multibuffer undoes the components of the
2881 // the last multibuffer transaction that are not already undone.
2882 multibuffer.undo(cx);
2883 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
2884
2885 multibuffer.undo(cx);
2886 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2887
2888 multibuffer.redo(cx);
2889 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2890
2891 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
2892 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
2893
2894 // Redo stack gets cleared after an edit.
2895 now += 2 * group_interval;
2896 multibuffer.start_transaction_at(now, cx);
2897 multibuffer.edit([(0..0, "X")], None, cx);
2898 multibuffer.end_transaction_at(now, cx);
2899 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2900 multibuffer.redo(cx);
2901 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2902 multibuffer.undo(cx);
2903 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
2904 multibuffer.undo(cx);
2905 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2906
2907 // Transactions can be grouped manually.
2908 multibuffer.redo(cx);
2909 multibuffer.redo(cx);
2910 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2911 multibuffer.group_until_transaction(transaction_1, cx);
2912 multibuffer.undo(cx);
2913 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2914 multibuffer.redo(cx);
2915 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2916 });
2917}
2918
2919#[gpui::test]
2920async fn test_enclosing_indent(cx: &mut TestAppContext) {
2921 async fn enclosing_indent(
2922 text: &str,
2923 buffer_row: u32,
2924 cx: &mut TestAppContext,
2925 ) -> Option<(Range<u32>, LineIndent)> {
2926 let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
2927 let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
2928 let (range, indent) = snapshot
2929 .enclosing_indent(MultiBufferRow(buffer_row))
2930 .await?;
2931 Some((range.start.0..range.end.0, indent))
2932 }
2933
2934 assert_eq!(
2935 enclosing_indent(
2936 indoc!(
2937 "
2938 fn b() {
2939 if c {
2940 let d = 2;
2941 }
2942 }
2943 "
2944 ),
2945 1,
2946 cx,
2947 )
2948 .await,
2949 Some((
2950 1..2,
2951 LineIndent {
2952 tabs: 0,
2953 spaces: 4,
2954 line_blank: false,
2955 }
2956 ))
2957 );
2958
2959 assert_eq!(
2960 enclosing_indent(
2961 indoc!(
2962 "
2963 fn b() {
2964 if c {
2965 let d = 2;
2966 }
2967 }
2968 "
2969 ),
2970 2,
2971 cx,
2972 )
2973 .await,
2974 Some((
2975 1..2,
2976 LineIndent {
2977 tabs: 0,
2978 spaces: 4,
2979 line_blank: false,
2980 }
2981 ))
2982 );
2983
2984 assert_eq!(
2985 enclosing_indent(
2986 indoc!(
2987 "
2988 fn b() {
2989 if c {
2990 let d = 2;
2991
2992 let e = 5;
2993 }
2994 }
2995 "
2996 ),
2997 3,
2998 cx,
2999 )
3000 .await,
3001 Some((
3002 1..4,
3003 LineIndent {
3004 tabs: 0,
3005 spaces: 4,
3006 line_blank: false,
3007 }
3008 ))
3009 );
3010}
3011
3012#[gpui::test]
3013fn test_summaries_for_anchors(cx: &mut TestAppContext) {
3014 let base_text_1 = indoc!(
3015 "
3016 bar
3017 "
3018 );
3019 let text_1 = indoc!(
3020 "
3021 BAR
3022 "
3023 );
3024 let base_text_2 = indoc!(
3025 "
3026 foo
3027 "
3028 );
3029 let text_2 = indoc!(
3030 "
3031 FOO
3032 "
3033 );
3034
3035 let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3036 let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
3037 let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_1, &buffer_1, cx));
3038 let diff_2 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_2, &buffer_2, cx));
3039 cx.run_until_parked();
3040
3041 let mut ids = vec![];
3042 let multibuffer = cx.new(|cx| {
3043 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3044 multibuffer.set_all_diff_hunks_expanded(cx);
3045 ids.extend(multibuffer.push_excerpts(
3046 buffer_1.clone(),
3047 [ExcerptRange {
3048 context: text::Anchor::MIN..text::Anchor::MAX,
3049 primary: None,
3050 }],
3051 cx,
3052 ));
3053 ids.extend(multibuffer.push_excerpts(
3054 buffer_2.clone(),
3055 [ExcerptRange {
3056 context: text::Anchor::MIN..text::Anchor::MAX,
3057 primary: None,
3058 }],
3059 cx,
3060 ));
3061 multibuffer.add_diff(diff_1.clone(), cx);
3062 multibuffer.add_diff(diff_2.clone(), cx);
3063 multibuffer
3064 });
3065
3066 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3067 (multibuffer.snapshot(cx), multibuffer.subscribe())
3068 });
3069
3070 assert_new_snapshot(
3071 &multibuffer,
3072 &mut snapshot,
3073 &mut subscription,
3074 cx,
3075 indoc!(
3076 "
3077 - bar
3078 + BAR
3079
3080 - foo
3081 + FOO
3082 "
3083 ),
3084 );
3085
3086 let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
3087 let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
3088
3089 let anchor_1 = Anchor::in_buffer(ids[0], id_1, text::Anchor::MIN);
3090 let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3091 assert_eq!(point_1, Point::new(0, 0));
3092
3093 let anchor_2 = Anchor::in_buffer(ids[1], id_2, text::Anchor::MIN);
3094 let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3095 assert_eq!(point_2, Point::new(3, 0));
3096}
3097
3098fn format_diff(
3099 text: &str,
3100 row_infos: &Vec<RowInfo>,
3101 boundary_rows: &HashSet<MultiBufferRow>,
3102 has_diff: Option<bool>,
3103) -> String {
3104 let has_diff =
3105 has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3106 text.split('\n')
3107 .enumerate()
3108 .zip(row_infos)
3109 .map(|((ix, line), info)| {
3110 let marker = match info.diff_status.map(|status| status.kind) {
3111 Some(DiffHunkStatusKind::Added) => "+ ",
3112 Some(DiffHunkStatusKind::Deleted) => "- ",
3113 Some(DiffHunkStatusKind::Modified) => unreachable!(),
3114 None => {
3115 if has_diff && !line.is_empty() {
3116 " "
3117 } else {
3118 ""
3119 }
3120 }
3121 };
3122 let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3123 if has_diff {
3124 " ----------\n"
3125 } else {
3126 "---------\n"
3127 }
3128 } else {
3129 ""
3130 };
3131 format!("{boundary_row}{marker}{line}")
3132 })
3133 .collect::<Vec<_>>()
3134 .join("\n")
3135}
3136
3137#[track_caller]
3138fn assert_excerpts_match(
3139 multibuffer: &Entity<MultiBuffer>,
3140 cx: &mut TestAppContext,
3141 expected: &str,
3142) {
3143 let mut output = String::new();
3144 multibuffer.read_with(cx, |multibuffer, cx| {
3145 for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
3146 output.push_str("-----\n");
3147 output.extend(buffer.text_for_range(range.context));
3148 if !output.ends_with('\n') {
3149 output.push('\n');
3150 }
3151 }
3152 });
3153 assert_eq!(output, expected);
3154}
3155
3156#[track_caller]
3157fn assert_new_snapshot(
3158 multibuffer: &Entity<MultiBuffer>,
3159 snapshot: &mut MultiBufferSnapshot,
3160 subscription: &mut Subscription,
3161 cx: &mut TestAppContext,
3162 expected_diff: &str,
3163) {
3164 let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3165 let actual_text = new_snapshot.text();
3166 let line_infos = new_snapshot
3167 .row_infos(MultiBufferRow(0))
3168 .collect::<Vec<_>>();
3169 let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
3170 pretty_assertions::assert_eq!(actual_diff, expected_diff);
3171 check_edits(
3172 snapshot,
3173 &new_snapshot,
3174 &subscription.consume().into_inner(),
3175 );
3176 *snapshot = new_snapshot;
3177}
3178
3179#[track_caller]
3180fn check_edits(
3181 old_snapshot: &MultiBufferSnapshot,
3182 new_snapshot: &MultiBufferSnapshot,
3183 edits: &[Edit<usize>],
3184) {
3185 let mut text = old_snapshot.text();
3186 let new_text = new_snapshot.text();
3187 for edit in edits.iter().rev() {
3188 if !text.is_char_boundary(edit.old.start)
3189 || !text.is_char_boundary(edit.old.end)
3190 || !new_text.is_char_boundary(edit.new.start)
3191 || !new_text.is_char_boundary(edit.new.end)
3192 {
3193 panic!(
3194 "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
3195 edits, text, new_text
3196 );
3197 }
3198
3199 text.replace_range(
3200 edit.old.start..edit.old.end,
3201 &new_text[edit.new.start..edit.new.end],
3202 );
3203 }
3204
3205 pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
3206}
3207
3208#[track_caller]
3209fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
3210 let full_text = snapshot.text();
3211 for ix in 0..full_text.len() {
3212 let mut chunks = snapshot.chunks(0..snapshot.len(), false);
3213 chunks.seek(ix..snapshot.len());
3214 let tail = chunks.map(|chunk| chunk.text).collect::<String>();
3215 assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
3216 }
3217}
3218
3219#[track_caller]
3220fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
3221 let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3222 for start_row in 1..all_line_numbers.len() {
3223 let line_numbers = snapshot
3224 .row_infos(MultiBufferRow(start_row as u32))
3225 .collect::<Vec<_>>();
3226 assert_eq!(
3227 line_numbers,
3228 all_line_numbers[start_row..],
3229 "start_row: {start_row}"
3230 );
3231 }
3232}
3233
3234#[track_caller]
3235fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
3236 let text = Rope::from(snapshot.text());
3237
3238 let mut left_anchors = Vec::new();
3239 let mut right_anchors = Vec::new();
3240 let mut offsets = Vec::new();
3241 let mut points = Vec::new();
3242 for offset in 0..=text.len() + 1 {
3243 let clipped_left = snapshot.clip_offset(offset, Bias::Left);
3244 let clipped_right = snapshot.clip_offset(offset, Bias::Right);
3245 assert_eq!(
3246 clipped_left,
3247 text.clip_offset(offset, Bias::Left),
3248 "clip_offset({offset:?}, Left)"
3249 );
3250 assert_eq!(
3251 clipped_right,
3252 text.clip_offset(offset, Bias::Right),
3253 "clip_offset({offset:?}, Right)"
3254 );
3255 assert_eq!(
3256 snapshot.offset_to_point(clipped_left),
3257 text.offset_to_point(clipped_left),
3258 "offset_to_point({clipped_left})"
3259 );
3260 assert_eq!(
3261 snapshot.offset_to_point(clipped_right),
3262 text.offset_to_point(clipped_right),
3263 "offset_to_point({clipped_right})"
3264 );
3265 let anchor_after = snapshot.anchor_after(clipped_left);
3266 assert_eq!(
3267 anchor_after.to_offset(snapshot),
3268 clipped_left,
3269 "anchor_after({clipped_left}).to_offset {anchor_after:?}"
3270 );
3271 let anchor_before = snapshot.anchor_before(clipped_left);
3272 assert_eq!(
3273 anchor_before.to_offset(snapshot),
3274 clipped_left,
3275 "anchor_before({clipped_left}).to_offset"
3276 );
3277 left_anchors.push(anchor_before);
3278 right_anchors.push(anchor_after);
3279 offsets.push(clipped_left);
3280 points.push(text.offset_to_point(clipped_left));
3281 }
3282
3283 for row in 0..text.max_point().row {
3284 for column in 0..text.line_len(row) + 1 {
3285 let point = Point { row, column };
3286 let clipped_left = snapshot.clip_point(point, Bias::Left);
3287 let clipped_right = snapshot.clip_point(point, Bias::Right);
3288 assert_eq!(
3289 clipped_left,
3290 text.clip_point(point, Bias::Left),
3291 "clip_point({point:?}, Left)"
3292 );
3293 assert_eq!(
3294 clipped_right,
3295 text.clip_point(point, Bias::Right),
3296 "clip_point({point:?}, Right)"
3297 );
3298 assert_eq!(
3299 snapshot.point_to_offset(clipped_left),
3300 text.point_to_offset(clipped_left),
3301 "point_to_offset({clipped_left:?})"
3302 );
3303 assert_eq!(
3304 snapshot.point_to_offset(clipped_right),
3305 text.point_to_offset(clipped_right),
3306 "point_to_offset({clipped_right:?})"
3307 );
3308 }
3309 }
3310
3311 assert_eq!(
3312 snapshot.summaries_for_anchors::<usize, _>(&left_anchors),
3313 offsets,
3314 "left_anchors <-> offsets"
3315 );
3316 assert_eq!(
3317 snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
3318 points,
3319 "left_anchors <-> points"
3320 );
3321 assert_eq!(
3322 snapshot.summaries_for_anchors::<usize, _>(&right_anchors),
3323 offsets,
3324 "right_anchors <-> offsets"
3325 );
3326 assert_eq!(
3327 snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
3328 points,
3329 "right_anchors <-> points"
3330 );
3331
3332 for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
3333 for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
3334 if ix > 0 {
3335 if *offset == 252 {
3336 if offset > &offsets[ix - 1] {
3337 let prev_anchor = left_anchors[ix - 1];
3338 assert!(
3339 anchor.cmp(&prev_anchor, snapshot).is_gt(),
3340 "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
3341 offsets[ix],
3342 offsets[ix - 1],
3343 );
3344 assert!(
3345 prev_anchor.cmp(&anchor, snapshot).is_lt(),
3346 "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
3347 offsets[ix - 1],
3348 offsets[ix],
3349 );
3350 }
3351 }
3352 }
3353 }
3354 }
3355}
3356
3357fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
3358 let max_row = snapshot.max_point().row;
3359 let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
3360 let text = text::Buffer::new(0, buffer_id, snapshot.text());
3361 let mut line_indents = text
3362 .line_indents_in_row_range(0..max_row + 1)
3363 .collect::<Vec<_>>();
3364 for start_row in 0..snapshot.max_point().row {
3365 pretty_assertions::assert_eq!(
3366 snapshot
3367 .line_indents(MultiBufferRow(start_row), |_| true)
3368 .map(|(row, indent, _)| (row.0, indent))
3369 .collect::<Vec<_>>(),
3370 &line_indents[(start_row as usize)..],
3371 "line_indents({start_row})"
3372 );
3373 }
3374
3375 line_indents.reverse();
3376 pretty_assertions::assert_eq!(
3377 snapshot
3378 .reversed_line_indents(MultiBufferRow(max_row), |_| true)
3379 .map(|(row, indent, _)| (row.0, indent))
3380 .collect::<Vec<_>>(),
3381 &line_indents[..],
3382 "reversed_line_indents({max_row})"
3383 );
3384}