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