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().remote_id());
2003 let base_id_2 = diff_2.read_with(cx, |diff, _| diff.base_text().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 base_buffer = diff.base_text();
2225
2226 let mut offset = buffer_range.start;
2227 let mut hunks = diff
2228 .hunks_intersecting_range(excerpt.range.clone(), buffer, cx)
2229 .peekable();
2230
2231 while let Some(hunk) = hunks.next() {
2232 // Ignore hunks that are outside the excerpt range.
2233 let mut hunk_range = hunk.buffer_range.to_offset(buffer);
2234
2235 hunk_range.end = hunk_range.end.min(buffer_range.end);
2236 if hunk_range.start > buffer_range.end || hunk_range.start < buffer_range.start {
2237 log::trace!("skipping hunk outside excerpt range");
2238 continue;
2239 }
2240
2241 if !excerpt.expanded_diff_hunks.iter().any(|expanded_anchor| {
2242 expanded_anchor.to_offset(&buffer).max(buffer_range.start)
2243 == hunk_range.start.max(buffer_range.start)
2244 }) {
2245 log::trace!("skipping a hunk that's not marked as expanded");
2246 continue;
2247 }
2248
2249 if !hunk.buffer_range.start.is_valid(&buffer) {
2250 log::trace!("skipping hunk with deleted start: {:?}", hunk.row_range);
2251 continue;
2252 }
2253
2254 if hunk_range.start >= offset {
2255 // Add the buffer text before the hunk
2256 let len = text.len();
2257 text.extend(buffer.text_for_range(offset..hunk_range.start));
2258 regions.push(ReferenceRegion {
2259 buffer_id: Some(buffer.remote_id()),
2260 range: len..text.len(),
2261 buffer_start: Some(buffer.offset_to_point(offset)),
2262 status: None,
2263 });
2264
2265 // Add the deleted text for the hunk.
2266 if !hunk.diff_base_byte_range.is_empty() {
2267 let mut base_text = base_buffer
2268 .text_for_range(hunk.diff_base_byte_range.clone())
2269 .collect::<String>();
2270 if !base_text.ends_with('\n') {
2271 base_text.push('\n');
2272 }
2273 let len = text.len();
2274 text.push_str(&base_text);
2275 regions.push(ReferenceRegion {
2276 buffer_id: Some(base_buffer.remote_id()),
2277 range: len..text.len(),
2278 buffer_start: Some(
2279 base_buffer.offset_to_point(hunk.diff_base_byte_range.start),
2280 ),
2281 status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2282 });
2283 }
2284
2285 offset = hunk_range.start;
2286 }
2287
2288 // Add the inserted text for the hunk.
2289 if hunk_range.end > offset {
2290 let len = text.len();
2291 text.extend(buffer.text_for_range(offset..hunk_range.end));
2292 regions.push(ReferenceRegion {
2293 buffer_id: Some(buffer.remote_id()),
2294 range: len..text.len(),
2295 buffer_start: Some(buffer.offset_to_point(offset)),
2296 status: Some(DiffHunkStatus::added(hunk.secondary_status)),
2297 });
2298 offset = hunk_range.end;
2299 }
2300 }
2301
2302 // Add the buffer text for the rest of the excerpt.
2303 let len = text.len();
2304 text.extend(buffer.text_for_range(offset..buffer_range.end));
2305 text.push('\n');
2306 regions.push(ReferenceRegion {
2307 buffer_id: Some(buffer.remote_id()),
2308 range: len..text.len(),
2309 buffer_start: Some(buffer.offset_to_point(offset)),
2310 status: None,
2311 });
2312 }
2313
2314 // Remove final trailing newline.
2315 if self.excerpts.is_empty() {
2316 regions.push(ReferenceRegion {
2317 buffer_id: None,
2318 range: 0..1,
2319 buffer_start: Some(Point::new(0, 0)),
2320 status: None,
2321 });
2322 } else {
2323 text.pop();
2324 }
2325
2326 // Retrieve the row info using the region that contains
2327 // the start of each multi-buffer line.
2328 let mut ix = 0;
2329 let row_infos = text
2330 .split('\n')
2331 .map(|line| {
2332 let row_info = regions
2333 .iter()
2334 .find(|region| region.range.contains(&ix))
2335 .map_or(RowInfo::default(), |region| {
2336 let buffer_row = region.buffer_start.map(|start_point| {
2337 start_point.row
2338 + text[region.range.start..ix].matches('\n').count() as u32
2339 });
2340 RowInfo {
2341 buffer_id: region.buffer_id,
2342 diff_status: region.status,
2343 buffer_row,
2344 multibuffer_row: Some(MultiBufferRow(
2345 text[..ix].matches('\n').count() as u32
2346 )),
2347 }
2348 });
2349 ix += line.len() + 1;
2350 row_info
2351 })
2352 .collect();
2353
2354 (text, row_infos, excerpt_boundary_rows)
2355 }
2356
2357 fn diffs_updated(&mut self, cx: &App) {
2358 for excerpt in &mut self.excerpts {
2359 let buffer = excerpt.buffer.read(cx).snapshot();
2360 let excerpt_range = excerpt.range.to_offset(&buffer);
2361 let buffer_id = buffer.remote_id();
2362 let diff = self.diffs.get(&buffer_id).unwrap().read(cx);
2363 let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer, cx).peekable();
2364 excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2365 if !hunk_anchor.is_valid(&buffer) {
2366 return false;
2367 }
2368 while let Some(hunk) = hunks.peek() {
2369 match hunk.buffer_range.start.cmp(&hunk_anchor, &buffer) {
2370 cmp::Ordering::Less => {
2371 hunks.next();
2372 }
2373 cmp::Ordering::Equal => {
2374 let hunk_range = hunk.buffer_range.to_offset(&buffer);
2375 return hunk_range.end >= excerpt_range.start
2376 && hunk_range.start <= excerpt_range.end;
2377 }
2378 cmp::Ordering::Greater => break,
2379 }
2380 }
2381 false
2382 });
2383 }
2384 }
2385
2386 fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2387 let buffer_id = diff.read(cx).buffer_id;
2388 self.diffs.insert(buffer_id, diff);
2389 }
2390}
2391
2392#[gpui::test(iterations = 100)]
2393async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
2394 let operations = env::var("OPERATIONS")
2395 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2396 .unwrap_or(10);
2397
2398 let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2399 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2400 let mut reference = ReferenceMultibuffer::default();
2401 let mut anchors = Vec::new();
2402 let mut old_versions = Vec::new();
2403 let mut needs_diff_calculation = false;
2404
2405 for _ in 0..operations {
2406 match rng.gen_range(0..100) {
2407 0..=14 if !buffers.is_empty() => {
2408 let buffer = buffers.choose(&mut rng).unwrap();
2409 buffer.update(cx, |buf, cx| {
2410 let edit_count = rng.gen_range(1..5);
2411 buf.randomly_edit(&mut rng, edit_count, cx);
2412 log::info!("buffer text:\n{}", buf.text());
2413 needs_diff_calculation = true;
2414 });
2415 cx.update(|cx| reference.diffs_updated(cx));
2416 }
2417 15..=19 if !reference.excerpts.is_empty() => {
2418 multibuffer.update(cx, |multibuffer, cx| {
2419 let ids = multibuffer.excerpt_ids();
2420 let mut excerpts = HashSet::default();
2421 for _ in 0..rng.gen_range(0..ids.len()) {
2422 excerpts.extend(ids.choose(&mut rng).copied());
2423 }
2424
2425 let line_count = rng.gen_range(0..5);
2426
2427 let excerpt_ixs = excerpts
2428 .iter()
2429 .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2430 .collect::<Vec<_>>();
2431 log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2432 multibuffer.expand_excerpts(
2433 excerpts.iter().cloned(),
2434 line_count,
2435 ExpandExcerptDirection::UpAndDown,
2436 cx,
2437 );
2438
2439 reference.expand_excerpts(&excerpts, line_count, cx);
2440 });
2441 }
2442 20..=29 if !reference.excerpts.is_empty() => {
2443 let mut ids_to_remove = vec![];
2444 for _ in 0..rng.gen_range(1..=3) {
2445 let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2446 break;
2447 };
2448 let id = excerpt.id;
2449 cx.update(|cx| reference.remove_excerpt(id, cx));
2450 ids_to_remove.push(id);
2451 }
2452 let snapshot =
2453 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2454 ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2455 drop(snapshot);
2456 multibuffer.update(cx, |multibuffer, cx| {
2457 multibuffer.remove_excerpts(ids_to_remove, cx)
2458 });
2459 }
2460 30..=39 if !reference.excerpts.is_empty() => {
2461 let multibuffer =
2462 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2463 let offset =
2464 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
2465 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
2466 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2467 anchors.push(multibuffer.anchor_at(offset, bias));
2468 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2469 }
2470 40..=44 if !anchors.is_empty() => {
2471 let multibuffer =
2472 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2473 let prev_len = anchors.len();
2474 anchors = multibuffer
2475 .refresh_anchors(&anchors)
2476 .into_iter()
2477 .map(|a| a.1)
2478 .collect();
2479
2480 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2481 // overshoot its boundaries.
2482 assert_eq!(anchors.len(), prev_len);
2483 for anchor in &anchors {
2484 if anchor.excerpt_id == ExcerptId::min()
2485 || anchor.excerpt_id == ExcerptId::max()
2486 {
2487 continue;
2488 }
2489
2490 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2491 assert_eq!(excerpt.id, anchor.excerpt_id);
2492 assert!(excerpt.contains(anchor));
2493 }
2494 }
2495 45..=55 if !reference.excerpts.is_empty() => {
2496 multibuffer.update(cx, |multibuffer, cx| {
2497 let snapshot = multibuffer.snapshot(cx);
2498 let excerpt_ix = rng.gen_range(0..reference.excerpts.len());
2499 let excerpt = &reference.excerpts[excerpt_ix];
2500 let start = excerpt.range.start;
2501 let end = excerpt.range.end;
2502 let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2503 ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2504
2505 log::info!(
2506 "expanding diff hunks in range {:?} (excerpt id {:?}) index {excerpt_ix:?})",
2507 range.to_offset(&snapshot),
2508 excerpt.id
2509 );
2510 reference.expand_diff_hunks(excerpt.id, start..end, cx);
2511 multibuffer.expand_diff_hunks(vec![range], cx);
2512 });
2513 }
2514 56..=85 if needs_diff_calculation => {
2515 multibuffer.update(cx, |multibuffer, cx| {
2516 for buffer in multibuffer.all_buffers() {
2517 let snapshot = buffer.read(cx).snapshot();
2518 let _ = multibuffer.diff_for(snapshot.remote_id()).unwrap().update(
2519 cx,
2520 |diff, cx| {
2521 log::info!(
2522 "recalculating diff for buffer {:?}",
2523 snapshot.remote_id(),
2524 );
2525 diff.recalculate_diff_sync(snapshot.text, cx);
2526 },
2527 );
2528 }
2529 reference.diffs_updated(cx);
2530 needs_diff_calculation = false;
2531 });
2532 }
2533 _ => {
2534 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2535 let base_text = util::RandomCharIter::new(&mut rng)
2536 .take(256)
2537 .collect::<String>();
2538
2539 let buffer = cx.new(|cx| Buffer::local(base_text.clone(), cx));
2540 let diff = cx.new(|cx| BufferDiff::new_with_base_text(&base_text, &buffer, cx));
2541
2542 multibuffer.update(cx, |multibuffer, cx| {
2543 reference.add_diff(diff.clone(), cx);
2544 multibuffer.add_diff(diff, cx)
2545 });
2546 buffers.push(buffer);
2547 buffers.last().unwrap()
2548 } else {
2549 buffers.choose(&mut rng).unwrap()
2550 };
2551
2552 let prev_excerpt_ix = rng.gen_range(0..=reference.excerpts.len());
2553 let prev_excerpt_id = reference
2554 .excerpts
2555 .get(prev_excerpt_ix)
2556 .map_or(ExcerptId::max(), |e| e.id);
2557 let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
2558
2559 let (range, anchor_range) = buffer_handle.read_with(cx, |buffer, _| {
2560 let end_row = rng.gen_range(0..=buffer.max_point().row);
2561 let start_row = rng.gen_range(0..=end_row);
2562 let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
2563 let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
2564 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2565
2566 log::info!(
2567 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2568 excerpt_ix,
2569 reference.excerpts.len(),
2570 buffer.remote_id(),
2571 buffer.text(),
2572 start_ix..end_ix,
2573 &buffer.text()[start_ix..end_ix]
2574 );
2575
2576 (start_ix..end_ix, anchor_range)
2577 });
2578
2579 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
2580 multibuffer
2581 .insert_excerpts_after(
2582 prev_excerpt_id,
2583 buffer_handle.clone(),
2584 [ExcerptRange {
2585 context: range,
2586 primary: None,
2587 }],
2588 cx,
2589 )
2590 .pop()
2591 .unwrap()
2592 });
2593
2594 reference.insert_excerpt_after(
2595 prev_excerpt_id,
2596 excerpt_id,
2597 (buffer_handle.clone(), anchor_range),
2598 );
2599 }
2600 }
2601
2602 if rng.gen_bool(0.3) {
2603 multibuffer.update(cx, |multibuffer, cx| {
2604 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
2605 })
2606 }
2607
2608 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2609 let actual_text = snapshot.text();
2610 let actual_boundary_rows = snapshot
2611 .excerpt_boundaries_in_range(0..)
2612 .filter_map(|b| if b.next.is_some() { Some(b.row) } else { None })
2613 .collect::<HashSet<_>>();
2614 let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
2615
2616 let (expected_text, expected_row_infos, expected_boundary_rows) =
2617 cx.update(|cx| reference.expected_content(cx));
2618
2619 let has_diff = actual_row_infos
2620 .iter()
2621 .any(|info| info.diff_status.is_some())
2622 || expected_row_infos
2623 .iter()
2624 .any(|info| info.diff_status.is_some());
2625 let actual_diff = format_diff(
2626 &actual_text,
2627 &actual_row_infos,
2628 &actual_boundary_rows,
2629 Some(has_diff),
2630 );
2631 let expected_diff = format_diff(
2632 &expected_text,
2633 &expected_row_infos,
2634 &expected_boundary_rows,
2635 Some(has_diff),
2636 );
2637
2638 log::info!("Multibuffer content:\n{}", actual_diff);
2639
2640 assert_eq!(
2641 actual_row_infos.len(),
2642 actual_text.split('\n').count(),
2643 "line count: {}",
2644 actual_text.split('\n').count()
2645 );
2646 pretty_assertions::assert_eq!(actual_diff, expected_diff);
2647 pretty_assertions::assert_eq!(actual_text, expected_text);
2648 pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
2649
2650 for _ in 0..5 {
2651 let start_row = rng.gen_range(0..=expected_row_infos.len());
2652 assert_eq!(
2653 snapshot
2654 .row_infos(MultiBufferRow(start_row as u32))
2655 .collect::<Vec<_>>(),
2656 &expected_row_infos[start_row..],
2657 "buffer_rows({})",
2658 start_row
2659 );
2660 }
2661
2662 assert_eq!(
2663 snapshot.widest_line_number(),
2664 expected_row_infos
2665 .into_iter()
2666 .filter_map(|info| {
2667 if info.diff_status.is_some_and(|status| status.is_deleted()) {
2668 None
2669 } else {
2670 info.buffer_row
2671 }
2672 })
2673 .max()
2674 .unwrap()
2675 + 1
2676 );
2677
2678 assert_consistent_line_numbers(&snapshot);
2679 assert_position_translation(&snapshot);
2680
2681 for (row, line) in expected_text.split('\n').enumerate() {
2682 assert_eq!(
2683 snapshot.line_len(MultiBufferRow(row as u32)),
2684 line.len() as u32,
2685 "line_len({}).",
2686 row
2687 );
2688 }
2689
2690 let text_rope = Rope::from(expected_text.as_str());
2691 for _ in 0..10 {
2692 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2693 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2694
2695 let text_for_range = snapshot
2696 .text_for_range(start_ix..end_ix)
2697 .collect::<String>();
2698 assert_eq!(
2699 text_for_range,
2700 &expected_text[start_ix..end_ix],
2701 "incorrect text for range {:?}",
2702 start_ix..end_ix
2703 );
2704
2705 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
2706 assert_eq!(
2707 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
2708 expected_summary,
2709 "incorrect summary for range {:?}",
2710 start_ix..end_ix
2711 );
2712 }
2713
2714 // Anchor resolution
2715 let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
2716 assert_eq!(anchors.len(), summaries.len());
2717 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
2718 assert!(resolved_offset <= snapshot.len());
2719 assert_eq!(
2720 snapshot.summary_for_anchor::<usize>(anchor),
2721 resolved_offset,
2722 "anchor: {:?}",
2723 anchor
2724 );
2725 }
2726
2727 for _ in 0..10 {
2728 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2729 assert_eq!(
2730 snapshot.reversed_chars_at(end_ix).collect::<String>(),
2731 expected_text[..end_ix].chars().rev().collect::<String>(),
2732 );
2733 }
2734
2735 for _ in 0..10 {
2736 let end_ix = rng.gen_range(0..=text_rope.len());
2737 let start_ix = rng.gen_range(0..=end_ix);
2738 assert_eq!(
2739 snapshot
2740 .bytes_in_range(start_ix..end_ix)
2741 .flatten()
2742 .copied()
2743 .collect::<Vec<_>>(),
2744 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
2745 "bytes_in_range({:?})",
2746 start_ix..end_ix,
2747 );
2748 }
2749 }
2750
2751 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2752 for (old_snapshot, subscription) in old_versions {
2753 let edits = subscription.consume().into_inner();
2754
2755 log::info!(
2756 "applying subscription edits to old text: {:?}: {:?}",
2757 old_snapshot.text(),
2758 edits,
2759 );
2760
2761 let mut text = old_snapshot.text();
2762 for edit in edits {
2763 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
2764 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
2765 }
2766 assert_eq!(text.to_string(), snapshot.text());
2767 }
2768}
2769
2770#[gpui::test]
2771fn test_history(cx: &mut App) {
2772 let test_settings = SettingsStore::test(cx);
2773 cx.set_global(test_settings);
2774 let group_interval: Duration = Duration::from_millis(1);
2775 let buffer_1 = cx.new(|cx| {
2776 let mut buf = Buffer::local("1234", cx);
2777 buf.set_group_interval(group_interval);
2778 buf
2779 });
2780 let buffer_2 = cx.new(|cx| {
2781 let mut buf = Buffer::local("5678", cx);
2782 buf.set_group_interval(group_interval);
2783 buf
2784 });
2785 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2786 multibuffer.update(cx, |this, _| {
2787 this.history.group_interval = group_interval;
2788 });
2789 multibuffer.update(cx, |multibuffer, cx| {
2790 multibuffer.push_excerpts(
2791 buffer_1.clone(),
2792 [ExcerptRange {
2793 context: 0..buffer_1.read(cx).len(),
2794 primary: None,
2795 }],
2796 cx,
2797 );
2798 multibuffer.push_excerpts(
2799 buffer_2.clone(),
2800 [ExcerptRange {
2801 context: 0..buffer_2.read(cx).len(),
2802 primary: None,
2803 }],
2804 cx,
2805 );
2806 });
2807
2808 let mut now = Instant::now();
2809
2810 multibuffer.update(cx, |multibuffer, cx| {
2811 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
2812 multibuffer.edit(
2813 [
2814 (Point::new(0, 0)..Point::new(0, 0), "A"),
2815 (Point::new(1, 0)..Point::new(1, 0), "A"),
2816 ],
2817 None,
2818 cx,
2819 );
2820 multibuffer.edit(
2821 [
2822 (Point::new(0, 1)..Point::new(0, 1), "B"),
2823 (Point::new(1, 1)..Point::new(1, 1), "B"),
2824 ],
2825 None,
2826 cx,
2827 );
2828 multibuffer.end_transaction_at(now, cx);
2829 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2830
2831 // Verify edited ranges for transaction 1
2832 assert_eq!(
2833 multibuffer.edited_ranges_for_transaction(transaction_1, cx),
2834 &[
2835 Point::new(0, 0)..Point::new(0, 2),
2836 Point::new(1, 0)..Point::new(1, 2)
2837 ]
2838 );
2839
2840 // Edit buffer 1 through the multibuffer
2841 now += 2 * group_interval;
2842 multibuffer.start_transaction_at(now, cx);
2843 multibuffer.edit([(2..2, "C")], None, cx);
2844 multibuffer.end_transaction_at(now, cx);
2845 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2846
2847 // Edit buffer 1 independently
2848 buffer_1.update(cx, |buffer_1, cx| {
2849 buffer_1.start_transaction_at(now);
2850 buffer_1.edit([(3..3, "D")], None, cx);
2851 buffer_1.end_transaction_at(now, cx);
2852
2853 now += 2 * group_interval;
2854 buffer_1.start_transaction_at(now);
2855 buffer_1.edit([(4..4, "E")], None, cx);
2856 buffer_1.end_transaction_at(now, cx);
2857 });
2858 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
2859
2860 // An undo in the multibuffer undoes the multibuffer transaction
2861 // and also any individual buffer edits that have occurred since
2862 // that transaction.
2863 multibuffer.undo(cx);
2864 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2865
2866 multibuffer.undo(cx);
2867 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2868
2869 multibuffer.redo(cx);
2870 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2871
2872 multibuffer.redo(cx);
2873 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
2874
2875 // Undo buffer 2 independently.
2876 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
2877 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
2878
2879 // An undo in the multibuffer undoes the components of the
2880 // the last multibuffer transaction that are not already undone.
2881 multibuffer.undo(cx);
2882 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
2883
2884 multibuffer.undo(cx);
2885 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2886
2887 multibuffer.redo(cx);
2888 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2889
2890 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
2891 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
2892
2893 // Redo stack gets cleared after an edit.
2894 now += 2 * group_interval;
2895 multibuffer.start_transaction_at(now, cx);
2896 multibuffer.edit([(0..0, "X")], None, cx);
2897 multibuffer.end_transaction_at(now, cx);
2898 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2899 multibuffer.redo(cx);
2900 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2901 multibuffer.undo(cx);
2902 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
2903 multibuffer.undo(cx);
2904 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2905
2906 // Transactions can be grouped manually.
2907 multibuffer.redo(cx);
2908 multibuffer.redo(cx);
2909 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2910 multibuffer.group_until_transaction(transaction_1, cx);
2911 multibuffer.undo(cx);
2912 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2913 multibuffer.redo(cx);
2914 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2915 });
2916}
2917
2918#[gpui::test]
2919async fn test_enclosing_indent(cx: &mut TestAppContext) {
2920 async fn enclosing_indent(
2921 text: &str,
2922 buffer_row: u32,
2923 cx: &mut TestAppContext,
2924 ) -> Option<(Range<u32>, LineIndent)> {
2925 let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
2926 let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
2927 let (range, indent) = snapshot
2928 .enclosing_indent(MultiBufferRow(buffer_row))
2929 .await?;
2930 Some((range.start.0..range.end.0, indent))
2931 }
2932
2933 assert_eq!(
2934 enclosing_indent(
2935 indoc!(
2936 "
2937 fn b() {
2938 if c {
2939 let d = 2;
2940 }
2941 }
2942 "
2943 ),
2944 1,
2945 cx,
2946 )
2947 .await,
2948 Some((
2949 1..2,
2950 LineIndent {
2951 tabs: 0,
2952 spaces: 4,
2953 line_blank: false,
2954 }
2955 ))
2956 );
2957
2958 assert_eq!(
2959 enclosing_indent(
2960 indoc!(
2961 "
2962 fn b() {
2963 if c {
2964 let d = 2;
2965 }
2966 }
2967 "
2968 ),
2969 2,
2970 cx,
2971 )
2972 .await,
2973 Some((
2974 1..2,
2975 LineIndent {
2976 tabs: 0,
2977 spaces: 4,
2978 line_blank: false,
2979 }
2980 ))
2981 );
2982
2983 assert_eq!(
2984 enclosing_indent(
2985 indoc!(
2986 "
2987 fn b() {
2988 if c {
2989 let d = 2;
2990
2991 let e = 5;
2992 }
2993 }
2994 "
2995 ),
2996 3,
2997 cx,
2998 )
2999 .await,
3000 Some((
3001 1..4,
3002 LineIndent {
3003 tabs: 0,
3004 spaces: 4,
3005 line_blank: false,
3006 }
3007 ))
3008 );
3009}
3010
3011#[gpui::test]
3012fn test_summaries_for_anchors(cx: &mut TestAppContext) {
3013 let base_text_1 = indoc!(
3014 "
3015 bar
3016 "
3017 );
3018 let text_1 = indoc!(
3019 "
3020 BAR
3021 "
3022 );
3023 let base_text_2 = indoc!(
3024 "
3025 foo
3026 "
3027 );
3028 let text_2 = indoc!(
3029 "
3030 FOO
3031 "
3032 );
3033
3034 let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3035 let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
3036 let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_1, &buffer_1, cx));
3037 let diff_2 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_2, &buffer_2, cx));
3038 cx.run_until_parked();
3039
3040 let mut ids = vec![];
3041 let multibuffer = cx.new(|cx| {
3042 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3043 multibuffer.set_all_diff_hunks_expanded(cx);
3044 ids.extend(multibuffer.push_excerpts(
3045 buffer_1.clone(),
3046 [ExcerptRange {
3047 context: text::Anchor::MIN..text::Anchor::MAX,
3048 primary: None,
3049 }],
3050 cx,
3051 ));
3052 ids.extend(multibuffer.push_excerpts(
3053 buffer_2.clone(),
3054 [ExcerptRange {
3055 context: text::Anchor::MIN..text::Anchor::MAX,
3056 primary: None,
3057 }],
3058 cx,
3059 ));
3060 multibuffer.add_diff(diff_1.clone(), cx);
3061 multibuffer.add_diff(diff_2.clone(), cx);
3062 multibuffer
3063 });
3064
3065 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3066 (multibuffer.snapshot(cx), multibuffer.subscribe())
3067 });
3068
3069 assert_new_snapshot(
3070 &multibuffer,
3071 &mut snapshot,
3072 &mut subscription,
3073 cx,
3074 indoc!(
3075 "
3076 - bar
3077 + BAR
3078
3079 - foo
3080 + FOO
3081 "
3082 ),
3083 );
3084
3085 let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
3086 let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
3087
3088 let anchor_1 = Anchor::in_buffer(ids[0], id_1, text::Anchor::MIN);
3089 let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3090 assert_eq!(point_1, Point::new(0, 0));
3091
3092 let anchor_2 = Anchor::in_buffer(ids[1], id_2, text::Anchor::MIN);
3093 let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3094 assert_eq!(point_2, Point::new(3, 0));
3095}
3096
3097fn format_diff(
3098 text: &str,
3099 row_infos: &Vec<RowInfo>,
3100 boundary_rows: &HashSet<MultiBufferRow>,
3101 has_diff: Option<bool>,
3102) -> String {
3103 let has_diff =
3104 has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3105 text.split('\n')
3106 .enumerate()
3107 .zip(row_infos)
3108 .map(|((ix, line), info)| {
3109 let marker = match info.diff_status.map(|status| status.kind) {
3110 Some(DiffHunkStatusKind::Added) => "+ ",
3111 Some(DiffHunkStatusKind::Deleted) => "- ",
3112 Some(DiffHunkStatusKind::Modified) => unreachable!(),
3113 None => {
3114 if has_diff && !line.is_empty() {
3115 " "
3116 } else {
3117 ""
3118 }
3119 }
3120 };
3121 let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3122 if has_diff {
3123 " ----------\n"
3124 } else {
3125 "---------\n"
3126 }
3127 } else {
3128 ""
3129 };
3130 format!("{boundary_row}{marker}{line}")
3131 })
3132 .collect::<Vec<_>>()
3133 .join("\n")
3134}
3135
3136#[track_caller]
3137fn assert_excerpts_match(
3138 multibuffer: &Entity<MultiBuffer>,
3139 cx: &mut TestAppContext,
3140 expected: &str,
3141) {
3142 let mut output = String::new();
3143 multibuffer.read_with(cx, |multibuffer, cx| {
3144 for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
3145 output.push_str("-----\n");
3146 output.extend(buffer.text_for_range(range.context));
3147 if !output.ends_with('\n') {
3148 output.push('\n');
3149 }
3150 }
3151 });
3152 assert_eq!(output, expected);
3153}
3154
3155#[track_caller]
3156fn assert_new_snapshot(
3157 multibuffer: &Entity<MultiBuffer>,
3158 snapshot: &mut MultiBufferSnapshot,
3159 subscription: &mut Subscription,
3160 cx: &mut TestAppContext,
3161 expected_diff: &str,
3162) {
3163 let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3164 let actual_text = new_snapshot.text();
3165 let line_infos = new_snapshot
3166 .row_infos(MultiBufferRow(0))
3167 .collect::<Vec<_>>();
3168 let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
3169 pretty_assertions::assert_eq!(actual_diff, expected_diff);
3170 check_edits(
3171 snapshot,
3172 &new_snapshot,
3173 &subscription.consume().into_inner(),
3174 );
3175 *snapshot = new_snapshot;
3176}
3177
3178#[track_caller]
3179fn check_edits(
3180 old_snapshot: &MultiBufferSnapshot,
3181 new_snapshot: &MultiBufferSnapshot,
3182 edits: &[Edit<usize>],
3183) {
3184 let mut text = old_snapshot.text();
3185 let new_text = new_snapshot.text();
3186 for edit in edits.iter().rev() {
3187 if !text.is_char_boundary(edit.old.start)
3188 || !text.is_char_boundary(edit.old.end)
3189 || !new_text.is_char_boundary(edit.new.start)
3190 || !new_text.is_char_boundary(edit.new.end)
3191 {
3192 panic!(
3193 "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
3194 edits, text, new_text
3195 );
3196 }
3197
3198 text.replace_range(
3199 edit.old.start..edit.old.end,
3200 &new_text[edit.new.start..edit.new.end],
3201 );
3202 }
3203
3204 pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
3205}
3206
3207#[track_caller]
3208fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
3209 let full_text = snapshot.text();
3210 for ix in 0..full_text.len() {
3211 let mut chunks = snapshot.chunks(0..snapshot.len(), false);
3212 chunks.seek(ix..snapshot.len());
3213 let tail = chunks.map(|chunk| chunk.text).collect::<String>();
3214 assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
3215 }
3216}
3217
3218#[track_caller]
3219fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
3220 let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3221 for start_row in 1..all_line_numbers.len() {
3222 let line_numbers = snapshot
3223 .row_infos(MultiBufferRow(start_row as u32))
3224 .collect::<Vec<_>>();
3225 assert_eq!(
3226 line_numbers,
3227 all_line_numbers[start_row..],
3228 "start_row: {start_row}"
3229 );
3230 }
3231}
3232
3233#[track_caller]
3234fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
3235 let text = Rope::from(snapshot.text());
3236
3237 let mut left_anchors = Vec::new();
3238 let mut right_anchors = Vec::new();
3239 let mut offsets = Vec::new();
3240 let mut points = Vec::new();
3241 for offset in 0..=text.len() + 1 {
3242 let clipped_left = snapshot.clip_offset(offset, Bias::Left);
3243 let clipped_right = snapshot.clip_offset(offset, Bias::Right);
3244 assert_eq!(
3245 clipped_left,
3246 text.clip_offset(offset, Bias::Left),
3247 "clip_offset({offset:?}, Left)"
3248 );
3249 assert_eq!(
3250 clipped_right,
3251 text.clip_offset(offset, Bias::Right),
3252 "clip_offset({offset:?}, Right)"
3253 );
3254 assert_eq!(
3255 snapshot.offset_to_point(clipped_left),
3256 text.offset_to_point(clipped_left),
3257 "offset_to_point({clipped_left})"
3258 );
3259 assert_eq!(
3260 snapshot.offset_to_point(clipped_right),
3261 text.offset_to_point(clipped_right),
3262 "offset_to_point({clipped_right})"
3263 );
3264 let anchor_after = snapshot.anchor_after(clipped_left);
3265 assert_eq!(
3266 anchor_after.to_offset(snapshot),
3267 clipped_left,
3268 "anchor_after({clipped_left}).to_offset {anchor_after:?}"
3269 );
3270 let anchor_before = snapshot.anchor_before(clipped_left);
3271 assert_eq!(
3272 anchor_before.to_offset(snapshot),
3273 clipped_left,
3274 "anchor_before({clipped_left}).to_offset"
3275 );
3276 left_anchors.push(anchor_before);
3277 right_anchors.push(anchor_after);
3278 offsets.push(clipped_left);
3279 points.push(text.offset_to_point(clipped_left));
3280 }
3281
3282 for row in 0..text.max_point().row {
3283 for column in 0..text.line_len(row) + 1 {
3284 let point = Point { row, column };
3285 let clipped_left = snapshot.clip_point(point, Bias::Left);
3286 let clipped_right = snapshot.clip_point(point, Bias::Right);
3287 assert_eq!(
3288 clipped_left,
3289 text.clip_point(point, Bias::Left),
3290 "clip_point({point:?}, Left)"
3291 );
3292 assert_eq!(
3293 clipped_right,
3294 text.clip_point(point, Bias::Right),
3295 "clip_point({point:?}, Right)"
3296 );
3297 assert_eq!(
3298 snapshot.point_to_offset(clipped_left),
3299 text.point_to_offset(clipped_left),
3300 "point_to_offset({clipped_left:?})"
3301 );
3302 assert_eq!(
3303 snapshot.point_to_offset(clipped_right),
3304 text.point_to_offset(clipped_right),
3305 "point_to_offset({clipped_right:?})"
3306 );
3307 }
3308 }
3309
3310 assert_eq!(
3311 snapshot.summaries_for_anchors::<usize, _>(&left_anchors),
3312 offsets,
3313 "left_anchors <-> offsets"
3314 );
3315 assert_eq!(
3316 snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
3317 points,
3318 "left_anchors <-> points"
3319 );
3320 assert_eq!(
3321 snapshot.summaries_for_anchors::<usize, _>(&right_anchors),
3322 offsets,
3323 "right_anchors <-> offsets"
3324 );
3325 assert_eq!(
3326 snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
3327 points,
3328 "right_anchors <-> points"
3329 );
3330
3331 for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
3332 for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
3333 if ix > 0 {
3334 if *offset == 252 {
3335 if offset > &offsets[ix - 1] {
3336 let prev_anchor = left_anchors[ix - 1];
3337 assert!(
3338 anchor.cmp(&prev_anchor, snapshot).is_gt(),
3339 "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
3340 offsets[ix],
3341 offsets[ix - 1],
3342 );
3343 assert!(
3344 prev_anchor.cmp(&anchor, snapshot).is_lt(),
3345 "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
3346 offsets[ix - 1],
3347 offsets[ix],
3348 );
3349 }
3350 }
3351 }
3352 }
3353 }
3354}
3355
3356fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
3357 let max_row = snapshot.max_point().row;
3358 let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
3359 let text = text::Buffer::new(0, buffer_id, snapshot.text());
3360 let mut line_indents = text
3361 .line_indents_in_row_range(0..max_row + 1)
3362 .collect::<Vec<_>>();
3363 for start_row in 0..snapshot.max_point().row {
3364 pretty_assertions::assert_eq!(
3365 snapshot
3366 .line_indents(MultiBufferRow(start_row), |_| true)
3367 .map(|(row, indent, _)| (row.0, indent))
3368 .collect::<Vec<_>>(),
3369 &line_indents[(start_row as usize)..],
3370 "line_indents({start_row})"
3371 );
3372 }
3373
3374 line_indents.reverse();
3375 pretty_assertions::assert_eq!(
3376 snapshot
3377 .reversed_line_indents(MultiBufferRow(max_row), |_| true)
3378 .map(|(row, indent, _)| (row.0, indent))
3379 .collect::<Vec<_>>(),
3380 &line_indents[..],
3381 "reversed_line_indents({max_row})"
3382 );
3383}