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 std::time::{Duration, Instant};
11use util::RandomCharIter;
12use util::rel_path::rel_path;
13use util::test::sample_text;
14
15#[ctor::ctor]
16fn init_logger() {
17 zlog::init_test();
18}
19
20#[gpui::test]
21fn test_empty_singleton(cx: &mut App) {
22 let buffer = cx.new(|cx| Buffer::local("", cx));
23 let buffer_id = buffer.read(cx).remote_id();
24 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
25 let snapshot = multibuffer.read(cx).snapshot(cx);
26 assert_eq!(snapshot.text(), "");
27 assert_eq!(
28 snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>(),
29 [RowInfo {
30 buffer_id: Some(buffer_id),
31 buffer_row: Some(0),
32 multibuffer_row: Some(MultiBufferRow(0)),
33 diff_status: None,
34 expand_info: None,
35 wrapped_buffer_row: None,
36 }]
37 );
38}
39
40#[gpui::test]
41fn test_singleton(cx: &mut App) {
42 let buffer = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
43 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
44
45 let snapshot = multibuffer.read(cx).snapshot(cx);
46 assert_eq!(snapshot.text(), buffer.read(cx).text());
47
48 assert_eq!(
49 snapshot
50 .row_infos(MultiBufferRow(0))
51 .map(|info| info.buffer_row)
52 .collect::<Vec<_>>(),
53 (0..buffer.read(cx).row_count())
54 .map(Some)
55 .collect::<Vec<_>>()
56 );
57 assert_consistent_line_numbers(&snapshot);
58
59 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
60 let snapshot = multibuffer.read(cx).snapshot(cx);
61
62 assert_eq!(snapshot.text(), buffer.read(cx).text());
63 assert_eq!(
64 snapshot
65 .row_infos(MultiBufferRow(0))
66 .map(|info| info.buffer_row)
67 .collect::<Vec<_>>(),
68 (0..buffer.read(cx).row_count())
69 .map(Some)
70 .collect::<Vec<_>>()
71 );
72 assert_consistent_line_numbers(&snapshot);
73}
74
75#[gpui::test]
76fn test_remote(cx: &mut App) {
77 let host_buffer = cx.new(|cx| Buffer::local("a", cx));
78 let guest_buffer = cx.new(|cx| {
79 let state = host_buffer.read(cx).to_proto(cx);
80 let ops = cx
81 .background_executor()
82 .block(host_buffer.read(cx).serialize_ops(None, cx));
83 let mut buffer =
84 Buffer::from_proto(ReplicaId::REMOTE_SERVER, Capability::ReadWrite, state, None)
85 .unwrap();
86 buffer.apply_ops(
87 ops.into_iter()
88 .map(|op| language::proto::deserialize_operation(op).unwrap()),
89 cx,
90 );
91 buffer
92 });
93 let multibuffer = cx.new(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
94 let snapshot = multibuffer.read(cx).snapshot(cx);
95 assert_eq!(snapshot.text(), "a");
96
97 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
98 let snapshot = multibuffer.read(cx).snapshot(cx);
99 assert_eq!(snapshot.text(), "ab");
100
101 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
102 let snapshot = multibuffer.read(cx).snapshot(cx);
103 assert_eq!(snapshot.text(), "abc");
104}
105
106#[gpui::test]
107fn test_excerpt_boundaries_and_clipping(cx: &mut App) {
108 let buffer_1 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
109 let buffer_2 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
110 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
111
112 let events = Arc::new(RwLock::new(Vec::<Event>::new()));
113 multibuffer.update(cx, |_, cx| {
114 let events = events.clone();
115 cx.subscribe(&multibuffer, move |_, _, event, _| {
116 if let Event::Edited { .. } = event {
117 events.write().push(event.clone())
118 }
119 })
120 .detach();
121 });
122
123 let subscription = multibuffer.update(cx, |multibuffer, cx| {
124 let subscription = multibuffer.subscribe();
125 multibuffer.push_excerpts(
126 buffer_1.clone(),
127 [ExcerptRange::new(Point::new(1, 2)..Point::new(2, 5))],
128 cx,
129 );
130 assert_eq!(
131 subscription.consume().into_inner(),
132 [Edit {
133 old: MultiBufferOffset(0)..MultiBufferOffset(0),
134 new: MultiBufferOffset(0)..MultiBufferOffset(10)
135 }]
136 );
137
138 multibuffer.push_excerpts(
139 buffer_1.clone(),
140 [ExcerptRange::new(Point::new(3, 3)..Point::new(4, 4))],
141 cx,
142 );
143 multibuffer.push_excerpts(
144 buffer_2.clone(),
145 [ExcerptRange::new(Point::new(3, 1)..Point::new(3, 3))],
146 cx,
147 );
148 assert_eq!(
149 subscription.consume().into_inner(),
150 [Edit {
151 old: MultiBufferOffset(10)..MultiBufferOffset(10),
152 new: MultiBufferOffset(10)..MultiBufferOffset(22)
153 }]
154 );
155
156 subscription
157 });
158
159 // Adding excerpts emits an edited event.
160 assert_eq!(
161 events.read().as_slice(),
162 &[
163 Event::Edited {
164 edited_buffer: None,
165 },
166 Event::Edited {
167 edited_buffer: None,
168 },
169 Event::Edited {
170 edited_buffer: None,
171 }
172 ]
173 );
174
175 let snapshot = multibuffer.read(cx).snapshot(cx);
176 assert_eq!(
177 snapshot.text(),
178 indoc!(
179 "
180 bbbb
181 ccccc
182 ddd
183 eeee
184 jj"
185 ),
186 );
187 assert_eq!(
188 snapshot
189 .row_infos(MultiBufferRow(0))
190 .map(|info| info.buffer_row)
191 .collect::<Vec<_>>(),
192 [Some(1), Some(2), Some(3), Some(4), Some(3)]
193 );
194 assert_eq!(
195 snapshot
196 .row_infos(MultiBufferRow(2))
197 .map(|info| info.buffer_row)
198 .collect::<Vec<_>>(),
199 [Some(3), Some(4), Some(3)]
200 );
201 assert_eq!(
202 snapshot
203 .row_infos(MultiBufferRow(4))
204 .map(|info| info.buffer_row)
205 .collect::<Vec<_>>(),
206 [Some(3)]
207 );
208 assert!(
209 snapshot
210 .row_infos(MultiBufferRow(5))
211 .map(|info| info.buffer_row)
212 .collect::<Vec<_>>()
213 .is_empty()
214 );
215
216 assert_eq!(
217 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
218 &[
219 (MultiBufferRow(0), "bbbb\nccccc".to_string(), true),
220 (MultiBufferRow(2), "ddd\neeee".to_string(), false),
221 (MultiBufferRow(4), "jj".to_string(), true),
222 ]
223 );
224 assert_eq!(
225 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
226 &[(MultiBufferRow(0), "bbbb\nccccc".to_string(), true)]
227 );
228 assert_eq!(
229 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
230 &[]
231 );
232 assert_eq!(
233 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
234 &[]
235 );
236 assert_eq!(
237 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
238 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
239 );
240 assert_eq!(
241 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
242 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
243 );
244 assert_eq!(
245 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
246 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
247 );
248 assert_eq!(
249 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
250 &[(MultiBufferRow(4), "jj".to_string(), true)]
251 );
252 assert_eq!(
253 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
254 &[]
255 );
256
257 buffer_1.update(cx, |buffer, cx| {
258 let text = "\n";
259 buffer.edit(
260 [
261 (Point::new(0, 0)..Point::new(0, 0), text),
262 (Point::new(2, 1)..Point::new(2, 3), text),
263 ],
264 None,
265 cx,
266 );
267 });
268
269 let snapshot = multibuffer.read(cx).snapshot(cx);
270 assert_eq!(
271 snapshot.text(),
272 concat!(
273 "bbbb\n", // Preserve newlines
274 "c\n", //
275 "cc\n", //
276 "ddd\n", //
277 "eeee\n", //
278 "jj" //
279 )
280 );
281
282 assert_eq!(
283 subscription.consume().into_inner(),
284 [Edit {
285 old: MultiBufferOffset(6)..MultiBufferOffset(8),
286 new: MultiBufferOffset(6)..MultiBufferOffset(7)
287 }]
288 );
289
290 let snapshot = multibuffer.read(cx).snapshot(cx);
291 assert_eq!(
292 snapshot.clip_point(Point::new(0, 5), Bias::Left),
293 Point::new(0, 4)
294 );
295 assert_eq!(
296 snapshot.clip_point(Point::new(0, 5), Bias::Right),
297 Point::new(0, 4)
298 );
299 assert_eq!(
300 snapshot.clip_point(Point::new(5, 1), Bias::Right),
301 Point::new(5, 1)
302 );
303 assert_eq!(
304 snapshot.clip_point(Point::new(5, 2), Bias::Right),
305 Point::new(5, 2)
306 );
307 assert_eq!(
308 snapshot.clip_point(Point::new(5, 3), Bias::Right),
309 Point::new(5, 2)
310 );
311
312 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
313 let (buffer_2_excerpt_id, _) =
314 multibuffer.excerpts_for_buffer(buffer_2.read(cx).remote_id(), cx)[0].clone();
315 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
316 multibuffer.snapshot(cx)
317 });
318
319 assert_eq!(
320 snapshot.text(),
321 concat!(
322 "bbbb\n", // Preserve newlines
323 "c\n", //
324 "cc\n", //
325 "ddd\n", //
326 "eeee", //
327 )
328 );
329
330 fn boundaries_in_range(
331 range: Range<Point>,
332 snapshot: &MultiBufferSnapshot,
333 ) -> Vec<(MultiBufferRow, String, bool)> {
334 snapshot
335 .excerpt_boundaries_in_range(range)
336 .map(|boundary| {
337 let starts_new_buffer = boundary.starts_new_buffer();
338 (
339 boundary.row,
340 boundary
341 .next
342 .buffer
343 .text_for_range(boundary.next.range.context)
344 .collect::<String>(),
345 starts_new_buffer,
346 )
347 })
348 .collect::<Vec<_>>()
349 }
350}
351
352#[gpui::test]
353async fn test_diff_boundary_anchors(cx: &mut TestAppContext) {
354 let base_text = "one\ntwo\nthree\n";
355 let text = "one\nthree\n";
356 let buffer = cx.new(|cx| Buffer::local(text, cx));
357 let diff = cx
358 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
359 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
360 multibuffer.update(cx, |multibuffer, cx| multibuffer.add_diff(diff, cx));
361
362 let (before, after) = multibuffer.update(cx, |multibuffer, cx| {
363 let before = multibuffer.snapshot(cx).anchor_before(Point::new(1, 0));
364 let after = multibuffer.snapshot(cx).anchor_after(Point::new(1, 0));
365 multibuffer.set_all_diff_hunks_expanded(cx);
366 (before, after)
367 });
368 cx.run_until_parked();
369
370 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
371 let actual_text = snapshot.text();
372 let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
373 let actual_diff = format_diff(&actual_text, &actual_row_infos, &Default::default(), None);
374 pretty_assertions::assert_eq!(
375 actual_diff,
376 indoc! {
377 " one
378 - two
379 three
380 "
381 },
382 );
383
384 multibuffer.update(cx, |multibuffer, cx| {
385 let snapshot = multibuffer.snapshot(cx);
386 assert_eq!(before.to_point(&snapshot), Point::new(1, 0));
387 assert_eq!(after.to_point(&snapshot), Point::new(2, 0));
388 assert_eq!(
389 vec![Point::new(1, 0), Point::new(2, 0),],
390 snapshot.summaries_for_anchors::<Point, _>(&[before, after]),
391 )
392 })
393}
394
395#[gpui::test]
396async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
397 let base_text = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n";
398 let text = "one\nfour\nseven\n";
399 let buffer = cx.new(|cx| Buffer::local(text, cx));
400 let diff = cx
401 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
402 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
403 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
404 (multibuffer.snapshot(cx), multibuffer.subscribe())
405 });
406
407 multibuffer.update(cx, |multibuffer, cx| {
408 multibuffer.add_diff(diff, cx);
409 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
410 });
411
412 assert_new_snapshot(
413 &multibuffer,
414 &mut snapshot,
415 &mut subscription,
416 cx,
417 indoc! {
418 " one
419 - two
420 - three
421 four
422 - five
423 - six
424 seven
425 - eight
426 "
427 },
428 );
429
430 assert_eq!(
431 snapshot
432 .diff_hunks_in_range(Point::new(1, 0)..Point::MAX)
433 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
434 .collect::<Vec<_>>(),
435 vec![1..3, 4..6, 7..8]
436 );
437
438 assert_eq!(snapshot.diff_hunk_before(Point::new(1, 1)), None,);
439 assert_eq!(
440 snapshot.diff_hunk_before(Point::new(7, 0)),
441 Some(MultiBufferRow(4))
442 );
443 assert_eq!(
444 snapshot.diff_hunk_before(Point::new(4, 0)),
445 Some(MultiBufferRow(1))
446 );
447
448 multibuffer.update(cx, |multibuffer, cx| {
449 multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
450 });
451
452 assert_new_snapshot(
453 &multibuffer,
454 &mut snapshot,
455 &mut subscription,
456 cx,
457 indoc! {
458 "
459 one
460 four
461 seven
462 "
463 },
464 );
465
466 assert_eq!(
467 snapshot.diff_hunk_before(Point::new(2, 0)),
468 Some(MultiBufferRow(1)),
469 );
470 assert_eq!(
471 snapshot.diff_hunk_before(Point::new(4, 0)),
472 Some(MultiBufferRow(2))
473 );
474}
475
476#[gpui::test]
477async fn test_inverted_diff_hunks_in_range(cx: &mut TestAppContext) {
478 let base_text = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n";
479 let text = "ZERO\none\nTHREE\nfour\nseven\nEIGHT\nNINE\n";
480 let buffer = cx.new(|cx| Buffer::local(text, cx));
481 let diff = cx
482 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
483 let base_text_buffer = diff.read_with(cx, |diff, _| diff.base_text_buffer());
484 let multibuffer = cx.new(|cx| MultiBuffer::singleton(base_text_buffer.clone(), cx));
485 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
486 (multibuffer.snapshot(cx), multibuffer.subscribe())
487 });
488
489 multibuffer.update(cx, |multibuffer, cx| {
490 multibuffer.add_inverted_diff(diff, buffer.clone(), cx);
491 });
492
493 assert_new_snapshot(
494 &multibuffer,
495 &mut snapshot,
496 &mut subscription,
497 cx,
498 indoc! {
499 " one
500 - two
501 - three
502 four
503 - five
504 - six
505 seven
506 - eight
507 "
508 },
509 );
510
511 assert_eq!(
512 snapshot
513 .diff_hunks_in_range(Point::new(0, 0)..Point::MAX)
514 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
515 .collect::<Vec<_>>(),
516 vec![0..0, 1..3, 4..6, 7..8]
517 );
518
519 assert_eq!(
520 snapshot.diff_hunk_before(Point::new(1, 1)),
521 Some(MultiBufferRow(0))
522 );
523 assert_eq!(
524 snapshot.diff_hunk_before(Point::new(7, 0)),
525 Some(MultiBufferRow(4))
526 );
527 assert_eq!(
528 snapshot.diff_hunk_before(Point::new(4, 0)),
529 Some(MultiBufferRow(1))
530 );
531}
532
533#[gpui::test]
534async fn test_editing_text_in_diff_hunks(cx: &mut TestAppContext) {
535 let base_text = "one\ntwo\nfour\nfive\nsix\nseven\n";
536 let text = "one\ntwo\nTHREE\nfour\nfive\nseven\n";
537 let buffer = cx.new(|cx| Buffer::local(text, cx));
538 let diff = cx
539 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
540 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
541
542 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
543 multibuffer.add_diff(diff.clone(), cx);
544 (multibuffer.snapshot(cx), multibuffer.subscribe())
545 });
546
547 cx.executor().run_until_parked();
548 multibuffer.update(cx, |multibuffer, cx| {
549 multibuffer.set_all_diff_hunks_expanded(cx);
550 });
551
552 assert_new_snapshot(
553 &multibuffer,
554 &mut snapshot,
555 &mut subscription,
556 cx,
557 indoc! {
558 "
559 one
560 two
561 + THREE
562 four
563 five
564 - six
565 seven
566 "
567 },
568 );
569
570 // Insert a newline within an insertion hunk
571 multibuffer.update(cx, |multibuffer, cx| {
572 multibuffer.edit([(Point::new(2, 0)..Point::new(2, 0), "__\n__")], None, cx);
573 });
574 assert_new_snapshot(
575 &multibuffer,
576 &mut snapshot,
577 &mut subscription,
578 cx,
579 indoc! {
580 "
581 one
582 two
583 + __
584 + __THREE
585 four
586 five
587 - six
588 seven
589 "
590 },
591 );
592
593 // Delete the newline before a deleted hunk.
594 multibuffer.update(cx, |multibuffer, cx| {
595 multibuffer.edit([(Point::new(5, 4)..Point::new(6, 0), "")], None, cx);
596 });
597 assert_new_snapshot(
598 &multibuffer,
599 &mut snapshot,
600 &mut subscription,
601 cx,
602 indoc! {
603 "
604 one
605 two
606 + __
607 + __THREE
608 four
609 fiveseven
610 "
611 },
612 );
613
614 multibuffer.update(cx, |multibuffer, cx| multibuffer.undo(cx));
615 assert_new_snapshot(
616 &multibuffer,
617 &mut snapshot,
618 &mut subscription,
619 cx,
620 indoc! {
621 "
622 one
623 two
624 + __
625 + __THREE
626 four
627 five
628 - six
629 seven
630 "
631 },
632 );
633
634 // Cannot (yet) insert at the beginning of a deleted hunk.
635 // (because it would put the newline in the wrong place)
636 multibuffer.update(cx, |multibuffer, cx| {
637 multibuffer.edit([(Point::new(6, 0)..Point::new(6, 0), "\n")], None, cx);
638 });
639 assert_new_snapshot(
640 &multibuffer,
641 &mut snapshot,
642 &mut subscription,
643 cx,
644 indoc! {
645 "
646 one
647 two
648 + __
649 + __THREE
650 four
651 five
652 - six
653 seven
654 "
655 },
656 );
657
658 // Replace a range that ends in a deleted hunk.
659 multibuffer.update(cx, |multibuffer, cx| {
660 multibuffer.edit([(Point::new(5, 2)..Point::new(6, 2), "fty-")], None, cx);
661 });
662 assert_new_snapshot(
663 &multibuffer,
664 &mut snapshot,
665 &mut subscription,
666 cx,
667 indoc! {
668 "
669 one
670 two
671 + __
672 + __THREE
673 four
674 fifty-seven
675 "
676 },
677 );
678}
679
680#[gpui::test]
681fn test_excerpt_events(cx: &mut App) {
682 let buffer_1 = cx.new(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
683 let buffer_2 = cx.new(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
684
685 let leader_multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
686 let follower_multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
687 let follower_edit_event_count = Arc::new(RwLock::new(0));
688
689 follower_multibuffer.update(cx, |_, cx| {
690 let follower_edit_event_count = follower_edit_event_count.clone();
691 cx.subscribe(
692 &leader_multibuffer,
693 move |follower, _, event, cx| match event.clone() {
694 Event::ExcerptsAdded {
695 buffer,
696 predecessor,
697 excerpts,
698 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
699 Event::ExcerptsRemoved { ids, .. } => follower.remove_excerpts(ids, cx),
700 Event::Edited { .. } => {
701 *follower_edit_event_count.write() += 1;
702 }
703 _ => {}
704 },
705 )
706 .detach();
707 });
708
709 leader_multibuffer.update(cx, |leader, cx| {
710 leader.push_excerpts(
711 buffer_1.clone(),
712 [ExcerptRange::new(0..8), ExcerptRange::new(12..16)],
713 cx,
714 );
715 leader.insert_excerpts_after(
716 leader.excerpt_ids()[0],
717 buffer_2.clone(),
718 [ExcerptRange::new(0..5), ExcerptRange::new(10..15)],
719 cx,
720 )
721 });
722 assert_eq!(
723 leader_multibuffer.read(cx).snapshot(cx).text(),
724 follower_multibuffer.read(cx).snapshot(cx).text(),
725 );
726 assert_eq!(*follower_edit_event_count.read(), 2);
727
728 leader_multibuffer.update(cx, |leader, cx| {
729 let excerpt_ids = leader.excerpt_ids();
730 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
731 });
732 assert_eq!(
733 leader_multibuffer.read(cx).snapshot(cx).text(),
734 follower_multibuffer.read(cx).snapshot(cx).text(),
735 );
736 assert_eq!(*follower_edit_event_count.read(), 3);
737
738 // Removing an empty set of excerpts is a noop.
739 leader_multibuffer.update(cx, |leader, cx| {
740 leader.remove_excerpts([], cx);
741 });
742 assert_eq!(
743 leader_multibuffer.read(cx).snapshot(cx).text(),
744 follower_multibuffer.read(cx).snapshot(cx).text(),
745 );
746 assert_eq!(*follower_edit_event_count.read(), 3);
747
748 // Adding an empty set of excerpts is a noop.
749 leader_multibuffer.update(cx, |leader, cx| {
750 leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
751 });
752 assert_eq!(
753 leader_multibuffer.read(cx).snapshot(cx).text(),
754 follower_multibuffer.read(cx).snapshot(cx).text(),
755 );
756 assert_eq!(*follower_edit_event_count.read(), 3);
757
758 leader_multibuffer.update(cx, |leader, cx| {
759 leader.clear(cx);
760 });
761 assert_eq!(
762 leader_multibuffer.read(cx).snapshot(cx).text(),
763 follower_multibuffer.read(cx).snapshot(cx).text(),
764 );
765 assert_eq!(*follower_edit_event_count.read(), 4);
766}
767
768#[gpui::test]
769fn test_expand_excerpts(cx: &mut App) {
770 let buffer = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
771 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
772
773 multibuffer.update(cx, |multibuffer, cx| {
774 multibuffer.set_excerpts_for_path(
775 PathKey::for_buffer(&buffer, cx),
776 buffer,
777 vec![
778 // Note that in this test, this first excerpt
779 // does not contain a new line
780 Point::new(3, 2)..Point::new(3, 3),
781 Point::new(7, 1)..Point::new(7, 3),
782 Point::new(15, 0)..Point::new(15, 0),
783 ],
784 1,
785 cx,
786 )
787 });
788
789 let snapshot = multibuffer.read(cx).snapshot(cx);
790
791 assert_eq!(
792 snapshot.text(),
793 concat!(
794 "ccc\n", //
795 "ddd\n", //
796 "eee", //
797 "\n", // End of excerpt
798 "ggg\n", //
799 "hhh\n", //
800 "iii", //
801 "\n", // End of excerpt
802 "ooo\n", //
803 "ppp\n", //
804 "qqq", // End of excerpt
805 )
806 );
807 drop(snapshot);
808
809 multibuffer.update(cx, |multibuffer, cx| {
810 let line_zero = multibuffer.snapshot(cx).anchor_before(Point::new(0, 0));
811 multibuffer.expand_excerpts(
812 multibuffer.excerpt_ids(),
813 1,
814 ExpandExcerptDirection::UpAndDown,
815 cx,
816 );
817 let snapshot = multibuffer.snapshot(cx);
818 let line_two = snapshot.anchor_before(Point::new(2, 0));
819 assert_eq!(line_two.cmp(&line_zero, &snapshot), cmp::Ordering::Greater);
820 });
821
822 let snapshot = multibuffer.read(cx).snapshot(cx);
823
824 assert_eq!(
825 snapshot.text(),
826 concat!(
827 "bbb\n", //
828 "ccc\n", //
829 "ddd\n", //
830 "eee\n", //
831 "fff\n", //
832 "ggg\n", //
833 "hhh\n", //
834 "iii\n", //
835 "jjj\n", // End of excerpt
836 "nnn\n", //
837 "ooo\n", //
838 "ppp\n", //
839 "qqq\n", //
840 "rrr", // End of excerpt
841 )
842 );
843}
844
845#[gpui::test(iterations = 100)]
846async fn test_set_anchored_excerpts_for_path(cx: &mut TestAppContext) {
847 let buffer_1 = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
848 let buffer_2 = cx.new(|cx| Buffer::local(sample_text(15, 4, 'a'), cx));
849 let snapshot_1 = buffer_1.update(cx, |buffer, _| buffer.snapshot());
850 let snapshot_2 = buffer_2.update(cx, |buffer, _| buffer.snapshot());
851 let ranges_1 = vec![
852 snapshot_1.anchor_before(Point::new(3, 2))..snapshot_1.anchor_before(Point::new(4, 2)),
853 snapshot_1.anchor_before(Point::new(7, 1))..snapshot_1.anchor_before(Point::new(7, 3)),
854 snapshot_1.anchor_before(Point::new(15, 0))..snapshot_1.anchor_before(Point::new(15, 0)),
855 ];
856 let ranges_2 = vec![
857 snapshot_2.anchor_before(Point::new(2, 1))..snapshot_2.anchor_before(Point::new(3, 1)),
858 snapshot_2.anchor_before(Point::new(10, 0))..snapshot_2.anchor_before(Point::new(10, 2)),
859 ];
860
861 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
862 let anchor_ranges_1 = multibuffer
863 .update(cx, |multibuffer, cx| {
864 multibuffer.set_anchored_excerpts_for_path(
865 PathKey::for_buffer(&buffer_1, cx),
866 buffer_1.clone(),
867 ranges_1,
868 2,
869 cx,
870 )
871 })
872 .await;
873 let snapshot_1 = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
874 assert_eq!(
875 anchor_ranges_1
876 .iter()
877 .map(|range| range.to_point(&snapshot_1))
878 .collect::<Vec<_>>(),
879 vec![
880 Point::new(2, 2)..Point::new(3, 2),
881 Point::new(6, 1)..Point::new(6, 3),
882 Point::new(11, 0)..Point::new(11, 0),
883 ]
884 );
885 let anchor_ranges_2 = multibuffer
886 .update(cx, |multibuffer, cx| {
887 multibuffer.set_anchored_excerpts_for_path(
888 PathKey::for_buffer(&buffer_2, cx),
889 buffer_2.clone(),
890 ranges_2,
891 2,
892 cx,
893 )
894 })
895 .await;
896 let snapshot_2 = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
897 assert_eq!(
898 anchor_ranges_2
899 .iter()
900 .map(|range| range.to_point(&snapshot_2))
901 .collect::<Vec<_>>(),
902 vec![
903 Point::new(16, 1)..Point::new(17, 1),
904 Point::new(22, 0)..Point::new(22, 2)
905 ]
906 );
907
908 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
909 assert_eq!(
910 snapshot.text(),
911 concat!(
912 "bbb\n", // buffer_1
913 "ccc\n", //
914 "ddd\n", // <-- excerpt 1
915 "eee\n", // <-- excerpt 1
916 "fff\n", //
917 "ggg\n", //
918 "hhh\n", // <-- excerpt 2
919 "iii\n", //
920 "jjj\n", //
921 //
922 "nnn\n", //
923 "ooo\n", //
924 "ppp\n", // <-- excerpt 3
925 "qqq\n", //
926 "rrr\n", //
927 //
928 "aaaa\n", // buffer 2
929 "bbbb\n", //
930 "cccc\n", // <-- excerpt 4
931 "dddd\n", // <-- excerpt 4
932 "eeee\n", //
933 "ffff\n", //
934 //
935 "iiii\n", //
936 "jjjj\n", //
937 "kkkk\n", // <-- excerpt 5
938 "llll\n", //
939 "mmmm", //
940 )
941 );
942}
943
944#[gpui::test]
945fn test_empty_multibuffer(cx: &mut App) {
946 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
947
948 let snapshot = multibuffer.read(cx).snapshot(cx);
949 assert_eq!(snapshot.text(), "");
950 assert_eq!(
951 snapshot
952 .row_infos(MultiBufferRow(0))
953 .map(|info| info.buffer_row)
954 .collect::<Vec<_>>(),
955 &[Some(0)]
956 );
957 assert!(
958 snapshot
959 .row_infos(MultiBufferRow(1))
960 .map(|info| info.buffer_row)
961 .collect::<Vec<_>>()
962 .is_empty(),
963 );
964}
965
966#[gpui::test]
967async fn test_empty_diff_excerpt(cx: &mut TestAppContext) {
968 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
969 let buffer = cx.new(|cx| Buffer::local("", cx));
970 let base_text = "a\nb\nc";
971
972 let diff = cx
973 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
974 multibuffer.update(cx, |multibuffer, cx| {
975 multibuffer.push_excerpts(buffer.clone(), [ExcerptRange::new(0..0)], cx);
976 multibuffer.set_all_diff_hunks_expanded(cx);
977 multibuffer.add_diff(diff.clone(), cx);
978 });
979 cx.run_until_parked();
980
981 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
982 assert_eq!(snapshot.text(), "a\nb\nc\n");
983
984 let hunk = snapshot
985 .diff_hunks_in_range(Point::new(1, 1)..Point::new(1, 1))
986 .next()
987 .unwrap();
988
989 assert_eq!(hunk.diff_base_byte_range.start, BufferOffset(0));
990
991 let buf2 = cx.new(|cx| Buffer::local("X", cx));
992 multibuffer.update(cx, |multibuffer, cx| {
993 multibuffer.push_excerpts(buf2, [ExcerptRange::new(0..1)], cx);
994 });
995
996 buffer.update(cx, |buffer, cx| {
997 buffer.edit([(0..0, "a\nb\nc")], None, cx);
998 diff.update(cx, |diff, cx| {
999 diff.recalculate_diff_sync(&buffer.text_snapshot(), cx);
1000 });
1001 assert_eq!(buffer.text(), "a\nb\nc")
1002 });
1003 cx.run_until_parked();
1004
1005 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
1006 assert_eq!(snapshot.text(), "a\nb\nc\nX");
1007
1008 buffer.update(cx, |buffer, cx| {
1009 buffer.undo(cx);
1010 diff.update(cx, |diff, cx| {
1011 diff.recalculate_diff_sync(&buffer.text_snapshot(), cx);
1012 });
1013 assert_eq!(buffer.text(), "")
1014 });
1015 cx.run_until_parked();
1016
1017 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
1018 assert_eq!(snapshot.text(), "a\nb\nc\n\nX");
1019}
1020
1021#[gpui::test]
1022fn test_singleton_multibuffer_anchors(cx: &mut App) {
1023 let buffer = cx.new(|cx| Buffer::local("abcd", cx));
1024 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
1025 let old_snapshot = multibuffer.read(cx).snapshot(cx);
1026 buffer.update(cx, |buffer, cx| {
1027 buffer.edit([(0..0, "X")], None, cx);
1028 buffer.edit([(5..5, "Y")], None, cx);
1029 });
1030 let new_snapshot = multibuffer.read(cx).snapshot(cx);
1031
1032 assert_eq!(old_snapshot.text(), "abcd");
1033 assert_eq!(new_snapshot.text(), "XabcdY");
1034
1035 assert_eq!(
1036 old_snapshot
1037 .anchor_before(MultiBufferOffset(0))
1038 .to_offset(&new_snapshot),
1039 MultiBufferOffset(0)
1040 );
1041 assert_eq!(
1042 old_snapshot
1043 .anchor_after(MultiBufferOffset(0))
1044 .to_offset(&new_snapshot),
1045 MultiBufferOffset(1)
1046 );
1047 assert_eq!(
1048 old_snapshot
1049 .anchor_before(MultiBufferOffset(4))
1050 .to_offset(&new_snapshot),
1051 MultiBufferOffset(5)
1052 );
1053 assert_eq!(
1054 old_snapshot
1055 .anchor_after(MultiBufferOffset(4))
1056 .to_offset(&new_snapshot),
1057 MultiBufferOffset(6)
1058 );
1059}
1060
1061#[gpui::test]
1062fn test_multibuffer_anchors(cx: &mut App) {
1063 let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
1064 let buffer_2 = cx.new(|cx| Buffer::local("efghi", cx));
1065 let multibuffer = cx.new(|cx| {
1066 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1067 multibuffer.push_excerpts(buffer_1.clone(), [ExcerptRange::new(0..4)], cx);
1068 multibuffer.push_excerpts(buffer_2.clone(), [ExcerptRange::new(0..5)], cx);
1069 multibuffer
1070 });
1071 let old_snapshot = multibuffer.read(cx).snapshot(cx);
1072
1073 assert_eq!(
1074 old_snapshot
1075 .anchor_before(MultiBufferOffset(0))
1076 .to_offset(&old_snapshot),
1077 MultiBufferOffset(0)
1078 );
1079 assert_eq!(
1080 old_snapshot
1081 .anchor_after(MultiBufferOffset(0))
1082 .to_offset(&old_snapshot),
1083 MultiBufferOffset(0)
1084 );
1085 assert_eq!(Anchor::min().to_offset(&old_snapshot), MultiBufferOffset(0));
1086 assert_eq!(Anchor::min().to_offset(&old_snapshot), MultiBufferOffset(0));
1087 assert_eq!(
1088 Anchor::max().to_offset(&old_snapshot),
1089 MultiBufferOffset(10)
1090 );
1091 assert_eq!(
1092 Anchor::max().to_offset(&old_snapshot),
1093 MultiBufferOffset(10)
1094 );
1095
1096 buffer_1.update(cx, |buffer, cx| {
1097 buffer.edit([(0..0, "W")], None, cx);
1098 buffer.edit([(5..5, "X")], None, cx);
1099 });
1100 buffer_2.update(cx, |buffer, cx| {
1101 buffer.edit([(0..0, "Y")], None, cx);
1102 buffer.edit([(6..6, "Z")], None, cx);
1103 });
1104 let new_snapshot = multibuffer.read(cx).snapshot(cx);
1105
1106 assert_eq!(old_snapshot.text(), "abcd\nefghi");
1107 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
1108
1109 assert_eq!(
1110 old_snapshot
1111 .anchor_before(MultiBufferOffset(0))
1112 .to_offset(&new_snapshot),
1113 MultiBufferOffset(0)
1114 );
1115 assert_eq!(
1116 old_snapshot
1117 .anchor_after(MultiBufferOffset(0))
1118 .to_offset(&new_snapshot),
1119 MultiBufferOffset(1)
1120 );
1121 assert_eq!(
1122 old_snapshot
1123 .anchor_before(MultiBufferOffset(1))
1124 .to_offset(&new_snapshot),
1125 MultiBufferOffset(2)
1126 );
1127 assert_eq!(
1128 old_snapshot
1129 .anchor_after(MultiBufferOffset(1))
1130 .to_offset(&new_snapshot),
1131 MultiBufferOffset(2)
1132 );
1133 assert_eq!(
1134 old_snapshot
1135 .anchor_before(MultiBufferOffset(2))
1136 .to_offset(&new_snapshot),
1137 MultiBufferOffset(3)
1138 );
1139 assert_eq!(
1140 old_snapshot
1141 .anchor_after(MultiBufferOffset(2))
1142 .to_offset(&new_snapshot),
1143 MultiBufferOffset(3)
1144 );
1145 assert_eq!(
1146 old_snapshot
1147 .anchor_before(MultiBufferOffset(5))
1148 .to_offset(&new_snapshot),
1149 MultiBufferOffset(7)
1150 );
1151 assert_eq!(
1152 old_snapshot
1153 .anchor_after(MultiBufferOffset(5))
1154 .to_offset(&new_snapshot),
1155 MultiBufferOffset(8)
1156 );
1157 assert_eq!(
1158 old_snapshot
1159 .anchor_before(MultiBufferOffset(10))
1160 .to_offset(&new_snapshot),
1161 MultiBufferOffset(13)
1162 );
1163 assert_eq!(
1164 old_snapshot
1165 .anchor_after(MultiBufferOffset(10))
1166 .to_offset(&new_snapshot),
1167 MultiBufferOffset(14)
1168 );
1169}
1170
1171#[gpui::test]
1172fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut App) {
1173 let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
1174 let buffer_2 = cx.new(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
1175 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1176
1177 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
1178 // Add an excerpt from buffer 1 that spans this new insertion.
1179 buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
1180 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
1181 multibuffer
1182 .push_excerpts(buffer_1.clone(), [ExcerptRange::new(0..7)], cx)
1183 .pop()
1184 .unwrap()
1185 });
1186
1187 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
1188 assert_eq!(snapshot_1.text(), "abcd123");
1189
1190 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
1191 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
1192 multibuffer.remove_excerpts([excerpt_id_1], cx);
1193 let mut ids = multibuffer
1194 .push_excerpts(
1195 buffer_2.clone(),
1196 [
1197 ExcerptRange::new(0..4),
1198 ExcerptRange::new(6..10),
1199 ExcerptRange::new(12..16),
1200 ],
1201 cx,
1202 )
1203 .into_iter();
1204 (ids.next().unwrap(), ids.next().unwrap())
1205 });
1206 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
1207 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
1208
1209 // The old excerpt id doesn't get reused.
1210 assert_ne!(excerpt_id_2, excerpt_id_1);
1211
1212 // Resolve some anchors from the previous snapshot in the new snapshot.
1213 // The current excerpts are from a different buffer, so we don't attempt to
1214 // resolve the old text anchor in the new buffer.
1215 assert_eq!(
1216 snapshot_2.summary_for_anchor::<MultiBufferOffset>(
1217 &snapshot_1.anchor_before(MultiBufferOffset(2))
1218 ),
1219 MultiBufferOffset(0)
1220 );
1221 assert_eq!(
1222 snapshot_2.summaries_for_anchors::<MultiBufferOffset, _>(&[
1223 snapshot_1.anchor_before(MultiBufferOffset(2)),
1224 snapshot_1.anchor_after(MultiBufferOffset(3))
1225 ]),
1226 vec![MultiBufferOffset(0), MultiBufferOffset(0)]
1227 );
1228
1229 // Refresh anchors from the old snapshot. The return value indicates that both
1230 // anchors lost their original excerpt.
1231 let refresh = snapshot_2.refresh_anchors(&[
1232 snapshot_1.anchor_before(MultiBufferOffset(2)),
1233 snapshot_1.anchor_after(MultiBufferOffset(3)),
1234 ]);
1235 assert_eq!(
1236 refresh,
1237 &[
1238 (0, snapshot_2.anchor_before(MultiBufferOffset(0)), false),
1239 (1, snapshot_2.anchor_after(MultiBufferOffset(0)), false),
1240 ]
1241 );
1242
1243 // Replace the middle excerpt with a smaller excerpt in buffer 2,
1244 // that intersects the old excerpt.
1245 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
1246 multibuffer.remove_excerpts([excerpt_id_3], cx);
1247 multibuffer
1248 .insert_excerpts_after(
1249 excerpt_id_2,
1250 buffer_2.clone(),
1251 [ExcerptRange::new(5..8)],
1252 cx,
1253 )
1254 .pop()
1255 .unwrap()
1256 });
1257
1258 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
1259 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
1260 assert_ne!(excerpt_id_5, excerpt_id_3);
1261
1262 // Resolve some anchors from the previous snapshot in the new snapshot.
1263 // The third anchor can't be resolved, since its excerpt has been removed,
1264 // so it resolves to the same position as its predecessor.
1265 let anchors = [
1266 snapshot_2.anchor_before(MultiBufferOffset(0)),
1267 snapshot_2.anchor_after(MultiBufferOffset(2)),
1268 snapshot_2.anchor_after(MultiBufferOffset(6)),
1269 snapshot_2.anchor_after(MultiBufferOffset(14)),
1270 ];
1271 assert_eq!(
1272 snapshot_3.summaries_for_anchors::<MultiBufferOffset, _>(&anchors),
1273 &[
1274 MultiBufferOffset(0),
1275 MultiBufferOffset(2),
1276 MultiBufferOffset(9),
1277 MultiBufferOffset(13)
1278 ]
1279 );
1280
1281 let new_anchors = snapshot_3.refresh_anchors(&anchors);
1282 assert_eq!(
1283 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
1284 &[(0, true), (1, true), (2, true), (3, true)]
1285 );
1286 assert_eq!(
1287 snapshot_3.summaries_for_anchors::<MultiBufferOffset, _>(new_anchors.iter().map(|a| &a.1)),
1288 &[
1289 MultiBufferOffset(0),
1290 MultiBufferOffset(2),
1291 MultiBufferOffset(7),
1292 MultiBufferOffset(13)
1293 ]
1294 );
1295}
1296
1297#[gpui::test]
1298async fn test_basic_diff_hunks(cx: &mut TestAppContext) {
1299 let text = indoc!(
1300 "
1301 ZERO
1302 one
1303 TWO
1304 three
1305 six
1306 "
1307 );
1308 let base_text = indoc!(
1309 "
1310 one
1311 two
1312 three
1313 four
1314 five
1315 six
1316 "
1317 );
1318
1319 let buffer = cx.new(|cx| Buffer::local(text, cx));
1320 let diff = cx
1321 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
1322 cx.run_until_parked();
1323
1324 let multibuffer = cx.new(|cx| {
1325 let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1326 multibuffer.add_diff(diff.clone(), cx);
1327 multibuffer
1328 });
1329
1330 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1331 (multibuffer.snapshot(cx), multibuffer.subscribe())
1332 });
1333 assert_eq!(
1334 snapshot.text(),
1335 indoc!(
1336 "
1337 ZERO
1338 one
1339 TWO
1340 three
1341 six
1342 "
1343 ),
1344 );
1345
1346 multibuffer.update(cx, |multibuffer, cx| {
1347 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1348 });
1349
1350 assert_new_snapshot(
1351 &multibuffer,
1352 &mut snapshot,
1353 &mut subscription,
1354 cx,
1355 indoc!(
1356 "
1357 + ZERO
1358 one
1359 - two
1360 + TWO
1361 three
1362 - four
1363 - five
1364 six
1365 "
1366 ),
1367 );
1368
1369 assert_eq!(
1370 snapshot
1371 .row_infos(MultiBufferRow(0))
1372 .map(|info| (info.buffer_row, info.diff_status))
1373 .collect::<Vec<_>>(),
1374 vec![
1375 (Some(0), Some(DiffHunkStatus::added_none())),
1376 (Some(1), None),
1377 (Some(1), Some(DiffHunkStatus::deleted_none())),
1378 (Some(2), Some(DiffHunkStatus::added_none())),
1379 (Some(3), None),
1380 (Some(3), Some(DiffHunkStatus::deleted_none())),
1381 (Some(4), Some(DiffHunkStatus::deleted_none())),
1382 (Some(4), None),
1383 (Some(5), None)
1384 ]
1385 );
1386
1387 assert_chunks_in_ranges(&snapshot);
1388 assert_consistent_line_numbers(&snapshot);
1389 assert_position_translation(&snapshot);
1390 assert_line_indents(&snapshot);
1391
1392 multibuffer.update(cx, |multibuffer, cx| {
1393 multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
1394 });
1395 assert_new_snapshot(
1396 &multibuffer,
1397 &mut snapshot,
1398 &mut subscription,
1399 cx,
1400 indoc!(
1401 "
1402 ZERO
1403 one
1404 TWO
1405 three
1406 six
1407 "
1408 ),
1409 );
1410
1411 assert_chunks_in_ranges(&snapshot);
1412 assert_consistent_line_numbers(&snapshot);
1413 assert_position_translation(&snapshot);
1414 assert_line_indents(&snapshot);
1415
1416 // Expand the first diff hunk
1417 multibuffer.update(cx, |multibuffer, cx| {
1418 let position = multibuffer.read(cx).anchor_before(Point::new(2, 2));
1419 multibuffer.expand_diff_hunks(vec![position..position], cx)
1420 });
1421 assert_new_snapshot(
1422 &multibuffer,
1423 &mut snapshot,
1424 &mut subscription,
1425 cx,
1426 indoc!(
1427 "
1428 ZERO
1429 one
1430 - two
1431 + TWO
1432 three
1433 six
1434 "
1435 ),
1436 );
1437
1438 // Expand the second diff hunk
1439 multibuffer.update(cx, |multibuffer, cx| {
1440 let start = multibuffer.read(cx).anchor_before(Point::new(4, 0));
1441 let end = multibuffer.read(cx).anchor_before(Point::new(5, 0));
1442 multibuffer.expand_diff_hunks(vec![start..end], cx)
1443 });
1444 assert_new_snapshot(
1445 &multibuffer,
1446 &mut snapshot,
1447 &mut subscription,
1448 cx,
1449 indoc!(
1450 "
1451 ZERO
1452 one
1453 - two
1454 + TWO
1455 three
1456 - four
1457 - five
1458 six
1459 "
1460 ),
1461 );
1462
1463 assert_chunks_in_ranges(&snapshot);
1464 assert_consistent_line_numbers(&snapshot);
1465 assert_position_translation(&snapshot);
1466 assert_line_indents(&snapshot);
1467
1468 // Edit the buffer before the first hunk
1469 buffer.update(cx, |buffer, cx| {
1470 buffer.edit_via_marked_text(
1471 indoc!(
1472 "
1473 ZERO
1474 one« hundred
1475 thousand»
1476 TWO
1477 three
1478 six
1479 "
1480 ),
1481 None,
1482 cx,
1483 );
1484 });
1485 assert_new_snapshot(
1486 &multibuffer,
1487 &mut snapshot,
1488 &mut subscription,
1489 cx,
1490 indoc!(
1491 "
1492 ZERO
1493 one hundred
1494 thousand
1495 - two
1496 + TWO
1497 three
1498 - four
1499 - five
1500 six
1501 "
1502 ),
1503 );
1504
1505 assert_chunks_in_ranges(&snapshot);
1506 assert_consistent_line_numbers(&snapshot);
1507 assert_position_translation(&snapshot);
1508 assert_line_indents(&snapshot);
1509
1510 // Recalculate the diff, changing the first diff hunk.
1511 diff.update(cx, |diff, cx| {
1512 diff.recalculate_diff_sync(&buffer.read(cx).text_snapshot(), cx);
1513 });
1514 cx.run_until_parked();
1515 assert_new_snapshot(
1516 &multibuffer,
1517 &mut snapshot,
1518 &mut subscription,
1519 cx,
1520 indoc!(
1521 "
1522 ZERO
1523 one hundred
1524 thousand
1525 TWO
1526 three
1527 - four
1528 - five
1529 six
1530 "
1531 ),
1532 );
1533
1534 assert_eq!(
1535 snapshot
1536 .diff_hunks_in_range(MultiBufferOffset(0)..snapshot.len())
1537 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
1538 .collect::<Vec<_>>(),
1539 &[0..4, 5..7]
1540 );
1541}
1542
1543#[gpui::test]
1544async fn test_repeatedly_expand_a_diff_hunk(cx: &mut TestAppContext) {
1545 let text = indoc!(
1546 "
1547 one
1548 TWO
1549 THREE
1550 four
1551 FIVE
1552 six
1553 "
1554 );
1555 let base_text = indoc!(
1556 "
1557 one
1558 four
1559 five
1560 six
1561 "
1562 );
1563
1564 let buffer = cx.new(|cx| Buffer::local(text, cx));
1565 let diff = cx
1566 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
1567 cx.run_until_parked();
1568
1569 let multibuffer = cx.new(|cx| {
1570 let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1571 multibuffer.add_diff(diff.clone(), cx);
1572 multibuffer
1573 });
1574
1575 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1576 (multibuffer.snapshot(cx), multibuffer.subscribe())
1577 });
1578
1579 multibuffer.update(cx, |multibuffer, cx| {
1580 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1581 });
1582
1583 assert_new_snapshot(
1584 &multibuffer,
1585 &mut snapshot,
1586 &mut subscription,
1587 cx,
1588 indoc!(
1589 "
1590 one
1591 + TWO
1592 + THREE
1593 four
1594 - five
1595 + FIVE
1596 six
1597 "
1598 ),
1599 );
1600
1601 // Regression test: expanding diff hunks that are already expanded should not change anything.
1602 multibuffer.update(cx, |multibuffer, cx| {
1603 multibuffer.expand_diff_hunks(
1604 vec![
1605 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_before(Point::new(2, 0)),
1606 ],
1607 cx,
1608 );
1609 });
1610
1611 assert_new_snapshot(
1612 &multibuffer,
1613 &mut snapshot,
1614 &mut subscription,
1615 cx,
1616 indoc!(
1617 "
1618 one
1619 + TWO
1620 + THREE
1621 four
1622 - five
1623 + FIVE
1624 six
1625 "
1626 ),
1627 );
1628
1629 // Now collapse all diff hunks
1630 multibuffer.update(cx, |multibuffer, cx| {
1631 multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1632 });
1633
1634 assert_new_snapshot(
1635 &multibuffer,
1636 &mut snapshot,
1637 &mut subscription,
1638 cx,
1639 indoc!(
1640 "
1641 one
1642 TWO
1643 THREE
1644 four
1645 FIVE
1646 six
1647 "
1648 ),
1649 );
1650
1651 // Expand the hunks again, but this time provide two ranges that are both within the same hunk
1652 // Target the first hunk which is between "one" and "four"
1653 multibuffer.update(cx, |multibuffer, cx| {
1654 multibuffer.expand_diff_hunks(
1655 vec![
1656 snapshot.anchor_before(Point::new(4, 0))..snapshot.anchor_before(Point::new(4, 0)),
1657 snapshot.anchor_before(Point::new(4, 2))..snapshot.anchor_before(Point::new(4, 2)),
1658 ],
1659 cx,
1660 );
1661 });
1662 assert_new_snapshot(
1663 &multibuffer,
1664 &mut snapshot,
1665 &mut subscription,
1666 cx,
1667 indoc!(
1668 "
1669 one
1670 TWO
1671 THREE
1672 four
1673 - five
1674 + FIVE
1675 six
1676 "
1677 ),
1678 );
1679}
1680
1681#[gpui::test]
1682fn test_set_excerpts_for_buffer_ordering(cx: &mut TestAppContext) {
1683 let buf1 = cx.new(|cx| {
1684 Buffer::local(
1685 indoc! {
1686 "zero
1687 one
1688 two
1689 two.five
1690 three
1691 four
1692 five
1693 six
1694 seven
1695 eight
1696 nine
1697 ten
1698 eleven
1699 ",
1700 },
1701 cx,
1702 )
1703 });
1704 let path1: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
1705
1706 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1707 multibuffer.update(cx, |multibuffer, cx| {
1708 multibuffer.set_excerpts_for_path(
1709 path1.clone(),
1710 buf1.clone(),
1711 vec![
1712 Point::row_range(1..2),
1713 Point::row_range(6..7),
1714 Point::row_range(11..12),
1715 ],
1716 1,
1717 cx,
1718 );
1719 });
1720
1721 assert_excerpts_match(
1722 &multibuffer,
1723 cx,
1724 indoc! {
1725 "-----
1726 zero
1727 one
1728 two
1729 two.five
1730 -----
1731 four
1732 five
1733 six
1734 seven
1735 -----
1736 nine
1737 ten
1738 eleven
1739 "
1740 },
1741 );
1742
1743 buf1.update(cx, |buffer, cx| buffer.edit([(0..5, "")], None, cx));
1744
1745 multibuffer.update(cx, |multibuffer, cx| {
1746 multibuffer.set_excerpts_for_path(
1747 path1.clone(),
1748 buf1.clone(),
1749 vec![
1750 Point::row_range(0..3),
1751 Point::row_range(5..7),
1752 Point::row_range(10..11),
1753 ],
1754 1,
1755 cx,
1756 );
1757 });
1758
1759 assert_excerpts_match(
1760 &multibuffer,
1761 cx,
1762 indoc! {
1763 "-----
1764 one
1765 two
1766 two.five
1767 three
1768 four
1769 five
1770 six
1771 seven
1772 eight
1773 nine
1774 ten
1775 eleven
1776 "
1777 },
1778 );
1779}
1780
1781#[gpui::test]
1782fn test_set_excerpts_for_buffer(cx: &mut TestAppContext) {
1783 let buf1 = cx.new(|cx| {
1784 Buffer::local(
1785 indoc! {
1786 "zero
1787 one
1788 two
1789 three
1790 four
1791 five
1792 six
1793 seven
1794 ",
1795 },
1796 cx,
1797 )
1798 });
1799 let path1: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
1800 let buf2 = cx.new(|cx| {
1801 Buffer::local(
1802 indoc! {
1803 "000
1804 111
1805 222
1806 333
1807 444
1808 555
1809 666
1810 777
1811 888
1812 999
1813 "
1814 },
1815 cx,
1816 )
1817 });
1818 let path2 = PathKey::with_sort_prefix(1, rel_path("root").into_arc());
1819
1820 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1821 multibuffer.update(cx, |multibuffer, cx| {
1822 multibuffer.set_excerpts_for_path(
1823 path1.clone(),
1824 buf1.clone(),
1825 vec![Point::row_range(0..1)],
1826 2,
1827 cx,
1828 );
1829 });
1830
1831 assert_excerpts_match(
1832 &multibuffer,
1833 cx,
1834 indoc! {
1835 "-----
1836 zero
1837 one
1838 two
1839 three
1840 "
1841 },
1842 );
1843
1844 multibuffer.update(cx, |multibuffer, cx| {
1845 multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1846 });
1847
1848 assert_excerpts_match(&multibuffer, cx, "");
1849
1850 multibuffer.update(cx, |multibuffer, cx| {
1851 multibuffer.set_excerpts_for_path(
1852 path1.clone(),
1853 buf1.clone(),
1854 vec![Point::row_range(0..1), Point::row_range(7..8)],
1855 2,
1856 cx,
1857 );
1858 });
1859
1860 assert_excerpts_match(
1861 &multibuffer,
1862 cx,
1863 indoc! {"-----
1864 zero
1865 one
1866 two
1867 three
1868 -----
1869 five
1870 six
1871 seven
1872 "},
1873 );
1874
1875 multibuffer.update(cx, |multibuffer, cx| {
1876 multibuffer.set_excerpts_for_path(
1877 path1.clone(),
1878 buf1.clone(),
1879 vec![Point::row_range(0..1), Point::row_range(5..6)],
1880 2,
1881 cx,
1882 );
1883 });
1884
1885 assert_excerpts_match(
1886 &multibuffer,
1887 cx,
1888 indoc! {"-----
1889 zero
1890 one
1891 two
1892 three
1893 four
1894 five
1895 six
1896 seven
1897 "},
1898 );
1899
1900 multibuffer.update(cx, |multibuffer, cx| {
1901 multibuffer.set_excerpts_for_path(
1902 path2.clone(),
1903 buf2.clone(),
1904 vec![Point::row_range(2..3)],
1905 2,
1906 cx,
1907 );
1908 });
1909
1910 assert_excerpts_match(
1911 &multibuffer,
1912 cx,
1913 indoc! {"-----
1914 zero
1915 one
1916 two
1917 three
1918 four
1919 five
1920 six
1921 seven
1922 -----
1923 000
1924 111
1925 222
1926 333
1927 444
1928 555
1929 "},
1930 );
1931
1932 multibuffer.update(cx, |multibuffer, cx| {
1933 multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1934 });
1935
1936 multibuffer.update(cx, |multibuffer, cx| {
1937 multibuffer.set_excerpts_for_path(
1938 path1.clone(),
1939 buf1.clone(),
1940 vec![Point::row_range(3..4)],
1941 2,
1942 cx,
1943 );
1944 });
1945
1946 assert_excerpts_match(
1947 &multibuffer,
1948 cx,
1949 indoc! {"-----
1950 one
1951 two
1952 three
1953 four
1954 five
1955 six
1956 -----
1957 000
1958 111
1959 222
1960 333
1961 444
1962 555
1963 "},
1964 );
1965
1966 multibuffer.update(cx, |multibuffer, cx| {
1967 multibuffer.set_excerpts_for_path(
1968 path1.clone(),
1969 buf1.clone(),
1970 vec![Point::row_range(3..4)],
1971 2,
1972 cx,
1973 );
1974 });
1975}
1976
1977#[gpui::test]
1978fn test_set_excerpts_for_buffer_rename(cx: &mut TestAppContext) {
1979 let buf1 = cx.new(|cx| {
1980 Buffer::local(
1981 indoc! {
1982 "zero
1983 one
1984 two
1985 three
1986 four
1987 five
1988 six
1989 seven
1990 ",
1991 },
1992 cx,
1993 )
1994 });
1995 let path: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
1996 let buf2 = cx.new(|cx| {
1997 Buffer::local(
1998 indoc! {
1999 "000
2000 111
2001 222
2002 333
2003 "
2004 },
2005 cx,
2006 )
2007 });
2008
2009 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2010 multibuffer.update(cx, |multibuffer, cx| {
2011 multibuffer.set_excerpts_for_path(
2012 path.clone(),
2013 buf1.clone(),
2014 vec![Point::row_range(1..1), Point::row_range(4..5)],
2015 1,
2016 cx,
2017 );
2018 });
2019
2020 assert_excerpts_match(
2021 &multibuffer,
2022 cx,
2023 indoc! {
2024 "-----
2025 zero
2026 one
2027 two
2028 three
2029 four
2030 five
2031 six
2032 "
2033 },
2034 );
2035
2036 multibuffer.update(cx, |multibuffer, cx| {
2037 multibuffer.set_excerpts_for_path(
2038 path.clone(),
2039 buf2.clone(),
2040 vec![Point::row_range(0..1)],
2041 2,
2042 cx,
2043 );
2044 });
2045
2046 assert_excerpts_match(
2047 &multibuffer,
2048 cx,
2049 indoc! {"-----
2050 000
2051 111
2052 222
2053 333
2054 "},
2055 );
2056}
2057
2058#[gpui::test]
2059async fn test_diff_hunks_with_multiple_excerpts(cx: &mut TestAppContext) {
2060 let base_text_1 = indoc!(
2061 "
2062 one
2063 two
2064 three
2065 four
2066 five
2067 six
2068 "
2069 );
2070 let text_1 = indoc!(
2071 "
2072 ZERO
2073 one
2074 TWO
2075 three
2076 six
2077 "
2078 );
2079 let base_text_2 = indoc!(
2080 "
2081 seven
2082 eight
2083 nine
2084 ten
2085 eleven
2086 twelve
2087 "
2088 );
2089 let text_2 = indoc!(
2090 "
2091 eight
2092 nine
2093 eleven
2094 THIRTEEN
2095 FOURTEEN
2096 "
2097 );
2098
2099 let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
2100 let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
2101 let diff_1 = cx.new(|cx| {
2102 BufferDiff::new_with_base_text(base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
2103 });
2104 let diff_2 = cx.new(|cx| {
2105 BufferDiff::new_with_base_text(base_text_2, &buffer_2.read(cx).text_snapshot(), cx)
2106 });
2107 cx.run_until_parked();
2108
2109 let multibuffer = cx.new(|cx| {
2110 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
2111 multibuffer.push_excerpts(
2112 buffer_1.clone(),
2113 [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
2114 cx,
2115 );
2116 multibuffer.push_excerpts(
2117 buffer_2.clone(),
2118 [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
2119 cx,
2120 );
2121 multibuffer.add_diff(diff_1.clone(), cx);
2122 multibuffer.add_diff(diff_2.clone(), cx);
2123 multibuffer
2124 });
2125
2126 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
2127 (multibuffer.snapshot(cx), multibuffer.subscribe())
2128 });
2129 assert_eq!(
2130 snapshot.text(),
2131 indoc!(
2132 "
2133 ZERO
2134 one
2135 TWO
2136 three
2137 six
2138
2139 eight
2140 nine
2141 eleven
2142 THIRTEEN
2143 FOURTEEN
2144 "
2145 ),
2146 );
2147
2148 multibuffer.update(cx, |multibuffer, cx| {
2149 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
2150 });
2151
2152 assert_new_snapshot(
2153 &multibuffer,
2154 &mut snapshot,
2155 &mut subscription,
2156 cx,
2157 indoc!(
2158 "
2159 + ZERO
2160 one
2161 - two
2162 + TWO
2163 three
2164 - four
2165 - five
2166 six
2167
2168 - seven
2169 eight
2170 nine
2171 - ten
2172 eleven
2173 - twelve
2174 + THIRTEEN
2175 + FOURTEEN
2176 "
2177 ),
2178 );
2179
2180 let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
2181 let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
2182 let base_id_1 = diff_1.read_with(cx, |diff, cx| diff.base_text(cx).remote_id());
2183 let base_id_2 = diff_2.read_with(cx, |diff, cx| diff.base_text(cx).remote_id());
2184
2185 let buffer_lines = (0..=snapshot.max_row().0)
2186 .map(|row| {
2187 let (buffer, range) = snapshot.buffer_line_for_row(MultiBufferRow(row))?;
2188 Some((
2189 buffer.remote_id(),
2190 buffer.text_for_range(range).collect::<String>(),
2191 ))
2192 })
2193 .collect::<Vec<_>>();
2194 pretty_assertions::assert_eq!(
2195 buffer_lines,
2196 [
2197 Some((id_1, "ZERO".into())),
2198 Some((id_1, "one".into())),
2199 Some((base_id_1, "two".into())),
2200 Some((id_1, "TWO".into())),
2201 Some((id_1, " three".into())),
2202 Some((base_id_1, "four".into())),
2203 Some((base_id_1, "five".into())),
2204 Some((id_1, "six".into())),
2205 Some((id_1, "".into())),
2206 Some((base_id_2, "seven".into())),
2207 Some((id_2, " eight".into())),
2208 Some((id_2, "nine".into())),
2209 Some((base_id_2, "ten".into())),
2210 Some((id_2, "eleven".into())),
2211 Some((base_id_2, "twelve".into())),
2212 Some((id_2, "THIRTEEN".into())),
2213 Some((id_2, "FOURTEEN".into())),
2214 Some((id_2, "".into())),
2215 ]
2216 );
2217
2218 let buffer_ids_by_range = [
2219 (Point::new(0, 0)..Point::new(0, 0), &[id_1] as &[_]),
2220 (Point::new(0, 0)..Point::new(2, 0), &[id_1]),
2221 (Point::new(2, 0)..Point::new(2, 0), &[id_1]),
2222 (Point::new(3, 0)..Point::new(3, 0), &[id_1]),
2223 (Point::new(8, 0)..Point::new(9, 0), &[id_1]),
2224 (Point::new(8, 0)..Point::new(10, 0), &[id_1, id_2]),
2225 (Point::new(9, 0)..Point::new(9, 0), &[id_2]),
2226 ];
2227 for (range, buffer_ids) in buffer_ids_by_range {
2228 assert_eq!(
2229 snapshot
2230 .buffer_ids_for_range(range.clone())
2231 .collect::<Vec<_>>(),
2232 buffer_ids,
2233 "buffer_ids_for_range({range:?}"
2234 );
2235 }
2236
2237 assert_position_translation(&snapshot);
2238 assert_line_indents(&snapshot);
2239
2240 assert_eq!(
2241 snapshot
2242 .diff_hunks_in_range(MultiBufferOffset(0)..snapshot.len())
2243 .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
2244 .collect::<Vec<_>>(),
2245 &[0..1, 2..4, 5..7, 9..10, 12..13, 14..17]
2246 );
2247
2248 buffer_2.update(cx, |buffer, cx| {
2249 buffer.edit_via_marked_text(
2250 indoc!(
2251 "
2252 eight
2253 «»eleven
2254 THIRTEEN
2255 FOURTEEN
2256 "
2257 ),
2258 None,
2259 cx,
2260 );
2261 });
2262
2263 assert_new_snapshot(
2264 &multibuffer,
2265 &mut snapshot,
2266 &mut subscription,
2267 cx,
2268 indoc!(
2269 "
2270 + ZERO
2271 one
2272 - two
2273 + TWO
2274 three
2275 - four
2276 - five
2277 six
2278
2279 - seven
2280 eight
2281 eleven
2282 - twelve
2283 + THIRTEEN
2284 + FOURTEEN
2285 "
2286 ),
2287 );
2288
2289 assert_line_indents(&snapshot);
2290}
2291
2292/// A naive implementation of a multi-buffer that does not maintain
2293/// any derived state, used for comparison in a randomized test.
2294#[derive(Default)]
2295struct ReferenceMultibuffer {
2296 excerpts: Vec<ReferenceExcerpt>,
2297 diffs: HashMap<BufferId, Entity<BufferDiff>>,
2298}
2299
2300#[derive(Debug)]
2301struct ReferenceExcerpt {
2302 id: ExcerptId,
2303 buffer: Entity<Buffer>,
2304 range: Range<text::Anchor>,
2305 expanded_diff_hunks: Vec<text::Anchor>,
2306}
2307
2308#[derive(Debug)]
2309struct ReferenceRegion {
2310 buffer_id: Option<BufferId>,
2311 range: Range<usize>,
2312 buffer_range: Option<Range<Point>>,
2313 status: Option<DiffHunkStatus>,
2314 excerpt_id: Option<ExcerptId>,
2315}
2316
2317impl ReferenceMultibuffer {
2318 fn expand_excerpts(&mut self, excerpts: &HashSet<ExcerptId>, line_count: u32, cx: &App) {
2319 if line_count == 0 {
2320 return;
2321 }
2322
2323 for id in excerpts {
2324 let excerpt = self.excerpts.iter_mut().find(|e| e.id == *id).unwrap();
2325 let snapshot = excerpt.buffer.read(cx).snapshot();
2326 let mut point_range = excerpt.range.to_point(&snapshot);
2327 point_range.start = Point::new(point_range.start.row.saturating_sub(line_count), 0);
2328 point_range.end =
2329 snapshot.clip_point(Point::new(point_range.end.row + line_count, 0), Bias::Left);
2330 point_range.end.column = snapshot.line_len(point_range.end.row);
2331 excerpt.range =
2332 snapshot.anchor_before(point_range.start)..snapshot.anchor_after(point_range.end);
2333 }
2334 }
2335
2336 fn remove_excerpt(&mut self, id: ExcerptId, cx: &App) {
2337 let ix = self
2338 .excerpts
2339 .iter()
2340 .position(|excerpt| excerpt.id == id)
2341 .unwrap();
2342 let excerpt = self.excerpts.remove(ix);
2343 let buffer = excerpt.buffer.read(cx);
2344 let id = buffer.remote_id();
2345 log::info!(
2346 "Removing excerpt {}: {:?}",
2347 ix,
2348 buffer
2349 .text_for_range(excerpt.range.to_offset(buffer))
2350 .collect::<String>(),
2351 );
2352 if !self
2353 .excerpts
2354 .iter()
2355 .any(|excerpt| excerpt.buffer.read(cx).remote_id() == id)
2356 {
2357 self.diffs.remove(&id);
2358 }
2359 }
2360
2361 fn insert_excerpt_after(
2362 &mut self,
2363 prev_id: ExcerptId,
2364 new_excerpt_id: ExcerptId,
2365 (buffer_handle, anchor_range): (Entity<Buffer>, Range<text::Anchor>),
2366 ) {
2367 let excerpt_ix = if prev_id == ExcerptId::max() {
2368 self.excerpts.len()
2369 } else {
2370 self.excerpts
2371 .iter()
2372 .position(|excerpt| excerpt.id == prev_id)
2373 .unwrap()
2374 + 1
2375 };
2376 self.excerpts.insert(
2377 excerpt_ix,
2378 ReferenceExcerpt {
2379 id: new_excerpt_id,
2380 buffer: buffer_handle,
2381 range: anchor_range,
2382 expanded_diff_hunks: Vec::new(),
2383 },
2384 );
2385 }
2386
2387 fn expand_diff_hunks(&mut self, excerpt_id: ExcerptId, range: Range<text::Anchor>, cx: &App) {
2388 let excerpt = self
2389 .excerpts
2390 .iter_mut()
2391 .find(|e| e.id == excerpt_id)
2392 .unwrap();
2393 let buffer = excerpt.buffer.read(cx).snapshot();
2394 let buffer_id = buffer.remote_id();
2395 let Some(diff) = self.diffs.get(&buffer_id) else {
2396 return;
2397 };
2398 let excerpt_range = excerpt.range.to_offset(&buffer);
2399 for hunk in diff
2400 .read(cx)
2401 .snapshot(cx)
2402 .hunks_intersecting_range(range, &buffer)
2403 {
2404 let hunk_range = hunk.buffer_range.to_offset(&buffer);
2405 if hunk_range.start < excerpt_range.start || hunk_range.start > excerpt_range.end {
2406 continue;
2407 }
2408 if let Err(ix) = excerpt
2409 .expanded_diff_hunks
2410 .binary_search_by(|anchor| anchor.cmp(&hunk.buffer_range.start, &buffer))
2411 {
2412 log::info!(
2413 "expanding diff hunk {:?}. excerpt:{:?}, excerpt range:{:?}",
2414 hunk_range,
2415 excerpt_id,
2416 excerpt_range
2417 );
2418 excerpt
2419 .expanded_diff_hunks
2420 .insert(ix, hunk.buffer_range.start);
2421 } else {
2422 log::trace!("hunk {hunk_range:?} already expanded in excerpt {excerpt_id:?}");
2423 }
2424 }
2425 }
2426
2427 fn expected_content(&self, cx: &App) -> (String, Vec<RowInfo>, HashSet<MultiBufferRow>) {
2428 let mut text = String::new();
2429 let mut regions = Vec::<ReferenceRegion>::new();
2430 let mut excerpt_boundary_rows = HashSet::default();
2431 for excerpt in &self.excerpts {
2432 excerpt_boundary_rows.insert(MultiBufferRow(text.matches('\n').count() as u32));
2433 let buffer = excerpt.buffer.read(cx);
2434 let buffer_range = excerpt.range.to_offset(buffer);
2435 let diff = self
2436 .diffs
2437 .get(&buffer.remote_id())
2438 .unwrap()
2439 .read(cx)
2440 .snapshot(cx);
2441 let base_buffer = diff.base_text();
2442
2443 let mut offset = buffer_range.start;
2444 let hunks = diff
2445 .hunks_intersecting_range(excerpt.range.clone(), buffer)
2446 .peekable();
2447
2448 for hunk in hunks {
2449 // Ignore hunks that are outside the excerpt range.
2450 let mut hunk_range = hunk.buffer_range.to_offset(buffer);
2451
2452 hunk_range.end = hunk_range.end.min(buffer_range.end);
2453 if hunk_range.start > buffer_range.end || hunk_range.start < buffer_range.start {
2454 log::trace!("skipping hunk outside excerpt range");
2455 continue;
2456 }
2457
2458 if !excerpt.expanded_diff_hunks.iter().any(|expanded_anchor| {
2459 expanded_anchor.to_offset(buffer).max(buffer_range.start)
2460 == hunk_range.start.max(buffer_range.start)
2461 }) {
2462 log::trace!("skipping a hunk that's not marked as expanded");
2463 continue;
2464 }
2465
2466 if !hunk.buffer_range.start.is_valid(buffer) {
2467 log::trace!("skipping hunk with deleted start: {:?}", hunk.range);
2468 continue;
2469 }
2470
2471 if hunk_range.start >= offset {
2472 // Add the buffer text before the hunk
2473 let len = text.len();
2474 text.extend(buffer.text_for_range(offset..hunk_range.start));
2475 if text.len() > len {
2476 regions.push(ReferenceRegion {
2477 buffer_id: Some(buffer.remote_id()),
2478 range: len..text.len(),
2479 buffer_range: Some((offset..hunk_range.start).to_point(&buffer)),
2480 status: None,
2481 excerpt_id: Some(excerpt.id),
2482 });
2483 }
2484
2485 // Add the deleted text for the hunk.
2486 if !hunk.diff_base_byte_range.is_empty() {
2487 let mut base_text = base_buffer
2488 .text_for_range(hunk.diff_base_byte_range.clone())
2489 .collect::<String>();
2490 if !base_text.ends_with('\n') {
2491 base_text.push('\n');
2492 }
2493 let len = text.len();
2494 text.push_str(&base_text);
2495 regions.push(ReferenceRegion {
2496 buffer_id: Some(base_buffer.remote_id()),
2497 range: len..text.len(),
2498 buffer_range: Some(hunk.diff_base_byte_range.to_point(&base_buffer)),
2499 status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2500 excerpt_id: Some(excerpt.id),
2501 });
2502 }
2503
2504 offset = hunk_range.start;
2505 }
2506
2507 // Add the inserted text for the hunk.
2508 if hunk_range.end > offset {
2509 let len = text.len();
2510 text.extend(buffer.text_for_range(offset..hunk_range.end));
2511 let range = len..text.len();
2512 let region = ReferenceRegion {
2513 buffer_id: Some(buffer.remote_id()),
2514 range,
2515 buffer_range: Some((offset..hunk_range.end).to_point(&buffer)),
2516 status: Some(DiffHunkStatus::added(hunk.secondary_status)),
2517 excerpt_id: Some(excerpt.id),
2518 };
2519 offset = hunk_range.end;
2520 regions.push(region);
2521 }
2522 }
2523
2524 // Add the buffer text for the rest of the excerpt.
2525 let len = text.len();
2526 text.extend(buffer.text_for_range(offset..buffer_range.end));
2527 text.push('\n');
2528 regions.push(ReferenceRegion {
2529 buffer_id: Some(buffer.remote_id()),
2530 range: len..text.len(),
2531 buffer_range: Some((offset..buffer_range.end).to_point(&buffer)),
2532 status: None,
2533 excerpt_id: Some(excerpt.id),
2534 });
2535 }
2536
2537 // Remove final trailing newline.
2538 if self.excerpts.is_empty() {
2539 regions.push(ReferenceRegion {
2540 buffer_id: None,
2541 range: 0..1,
2542 buffer_range: Some(Point::new(0, 0)..Point::new(0, 1)),
2543 status: None,
2544 excerpt_id: None,
2545 });
2546 } else {
2547 text.pop();
2548 }
2549
2550 // Retrieve the row info using the region that contains
2551 // the start of each multi-buffer line.
2552 let mut ix = 0;
2553 let row_infos = text
2554 .split('\n')
2555 .map(|line| {
2556 let row_info = regions
2557 .iter()
2558 .position(|region| region.range.contains(&ix))
2559 .map_or(RowInfo::default(), |region_ix| {
2560 let region = ®ions[region_ix];
2561 let buffer_row = region.buffer_range.as_ref().map(|buffer_range| {
2562 buffer_range.start.row
2563 + text[region.range.start..ix].matches('\n').count() as u32
2564 });
2565 let main_buffer = self
2566 .excerpts
2567 .iter()
2568 .find(|e| e.id == region.excerpt_id.unwrap())
2569 .map(|e| e.buffer.clone());
2570 let is_excerpt_start = region_ix == 0
2571 || ®ions[region_ix - 1].excerpt_id != ®ion.excerpt_id
2572 || regions[region_ix - 1].range.is_empty();
2573 let mut is_excerpt_end = region_ix == regions.len() - 1
2574 || ®ions[region_ix + 1].excerpt_id != ®ion.excerpt_id;
2575 let is_start = !text[region.range.start..ix].contains('\n');
2576 let mut is_end = if region.range.end > text.len() {
2577 !text[ix..].contains('\n')
2578 } else {
2579 text[ix..region.range.end.min(text.len())]
2580 .matches('\n')
2581 .count()
2582 == 1
2583 };
2584 if region_ix < regions.len() - 1
2585 && !text[ix..].contains("\n")
2586 && region.status == Some(DiffHunkStatus::added_none())
2587 && regions[region_ix + 1].excerpt_id == region.excerpt_id
2588 && regions[region_ix + 1].range.start == text.len()
2589 {
2590 is_end = true;
2591 is_excerpt_end = true;
2592 }
2593 let multibuffer_row =
2594 MultiBufferRow(text[..ix].matches('\n').count() as u32);
2595 let mut expand_direction = None;
2596 if let Some(buffer) = &main_buffer {
2597 let buffer_row = buffer_row.unwrap();
2598 let needs_expand_up = is_excerpt_start && is_start && buffer_row > 0;
2599 let needs_expand_down = is_excerpt_end
2600 && is_end
2601 && buffer.read(cx).max_point().row > buffer_row;
2602 expand_direction = if needs_expand_up && needs_expand_down {
2603 Some(ExpandExcerptDirection::UpAndDown)
2604 } else if needs_expand_up {
2605 Some(ExpandExcerptDirection::Up)
2606 } else if needs_expand_down {
2607 Some(ExpandExcerptDirection::Down)
2608 } else {
2609 None
2610 };
2611 }
2612 RowInfo {
2613 buffer_id: region.buffer_id,
2614 diff_status: region.status,
2615 buffer_row,
2616 wrapped_buffer_row: None,
2617
2618 multibuffer_row: Some(multibuffer_row),
2619 expand_info: expand_direction.zip(region.excerpt_id).map(
2620 |(direction, excerpt_id)| ExpandInfo {
2621 direction,
2622 excerpt_id,
2623 },
2624 ),
2625 }
2626 });
2627 ix += line.len() + 1;
2628 row_info
2629 })
2630 .collect();
2631
2632 (text, row_infos, excerpt_boundary_rows)
2633 }
2634
2635 fn diffs_updated(&mut self, cx: &App) {
2636 for excerpt in &mut self.excerpts {
2637 let buffer = excerpt.buffer.read(cx).snapshot();
2638 let excerpt_range = excerpt.range.to_offset(&buffer);
2639 let buffer_id = buffer.remote_id();
2640 let diff = self.diffs.get(&buffer_id).unwrap().read(cx).snapshot(cx);
2641 let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer).peekable();
2642 excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2643 if !hunk_anchor.is_valid(&buffer) {
2644 return false;
2645 }
2646 while let Some(hunk) = hunks.peek() {
2647 match hunk.buffer_range.start.cmp(hunk_anchor, &buffer) {
2648 cmp::Ordering::Less => {
2649 hunks.next();
2650 }
2651 cmp::Ordering::Equal => {
2652 let hunk_range = hunk.buffer_range.to_offset(&buffer);
2653 return hunk_range.end >= excerpt_range.start
2654 && hunk_range.start <= excerpt_range.end;
2655 }
2656 cmp::Ordering::Greater => break,
2657 }
2658 }
2659 false
2660 });
2661 }
2662 }
2663
2664 fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2665 let buffer_id = diff.read(cx).buffer_id;
2666 self.diffs.insert(buffer_id, diff);
2667 }
2668}
2669
2670#[gpui::test(iterations = 100)]
2671async fn test_random_set_ranges(cx: &mut TestAppContext, mut rng: StdRng) {
2672 let base_text = "a\n".repeat(100);
2673 let buf = cx.update(|cx| cx.new(|cx| Buffer::local(base_text, cx)));
2674 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2675
2676 let operations = env::var("OPERATIONS")
2677 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2678 .unwrap_or(10);
2679
2680 fn row_ranges(ranges: &Vec<Range<Point>>) -> Vec<Range<u32>> {
2681 ranges
2682 .iter()
2683 .map(|range| range.start.row..range.end.row)
2684 .collect()
2685 }
2686
2687 for _ in 0..operations {
2688 let snapshot = buf.update(cx, |buf, _| buf.snapshot());
2689 let num_ranges = rng.random_range(0..=10);
2690 let max_row = snapshot.max_point().row;
2691 let mut ranges = (0..num_ranges)
2692 .map(|_| {
2693 let start = rng.random_range(0..max_row);
2694 let end = rng.random_range(start + 1..max_row + 1);
2695 Point::row_range(start..end)
2696 })
2697 .collect::<Vec<_>>();
2698 ranges.sort_by_key(|range| range.start);
2699 log::info!("Setting ranges: {:?}", row_ranges(&ranges));
2700 let (created, _) = multibuffer.update(cx, |multibuffer, cx| {
2701 multibuffer.set_excerpts_for_path(
2702 PathKey::for_buffer(&buf, cx),
2703 buf.clone(),
2704 ranges.clone(),
2705 2,
2706 cx,
2707 )
2708 });
2709
2710 assert_eq!(created.len(), ranges.len());
2711
2712 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2713 let mut last_end = None;
2714 let mut seen_ranges = Vec::default();
2715
2716 for (_, buf, range) in snapshot.excerpts() {
2717 let start = range.context.start.to_point(buf);
2718 let end = range.context.end.to_point(buf);
2719 seen_ranges.push(start..end);
2720
2721 if let Some(last_end) = last_end.take() {
2722 assert!(
2723 start > last_end,
2724 "multibuffer has out-of-order ranges: {:?}; {:?} <= {:?}",
2725 row_ranges(&seen_ranges),
2726 start,
2727 last_end
2728 )
2729 }
2730
2731 ranges.retain(|range| range.start < start || range.end > end);
2732
2733 last_end = Some(end)
2734 }
2735
2736 assert!(
2737 ranges.is_empty(),
2738 "multibuffer {:?} did not include all ranges: {:?}",
2739 row_ranges(&seen_ranges),
2740 row_ranges(&ranges)
2741 );
2742 }
2743}
2744
2745#[gpui::test(iterations = 100)]
2746async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
2747 let operations = env::var("OPERATIONS")
2748 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2749 .unwrap_or(10);
2750 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2751 let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2752 let mut base_texts: HashMap<BufferId, String> = HashMap::default();
2753 let mut reference = ReferenceMultibuffer::default();
2754 let mut anchors = Vec::new();
2755 let mut old_versions = Vec::new();
2756 let mut needs_diff_calculation = false;
2757 for _ in 0..operations {
2758 match rng.random_range(0..100) {
2759 0..=14 if !buffers.is_empty() => {
2760 let buffer = buffers.choose(&mut rng).unwrap();
2761 buffer.update(cx, |buf, cx| {
2762 let edit_count = rng.random_range(1..5);
2763 buf.randomly_edit(&mut rng, edit_count, cx);
2764 log::info!("buffer text:\n{}", buf.text());
2765 needs_diff_calculation = true;
2766 });
2767 cx.update(|cx| reference.diffs_updated(cx));
2768 }
2769 15..=19 if !reference.excerpts.is_empty() => {
2770 multibuffer.update(cx, |multibuffer, cx| {
2771 let ids = multibuffer.excerpt_ids();
2772 let mut excerpts = HashSet::default();
2773 for _ in 0..rng.random_range(0..ids.len()) {
2774 excerpts.extend(ids.choose(&mut rng).copied());
2775 }
2776
2777 let line_count = rng.random_range(0..5);
2778
2779 let excerpt_ixs = excerpts
2780 .iter()
2781 .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2782 .collect::<Vec<_>>();
2783 log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2784 multibuffer.expand_excerpts(
2785 excerpts.iter().cloned(),
2786 line_count,
2787 ExpandExcerptDirection::UpAndDown,
2788 cx,
2789 );
2790
2791 reference.expand_excerpts(&excerpts, line_count, cx);
2792 });
2793 }
2794 20..=29 if !reference.excerpts.is_empty() => {
2795 let mut ids_to_remove = vec![];
2796 for _ in 0..rng.random_range(1..=3) {
2797 let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2798 break;
2799 };
2800 let id = excerpt.id;
2801 cx.update(|cx| reference.remove_excerpt(id, cx));
2802 ids_to_remove.push(id);
2803 }
2804 let snapshot =
2805 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2806 ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2807 drop(snapshot);
2808 multibuffer.update(cx, |multibuffer, cx| {
2809 multibuffer.remove_excerpts(ids_to_remove, cx)
2810 });
2811 }
2812 30..=39 if !reference.excerpts.is_empty() => {
2813 let multibuffer =
2814 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2815 let offset = multibuffer.clip_offset(
2816 MultiBufferOffset(rng.random_range(0..=multibuffer.len().0)),
2817 Bias::Left,
2818 );
2819 let bias = if rng.random() {
2820 Bias::Left
2821 } else {
2822 Bias::Right
2823 };
2824 log::info!("Creating anchor at {} with bias {:?}", offset.0, bias);
2825 anchors.push(multibuffer.anchor_at(offset, bias));
2826 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2827 }
2828 40..=44 if !anchors.is_empty() => {
2829 let multibuffer =
2830 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2831 let prev_len = anchors.len();
2832 anchors = multibuffer
2833 .refresh_anchors(&anchors)
2834 .into_iter()
2835 .map(|a| a.1)
2836 .collect();
2837
2838 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2839 // overshoot its boundaries.
2840 assert_eq!(anchors.len(), prev_len);
2841 for anchor in &anchors {
2842 if anchor.excerpt_id == ExcerptId::min()
2843 || anchor.excerpt_id == ExcerptId::max()
2844 {
2845 continue;
2846 }
2847
2848 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2849 assert_eq!(excerpt.id, anchor.excerpt_id);
2850 assert!(excerpt.contains(anchor));
2851 }
2852 }
2853 45..=55 if !reference.excerpts.is_empty() => {
2854 multibuffer.update(cx, |multibuffer, cx| {
2855 let snapshot = multibuffer.snapshot(cx);
2856 let excerpt_ix = rng.random_range(0..reference.excerpts.len());
2857 let excerpt = &reference.excerpts[excerpt_ix];
2858 let start = excerpt.range.start;
2859 let end = excerpt.range.end;
2860 let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2861 ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2862
2863 log::info!(
2864 "expanding diff hunks in range {:?} (excerpt id {:?}, index {excerpt_ix:?}, buffer id {:?})",
2865 range.to_offset(&snapshot),
2866 excerpt.id,
2867 excerpt.buffer.read(cx).remote_id(),
2868 );
2869 reference.expand_diff_hunks(excerpt.id, start..end, cx);
2870 multibuffer.expand_diff_hunks(vec![range], cx);
2871 });
2872 }
2873 56..=85 if needs_diff_calculation => {
2874 multibuffer.update(cx, |multibuffer, cx| {
2875 for buffer in multibuffer.all_buffers() {
2876 let snapshot = buffer.read(cx).snapshot();
2877 multibuffer.diff_for(snapshot.remote_id()).unwrap().update(
2878 cx,
2879 |diff, cx| {
2880 log::info!(
2881 "recalculating diff for buffer {:?}",
2882 snapshot.remote_id(),
2883 );
2884 diff.recalculate_diff_sync(&snapshot.text, cx);
2885 },
2886 );
2887 }
2888 reference.diffs_updated(cx);
2889 needs_diff_calculation = false;
2890 });
2891 }
2892 _ => {
2893 let buffer_handle = if buffers.is_empty() || rng.random_bool(0.4) {
2894 let mut base_text = util::RandomCharIter::new(&mut rng)
2895 .take(256)
2896 .collect::<String>();
2897
2898 let buffer = cx.new(|cx| Buffer::local(base_text.clone(), cx));
2899 text::LineEnding::normalize(&mut base_text);
2900 base_texts.insert(
2901 buffer.read_with(cx, |buffer, _| buffer.remote_id()),
2902 base_text,
2903 );
2904 buffers.push(buffer);
2905 buffers.last().unwrap()
2906 } else {
2907 buffers.choose(&mut rng).unwrap()
2908 };
2909
2910 let prev_excerpt_ix = rng.random_range(0..=reference.excerpts.len());
2911 let prev_excerpt_id = reference
2912 .excerpts
2913 .get(prev_excerpt_ix)
2914 .map_or(ExcerptId::max(), |e| e.id);
2915 let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
2916
2917 let (range, anchor_range) = buffer_handle.read_with(cx, |buffer, _| {
2918 let end_row = rng.random_range(0..=buffer.max_point().row);
2919 let start_row = rng.random_range(0..=end_row);
2920 let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
2921 let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
2922 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2923
2924 log::info!(
2925 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2926 excerpt_ix,
2927 reference.excerpts.len(),
2928 buffer.remote_id(),
2929 buffer.text(),
2930 start_ix..end_ix,
2931 &buffer.text()[start_ix..end_ix]
2932 );
2933
2934 (start_ix..end_ix, anchor_range)
2935 });
2936
2937 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
2938 multibuffer
2939 .insert_excerpts_after(
2940 prev_excerpt_id,
2941 buffer_handle.clone(),
2942 [ExcerptRange::new(range.clone())],
2943 cx,
2944 )
2945 .pop()
2946 .unwrap()
2947 });
2948
2949 reference.insert_excerpt_after(
2950 prev_excerpt_id,
2951 excerpt_id,
2952 (buffer_handle.clone(), anchor_range),
2953 );
2954
2955 multibuffer.update(cx, |multibuffer, cx| {
2956 let id = buffer_handle.read(cx).remote_id();
2957 if multibuffer.diff_for(id).is_none() {
2958 let base_text = base_texts.get(&id).unwrap();
2959 let diff = cx.new(|cx| {
2960 BufferDiff::new_with_base_text(
2961 base_text,
2962 &buffer_handle.read(cx).text_snapshot(),
2963 cx,
2964 )
2965 });
2966 reference.add_diff(diff.clone(), cx);
2967 multibuffer.add_diff(diff, cx)
2968 }
2969 });
2970 }
2971 }
2972
2973 if rng.random_bool(0.3) {
2974 multibuffer.update(cx, |multibuffer, cx| {
2975 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
2976 })
2977 }
2978
2979 multibuffer.read_with(cx, |multibuffer, cx| {
2980 check_multibuffer(multibuffer, &reference, &anchors, cx, &mut rng);
2981 });
2982 }
2983 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2984 for (old_snapshot, subscription) in old_versions {
2985 check_multibuffer_edits(&snapshot, &old_snapshot, subscription);
2986 }
2987}
2988
2989fn check_multibuffer(
2990 multibuffer: &MultiBuffer,
2991 reference: &ReferenceMultibuffer,
2992 anchors: &[Anchor],
2993 cx: &App,
2994 rng: &mut StdRng,
2995) {
2996 let snapshot = multibuffer.snapshot(cx);
2997 let actual_text = snapshot.text();
2998 let actual_boundary_rows = snapshot
2999 .excerpt_boundaries_in_range(MultiBufferOffset(0)..)
3000 .map(|b| b.row)
3001 .collect::<HashSet<_>>();
3002 let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3003
3004 let (expected_text, expected_row_infos, expected_boundary_rows) =
3005 reference.expected_content(cx);
3006
3007 let has_diff = actual_row_infos
3008 .iter()
3009 .any(|info| info.diff_status.is_some())
3010 || expected_row_infos
3011 .iter()
3012 .any(|info| info.diff_status.is_some());
3013 let actual_diff = format_diff(
3014 &actual_text,
3015 &actual_row_infos,
3016 &actual_boundary_rows,
3017 Some(has_diff),
3018 );
3019 let expected_diff = format_diff(
3020 &expected_text,
3021 &expected_row_infos,
3022 &expected_boundary_rows,
3023 Some(has_diff),
3024 );
3025
3026 log::info!("Multibuffer content:\n{}", actual_diff);
3027
3028 assert_eq!(
3029 actual_row_infos.len(),
3030 actual_text.split('\n').count(),
3031 "line count: {}",
3032 actual_text.split('\n').count()
3033 );
3034 pretty_assertions::assert_eq!(actual_diff, expected_diff);
3035 pretty_assertions::assert_eq!(actual_text, expected_text);
3036 pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
3037
3038 for _ in 0..5 {
3039 let start_row = rng.random_range(0..=expected_row_infos.len());
3040 assert_eq!(
3041 snapshot
3042 .row_infos(MultiBufferRow(start_row as u32))
3043 .collect::<Vec<_>>(),
3044 &expected_row_infos[start_row..],
3045 "buffer_rows({})",
3046 start_row
3047 );
3048 }
3049
3050 assert_eq!(
3051 snapshot.widest_line_number(),
3052 expected_row_infos
3053 .into_iter()
3054 .filter_map(|info| {
3055 if info.diff_status.is_some_and(|status| status.is_deleted()) {
3056 None
3057 } else {
3058 info.buffer_row
3059 }
3060 })
3061 .max()
3062 .unwrap()
3063 + 1
3064 );
3065 let reference_ranges = reference
3066 .excerpts
3067 .iter()
3068 .map(|excerpt| {
3069 (
3070 excerpt.id,
3071 excerpt.range.to_offset(&excerpt.buffer.read(cx).snapshot()),
3072 )
3073 })
3074 .collect::<HashMap<_, _>>();
3075 for i in 0..snapshot.len().0 {
3076 let excerpt = snapshot
3077 .excerpt_containing(MultiBufferOffset(i)..MultiBufferOffset(i))
3078 .unwrap();
3079 assert_eq!(
3080 excerpt.buffer_range().start.0..excerpt.buffer_range().end.0,
3081 reference_ranges[&excerpt.id()]
3082 );
3083 }
3084
3085 assert_consistent_line_numbers(&snapshot);
3086 assert_position_translation(&snapshot);
3087
3088 for (row, line) in expected_text.split('\n').enumerate() {
3089 assert_eq!(
3090 snapshot.line_len(MultiBufferRow(row as u32)),
3091 line.len() as u32,
3092 "line_len({}).",
3093 row
3094 );
3095 }
3096
3097 let text_rope = Rope::from(expected_text.as_str());
3098 for _ in 0..10 {
3099 let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
3100 let start_ix = text_rope.clip_offset(rng.random_range(0..=end_ix), Bias::Left);
3101
3102 let text_for_range = snapshot
3103 .text_for_range(MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix))
3104 .collect::<String>();
3105 assert_eq!(
3106 text_for_range,
3107 &expected_text[start_ix..end_ix],
3108 "incorrect text for range {:?}",
3109 start_ix..end_ix
3110 );
3111
3112 let expected_summary =
3113 MBTextSummary::from(TextSummary::from(&expected_text[start_ix..end_ix]));
3114 assert_eq!(
3115 snapshot.text_summary_for_range::<MBTextSummary, _>(
3116 MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix)
3117 ),
3118 expected_summary,
3119 "incorrect summary for range {:?}",
3120 start_ix..end_ix
3121 );
3122 }
3123
3124 // Anchor resolution
3125 let summaries = snapshot.summaries_for_anchors::<MultiBufferOffset, _>(anchors);
3126 assert_eq!(anchors.len(), summaries.len());
3127 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
3128 assert!(resolved_offset <= snapshot.len());
3129 assert_eq!(
3130 snapshot.summary_for_anchor::<MultiBufferOffset>(anchor),
3131 resolved_offset,
3132 "anchor: {:?}",
3133 anchor
3134 );
3135 }
3136
3137 for _ in 0..10 {
3138 let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
3139 assert_eq!(
3140 snapshot
3141 .reversed_chars_at(MultiBufferOffset(end_ix))
3142 .collect::<String>(),
3143 expected_text[..end_ix].chars().rev().collect::<String>(),
3144 );
3145 }
3146
3147 for _ in 0..10 {
3148 let end_ix = rng.random_range(0..=text_rope.len());
3149 let end_ix = text_rope.floor_char_boundary(end_ix);
3150 let start_ix = rng.random_range(0..=end_ix);
3151 let start_ix = text_rope.floor_char_boundary(start_ix);
3152 assert_eq!(
3153 snapshot
3154 .bytes_in_range(MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix))
3155 .flatten()
3156 .copied()
3157 .collect::<Vec<_>>(),
3158 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3159 "bytes_in_range({:?})",
3160 start_ix..end_ix,
3161 );
3162 }
3163}
3164
3165fn check_multibuffer_edits(
3166 snapshot: &MultiBufferSnapshot,
3167 old_snapshot: &MultiBufferSnapshot,
3168 subscription: Subscription<MultiBufferOffset>,
3169) {
3170 let edits = subscription.consume().into_inner();
3171
3172 log::info!(
3173 "applying subscription edits to old text: {:?}: {:#?}",
3174 old_snapshot.text(),
3175 edits,
3176 );
3177
3178 let mut text = old_snapshot.text();
3179 for edit in edits {
3180 let new_text: String = snapshot
3181 .text_for_range(edit.new.start..edit.new.end)
3182 .collect();
3183 text.replace_range(
3184 (edit.new.start.0..edit.new.start.0 + (edit.old.end.0 - edit.old.start.0)).clone(),
3185 &new_text,
3186 );
3187 pretty_assertions::assert_eq!(
3188 &text[0..edit.new.end.0],
3189 snapshot
3190 .text_for_range(MultiBufferOffset(0)..edit.new.end)
3191 .collect::<String>()
3192 );
3193 }
3194 pretty_assertions::assert_eq!(text, snapshot.text());
3195}
3196
3197#[gpui::test]
3198fn test_history(cx: &mut App) {
3199 let test_settings = SettingsStore::test(cx);
3200 cx.set_global(test_settings);
3201
3202 let group_interval: Duration = Duration::from_millis(1);
3203 let buffer_1 = cx.new(|cx| {
3204 let mut buf = Buffer::local("1234", cx);
3205 buf.set_group_interval(group_interval);
3206 buf
3207 });
3208 let buffer_2 = cx.new(|cx| {
3209 let mut buf = Buffer::local("5678", cx);
3210 buf.set_group_interval(group_interval);
3211 buf
3212 });
3213 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
3214 multibuffer.update(cx, |this, _| {
3215 this.set_group_interval(group_interval);
3216 });
3217 multibuffer.update(cx, |multibuffer, cx| {
3218 multibuffer.push_excerpts(
3219 buffer_1.clone(),
3220 [ExcerptRange::new(0..buffer_1.read(cx).len())],
3221 cx,
3222 );
3223 multibuffer.push_excerpts(
3224 buffer_2.clone(),
3225 [ExcerptRange::new(0..buffer_2.read(cx).len())],
3226 cx,
3227 );
3228 });
3229
3230 let mut now = Instant::now();
3231
3232 multibuffer.update(cx, |multibuffer, cx| {
3233 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
3234 multibuffer.edit(
3235 [
3236 (Point::new(0, 0)..Point::new(0, 0), "A"),
3237 (Point::new(1, 0)..Point::new(1, 0), "A"),
3238 ],
3239 None,
3240 cx,
3241 );
3242 multibuffer.edit(
3243 [
3244 (Point::new(0, 1)..Point::new(0, 1), "B"),
3245 (Point::new(1, 1)..Point::new(1, 1), "B"),
3246 ],
3247 None,
3248 cx,
3249 );
3250 multibuffer.end_transaction_at(now, cx);
3251 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3252
3253 // Verify edited ranges for transaction 1
3254 assert_eq!(
3255 multibuffer.edited_ranges_for_transaction(transaction_1, cx),
3256 &[
3257 Point::new(0, 0)..Point::new(0, 2),
3258 Point::new(1, 0)..Point::new(1, 2)
3259 ]
3260 );
3261
3262 // Edit buffer 1 through the multibuffer
3263 now += 2 * group_interval;
3264 multibuffer.start_transaction_at(now, cx);
3265 multibuffer.edit(
3266 [(MultiBufferOffset(2)..MultiBufferOffset(2), "C")],
3267 None,
3268 cx,
3269 );
3270 multibuffer.end_transaction_at(now, cx);
3271 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3272
3273 // Edit buffer 1 independently
3274 buffer_1.update(cx, |buffer_1, cx| {
3275 buffer_1.start_transaction_at(now);
3276 buffer_1.edit([(3..3, "D")], None, cx);
3277 buffer_1.end_transaction_at(now, cx);
3278
3279 now += 2 * group_interval;
3280 buffer_1.start_transaction_at(now);
3281 buffer_1.edit([(4..4, "E")], None, cx);
3282 buffer_1.end_transaction_at(now, cx);
3283 });
3284 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3285
3286 // An undo in the multibuffer undoes the multibuffer transaction
3287 // and also any individual buffer edits that have occurred since
3288 // that transaction.
3289 multibuffer.undo(cx);
3290 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3291
3292 multibuffer.undo(cx);
3293 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3294
3295 multibuffer.redo(cx);
3296 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3297
3298 multibuffer.redo(cx);
3299 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3300
3301 // Undo buffer 2 independently.
3302 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
3303 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
3304
3305 // An undo in the multibuffer undoes the components of the
3306 // the last multibuffer transaction that are not already undone.
3307 multibuffer.undo(cx);
3308 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
3309
3310 multibuffer.undo(cx);
3311 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3312
3313 multibuffer.redo(cx);
3314 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3315
3316 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3317 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3318
3319 // Redo stack gets cleared after an edit.
3320 now += 2 * group_interval;
3321 multibuffer.start_transaction_at(now, cx);
3322 multibuffer.edit(
3323 [(MultiBufferOffset(0)..MultiBufferOffset(0), "X")],
3324 None,
3325 cx,
3326 );
3327 multibuffer.end_transaction_at(now, cx);
3328 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3329 multibuffer.redo(cx);
3330 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3331 multibuffer.undo(cx);
3332 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3333 multibuffer.undo(cx);
3334 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3335
3336 // Transactions can be grouped manually.
3337 multibuffer.redo(cx);
3338 multibuffer.redo(cx);
3339 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3340 multibuffer.group_until_transaction(transaction_1, cx);
3341 multibuffer.undo(cx);
3342 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3343 multibuffer.redo(cx);
3344 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3345 });
3346}
3347
3348#[gpui::test]
3349async fn test_enclosing_indent(cx: &mut TestAppContext) {
3350 async fn enclosing_indent(
3351 text: &str,
3352 buffer_row: u32,
3353 cx: &mut TestAppContext,
3354 ) -> Option<(Range<u32>, LineIndent)> {
3355 let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
3356 let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
3357 let (range, indent) = snapshot
3358 .enclosing_indent(MultiBufferRow(buffer_row))
3359 .await?;
3360 Some((range.start.0..range.end.0, indent))
3361 }
3362
3363 assert_eq!(
3364 enclosing_indent(
3365 indoc!(
3366 "
3367 fn b() {
3368 if c {
3369 let d = 2;
3370 }
3371 }
3372 "
3373 ),
3374 1,
3375 cx,
3376 )
3377 .await,
3378 Some((
3379 1..2,
3380 LineIndent {
3381 tabs: 0,
3382 spaces: 4,
3383 line_blank: false,
3384 }
3385 ))
3386 );
3387
3388 assert_eq!(
3389 enclosing_indent(
3390 indoc!(
3391 "
3392 fn b() {
3393 if c {
3394 let d = 2;
3395 }
3396 }
3397 "
3398 ),
3399 2,
3400 cx,
3401 )
3402 .await,
3403 Some((
3404 1..2,
3405 LineIndent {
3406 tabs: 0,
3407 spaces: 4,
3408 line_blank: false,
3409 }
3410 ))
3411 );
3412
3413 assert_eq!(
3414 enclosing_indent(
3415 indoc!(
3416 "
3417 fn b() {
3418 if c {
3419 let d = 2;
3420
3421 let e = 5;
3422 }
3423 }
3424 "
3425 ),
3426 3,
3427 cx,
3428 )
3429 .await,
3430 Some((
3431 1..4,
3432 LineIndent {
3433 tabs: 0,
3434 spaces: 4,
3435 line_blank: false,
3436 }
3437 ))
3438 );
3439}
3440
3441#[gpui::test]
3442async fn test_summaries_for_anchors(cx: &mut TestAppContext) {
3443 let base_text_1 = indoc!(
3444 "
3445 bar
3446 "
3447 );
3448 let text_1 = indoc!(
3449 "
3450 BAR
3451 "
3452 );
3453 let base_text_2 = indoc!(
3454 "
3455 foo
3456 "
3457 );
3458 let text_2 = indoc!(
3459 "
3460 FOO
3461 "
3462 );
3463
3464 let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3465 let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
3466 let diff_1 = cx.new(|cx| {
3467 BufferDiff::new_with_base_text(base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
3468 });
3469 let diff_2 = cx.new(|cx| {
3470 BufferDiff::new_with_base_text(base_text_2, &buffer_2.read(cx).text_snapshot(), cx)
3471 });
3472 cx.run_until_parked();
3473
3474 let mut ids = vec![];
3475 let multibuffer = cx.new(|cx| {
3476 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3477 multibuffer.set_all_diff_hunks_expanded(cx);
3478 ids.extend(multibuffer.push_excerpts(
3479 buffer_1.clone(),
3480 [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3481 cx,
3482 ));
3483 ids.extend(multibuffer.push_excerpts(
3484 buffer_2.clone(),
3485 [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3486 cx,
3487 ));
3488 multibuffer.add_diff(diff_1.clone(), cx);
3489 multibuffer.add_diff(diff_2.clone(), cx);
3490 multibuffer
3491 });
3492
3493 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3494 (multibuffer.snapshot(cx), multibuffer.subscribe())
3495 });
3496
3497 assert_new_snapshot(
3498 &multibuffer,
3499 &mut snapshot,
3500 &mut subscription,
3501 cx,
3502 indoc!(
3503 "
3504 - bar
3505 + BAR
3506
3507 - foo
3508 + FOO
3509 "
3510 ),
3511 );
3512
3513 let anchor_1 = Anchor::in_buffer(ids[0], text::Anchor::MIN);
3514 let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3515 assert_eq!(point_1, Point::new(0, 0));
3516
3517 let anchor_2 = Anchor::in_buffer(ids[1], text::Anchor::MIN);
3518 let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3519 assert_eq!(point_2, Point::new(3, 0));
3520}
3521
3522#[gpui::test]
3523async fn test_trailing_deletion_without_newline(cx: &mut TestAppContext) {
3524 let base_text_1 = "one\ntwo".to_owned();
3525 let text_1 = "one\n".to_owned();
3526
3527 let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3528 let diff_1 = cx.new(|cx| {
3529 BufferDiff::new_with_base_text(&base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
3530 });
3531 cx.run_until_parked();
3532
3533 let multibuffer = cx.new(|cx| {
3534 let mut multibuffer = MultiBuffer::singleton(buffer_1.clone(), cx);
3535 multibuffer.add_diff(diff_1.clone(), cx);
3536 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
3537 multibuffer
3538 });
3539
3540 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3541 (multibuffer.snapshot(cx), multibuffer.subscribe())
3542 });
3543
3544 assert_new_snapshot(
3545 &multibuffer,
3546 &mut snapshot,
3547 &mut subscription,
3548 cx,
3549 indoc!(
3550 "
3551 one
3552 - two
3553 "
3554 ),
3555 );
3556
3557 assert_eq!(snapshot.max_point(), Point::new(2, 0));
3558 assert_eq!(snapshot.len().0, 8);
3559
3560 assert_eq!(
3561 snapshot
3562 .dimensions_from_points::<Point>([Point::new(2, 0)])
3563 .collect::<Vec<_>>(),
3564 vec![Point::new(2, 0)]
3565 );
3566
3567 let (_, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3568 assert_eq!(translated_offset.0, "one\n".len());
3569 let (_, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3570 assert_eq!(translated_point, Point::new(1, 0));
3571
3572 // The same, for an excerpt that's not at the end of the multibuffer.
3573
3574 let text_2 = "foo\n".to_owned();
3575 let buffer_2 = cx.new(|cx| Buffer::local(&text_2, cx));
3576 multibuffer.update(cx, |multibuffer, cx| {
3577 multibuffer.push_excerpts(
3578 buffer_2.clone(),
3579 [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
3580 cx,
3581 );
3582 });
3583
3584 assert_new_snapshot(
3585 &multibuffer,
3586 &mut snapshot,
3587 &mut subscription,
3588 cx,
3589 indoc!(
3590 "
3591 one
3592 - two
3593
3594 foo
3595 "
3596 ),
3597 );
3598
3599 assert_eq!(
3600 snapshot
3601 .dimensions_from_points::<Point>([Point::new(2, 0)])
3602 .collect::<Vec<_>>(),
3603 vec![Point::new(2, 0)]
3604 );
3605
3606 let buffer_1_id = buffer_1.read_with(cx, |buffer_1, _| buffer_1.remote_id());
3607 let (buffer, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3608 assert_eq!(buffer.remote_id(), buffer_1_id);
3609 assert_eq!(translated_offset.0, "one\n".len());
3610 let (buffer, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3611 assert_eq!(buffer.remote_id(), buffer_1_id);
3612 assert_eq!(translated_point, Point::new(1, 0));
3613}
3614
3615fn format_diff(
3616 text: &str,
3617 row_infos: &Vec<RowInfo>,
3618 boundary_rows: &HashSet<MultiBufferRow>,
3619 has_diff: Option<bool>,
3620) -> String {
3621 let has_diff =
3622 has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3623 text.split('\n')
3624 .enumerate()
3625 .zip(row_infos)
3626 .map(|((ix, line), info)| {
3627 let marker = match info.diff_status.map(|status| status.kind) {
3628 Some(DiffHunkStatusKind::Added) => "+ ",
3629 Some(DiffHunkStatusKind::Deleted) => "- ",
3630 Some(DiffHunkStatusKind::Modified) => unreachable!(),
3631 None => {
3632 if has_diff && !line.is_empty() {
3633 " "
3634 } else {
3635 ""
3636 }
3637 }
3638 };
3639 let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3640 if has_diff {
3641 " ----------\n"
3642 } else {
3643 "---------\n"
3644 }
3645 } else {
3646 ""
3647 };
3648 let expand = info
3649 .expand_info
3650 .map(|expand_info| match expand_info.direction {
3651 ExpandExcerptDirection::Up => " [↑]",
3652 ExpandExcerptDirection::Down => " [↓]",
3653 ExpandExcerptDirection::UpAndDown => " [↕]",
3654 })
3655 .unwrap_or_default();
3656
3657 format!("{boundary_row}{marker}{line}{expand}")
3658 // let mbr = info
3659 // .multibuffer_row
3660 // .map(|row| format!("{:0>3}", row.0))
3661 // .unwrap_or_else(|| "???".to_string());
3662 // let byte_range = format!("{byte_range_start:0>3}..{byte_range_end:0>3}");
3663 // format!("{boundary_row}Row: {mbr}, Bytes: {byte_range} | {marker}{line}{expand}")
3664 })
3665 .collect::<Vec<_>>()
3666 .join("\n")
3667}
3668
3669// fn format_transforms(snapshot: &MultiBufferSnapshot) -> String {
3670// snapshot
3671// .diff_transforms
3672// .iter()
3673// .map(|transform| {
3674// let (kind, summary) = match transform {
3675// DiffTransform::DeletedHunk { summary, .. } => (" Deleted", (*summary).into()),
3676// DiffTransform::FilteredInsertedHunk { summary, .. } => (" Filtered", *summary),
3677// DiffTransform::InsertedHunk { summary, .. } => (" Inserted", *summary),
3678// DiffTransform::Unmodified { summary, .. } => ("Unmodified", *summary),
3679// };
3680// format!("{kind}(len: {}, lines: {:?})", summary.len, summary.lines)
3681// })
3682// .join("\n")
3683// }
3684
3685// fn format_excerpts(snapshot: &MultiBufferSnapshot) -> String {
3686// snapshot
3687// .excerpts
3688// .iter()
3689// .map(|excerpt| {
3690// format!(
3691// "Excerpt(buffer_range = {:?}, lines = {:?}, has_trailing_newline = {:?})",
3692// excerpt.range.context.to_point(&excerpt.buffer),
3693// excerpt.text_summary.lines,
3694// excerpt.has_trailing_newline
3695// )
3696// })
3697// .join("\n")
3698// }
3699
3700#[gpui::test]
3701async fn test_singleton_with_inverted_diff(cx: &mut TestAppContext) {
3702 let text = indoc!(
3703 "
3704 ZERO
3705 one
3706 TWO
3707 three
3708 six
3709 "
3710 );
3711 let base_text = indoc!(
3712 "
3713 one
3714 two
3715 three
3716 four
3717 five
3718 six
3719 "
3720 );
3721
3722 let buffer = cx.new(|cx| Buffer::local(text, cx));
3723 let diff = cx
3724 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
3725 cx.run_until_parked();
3726
3727 let base_text_buffer = diff.read_with(cx, |diff, _| diff.base_text_buffer());
3728
3729 let multibuffer = cx.new(|cx| {
3730 let mut multibuffer = MultiBuffer::singleton(base_text_buffer.clone(), cx);
3731 multibuffer.set_all_diff_hunks_expanded(cx);
3732 multibuffer.add_inverted_diff(diff.clone(), buffer.clone(), cx);
3733 multibuffer
3734 });
3735
3736 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3737 (multibuffer.snapshot(cx), multibuffer.subscribe())
3738 });
3739
3740 assert_eq!(snapshot.text(), base_text);
3741 assert_new_snapshot(
3742 &multibuffer,
3743 &mut snapshot,
3744 &mut subscription,
3745 cx,
3746 indoc!(
3747 "
3748 one
3749 - two
3750 three
3751 - four
3752 - five
3753 six
3754 "
3755 ),
3756 );
3757
3758 buffer.update(cx, |buffer, cx| {
3759 buffer.edit_via_marked_text(
3760 indoc!(
3761 "
3762 ZERO
3763 one
3764 «<inserted>»W«O
3765 T»hree
3766 six
3767 "
3768 ),
3769 None,
3770 cx,
3771 );
3772 });
3773 cx.run_until_parked();
3774 let update = diff
3775 .update(cx, |diff, cx| {
3776 diff.update_diff(
3777 buffer.read(cx).text_snapshot(),
3778 Some(base_text.into()),
3779 false,
3780 None,
3781 cx,
3782 )
3783 })
3784 .await;
3785 diff.update(cx, |diff, cx| {
3786 diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), cx);
3787 });
3788 cx.run_until_parked();
3789
3790 assert_new_snapshot(
3791 &multibuffer,
3792 &mut snapshot,
3793 &mut subscription,
3794 cx,
3795 indoc! {
3796 "
3797 one
3798 - two
3799 - three
3800 - four
3801 - five
3802 six
3803 "
3804 },
3805 );
3806
3807 buffer.update(cx, |buffer, cx| {
3808 buffer.set_text("ZERO\nONE\nTWO\n", cx);
3809 });
3810 cx.run_until_parked();
3811 let update = diff
3812 .update(cx, |diff, cx| {
3813 diff.update_diff(
3814 buffer.read(cx).text_snapshot(),
3815 Some(base_text.into()),
3816 false,
3817 None,
3818 cx,
3819 )
3820 })
3821 .await;
3822 diff.update(cx, |diff, cx| {
3823 diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), cx);
3824 });
3825 cx.run_until_parked();
3826
3827 assert_new_snapshot(
3828 &multibuffer,
3829 &mut snapshot,
3830 &mut subscription,
3831 cx,
3832 indoc! {
3833 "
3834 - one
3835 - two
3836 - three
3837 - four
3838 - five
3839 - six
3840 "
3841 },
3842 );
3843
3844 diff.update(cx, |diff, cx| {
3845 diff.set_base_text(
3846 Some("new base\n".into()),
3847 None,
3848 buffer.read(cx).text_snapshot(),
3849 cx,
3850 )
3851 })
3852 .await
3853 .unwrap();
3854 cx.run_until_parked();
3855
3856 assert_new_snapshot(
3857 &multibuffer,
3858 &mut snapshot,
3859 &mut subscription,
3860 cx,
3861 indoc! {"
3862 - new base
3863 "},
3864 );
3865}
3866
3867#[track_caller]
3868fn assert_excerpts_match(
3869 multibuffer: &Entity<MultiBuffer>,
3870 cx: &mut TestAppContext,
3871 expected: &str,
3872) {
3873 let mut output = String::new();
3874 multibuffer.read_with(cx, |multibuffer, cx| {
3875 for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
3876 output.push_str("-----\n");
3877 output.extend(buffer.text_for_range(range.context));
3878 if !output.ends_with('\n') {
3879 output.push('\n');
3880 }
3881 }
3882 });
3883 assert_eq!(output, expected);
3884}
3885
3886#[track_caller]
3887fn assert_new_snapshot(
3888 multibuffer: &Entity<MultiBuffer>,
3889 snapshot: &mut MultiBufferSnapshot,
3890 subscription: &mut Subscription<MultiBufferOffset>,
3891 cx: &mut TestAppContext,
3892 expected_diff: &str,
3893) {
3894 let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3895 let actual_text = new_snapshot.text();
3896 let line_infos = new_snapshot
3897 .row_infos(MultiBufferRow(0))
3898 .collect::<Vec<_>>();
3899 let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
3900 pretty_assertions::assert_eq!(actual_diff, expected_diff);
3901 check_edits(
3902 snapshot,
3903 &new_snapshot,
3904 &subscription.consume().into_inner(),
3905 );
3906 *snapshot = new_snapshot;
3907}
3908
3909#[track_caller]
3910fn check_edits(
3911 old_snapshot: &MultiBufferSnapshot,
3912 new_snapshot: &MultiBufferSnapshot,
3913 edits: &[Edit<MultiBufferOffset>],
3914) {
3915 let mut text = old_snapshot.text();
3916 let new_text = new_snapshot.text();
3917 for edit in edits.iter().rev() {
3918 if !text.is_char_boundary(edit.old.start.0)
3919 || !text.is_char_boundary(edit.old.end.0)
3920 || !new_text.is_char_boundary(edit.new.start.0)
3921 || !new_text.is_char_boundary(edit.new.end.0)
3922 {
3923 panic!(
3924 "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
3925 edits, text, new_text
3926 );
3927 }
3928
3929 text.replace_range(
3930 edit.old.start.0..edit.old.end.0,
3931 &new_text[edit.new.start.0..edit.new.end.0],
3932 );
3933 }
3934
3935 pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
3936}
3937
3938#[track_caller]
3939fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
3940 let full_text = snapshot.text();
3941 for ix in 0..full_text.len() {
3942 let mut chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
3943 chunks.seek(MultiBufferOffset(ix)..snapshot.len());
3944 let tail = chunks.map(|chunk| chunk.text).collect::<String>();
3945 assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
3946 }
3947}
3948
3949#[track_caller]
3950fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
3951 let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3952 for start_row in 1..all_line_numbers.len() {
3953 let line_numbers = snapshot
3954 .row_infos(MultiBufferRow(start_row as u32))
3955 .collect::<Vec<_>>();
3956 assert_eq!(
3957 line_numbers,
3958 all_line_numbers[start_row..],
3959 "start_row: {start_row}"
3960 );
3961 }
3962}
3963
3964#[track_caller]
3965fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
3966 let text = Rope::from(snapshot.text());
3967
3968 let mut left_anchors = Vec::new();
3969 let mut right_anchors = Vec::new();
3970 let mut offsets = Vec::new();
3971 let mut points = Vec::new();
3972 for offset in 0..=text.len() + 1 {
3973 let offset = MultiBufferOffset(offset);
3974 let clipped_left = snapshot.clip_offset(offset, Bias::Left);
3975 let clipped_right = snapshot.clip_offset(offset, Bias::Right);
3976 assert_eq!(
3977 clipped_left.0,
3978 text.clip_offset(offset.0, Bias::Left),
3979 "clip_offset({offset:?}, Left)"
3980 );
3981 assert_eq!(
3982 clipped_right.0,
3983 text.clip_offset(offset.0, Bias::Right),
3984 "clip_offset({offset:?}, Right)"
3985 );
3986 assert_eq!(
3987 snapshot.offset_to_point(clipped_left),
3988 text.offset_to_point(clipped_left.0),
3989 "offset_to_point({})",
3990 clipped_left.0
3991 );
3992 assert_eq!(
3993 snapshot.offset_to_point(clipped_right),
3994 text.offset_to_point(clipped_right.0),
3995 "offset_to_point({})",
3996 clipped_right.0
3997 );
3998 let anchor_after = snapshot.anchor_after(clipped_left);
3999 assert_eq!(
4000 anchor_after.to_offset(snapshot),
4001 clipped_left,
4002 "anchor_after({}).to_offset {anchor_after:?}",
4003 clipped_left.0
4004 );
4005 let anchor_before = snapshot.anchor_before(clipped_left);
4006 assert_eq!(
4007 anchor_before.to_offset(snapshot),
4008 clipped_left,
4009 "anchor_before({}).to_offset",
4010 clipped_left.0
4011 );
4012 left_anchors.push(anchor_before);
4013 right_anchors.push(anchor_after);
4014 offsets.push(clipped_left);
4015 points.push(text.offset_to_point(clipped_left.0));
4016 }
4017
4018 for row in 0..text.max_point().row {
4019 for column in 0..text.line_len(row) + 1 {
4020 let point = Point { row, column };
4021 let clipped_left = snapshot.clip_point(point, Bias::Left);
4022 let clipped_right = snapshot.clip_point(point, Bias::Right);
4023 assert_eq!(
4024 clipped_left,
4025 text.clip_point(point, Bias::Left),
4026 "clip_point({point:?}, Left)"
4027 );
4028 assert_eq!(
4029 clipped_right,
4030 text.clip_point(point, Bias::Right),
4031 "clip_point({point:?}, Right)"
4032 );
4033 assert_eq!(
4034 snapshot.point_to_offset(clipped_left).0,
4035 text.point_to_offset(clipped_left),
4036 "point_to_offset({clipped_left:?})"
4037 );
4038 assert_eq!(
4039 snapshot.point_to_offset(clipped_right).0,
4040 text.point_to_offset(clipped_right),
4041 "point_to_offset({clipped_right:?})"
4042 );
4043 }
4044 }
4045
4046 assert_eq!(
4047 snapshot.summaries_for_anchors::<MultiBufferOffset, _>(&left_anchors),
4048 offsets,
4049 "left_anchors <-> offsets"
4050 );
4051 assert_eq!(
4052 snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
4053 points,
4054 "left_anchors <-> points"
4055 );
4056 assert_eq!(
4057 snapshot.summaries_for_anchors::<MultiBufferOffset, _>(&right_anchors),
4058 offsets,
4059 "right_anchors <-> offsets"
4060 );
4061 assert_eq!(
4062 snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
4063 points,
4064 "right_anchors <-> points"
4065 );
4066
4067 for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
4068 for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
4069 if ix > 0 && *offset == MultiBufferOffset(252) && offset > &offsets[ix - 1] {
4070 let prev_anchor = left_anchors[ix - 1];
4071 assert!(
4072 anchor.cmp(&prev_anchor, snapshot).is_gt(),
4073 "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
4074 offsets[ix],
4075 offsets[ix - 1],
4076 );
4077 assert!(
4078 prev_anchor.cmp(anchor, snapshot).is_lt(),
4079 "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
4080 offsets[ix - 1],
4081 offsets[ix],
4082 );
4083 }
4084 }
4085 }
4086
4087 if let Some((buffer, offset)) = snapshot.point_to_buffer_offset(snapshot.max_point()) {
4088 assert!(offset.0 <= buffer.len());
4089 }
4090 if let Some((buffer, point, _)) = snapshot.point_to_buffer_point(snapshot.max_point()) {
4091 assert!(point <= buffer.max_point());
4092 }
4093}
4094
4095fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
4096 let max_row = snapshot.max_point().row;
4097 let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
4098 let text = text::Buffer::new(ReplicaId::LOCAL, buffer_id, snapshot.text());
4099 let mut line_indents = text
4100 .line_indents_in_row_range(0..max_row + 1)
4101 .collect::<Vec<_>>();
4102 for start_row in 0..snapshot.max_point().row {
4103 pretty_assertions::assert_eq!(
4104 snapshot
4105 .line_indents(MultiBufferRow(start_row), |_| true)
4106 .map(|(row, indent, _)| (row.0, indent))
4107 .collect::<Vec<_>>(),
4108 &line_indents[(start_row as usize)..],
4109 "line_indents({start_row})"
4110 );
4111 }
4112
4113 line_indents.reverse();
4114 pretty_assertions::assert_eq!(
4115 snapshot
4116 .reversed_line_indents(MultiBufferRow(max_row), |_| true)
4117 .map(|(row, indent, _)| (row.0, indent))
4118 .collect::<Vec<_>>(),
4119 &line_indents[..],
4120 "reversed_line_indents({max_row})"
4121 );
4122}
4123
4124#[gpui::test]
4125fn test_new_empty_buffer_uses_untitled_title(cx: &mut App) {
4126 let buffer = cx.new(|cx| Buffer::local("", cx));
4127 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4128
4129 assert_eq!(multibuffer.read(cx).title(cx), "untitled");
4130}
4131
4132#[gpui::test]
4133fn test_new_empty_buffer_uses_untitled_title_when_only_contains_whitespace(cx: &mut App) {
4134 let buffer = cx.new(|cx| Buffer::local("\n ", cx));
4135 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4136
4137 assert_eq!(multibuffer.read(cx).title(cx), "untitled");
4138}
4139
4140#[gpui::test]
4141fn test_new_empty_buffer_takes_first_line_for_title(cx: &mut App) {
4142 let buffer = cx.new(|cx| Buffer::local("Hello World\nSecond line", cx));
4143 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4144
4145 assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
4146}
4147
4148#[gpui::test]
4149fn test_new_empty_buffer_takes_trimmed_first_line_for_title(cx: &mut App) {
4150 let buffer = cx.new(|cx| Buffer::local("\nHello, World ", cx));
4151 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4152
4153 assert_eq!(multibuffer.read(cx).title(cx), "Hello, World");
4154}
4155
4156#[gpui::test]
4157fn test_new_empty_buffer_uses_truncated_first_line_for_title(cx: &mut App) {
4158 let title = "aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeee";
4159 let title_after = "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd";
4160 let buffer = cx.new(|cx| Buffer::local(title, cx));
4161 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4162
4163 assert_eq!(multibuffer.read(cx).title(cx), title_after);
4164}
4165
4166#[gpui::test]
4167fn test_new_empty_buffer_uses_truncated_first_line_for_title_after_merging_adjacent_spaces(
4168 cx: &mut App,
4169) {
4170 let title = "aaaaaaaaaabbbbbbbbbb ccccccccccddddddddddeeeeeeeeee";
4171 let title_after = "aaaaaaaaaabbbbbbbbbb ccccccccccddddddddd";
4172 let buffer = cx.new(|cx| Buffer::local(title, cx));
4173 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4174
4175 assert_eq!(multibuffer.read(cx).title(cx), title_after);
4176}
4177
4178#[gpui::test]
4179fn test_new_empty_buffers_title_can_be_set(cx: &mut App) {
4180 let buffer = cx.new(|cx| Buffer::local("Hello World", cx));
4181 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4182 assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
4183
4184 multibuffer.update(cx, |multibuffer, cx| {
4185 multibuffer.set_title("Hey".into(), cx)
4186 });
4187 assert_eq!(multibuffer.read(cx).title(cx), "Hey");
4188}
4189
4190#[gpui::test(iterations = 100)]
4191fn test_random_chunk_bitmaps(cx: &mut App, mut rng: StdRng) {
4192 let multibuffer = if rng.random() {
4193 let len = rng.random_range(0..10000);
4194 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
4195 let buffer = cx.new(|cx| Buffer::local(text, cx));
4196 cx.new(|cx| MultiBuffer::singleton(buffer, cx))
4197 } else {
4198 MultiBuffer::build_random(&mut rng, cx)
4199 };
4200
4201 let snapshot = multibuffer.read(cx).snapshot(cx);
4202
4203 let chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4204
4205 for chunk in chunks {
4206 let chunk_text = chunk.text;
4207 let chars_bitmap = chunk.chars;
4208 let tabs_bitmap = chunk.tabs;
4209
4210 if chunk_text.is_empty() {
4211 assert_eq!(
4212 chars_bitmap, 0,
4213 "Empty chunk should have empty chars bitmap"
4214 );
4215 assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
4216 continue;
4217 }
4218
4219 assert!(
4220 chunk_text.len() <= 128,
4221 "Chunk text length {} exceeds 128 bytes",
4222 chunk_text.len()
4223 );
4224
4225 // Verify chars bitmap
4226 let char_indices = chunk_text
4227 .char_indices()
4228 .map(|(i, _)| i)
4229 .collect::<Vec<_>>();
4230
4231 for byte_idx in 0..chunk_text.len() {
4232 let should_have_bit = char_indices.contains(&byte_idx);
4233 let has_bit = chars_bitmap & (1 << byte_idx) != 0;
4234
4235 if has_bit != should_have_bit {
4236 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4237 eprintln!("Char indices: {:?}", char_indices);
4238 eprintln!("Chars bitmap: {:#b}", chars_bitmap);
4239 }
4240
4241 assert_eq!(
4242 has_bit, should_have_bit,
4243 "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
4244 byte_idx, chunk_text, should_have_bit, has_bit
4245 );
4246 }
4247
4248 for (byte_idx, byte) in chunk_text.bytes().enumerate() {
4249 let is_tab = byte == b'\t';
4250 let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
4251
4252 if has_bit != is_tab {
4253 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4254 eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
4255 assert_eq!(
4256 has_bit, is_tab,
4257 "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
4258 byte_idx, chunk_text, byte as char, is_tab, has_bit
4259 );
4260 }
4261 }
4262 }
4263}
4264
4265#[gpui::test(iterations = 10)]
4266fn test_random_chunk_bitmaps_with_diffs(cx: &mut App, mut rng: StdRng) {
4267 let settings_store = SettingsStore::test(cx);
4268 cx.set_global(settings_store);
4269 use buffer_diff::BufferDiff;
4270 use util::RandomCharIter;
4271
4272 let multibuffer = if rng.random() {
4273 let len = rng.random_range(100..10000);
4274 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
4275 let buffer = cx.new(|cx| Buffer::local(text, cx));
4276 cx.new(|cx| MultiBuffer::singleton(buffer, cx))
4277 } else {
4278 MultiBuffer::build_random(&mut rng, cx)
4279 };
4280
4281 let _diff_count = rng.random_range(1..5);
4282 let mut diffs = Vec::new();
4283
4284 multibuffer.update(cx, |multibuffer, cx| {
4285 for buffer_id in multibuffer.excerpt_buffer_ids() {
4286 if rng.random_bool(0.7) {
4287 if let Some(buffer_handle) = multibuffer.buffer(buffer_id) {
4288 let buffer_text = buffer_handle.read(cx).text();
4289 let mut base_text = String::new();
4290
4291 for line in buffer_text.lines() {
4292 if rng.random_bool(0.3) {
4293 continue;
4294 } else if rng.random_bool(0.3) {
4295 let line_len = rng.random_range(0..50);
4296 let modified_line = RandomCharIter::new(&mut rng)
4297 .take(line_len)
4298 .collect::<String>();
4299 base_text.push_str(&modified_line);
4300 base_text.push('\n');
4301 } else {
4302 base_text.push_str(line);
4303 base_text.push('\n');
4304 }
4305 }
4306
4307 if rng.random_bool(0.5) {
4308 let extra_lines = rng.random_range(1..5);
4309 for _ in 0..extra_lines {
4310 let line_len = rng.random_range(0..50);
4311 let extra_line = RandomCharIter::new(&mut rng)
4312 .take(line_len)
4313 .collect::<String>();
4314 base_text.push_str(&extra_line);
4315 base_text.push('\n');
4316 }
4317 }
4318
4319 let diff = cx.new(|cx| {
4320 BufferDiff::new_with_base_text(
4321 &base_text,
4322 &buffer_handle.read(cx).text_snapshot(),
4323 cx,
4324 )
4325 });
4326 diffs.push(diff.clone());
4327 multibuffer.add_diff(diff, cx);
4328 }
4329 }
4330 }
4331 });
4332
4333 multibuffer.update(cx, |multibuffer, cx| {
4334 if rng.random_bool(0.5) {
4335 multibuffer.set_all_diff_hunks_expanded(cx);
4336 } else {
4337 let snapshot = multibuffer.snapshot(cx);
4338 let text = snapshot.text();
4339
4340 let mut ranges = Vec::new();
4341 for _ in 0..rng.random_range(1..5) {
4342 if snapshot.len().0 == 0 {
4343 break;
4344 }
4345
4346 let diff_size = rng.random_range(5..1000);
4347 let mut start = rng.random_range(0..snapshot.len().0);
4348
4349 while !text.is_char_boundary(start) {
4350 start = start.saturating_sub(1);
4351 }
4352
4353 let mut end = rng.random_range(start..snapshot.len().0.min(start + diff_size));
4354
4355 while !text.is_char_boundary(end) {
4356 end = end.saturating_add(1);
4357 }
4358 let start_anchor = snapshot.anchor_after(MultiBufferOffset(start));
4359 let end_anchor = snapshot.anchor_before(MultiBufferOffset(end));
4360 ranges.push(start_anchor..end_anchor);
4361 }
4362 multibuffer.expand_diff_hunks(ranges, cx);
4363 }
4364 });
4365
4366 let snapshot = multibuffer.read(cx).snapshot(cx);
4367
4368 let chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4369
4370 for chunk in chunks {
4371 let chunk_text = chunk.text;
4372 let chars_bitmap = chunk.chars;
4373 let tabs_bitmap = chunk.tabs;
4374
4375 if chunk_text.is_empty() {
4376 assert_eq!(
4377 chars_bitmap, 0,
4378 "Empty chunk should have empty chars bitmap"
4379 );
4380 assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
4381 continue;
4382 }
4383
4384 assert!(
4385 chunk_text.len() <= 128,
4386 "Chunk text length {} exceeds 128 bytes",
4387 chunk_text.len()
4388 );
4389
4390 let char_indices = chunk_text
4391 .char_indices()
4392 .map(|(i, _)| i)
4393 .collect::<Vec<_>>();
4394
4395 for byte_idx in 0..chunk_text.len() {
4396 let should_have_bit = char_indices.contains(&byte_idx);
4397 let has_bit = chars_bitmap & (1 << byte_idx) != 0;
4398
4399 if has_bit != should_have_bit {
4400 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4401 eprintln!("Char indices: {:?}", char_indices);
4402 eprintln!("Chars bitmap: {:#b}", chars_bitmap);
4403 }
4404
4405 assert_eq!(
4406 has_bit, should_have_bit,
4407 "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
4408 byte_idx, chunk_text, should_have_bit, has_bit
4409 );
4410 }
4411
4412 for (byte_idx, byte) in chunk_text.bytes().enumerate() {
4413 let is_tab = byte == b'\t';
4414 let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
4415
4416 if has_bit != is_tab {
4417 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4418 eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
4419 assert_eq!(
4420 has_bit, is_tab,
4421 "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
4422 byte_idx, chunk_text, byte as char, is_tab, has_bit
4423 );
4424 }
4425 }
4426 }
4427}
4428
4429fn collect_word_diffs(
4430 base_text: &str,
4431 modified_text: &str,
4432 cx: &mut TestAppContext,
4433) -> Vec<String> {
4434 let buffer = cx.new(|cx| Buffer::local(modified_text, cx));
4435 let diff = cx
4436 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
4437 cx.run_until_parked();
4438
4439 let multibuffer = cx.new(|cx| {
4440 let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
4441 multibuffer.add_diff(diff.clone(), cx);
4442 multibuffer
4443 });
4444
4445 multibuffer.update(cx, |multibuffer, cx| {
4446 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
4447 });
4448
4449 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4450 let text = snapshot.text();
4451
4452 snapshot
4453 .diff_hunks()
4454 .flat_map(|hunk| hunk.word_diffs)
4455 .map(|range| text[range.start.0..range.end.0].to_string())
4456 .collect()
4457}
4458
4459#[gpui::test]
4460async fn test_word_diff_simple_replacement(cx: &mut TestAppContext) {
4461 let settings_store = cx.update(|cx| SettingsStore::test(cx));
4462 cx.set_global(settings_store);
4463
4464 let base_text = "hello world foo bar\n";
4465 let modified_text = "hello WORLD foo BAR\n";
4466
4467 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4468
4469 assert_eq!(word_diffs, vec!["world", "bar", "WORLD", "BAR"]);
4470}
4471
4472#[gpui::test]
4473async fn test_word_diff_consecutive_modified_lines(cx: &mut TestAppContext) {
4474 let settings_store = cx.update(|cx| SettingsStore::test(cx));
4475 cx.set_global(settings_store);
4476
4477 let base_text = "aaa bbb\nccc ddd\n";
4478 let modified_text = "aaa BBB\nccc DDD\n";
4479
4480 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4481
4482 assert_eq!(
4483 word_diffs,
4484 vec!["bbb", "ddd", "BBB", "DDD"],
4485 "consecutive modified lines should produce word diffs when line counts match"
4486 );
4487}
4488
4489#[gpui::test]
4490async fn test_word_diff_modified_lines_with_deletion_between(cx: &mut TestAppContext) {
4491 let settings_store = cx.update(|cx| SettingsStore::test(cx));
4492 cx.set_global(settings_store);
4493
4494 let base_text = "aaa bbb\ndeleted line\nccc ddd\n";
4495 let modified_text = "aaa BBB\nccc DDD\n";
4496
4497 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4498
4499 assert_eq!(
4500 word_diffs,
4501 Vec::<String>::new(),
4502 "modified lines with a deleted line between should not produce word diffs"
4503 );
4504}
4505
4506#[gpui::test]
4507async fn test_word_diff_disabled(cx: &mut TestAppContext) {
4508 let settings_store = cx.update(|cx| {
4509 let mut settings_store = SettingsStore::test(cx);
4510 settings_store.update_user_settings(cx, |settings| {
4511 settings.project.all_languages.defaults.word_diff_enabled = Some(false);
4512 });
4513 settings_store
4514 });
4515 cx.set_global(settings_store);
4516
4517 let base_text = "hello world\n";
4518 let modified_text = "hello WORLD\n";
4519
4520 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4521
4522 assert_eq!(
4523 word_diffs,
4524 Vec::<String>::new(),
4525 "word diffs should be empty when disabled"
4526 );
4527}
4528
4529/// Tests `excerpt_containing` and `excerpts_for_range` (functions mapping multi-buffer text-coordinates to excerpts)
4530#[gpui::test]
4531fn test_excerpts_containment_functions(cx: &mut App) {
4532 // Multibuffer content for these tests:
4533 // 0123
4534 // 0: aa0
4535 // 1: aa1
4536 // -----
4537 // 2: bb0
4538 // 3: bb1
4539 // -----MultiBufferOffset(0)..
4540 // 4: cc0
4541
4542 let buffer_1 = cx.new(|cx| Buffer::local("aa0\naa1", cx));
4543 let buffer_2 = cx.new(|cx| Buffer::local("bb0\nbb1", cx));
4544 let buffer_3 = cx.new(|cx| Buffer::local("cc0", cx));
4545
4546 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
4547
4548 let (excerpt_1_id, excerpt_2_id, excerpt_3_id) = multibuffer.update(cx, |multibuffer, cx| {
4549 let excerpt_1_id = multibuffer.push_excerpts(
4550 buffer_1.clone(),
4551 [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4552 cx,
4553 )[0];
4554
4555 let excerpt_2_id = multibuffer.push_excerpts(
4556 buffer_2.clone(),
4557 [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4558 cx,
4559 )[0];
4560
4561 let excerpt_3_id = multibuffer.push_excerpts(
4562 buffer_3.clone(),
4563 [ExcerptRange::new(Point::new(0, 0)..Point::new(0, 3))],
4564 cx,
4565 )[0];
4566
4567 (excerpt_1_id, excerpt_2_id, excerpt_3_id)
4568 });
4569
4570 let snapshot = multibuffer.read(cx).snapshot(cx);
4571
4572 assert_eq!(snapshot.text(), "aa0\naa1\nbb0\nbb1\ncc0");
4573
4574 //// Test `excerpts_for_range`
4575
4576 let p00 = snapshot.point_to_offset(Point::new(0, 0));
4577 let p10 = snapshot.point_to_offset(Point::new(1, 0));
4578 let p20 = snapshot.point_to_offset(Point::new(2, 0));
4579 let p23 = snapshot.point_to_offset(Point::new(2, 3));
4580 let p13 = snapshot.point_to_offset(Point::new(1, 3));
4581 let p40 = snapshot.point_to_offset(Point::new(4, 0));
4582 let p43 = snapshot.point_to_offset(Point::new(4, 3));
4583
4584 let excerpts: Vec<_> = snapshot.excerpts_for_range(p00..p00).collect();
4585 assert_eq!(excerpts.len(), 1);
4586 assert_eq!(excerpts[0].id, excerpt_1_id);
4587
4588 // Cursor at very end of excerpt 3
4589 let excerpts: Vec<_> = snapshot.excerpts_for_range(p43..p43).collect();
4590 assert_eq!(excerpts.len(), 1);
4591 assert_eq!(excerpts[0].id, excerpt_3_id);
4592
4593 let excerpts: Vec<_> = snapshot.excerpts_for_range(p00..p23).collect();
4594 assert_eq!(excerpts.len(), 2);
4595 assert_eq!(excerpts[0].id, excerpt_1_id);
4596 assert_eq!(excerpts[1].id, excerpt_2_id);
4597
4598 // This range represent an selection with end-point just inside excerpt_2
4599 // Today we only expand the first excerpt, but another interpretation that
4600 // we could consider is expanding both here
4601 let excerpts: Vec<_> = snapshot.excerpts_for_range(p10..p20).collect();
4602 assert_eq!(excerpts.len(), 1);
4603 assert_eq!(excerpts[0].id, excerpt_1_id);
4604
4605 //// Test that `excerpts_for_range` and `excerpt_containing` agree for all single offsets (cursor positions)
4606 for offset in 0..=snapshot.len().0 {
4607 let offset = MultiBufferOffset(offset);
4608 let excerpts_for_range: Vec<_> = snapshot.excerpts_for_range(offset..offset).collect();
4609 assert_eq!(
4610 excerpts_for_range.len(),
4611 1,
4612 "Expected exactly one excerpt for offset {offset}",
4613 );
4614
4615 let excerpt_containing = snapshot.excerpt_containing(offset..offset);
4616 assert!(
4617 excerpt_containing.is_some(),
4618 "Expected excerpt_containing to find excerpt for offset {offset}",
4619 );
4620
4621 assert_eq!(
4622 excerpts_for_range[0].id,
4623 excerpt_containing.unwrap().id(),
4624 "excerpts_for_range and excerpt_containing should agree for offset {offset}",
4625 );
4626 }
4627
4628 //// Test `excerpt_containing` behavior with ranges:
4629
4630 // Ranges intersecting a single-excerpt
4631 let containing = snapshot.excerpt_containing(p00..p13);
4632 assert!(containing.is_some());
4633 assert_eq!(containing.unwrap().id(), excerpt_1_id);
4634
4635 // Ranges intersecting multiple excerpts (should return None)
4636 let containing = snapshot.excerpt_containing(p20..p40);
4637 assert!(
4638 containing.is_none(),
4639 "excerpt_containing should return None for ranges spanning multiple excerpts"
4640 );
4641}