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 inverted_diffs: HashMap<BufferId, (Entity<BufferDiff>, WeakEntity<Buffer>)>,
2299}
2300
2301#[derive(Debug)]
2302struct ReferenceExcerpt {
2303 id: ExcerptId,
2304 buffer: Entity<Buffer>,
2305 range: Range<text::Anchor>,
2306 expanded_diff_hunks: Vec<text::Anchor>,
2307}
2308
2309#[derive(Debug)]
2310struct ReferenceRegion {
2311 buffer_id: Option<BufferId>,
2312 range: Range<usize>,
2313 buffer_range: Option<Range<Point>>,
2314 status: Option<DiffHunkStatus>,
2315 excerpt_id: Option<ExcerptId>,
2316}
2317
2318impl ReferenceMultibuffer {
2319 fn expand_excerpts(&mut self, excerpts: &HashSet<ExcerptId>, line_count: u32, cx: &App) {
2320 if line_count == 0 {
2321 return;
2322 }
2323
2324 for id in excerpts {
2325 let excerpt = self.excerpts.iter_mut().find(|e| e.id == *id).unwrap();
2326 let snapshot = excerpt.buffer.read(cx).snapshot();
2327 let mut point_range = excerpt.range.to_point(&snapshot);
2328 point_range.start = Point::new(point_range.start.row.saturating_sub(line_count), 0);
2329 point_range.end =
2330 snapshot.clip_point(Point::new(point_range.end.row + line_count, 0), Bias::Left);
2331 point_range.end.column = snapshot.line_len(point_range.end.row);
2332 excerpt.range =
2333 snapshot.anchor_before(point_range.start)..snapshot.anchor_after(point_range.end);
2334 }
2335 }
2336
2337 fn remove_excerpt(&mut self, id: ExcerptId, cx: &App) {
2338 let ix = self
2339 .excerpts
2340 .iter()
2341 .position(|excerpt| excerpt.id == id)
2342 .unwrap();
2343 let excerpt = self.excerpts.remove(ix);
2344 let buffer = excerpt.buffer.read(cx);
2345 let buffer_id = buffer.remote_id();
2346 log::info!(
2347 "Removing excerpt {}: {:?}",
2348 ix,
2349 buffer
2350 .text_for_range(excerpt.range.to_offset(buffer))
2351 .collect::<String>(),
2352 );
2353 if !self
2354 .excerpts
2355 .iter()
2356 .any(|excerpt| excerpt.buffer.read(cx).remote_id() == buffer_id)
2357 {
2358 self.diffs.remove(&buffer_id);
2359 self.inverted_diffs.remove(&buffer_id);
2360 }
2361 }
2362
2363 fn insert_excerpt_after(
2364 &mut self,
2365 prev_id: ExcerptId,
2366 new_excerpt_id: ExcerptId,
2367 (buffer_handle, anchor_range): (Entity<Buffer>, Range<text::Anchor>),
2368 ) {
2369 let excerpt_ix = if prev_id == ExcerptId::max() {
2370 self.excerpts.len()
2371 } else {
2372 self.excerpts
2373 .iter()
2374 .position(|excerpt| excerpt.id == prev_id)
2375 .unwrap()
2376 + 1
2377 };
2378 self.excerpts.insert(
2379 excerpt_ix,
2380 ReferenceExcerpt {
2381 id: new_excerpt_id,
2382 buffer: buffer_handle,
2383 range: anchor_range,
2384 expanded_diff_hunks: Vec::new(),
2385 },
2386 );
2387 }
2388
2389 fn expand_diff_hunks(&mut self, excerpt_id: ExcerptId, range: Range<text::Anchor>, cx: &App) {
2390 let excerpt = self
2391 .excerpts
2392 .iter_mut()
2393 .find(|e| e.id == excerpt_id)
2394 .unwrap();
2395 let buffer = excerpt.buffer.read(cx).snapshot();
2396 let buffer_id = buffer.remote_id();
2397
2398 // Skip inverted excerpts - hunks are always expanded
2399 if self.inverted_diffs.contains_key(&buffer_id) {
2400 return;
2401 }
2402
2403 let Some(diff) = self.diffs.get(&buffer_id) else {
2404 return;
2405 };
2406 let excerpt_range = excerpt.range.to_offset(&buffer);
2407 for hunk in diff
2408 .read(cx)
2409 .snapshot(cx)
2410 .hunks_intersecting_range(range, &buffer)
2411 {
2412 let hunk_range = hunk.buffer_range.to_offset(&buffer);
2413 if hunk_range.start < excerpt_range.start || hunk_range.start > excerpt_range.end {
2414 continue;
2415 }
2416 if let Err(ix) = excerpt
2417 .expanded_diff_hunks
2418 .binary_search_by(|anchor| anchor.cmp(&hunk.buffer_range.start, &buffer))
2419 {
2420 log::info!(
2421 "expanding diff hunk {:?}. excerpt:{:?}, excerpt range:{:?}",
2422 hunk_range,
2423 excerpt_id,
2424 excerpt_range
2425 );
2426 excerpt
2427 .expanded_diff_hunks
2428 .insert(ix, hunk.buffer_range.start);
2429 } else {
2430 log::trace!("hunk {hunk_range:?} already expanded in excerpt {excerpt_id:?}");
2431 }
2432 }
2433 }
2434
2435 fn expected_content(&self, cx: &App) -> (String, Vec<RowInfo>, HashSet<MultiBufferRow>) {
2436 let mut text = String::new();
2437 let mut regions = Vec::<ReferenceRegion>::new();
2438 let mut excerpt_boundary_rows = HashSet::default();
2439 for excerpt in &self.excerpts {
2440 excerpt_boundary_rows.insert(MultiBufferRow(text.matches('\n').count() as u32));
2441 let buffer = excerpt.buffer.read(cx);
2442 let buffer_id = buffer.remote_id();
2443 let buffer_range = excerpt.range.to_offset(buffer);
2444
2445 if let Some((diff, main_buffer)) = self.inverted_diffs.get(&buffer_id) {
2446 let diff_snapshot = diff.read(cx).snapshot(cx);
2447 let main_buffer_snapshot = main_buffer
2448 .read_with(cx, |main_buffer, _| main_buffer.snapshot())
2449 .unwrap();
2450
2451 let mut offset = buffer_range.start;
2452 for hunk in diff_snapshot
2453 .hunks_intersecting_base_text_range(buffer_range.clone(), &main_buffer_snapshot)
2454 {
2455 let mut hunk_base_range = hunk.diff_base_byte_range.clone();
2456
2457 hunk_base_range.end = hunk_base_range.end.min(buffer_range.end);
2458 if hunk_base_range.start > buffer_range.end
2459 || hunk_base_range.start < buffer_range.start
2460 {
2461 continue;
2462 }
2463
2464 if !hunk.buffer_range.start.is_valid(&main_buffer_snapshot) {
2465 continue;
2466 }
2467
2468 // Add the text before the hunk
2469 if hunk_base_range.start >= offset {
2470 let len = text.len();
2471 text.extend(buffer.text_for_range(offset..hunk_base_range.start));
2472 if text.len() > len {
2473 regions.push(ReferenceRegion {
2474 buffer_id: Some(buffer_id),
2475 range: len..text.len(),
2476 buffer_range: Some(
2477 (offset..hunk_base_range.start).to_point(&buffer),
2478 ),
2479 status: None,
2480 excerpt_id: Some(excerpt.id),
2481 });
2482 }
2483 }
2484
2485 // Add the "deleted" region (base text that's not in main)
2486 if !hunk_base_range.is_empty() {
2487 let len = text.len();
2488 text.extend(buffer.text_for_range(hunk_base_range.clone()));
2489 regions.push(ReferenceRegion {
2490 buffer_id: Some(buffer_id),
2491 range: len..text.len(),
2492 buffer_range: Some(hunk_base_range.to_point(&buffer)),
2493 status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2494 excerpt_id: Some(excerpt.id),
2495 });
2496 }
2497
2498 offset = hunk_base_range.end;
2499 }
2500
2501 // Add remaining buffer text
2502 let len = text.len();
2503 text.extend(buffer.text_for_range(offset..buffer_range.end));
2504 text.push('\n');
2505 regions.push(ReferenceRegion {
2506 buffer_id: Some(buffer_id),
2507 range: len..text.len(),
2508 buffer_range: Some((offset..buffer_range.end).to_point(&buffer)),
2509 status: None,
2510 excerpt_id: Some(excerpt.id),
2511 });
2512 } else {
2513 let diff = self.diffs.get(&buffer_id).unwrap().read(cx).snapshot(cx);
2514 let base_buffer = diff.base_text();
2515
2516 let mut offset = buffer_range.start;
2517 let hunks = diff
2518 .hunks_intersecting_range(excerpt.range.clone(), buffer)
2519 .peekable();
2520
2521 for hunk in hunks {
2522 // Ignore hunks that are outside the excerpt range.
2523 let mut hunk_range = hunk.buffer_range.to_offset(buffer);
2524
2525 hunk_range.end = hunk_range.end.min(buffer_range.end);
2526 if hunk_range.start > buffer_range.end || hunk_range.start < buffer_range.start
2527 {
2528 log::trace!("skipping hunk outside excerpt range");
2529 continue;
2530 }
2531
2532 if !excerpt.expanded_diff_hunks.iter().any(|expanded_anchor| {
2533 expanded_anchor.to_offset(buffer).max(buffer_range.start)
2534 == hunk_range.start.max(buffer_range.start)
2535 }) {
2536 log::trace!("skipping a hunk that's not marked as expanded");
2537 continue;
2538 }
2539
2540 if !hunk.buffer_range.start.is_valid(buffer) {
2541 log::trace!("skipping hunk with deleted start: {:?}", hunk.range);
2542 continue;
2543 }
2544
2545 if hunk_range.start >= offset {
2546 // Add the buffer text before the hunk
2547 let len = text.len();
2548 text.extend(buffer.text_for_range(offset..hunk_range.start));
2549 if text.len() > len {
2550 regions.push(ReferenceRegion {
2551 buffer_id: Some(buffer_id),
2552 range: len..text.len(),
2553 buffer_range: Some((offset..hunk_range.start).to_point(&buffer)),
2554 status: None,
2555 excerpt_id: Some(excerpt.id),
2556 });
2557 }
2558
2559 // Add the deleted text for the hunk.
2560 if !hunk.diff_base_byte_range.is_empty() {
2561 let mut base_text = base_buffer
2562 .text_for_range(hunk.diff_base_byte_range.clone())
2563 .collect::<String>();
2564 if !base_text.ends_with('\n') {
2565 base_text.push('\n');
2566 }
2567 let len = text.len();
2568 text.push_str(&base_text);
2569 regions.push(ReferenceRegion {
2570 buffer_id: Some(base_buffer.remote_id()),
2571 range: len..text.len(),
2572 buffer_range: Some(
2573 hunk.diff_base_byte_range.to_point(&base_buffer),
2574 ),
2575 status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2576 excerpt_id: Some(excerpt.id),
2577 });
2578 }
2579
2580 offset = hunk_range.start;
2581 }
2582
2583 // Add the inserted text for the hunk.
2584 if hunk_range.end > offset {
2585 let len = text.len();
2586 text.extend(buffer.text_for_range(offset..hunk_range.end));
2587 let range = len..text.len();
2588 let region = ReferenceRegion {
2589 buffer_id: Some(buffer_id),
2590 range,
2591 buffer_range: Some((offset..hunk_range.end).to_point(&buffer)),
2592 status: Some(DiffHunkStatus::added(hunk.secondary_status)),
2593 excerpt_id: Some(excerpt.id),
2594 };
2595 offset = hunk_range.end;
2596 regions.push(region);
2597 }
2598 }
2599
2600 // Add the buffer text for the rest of the excerpt.
2601 let len = text.len();
2602 text.extend(buffer.text_for_range(offset..buffer_range.end));
2603 text.push('\n');
2604 regions.push(ReferenceRegion {
2605 buffer_id: Some(buffer_id),
2606 range: len..text.len(),
2607 buffer_range: Some((offset..buffer_range.end).to_point(&buffer)),
2608 status: None,
2609 excerpt_id: Some(excerpt.id),
2610 });
2611 }
2612 }
2613
2614 // Remove final trailing newline.
2615 if self.excerpts.is_empty() {
2616 regions.push(ReferenceRegion {
2617 buffer_id: None,
2618 range: 0..1,
2619 buffer_range: Some(Point::new(0, 0)..Point::new(0, 1)),
2620 status: None,
2621 excerpt_id: None,
2622 });
2623 } else {
2624 text.pop();
2625 }
2626
2627 // Retrieve the row info using the region that contains
2628 // the start of each multi-buffer line.
2629 let mut ix = 0;
2630 let row_infos = text
2631 .split('\n')
2632 .map(|line| {
2633 let row_info = regions
2634 .iter()
2635 .position(|region| region.range.contains(&ix))
2636 .map_or(RowInfo::default(), |region_ix| {
2637 let region = ®ions[region_ix];
2638 let buffer_row = region.buffer_range.as_ref().map(|buffer_range| {
2639 buffer_range.start.row
2640 + text[region.range.start..ix].matches('\n').count() as u32
2641 });
2642 let main_buffer = self
2643 .excerpts
2644 .iter()
2645 .find(|e| e.id == region.excerpt_id.unwrap())
2646 .map(|e| e.buffer.clone());
2647 let is_excerpt_start = region_ix == 0
2648 || ®ions[region_ix - 1].excerpt_id != ®ion.excerpt_id
2649 || regions[region_ix - 1].range.is_empty();
2650 let mut is_excerpt_end = region_ix == regions.len() - 1
2651 || ®ions[region_ix + 1].excerpt_id != ®ion.excerpt_id;
2652 let is_start = !text[region.range.start..ix].contains('\n');
2653 let mut is_end = if region.range.end > text.len() {
2654 !text[ix..].contains('\n')
2655 } else {
2656 text[ix..region.range.end.min(text.len())]
2657 .matches('\n')
2658 .count()
2659 == 1
2660 };
2661 if region_ix < regions.len() - 1
2662 && !text[ix..].contains("\n")
2663 && (region.status == Some(DiffHunkStatus::added_none())
2664 || region.status.is_some_and(|s| s.is_deleted()))
2665 && regions[region_ix + 1].excerpt_id == region.excerpt_id
2666 && regions[region_ix + 1].range.start == text.len()
2667 {
2668 is_end = true;
2669 is_excerpt_end = true;
2670 }
2671 let multibuffer_row =
2672 MultiBufferRow(text[..ix].matches('\n').count() as u32);
2673 let mut expand_direction = None;
2674 if let Some(buffer) = &main_buffer {
2675 let buffer_row = buffer_row.unwrap();
2676 let needs_expand_up = is_excerpt_start && is_start && buffer_row > 0;
2677 let needs_expand_down = is_excerpt_end
2678 && is_end
2679 && buffer.read(cx).max_point().row > buffer_row;
2680 expand_direction = if needs_expand_up && needs_expand_down {
2681 Some(ExpandExcerptDirection::UpAndDown)
2682 } else if needs_expand_up {
2683 Some(ExpandExcerptDirection::Up)
2684 } else if needs_expand_down {
2685 Some(ExpandExcerptDirection::Down)
2686 } else {
2687 None
2688 };
2689 }
2690 RowInfo {
2691 buffer_id: region.buffer_id,
2692 diff_status: region.status,
2693 buffer_row,
2694 wrapped_buffer_row: None,
2695
2696 multibuffer_row: Some(multibuffer_row),
2697 expand_info: expand_direction.zip(region.excerpt_id).map(
2698 |(direction, excerpt_id)| ExpandInfo {
2699 direction,
2700 excerpt_id,
2701 },
2702 ),
2703 }
2704 });
2705 ix += line.len() + 1;
2706 row_info
2707 })
2708 .collect();
2709
2710 (text, row_infos, excerpt_boundary_rows)
2711 }
2712
2713 fn diffs_updated(&mut self, cx: &App) {
2714 for excerpt in &mut self.excerpts {
2715 let buffer = excerpt.buffer.read(cx).snapshot();
2716 let buffer_id = buffer.remote_id();
2717
2718 // Skip inverted diff excerpts - hunks are always expanded
2719 if self.inverted_diffs.contains_key(&buffer_id) {
2720 continue;
2721 }
2722
2723 let excerpt_range = excerpt.range.to_offset(&buffer);
2724 let Some(diff) = self.diffs.get(&buffer_id) else {
2725 continue;
2726 };
2727 let diff = diff.read(cx).snapshot(cx);
2728 let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer).peekable();
2729 excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2730 if !hunk_anchor.is_valid(&buffer) {
2731 return false;
2732 }
2733 while let Some(hunk) = hunks.peek() {
2734 match hunk.buffer_range.start.cmp(hunk_anchor, &buffer) {
2735 cmp::Ordering::Less => {
2736 hunks.next();
2737 }
2738 cmp::Ordering::Equal => {
2739 let hunk_range = hunk.buffer_range.to_offset(&buffer);
2740 return hunk_range.end >= excerpt_range.start
2741 && hunk_range.start <= excerpt_range.end;
2742 }
2743 cmp::Ordering::Greater => break,
2744 }
2745 }
2746 false
2747 });
2748 }
2749 }
2750
2751 fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2752 let buffer_id = diff.read(cx).buffer_id;
2753 self.diffs.insert(buffer_id, diff);
2754 }
2755
2756 fn add_inverted_diff(
2757 &mut self,
2758 diff: Entity<BufferDiff>,
2759 main_buffer: Entity<Buffer>,
2760 cx: &App,
2761 ) {
2762 let base_text_buffer_id = diff.read(cx).base_text(cx).remote_id();
2763 self.inverted_diffs
2764 .insert(base_text_buffer_id, (diff, main_buffer.downgrade()));
2765 }
2766}
2767
2768#[gpui::test(iterations = 100)]
2769async fn test_random_set_ranges(cx: &mut TestAppContext, mut rng: StdRng) {
2770 let base_text = "a\n".repeat(100);
2771 let buf = cx.update(|cx| cx.new(|cx| Buffer::local(base_text, cx)));
2772 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2773
2774 let operations = env::var("OPERATIONS")
2775 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2776 .unwrap_or(10);
2777
2778 fn row_ranges(ranges: &Vec<Range<Point>>) -> Vec<Range<u32>> {
2779 ranges
2780 .iter()
2781 .map(|range| range.start.row..range.end.row)
2782 .collect()
2783 }
2784
2785 for _ in 0..operations {
2786 let snapshot = buf.update(cx, |buf, _| buf.snapshot());
2787 let num_ranges = rng.random_range(0..=10);
2788 let max_row = snapshot.max_point().row;
2789 let mut ranges = (0..num_ranges)
2790 .map(|_| {
2791 let start = rng.random_range(0..max_row);
2792 let end = rng.random_range(start + 1..max_row + 1);
2793 Point::row_range(start..end)
2794 })
2795 .collect::<Vec<_>>();
2796 ranges.sort_by_key(|range| range.start);
2797 log::info!("Setting ranges: {:?}", row_ranges(&ranges));
2798 let (created, _) = multibuffer.update(cx, |multibuffer, cx| {
2799 multibuffer.set_excerpts_for_path(
2800 PathKey::for_buffer(&buf, cx),
2801 buf.clone(),
2802 ranges.clone(),
2803 2,
2804 cx,
2805 )
2806 });
2807
2808 assert_eq!(created.len(), ranges.len());
2809
2810 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2811 let mut last_end = None;
2812 let mut seen_ranges = Vec::default();
2813
2814 for (_, buf, range) in snapshot.excerpts() {
2815 let start = range.context.start.to_point(buf);
2816 let end = range.context.end.to_point(buf);
2817 seen_ranges.push(start..end);
2818
2819 if let Some(last_end) = last_end.take() {
2820 assert!(
2821 start > last_end,
2822 "multibuffer has out-of-order ranges: {:?}; {:?} <= {:?}",
2823 row_ranges(&seen_ranges),
2824 start,
2825 last_end
2826 )
2827 }
2828
2829 ranges.retain(|range| range.start < start || range.end > end);
2830
2831 last_end = Some(end)
2832 }
2833
2834 assert!(
2835 ranges.is_empty(),
2836 "multibuffer {:?} did not include all ranges: {:?}",
2837 row_ranges(&seen_ranges),
2838 row_ranges(&ranges)
2839 );
2840 }
2841}
2842
2843#[gpui::test(iterations = 100)]
2844async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
2845 let operations = env::var("OPERATIONS")
2846 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2847 .unwrap_or(10);
2848 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2849 let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2850 let mut base_texts: HashMap<BufferId, String> = HashMap::default();
2851 let mut reference = ReferenceMultibuffer::default();
2852 let mut anchors = Vec::new();
2853 let mut old_versions = Vec::new();
2854 let mut needs_diff_calculation = false;
2855 let mut inverted_diff_main_buffers: HashMap<BufferId, Entity<BufferDiff>> = HashMap::default();
2856 for _ in 0..operations {
2857 match rng.random_range(0..100) {
2858 0..=14 if !buffers.is_empty() => {
2859 let buffer = buffers.choose(&mut rng).unwrap();
2860 buffer.update(cx, |buf, cx| {
2861 let edit_count = rng.random_range(1..5);
2862 buf.randomly_edit(&mut rng, edit_count, cx);
2863 log::info!("buffer text:\n{}", buf.text());
2864 needs_diff_calculation = true;
2865 });
2866 cx.update(|cx| reference.diffs_updated(cx));
2867 }
2868 15..=19 if !reference.excerpts.is_empty() => {
2869 multibuffer.update(cx, |multibuffer, cx| {
2870 let ids = multibuffer.excerpt_ids();
2871 let mut excerpts = HashSet::default();
2872 for _ in 0..rng.random_range(0..ids.len()) {
2873 excerpts.extend(ids.choose(&mut rng).copied());
2874 }
2875
2876 let line_count = rng.random_range(0..5);
2877
2878 let excerpt_ixs = excerpts
2879 .iter()
2880 .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2881 .collect::<Vec<_>>();
2882 log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2883 multibuffer.expand_excerpts(
2884 excerpts.iter().cloned(),
2885 line_count,
2886 ExpandExcerptDirection::UpAndDown,
2887 cx,
2888 );
2889
2890 reference.expand_excerpts(&excerpts, line_count, cx);
2891 });
2892 }
2893 20..=29 if !reference.excerpts.is_empty() => {
2894 let mut ids_to_remove = vec![];
2895 for _ in 0..rng.random_range(1..=3) {
2896 let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2897 break;
2898 };
2899 let id = excerpt.id;
2900 cx.update(|cx| reference.remove_excerpt(id, cx));
2901 ids_to_remove.push(id);
2902 }
2903 let snapshot =
2904 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2905 ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2906 drop(snapshot);
2907 multibuffer.update(cx, |multibuffer, cx| {
2908 multibuffer.remove_excerpts(ids_to_remove, cx)
2909 });
2910 }
2911 30..=39 if !reference.excerpts.is_empty() => {
2912 let multibuffer =
2913 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2914 let offset = multibuffer.clip_offset(
2915 MultiBufferOffset(rng.random_range(0..=multibuffer.len().0)),
2916 Bias::Left,
2917 );
2918 let bias = if rng.random() {
2919 Bias::Left
2920 } else {
2921 Bias::Right
2922 };
2923 log::info!("Creating anchor at {} with bias {:?}", offset.0, bias);
2924 anchors.push(multibuffer.anchor_at(offset, bias));
2925 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2926 }
2927 40..=44 if !anchors.is_empty() => {
2928 let multibuffer =
2929 multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2930 let prev_len = anchors.len();
2931 anchors = multibuffer
2932 .refresh_anchors(&anchors)
2933 .into_iter()
2934 .map(|a| a.1)
2935 .collect();
2936
2937 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2938 // overshoot its boundaries.
2939 assert_eq!(anchors.len(), prev_len);
2940 for anchor in &anchors {
2941 if anchor.excerpt_id == ExcerptId::min()
2942 || anchor.excerpt_id == ExcerptId::max()
2943 {
2944 continue;
2945 }
2946
2947 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2948 assert_eq!(excerpt.id, anchor.excerpt_id);
2949 assert!(excerpt.contains(anchor));
2950 }
2951 }
2952 45..=55 if !reference.excerpts.is_empty() => {
2953 multibuffer.update(cx, |multibuffer, cx| {
2954 let snapshot = multibuffer.snapshot(cx);
2955 let excerpt_ix = rng.random_range(0..reference.excerpts.len());
2956 let excerpt = &reference.excerpts[excerpt_ix];
2957
2958 // Skip inverted excerpts - hunks can't be collapsed
2959 let buffer_id = excerpt.buffer.read(cx).remote_id();
2960 if reference.inverted_diffs.contains_key(&buffer_id) {
2961 return;
2962 }
2963
2964 let start = excerpt.range.start;
2965 let end = excerpt.range.end;
2966 let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2967 ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2968
2969 log::info!(
2970 "expanding diff hunks in range {:?} (excerpt id {:?}, index {excerpt_ix:?}, buffer id {:?})",
2971 range.to_offset(&snapshot),
2972 excerpt.id,
2973 buffer_id,
2974 );
2975 reference.expand_diff_hunks(excerpt.id, start..end, cx);
2976 multibuffer.expand_diff_hunks(vec![range], cx);
2977 });
2978 }
2979 56..=85 if needs_diff_calculation => {
2980 multibuffer.update(cx, |multibuffer, cx| {
2981 for buffer in multibuffer.all_buffers() {
2982 let snapshot = buffer.read(cx).snapshot();
2983 let buffer_id = snapshot.remote_id();
2984
2985 if let Some(diff) = multibuffer.diff_for(buffer_id) {
2986 diff.update(cx, |diff, cx| {
2987 log::info!("recalculating diff for buffer {:?}", buffer_id,);
2988 diff.recalculate_diff_sync(&snapshot.text, cx);
2989 });
2990 }
2991
2992 if let Some(inverted_diff) = inverted_diff_main_buffers.get(&buffer_id) {
2993 inverted_diff.update(cx, |diff, cx| {
2994 log::info!(
2995 "recalculating inverted diff for main buffer {:?}",
2996 buffer_id,
2997 );
2998 diff.recalculate_diff_sync(&snapshot.text, cx);
2999 });
3000 }
3001 }
3002 reference.diffs_updated(cx);
3003 needs_diff_calculation = false;
3004 });
3005 }
3006 _ => {
3007 // Decide if we're creating a new buffer or reusing an existing one
3008 let create_new_buffer = buffers.is_empty() || rng.random_bool(0.4);
3009
3010 let prev_excerpt_ix = rng.random_range(0..=reference.excerpts.len());
3011 let prev_excerpt_id = reference
3012 .excerpts
3013 .get(prev_excerpt_ix)
3014 .map_or(ExcerptId::max(), |e| e.id);
3015 let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
3016
3017 let (excerpt_buffer, diff, inverted_main_buffer) = if create_new_buffer {
3018 let create_inverted = rng.random_bool(0.3);
3019
3020 if create_inverted {
3021 let mut main_buffer_text = util::RandomCharIter::new(&mut rng)
3022 .take(256)
3023 .collect::<String>();
3024 let main_buffer = cx.new(|cx| Buffer::local(main_buffer_text.clone(), cx));
3025 text::LineEnding::normalize(&mut main_buffer_text);
3026 let main_buffer_id =
3027 main_buffer.read_with(cx, |buffer, _| buffer.remote_id());
3028 base_texts.insert(main_buffer_id, main_buffer_text.clone());
3029 buffers.push(main_buffer.clone());
3030
3031 let diff = cx.new(|cx| {
3032 BufferDiff::new_with_base_text(
3033 &main_buffer_text,
3034 &main_buffer.read(cx).text_snapshot(),
3035 cx,
3036 )
3037 });
3038
3039 let base_text_buffer =
3040 diff.read_with(cx, |diff, _| diff.base_text_buffer());
3041
3042 // Track for recalculation when main buffer is edited
3043 inverted_diff_main_buffers.insert(main_buffer_id, diff.clone());
3044
3045 (base_text_buffer, diff, Some(main_buffer))
3046 } else {
3047 let mut base_text = util::RandomCharIter::new(&mut rng)
3048 .take(256)
3049 .collect::<String>();
3050
3051 let buffer_handle = cx.new(|cx| Buffer::local(base_text.clone(), cx));
3052 text::LineEnding::normalize(&mut base_text);
3053 let buffer_id = buffer_handle.read_with(cx, |buffer, _| buffer.remote_id());
3054 base_texts.insert(buffer_id, base_text.clone());
3055 buffers.push(buffer_handle.clone());
3056
3057 let diff = cx.new(|cx| {
3058 BufferDiff::new_with_base_text(
3059 &base_text,
3060 &buffer_handle.read(cx).text_snapshot(),
3061 cx,
3062 )
3063 });
3064
3065 (buffer_handle, diff, None)
3066 }
3067 } else {
3068 // Reuse an existing buffer
3069 let buffer_handle = buffers.choose(&mut rng).unwrap().clone();
3070 let buffer_id = buffer_handle.read_with(cx, |buffer, _| buffer.remote_id());
3071
3072 if let Some(diff) = inverted_diff_main_buffers.get(&buffer_id) {
3073 let base_text_buffer =
3074 diff.read_with(cx, |diff, _| diff.base_text_buffer());
3075 (base_text_buffer, diff.clone(), Some(buffer_handle))
3076 } else {
3077 // Get existing diff or create new one for regular buffer
3078 let diff = multibuffer
3079 .read_with(cx, |mb, _| mb.diff_for(buffer_id))
3080 .unwrap_or_else(|| {
3081 let base_text = base_texts.get(&buffer_id).unwrap();
3082 cx.new(|cx| {
3083 BufferDiff::new_with_base_text(
3084 base_text,
3085 &buffer_handle.read(cx).text_snapshot(),
3086 cx,
3087 )
3088 })
3089 });
3090 (buffer_handle, diff, None)
3091 }
3092 };
3093
3094 let (range, anchor_range) = excerpt_buffer.read_with(cx, |buffer, _| {
3095 let end_row = rng.random_range(0..=buffer.max_point().row);
3096 let start_row = rng.random_range(0..=end_row);
3097 let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
3098 let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
3099 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3100
3101 log::info!(
3102 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3103 excerpt_ix,
3104 reference.excerpts.len(),
3105 buffer.remote_id(),
3106 buffer.text(),
3107 start_ix..end_ix,
3108 &buffer.text()[start_ix..end_ix]
3109 );
3110
3111 (start_ix..end_ix, anchor_range)
3112 });
3113
3114 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3115 multibuffer
3116 .insert_excerpts_after(
3117 prev_excerpt_id,
3118 excerpt_buffer.clone(),
3119 [ExcerptRange::new(range.clone())],
3120 cx,
3121 )
3122 .pop()
3123 .unwrap()
3124 });
3125
3126 reference.insert_excerpt_after(
3127 prev_excerpt_id,
3128 excerpt_id,
3129 (excerpt_buffer.clone(), anchor_range),
3130 );
3131
3132 let excerpt_buffer_id =
3133 excerpt_buffer.read_with(cx, |buffer, _| buffer.remote_id());
3134 multibuffer.update(cx, |multibuffer, cx| {
3135 if multibuffer.diff_for(excerpt_buffer_id).is_none() {
3136 if let Some(main_buffer) = inverted_main_buffer {
3137 reference.add_inverted_diff(diff.clone(), main_buffer.clone(), cx);
3138 multibuffer.add_inverted_diff(diff, main_buffer, cx);
3139 } else {
3140 reference.add_diff(diff.clone(), cx);
3141 multibuffer.add_diff(diff, cx);
3142 }
3143 }
3144 });
3145 }
3146 }
3147
3148 if rng.random_bool(0.3) {
3149 multibuffer.update(cx, |multibuffer, cx| {
3150 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3151 })
3152 }
3153
3154 multibuffer.read_with(cx, |multibuffer, cx| {
3155 check_multibuffer(multibuffer, &reference, &anchors, cx, &mut rng);
3156 });
3157 }
3158 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3159 for (old_snapshot, subscription) in old_versions {
3160 check_multibuffer_edits(&snapshot, &old_snapshot, subscription);
3161 }
3162}
3163
3164fn check_multibuffer(
3165 multibuffer: &MultiBuffer,
3166 reference: &ReferenceMultibuffer,
3167 anchors: &[Anchor],
3168 cx: &App,
3169 rng: &mut StdRng,
3170) {
3171 let snapshot = multibuffer.snapshot(cx);
3172 let actual_text = snapshot.text();
3173 let actual_boundary_rows = snapshot
3174 .excerpt_boundaries_in_range(MultiBufferOffset(0)..)
3175 .map(|b| b.row)
3176 .collect::<HashSet<_>>();
3177 let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3178
3179 let (expected_text, expected_row_infos, expected_boundary_rows) =
3180 reference.expected_content(cx);
3181
3182 let has_diff = actual_row_infos
3183 .iter()
3184 .any(|info| info.diff_status.is_some())
3185 || expected_row_infos
3186 .iter()
3187 .any(|info| info.diff_status.is_some());
3188 let actual_diff = format_diff(
3189 &actual_text,
3190 &actual_row_infos,
3191 &actual_boundary_rows,
3192 Some(has_diff),
3193 );
3194 let expected_diff = format_diff(
3195 &expected_text,
3196 &expected_row_infos,
3197 &expected_boundary_rows,
3198 Some(has_diff),
3199 );
3200
3201 log::info!("Multibuffer content:\n{}", actual_diff);
3202
3203 assert_eq!(
3204 actual_row_infos.len(),
3205 actual_text.split('\n').count(),
3206 "line count: {}",
3207 actual_text.split('\n').count()
3208 );
3209 pretty_assertions::assert_eq!(actual_diff, expected_diff);
3210 pretty_assertions::assert_eq!(actual_text, expected_text);
3211 pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
3212
3213 for _ in 0..5 {
3214 let start_row = rng.random_range(0..=expected_row_infos.len());
3215 assert_eq!(
3216 snapshot
3217 .row_infos(MultiBufferRow(start_row as u32))
3218 .collect::<Vec<_>>(),
3219 &expected_row_infos[start_row..],
3220 "buffer_rows({})",
3221 start_row
3222 );
3223 }
3224
3225 assert_eq!(
3226 snapshot.widest_line_number(),
3227 expected_row_infos
3228 .into_iter()
3229 .filter_map(|info| {
3230 // For inverted diffs, deleted rows are visible and should be counted.
3231 // Only filter out deleted rows that are NOT from inverted diffs.
3232 let is_inverted_diff = info
3233 .buffer_id
3234 .is_some_and(|id| reference.inverted_diffs.contains_key(&id));
3235 if info.diff_status.is_some_and(|status| status.is_deleted()) && !is_inverted_diff {
3236 None
3237 } else {
3238 info.buffer_row
3239 }
3240 })
3241 .max()
3242 .unwrap()
3243 + 1
3244 );
3245 let reference_ranges = reference
3246 .excerpts
3247 .iter()
3248 .map(|excerpt| {
3249 (
3250 excerpt.id,
3251 excerpt.range.to_offset(&excerpt.buffer.read(cx).snapshot()),
3252 )
3253 })
3254 .collect::<HashMap<_, _>>();
3255 for i in 0..snapshot.len().0 {
3256 let excerpt = snapshot
3257 .excerpt_containing(MultiBufferOffset(i)..MultiBufferOffset(i))
3258 .unwrap();
3259 assert_eq!(
3260 excerpt.buffer_range().start.0..excerpt.buffer_range().end.0,
3261 reference_ranges[&excerpt.id()]
3262 );
3263 }
3264
3265 assert_consistent_line_numbers(&snapshot);
3266 assert_position_translation(&snapshot);
3267
3268 for (row, line) in expected_text.split('\n').enumerate() {
3269 assert_eq!(
3270 snapshot.line_len(MultiBufferRow(row as u32)),
3271 line.len() as u32,
3272 "line_len({}).",
3273 row
3274 );
3275 }
3276
3277 let text_rope = Rope::from(expected_text.as_str());
3278 for _ in 0..10 {
3279 let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
3280 let start_ix = text_rope.clip_offset(rng.random_range(0..=end_ix), Bias::Left);
3281
3282 let text_for_range = snapshot
3283 .text_for_range(MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix))
3284 .collect::<String>();
3285 assert_eq!(
3286 text_for_range,
3287 &expected_text[start_ix..end_ix],
3288 "incorrect text for range {:?}",
3289 start_ix..end_ix
3290 );
3291
3292 let expected_summary =
3293 MBTextSummary::from(TextSummary::from(&expected_text[start_ix..end_ix]));
3294 assert_eq!(
3295 snapshot.text_summary_for_range::<MBTextSummary, _>(
3296 MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix)
3297 ),
3298 expected_summary,
3299 "incorrect summary for range {:?}",
3300 start_ix..end_ix
3301 );
3302 }
3303
3304 // Anchor resolution
3305 let summaries = snapshot.summaries_for_anchors::<MultiBufferOffset, _>(anchors);
3306 assert_eq!(anchors.len(), summaries.len());
3307 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
3308 assert!(resolved_offset <= snapshot.len());
3309 assert_eq!(
3310 snapshot.summary_for_anchor::<MultiBufferOffset>(anchor),
3311 resolved_offset,
3312 "anchor: {:?}",
3313 anchor
3314 );
3315 }
3316
3317 for _ in 0..10 {
3318 let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
3319 assert_eq!(
3320 snapshot
3321 .reversed_chars_at(MultiBufferOffset(end_ix))
3322 .collect::<String>(),
3323 expected_text[..end_ix].chars().rev().collect::<String>(),
3324 );
3325 }
3326
3327 for _ in 0..10 {
3328 let end_ix = rng.random_range(0..=text_rope.len());
3329 let end_ix = text_rope.floor_char_boundary(end_ix);
3330 let start_ix = rng.random_range(0..=end_ix);
3331 let start_ix = text_rope.floor_char_boundary(start_ix);
3332 assert_eq!(
3333 snapshot
3334 .bytes_in_range(MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix))
3335 .flatten()
3336 .copied()
3337 .collect::<Vec<_>>(),
3338 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3339 "bytes_in_range({:?})",
3340 start_ix..end_ix,
3341 );
3342 }
3343}
3344
3345fn check_multibuffer_edits(
3346 snapshot: &MultiBufferSnapshot,
3347 old_snapshot: &MultiBufferSnapshot,
3348 subscription: Subscription<MultiBufferOffset>,
3349) {
3350 let edits = subscription.consume().into_inner();
3351
3352 log::info!(
3353 "applying subscription edits to old text: {:?}: {:#?}",
3354 old_snapshot.text(),
3355 edits,
3356 );
3357
3358 let mut text = old_snapshot.text();
3359 for edit in edits {
3360 let new_text: String = snapshot
3361 .text_for_range(edit.new.start..edit.new.end)
3362 .collect();
3363 text.replace_range(
3364 (edit.new.start.0..edit.new.start.0 + (edit.old.end.0 - edit.old.start.0)).clone(),
3365 &new_text,
3366 );
3367 pretty_assertions::assert_eq!(
3368 &text[0..edit.new.end.0],
3369 snapshot
3370 .text_for_range(MultiBufferOffset(0)..edit.new.end)
3371 .collect::<String>()
3372 );
3373 }
3374 pretty_assertions::assert_eq!(text, snapshot.text());
3375}
3376
3377#[gpui::test]
3378fn test_history(cx: &mut App) {
3379 let test_settings = SettingsStore::test(cx);
3380 cx.set_global(test_settings);
3381
3382 let group_interval: Duration = Duration::from_millis(1);
3383 let buffer_1 = cx.new(|cx| {
3384 let mut buf = Buffer::local("1234", cx);
3385 buf.set_group_interval(group_interval);
3386 buf
3387 });
3388 let buffer_2 = cx.new(|cx| {
3389 let mut buf = Buffer::local("5678", cx);
3390 buf.set_group_interval(group_interval);
3391 buf
3392 });
3393 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
3394 multibuffer.update(cx, |this, _| {
3395 this.set_group_interval(group_interval);
3396 });
3397 multibuffer.update(cx, |multibuffer, cx| {
3398 multibuffer.push_excerpts(
3399 buffer_1.clone(),
3400 [ExcerptRange::new(0..buffer_1.read(cx).len())],
3401 cx,
3402 );
3403 multibuffer.push_excerpts(
3404 buffer_2.clone(),
3405 [ExcerptRange::new(0..buffer_2.read(cx).len())],
3406 cx,
3407 );
3408 });
3409
3410 let mut now = Instant::now();
3411
3412 multibuffer.update(cx, |multibuffer, cx| {
3413 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
3414 multibuffer.edit(
3415 [
3416 (Point::new(0, 0)..Point::new(0, 0), "A"),
3417 (Point::new(1, 0)..Point::new(1, 0), "A"),
3418 ],
3419 None,
3420 cx,
3421 );
3422 multibuffer.edit(
3423 [
3424 (Point::new(0, 1)..Point::new(0, 1), "B"),
3425 (Point::new(1, 1)..Point::new(1, 1), "B"),
3426 ],
3427 None,
3428 cx,
3429 );
3430 multibuffer.end_transaction_at(now, cx);
3431 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3432
3433 // Verify edited ranges for transaction 1
3434 assert_eq!(
3435 multibuffer.edited_ranges_for_transaction(transaction_1, cx),
3436 &[
3437 Point::new(0, 0)..Point::new(0, 2),
3438 Point::new(1, 0)..Point::new(1, 2)
3439 ]
3440 );
3441
3442 // Edit buffer 1 through the multibuffer
3443 now += 2 * group_interval;
3444 multibuffer.start_transaction_at(now, cx);
3445 multibuffer.edit(
3446 [(MultiBufferOffset(2)..MultiBufferOffset(2), "C")],
3447 None,
3448 cx,
3449 );
3450 multibuffer.end_transaction_at(now, cx);
3451 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3452
3453 // Edit buffer 1 independently
3454 buffer_1.update(cx, |buffer_1, cx| {
3455 buffer_1.start_transaction_at(now);
3456 buffer_1.edit([(3..3, "D")], None, cx);
3457 buffer_1.end_transaction_at(now, cx);
3458
3459 now += 2 * group_interval;
3460 buffer_1.start_transaction_at(now);
3461 buffer_1.edit([(4..4, "E")], None, cx);
3462 buffer_1.end_transaction_at(now, cx);
3463 });
3464 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3465
3466 // An undo in the multibuffer undoes the multibuffer transaction
3467 // and also any individual buffer edits that have occurred since
3468 // that transaction.
3469 multibuffer.undo(cx);
3470 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3471
3472 multibuffer.undo(cx);
3473 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3474
3475 multibuffer.redo(cx);
3476 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3477
3478 multibuffer.redo(cx);
3479 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3480
3481 // Undo buffer 2 independently.
3482 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
3483 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
3484
3485 // An undo in the multibuffer undoes the components of the
3486 // the last multibuffer transaction that are not already undone.
3487 multibuffer.undo(cx);
3488 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
3489
3490 multibuffer.undo(cx);
3491 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3492
3493 multibuffer.redo(cx);
3494 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3495
3496 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3497 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3498
3499 // Redo stack gets cleared after an edit.
3500 now += 2 * group_interval;
3501 multibuffer.start_transaction_at(now, cx);
3502 multibuffer.edit(
3503 [(MultiBufferOffset(0)..MultiBufferOffset(0), "X")],
3504 None,
3505 cx,
3506 );
3507 multibuffer.end_transaction_at(now, cx);
3508 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3509 multibuffer.redo(cx);
3510 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3511 multibuffer.undo(cx);
3512 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3513 multibuffer.undo(cx);
3514 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3515
3516 // Transactions can be grouped manually.
3517 multibuffer.redo(cx);
3518 multibuffer.redo(cx);
3519 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3520 multibuffer.group_until_transaction(transaction_1, cx);
3521 multibuffer.undo(cx);
3522 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3523 multibuffer.redo(cx);
3524 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3525 });
3526}
3527
3528#[gpui::test]
3529async fn test_enclosing_indent(cx: &mut TestAppContext) {
3530 async fn enclosing_indent(
3531 text: &str,
3532 buffer_row: u32,
3533 cx: &mut TestAppContext,
3534 ) -> Option<(Range<u32>, LineIndent)> {
3535 let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
3536 let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
3537 let (range, indent) = snapshot
3538 .enclosing_indent(MultiBufferRow(buffer_row))
3539 .await?;
3540 Some((range.start.0..range.end.0, indent))
3541 }
3542
3543 assert_eq!(
3544 enclosing_indent(
3545 indoc!(
3546 "
3547 fn b() {
3548 if c {
3549 let d = 2;
3550 }
3551 }
3552 "
3553 ),
3554 1,
3555 cx,
3556 )
3557 .await,
3558 Some((
3559 1..2,
3560 LineIndent {
3561 tabs: 0,
3562 spaces: 4,
3563 line_blank: false,
3564 }
3565 ))
3566 );
3567
3568 assert_eq!(
3569 enclosing_indent(
3570 indoc!(
3571 "
3572 fn b() {
3573 if c {
3574 let d = 2;
3575 }
3576 }
3577 "
3578 ),
3579 2,
3580 cx,
3581 )
3582 .await,
3583 Some((
3584 1..2,
3585 LineIndent {
3586 tabs: 0,
3587 spaces: 4,
3588 line_blank: false,
3589 }
3590 ))
3591 );
3592
3593 assert_eq!(
3594 enclosing_indent(
3595 indoc!(
3596 "
3597 fn b() {
3598 if c {
3599 let d = 2;
3600
3601 let e = 5;
3602 }
3603 }
3604 "
3605 ),
3606 3,
3607 cx,
3608 )
3609 .await,
3610 Some((
3611 1..4,
3612 LineIndent {
3613 tabs: 0,
3614 spaces: 4,
3615 line_blank: false,
3616 }
3617 ))
3618 );
3619}
3620
3621#[gpui::test]
3622async fn test_summaries_for_anchors(cx: &mut TestAppContext) {
3623 let base_text_1 = indoc!(
3624 "
3625 bar
3626 "
3627 );
3628 let text_1 = indoc!(
3629 "
3630 BAR
3631 "
3632 );
3633 let base_text_2 = indoc!(
3634 "
3635 foo
3636 "
3637 );
3638 let text_2 = indoc!(
3639 "
3640 FOO
3641 "
3642 );
3643
3644 let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3645 let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
3646 let diff_1 = cx.new(|cx| {
3647 BufferDiff::new_with_base_text(base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
3648 });
3649 let diff_2 = cx.new(|cx| {
3650 BufferDiff::new_with_base_text(base_text_2, &buffer_2.read(cx).text_snapshot(), cx)
3651 });
3652 cx.run_until_parked();
3653
3654 let mut ids = vec![];
3655 let multibuffer = cx.new(|cx| {
3656 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3657 multibuffer.set_all_diff_hunks_expanded(cx);
3658 ids.extend(multibuffer.push_excerpts(
3659 buffer_1.clone(),
3660 [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3661 cx,
3662 ));
3663 ids.extend(multibuffer.push_excerpts(
3664 buffer_2.clone(),
3665 [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3666 cx,
3667 ));
3668 multibuffer.add_diff(diff_1.clone(), cx);
3669 multibuffer.add_diff(diff_2.clone(), cx);
3670 multibuffer
3671 });
3672
3673 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3674 (multibuffer.snapshot(cx), multibuffer.subscribe())
3675 });
3676
3677 assert_new_snapshot(
3678 &multibuffer,
3679 &mut snapshot,
3680 &mut subscription,
3681 cx,
3682 indoc!(
3683 "
3684 - bar
3685 + BAR
3686
3687 - foo
3688 + FOO
3689 "
3690 ),
3691 );
3692
3693 let anchor_1 = Anchor::in_buffer(ids[0], text::Anchor::MIN);
3694 let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3695 assert_eq!(point_1, Point::new(0, 0));
3696
3697 let anchor_2 = Anchor::in_buffer(ids[1], text::Anchor::MIN);
3698 let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3699 assert_eq!(point_2, Point::new(3, 0));
3700}
3701
3702#[gpui::test]
3703async fn test_trailing_deletion_without_newline(cx: &mut TestAppContext) {
3704 let base_text_1 = "one\ntwo".to_owned();
3705 let text_1 = "one\n".to_owned();
3706
3707 let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3708 let diff_1 = cx.new(|cx| {
3709 BufferDiff::new_with_base_text(&base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
3710 });
3711 cx.run_until_parked();
3712
3713 let multibuffer = cx.new(|cx| {
3714 let mut multibuffer = MultiBuffer::singleton(buffer_1.clone(), cx);
3715 multibuffer.add_diff(diff_1.clone(), cx);
3716 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
3717 multibuffer
3718 });
3719
3720 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3721 (multibuffer.snapshot(cx), multibuffer.subscribe())
3722 });
3723
3724 assert_new_snapshot(
3725 &multibuffer,
3726 &mut snapshot,
3727 &mut subscription,
3728 cx,
3729 indoc!(
3730 "
3731 one
3732 - two
3733 "
3734 ),
3735 );
3736
3737 assert_eq!(snapshot.max_point(), Point::new(2, 0));
3738 assert_eq!(snapshot.len().0, 8);
3739
3740 assert_eq!(
3741 snapshot
3742 .dimensions_from_points::<Point>([Point::new(2, 0)])
3743 .collect::<Vec<_>>(),
3744 vec![Point::new(2, 0)]
3745 );
3746
3747 let (_, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3748 assert_eq!(translated_offset.0, "one\n".len());
3749 let (_, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3750 assert_eq!(translated_point, Point::new(1, 0));
3751
3752 // The same, for an excerpt that's not at the end of the multibuffer.
3753
3754 let text_2 = "foo\n".to_owned();
3755 let buffer_2 = cx.new(|cx| Buffer::local(&text_2, cx));
3756 multibuffer.update(cx, |multibuffer, cx| {
3757 multibuffer.push_excerpts(
3758 buffer_2.clone(),
3759 [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
3760 cx,
3761 );
3762 });
3763
3764 assert_new_snapshot(
3765 &multibuffer,
3766 &mut snapshot,
3767 &mut subscription,
3768 cx,
3769 indoc!(
3770 "
3771 one
3772 - two
3773
3774 foo
3775 "
3776 ),
3777 );
3778
3779 assert_eq!(
3780 snapshot
3781 .dimensions_from_points::<Point>([Point::new(2, 0)])
3782 .collect::<Vec<_>>(),
3783 vec![Point::new(2, 0)]
3784 );
3785
3786 let buffer_1_id = buffer_1.read_with(cx, |buffer_1, _| buffer_1.remote_id());
3787 let (buffer, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3788 assert_eq!(buffer.remote_id(), buffer_1_id);
3789 assert_eq!(translated_offset.0, "one\n".len());
3790 let (buffer, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3791 assert_eq!(buffer.remote_id(), buffer_1_id);
3792 assert_eq!(translated_point, Point::new(1, 0));
3793}
3794
3795fn format_diff(
3796 text: &str,
3797 row_infos: &Vec<RowInfo>,
3798 boundary_rows: &HashSet<MultiBufferRow>,
3799 has_diff: Option<bool>,
3800) -> String {
3801 let has_diff =
3802 has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3803 text.split('\n')
3804 .enumerate()
3805 .zip(row_infos)
3806 .map(|((ix, line), info)| {
3807 let marker = match info.diff_status.map(|status| status.kind) {
3808 Some(DiffHunkStatusKind::Added) => "+ ",
3809 Some(DiffHunkStatusKind::Deleted) => "- ",
3810 Some(DiffHunkStatusKind::Modified) => unreachable!(),
3811 None => {
3812 if has_diff && !line.is_empty() {
3813 " "
3814 } else {
3815 ""
3816 }
3817 }
3818 };
3819 let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3820 if has_diff {
3821 " ----------\n"
3822 } else {
3823 "---------\n"
3824 }
3825 } else {
3826 ""
3827 };
3828 let expand = info
3829 .expand_info
3830 .map(|expand_info| match expand_info.direction {
3831 ExpandExcerptDirection::Up => " [↑]",
3832 ExpandExcerptDirection::Down => " [↓]",
3833 ExpandExcerptDirection::UpAndDown => " [↕]",
3834 })
3835 .unwrap_or_default();
3836
3837 format!("{boundary_row}{marker}{line}{expand}")
3838 // let mbr = info
3839 // .multibuffer_row
3840 // .map(|row| format!("{:0>3}", row.0))
3841 // .unwrap_or_else(|| "???".to_string());
3842 // let byte_range = format!("{byte_range_start:0>3}..{byte_range_end:0>3}");
3843 // format!("{boundary_row}Row: {mbr}, Bytes: {byte_range} | {marker}{line}{expand}")
3844 })
3845 .collect::<Vec<_>>()
3846 .join("\n")
3847}
3848
3849// fn format_transforms(snapshot: &MultiBufferSnapshot) -> String {
3850// snapshot
3851// .diff_transforms
3852// .iter()
3853// .map(|transform| {
3854// let (kind, summary) = match transform {
3855// DiffTransform::DeletedHunk { summary, .. } => (" Deleted", (*summary).into()),
3856// DiffTransform::FilteredInsertedHunk { summary, .. } => (" Filtered", *summary),
3857// DiffTransform::InsertedHunk { summary, .. } => (" Inserted", *summary),
3858// DiffTransform::Unmodified { summary, .. } => ("Unmodified", *summary),
3859// };
3860// format!("{kind}(len: {}, lines: {:?})", summary.len, summary.lines)
3861// })
3862// .join("\n")
3863// }
3864
3865// fn format_excerpts(snapshot: &MultiBufferSnapshot) -> String {
3866// snapshot
3867// .excerpts
3868// .iter()
3869// .map(|excerpt| {
3870// format!(
3871// "Excerpt(buffer_range = {:?}, lines = {:?}, has_trailing_newline = {:?})",
3872// excerpt.range.context.to_point(&excerpt.buffer),
3873// excerpt.text_summary.lines,
3874// excerpt.has_trailing_newline
3875// )
3876// })
3877// .join("\n")
3878// }
3879
3880#[gpui::test]
3881async fn test_inverted_diff_hunk_invalidation_on_main_buffer_edit(cx: &mut TestAppContext) {
3882 let text = "one\ntwo\nthree\n";
3883 let base_text = "one\nTWO\nthree\n";
3884
3885 let buffer = cx.new(|cx| Buffer::local(text, cx));
3886 let diff = cx
3887 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
3888 cx.run_until_parked();
3889
3890 let base_text_buffer = diff.read_with(cx, |diff, _| diff.base_text_buffer());
3891
3892 let multibuffer = cx.new(|cx| {
3893 let mut multibuffer = MultiBuffer::singleton(base_text_buffer.clone(), cx);
3894 multibuffer.add_inverted_diff(diff.clone(), buffer.clone(), cx);
3895 multibuffer
3896 });
3897
3898 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3899 (multibuffer.snapshot(cx), multibuffer.subscribe())
3900 });
3901
3902 assert_new_snapshot(
3903 &multibuffer,
3904 &mut snapshot,
3905 &mut subscription,
3906 cx,
3907 indoc!(
3908 "
3909 one
3910 - TWO
3911 three
3912 "
3913 ),
3914 );
3915
3916 buffer.update(cx, |buffer, cx| {
3917 buffer.edit([(3..5, "")], None, cx);
3918 });
3919 cx.run_until_parked();
3920
3921 assert_new_snapshot(
3922 &multibuffer,
3923 &mut snapshot,
3924 &mut subscription,
3925 cx,
3926 indoc!(
3927 "
3928 one
3929 TWO
3930 three
3931 "
3932 ),
3933 );
3934}
3935
3936#[gpui::test]
3937async fn test_singleton_with_inverted_diff(cx: &mut TestAppContext) {
3938 let text = indoc!(
3939 "
3940 ZERO
3941 one
3942 TWO
3943 three
3944 six
3945 "
3946 );
3947 let base_text = indoc!(
3948 "
3949 one
3950 two
3951 three
3952 four
3953 five
3954 six
3955 "
3956 );
3957
3958 let buffer = cx.new(|cx| Buffer::local(text, cx));
3959 let diff = cx
3960 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
3961 cx.run_until_parked();
3962
3963 let base_text_buffer = diff.read_with(cx, |diff, _| diff.base_text_buffer());
3964
3965 let multibuffer = cx.new(|cx| {
3966 let mut multibuffer = MultiBuffer::singleton(base_text_buffer.clone(), cx);
3967 multibuffer.set_all_diff_hunks_expanded(cx);
3968 multibuffer.add_inverted_diff(diff.clone(), buffer.clone(), cx);
3969 multibuffer
3970 });
3971
3972 let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3973 (multibuffer.snapshot(cx), multibuffer.subscribe())
3974 });
3975
3976 assert_eq!(snapshot.text(), base_text);
3977 assert_new_snapshot(
3978 &multibuffer,
3979 &mut snapshot,
3980 &mut subscription,
3981 cx,
3982 indoc!(
3983 "
3984 one
3985 - two
3986 three
3987 - four
3988 - five
3989 six
3990 "
3991 ),
3992 );
3993
3994 buffer.update(cx, |buffer, cx| {
3995 buffer.edit_via_marked_text(
3996 indoc!(
3997 "
3998 ZERO
3999 one
4000 «<inserted>»W«O
4001 T»hree
4002 six
4003 "
4004 ),
4005 None,
4006 cx,
4007 );
4008 });
4009 cx.run_until_parked();
4010 let update = diff
4011 .update(cx, |diff, cx| {
4012 diff.update_diff(
4013 buffer.read(cx).text_snapshot(),
4014 Some(base_text.into()),
4015 false,
4016 None,
4017 cx,
4018 )
4019 })
4020 .await;
4021 diff.update(cx, |diff, cx| {
4022 diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), cx)
4023 })
4024 .await;
4025 cx.run_until_parked();
4026
4027 assert_new_snapshot(
4028 &multibuffer,
4029 &mut snapshot,
4030 &mut subscription,
4031 cx,
4032 indoc! {
4033 "
4034 one
4035 - two
4036 - three
4037 - four
4038 - five
4039 six
4040 "
4041 },
4042 );
4043
4044 buffer.update(cx, |buffer, cx| {
4045 buffer.set_text("ZERO\nONE\nTWO\n", cx);
4046 });
4047 cx.run_until_parked();
4048 let update = diff
4049 .update(cx, |diff, cx| {
4050 diff.update_diff(
4051 buffer.read(cx).text_snapshot(),
4052 Some(base_text.into()),
4053 false,
4054 None,
4055 cx,
4056 )
4057 })
4058 .await;
4059 diff.update(cx, |diff, cx| {
4060 diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), cx)
4061 })
4062 .await;
4063 cx.run_until_parked();
4064
4065 assert_new_snapshot(
4066 &multibuffer,
4067 &mut snapshot,
4068 &mut subscription,
4069 cx,
4070 indoc! {
4071 "
4072 - one
4073 - two
4074 - three
4075 - four
4076 - five
4077 - six
4078 "
4079 },
4080 );
4081
4082 diff.update(cx, |diff, cx| {
4083 diff.set_base_text(
4084 Some("new base\n".into()),
4085 None,
4086 buffer.read(cx).text_snapshot(),
4087 cx,
4088 )
4089 })
4090 .await
4091 .unwrap();
4092 cx.run_until_parked();
4093
4094 assert_new_snapshot(
4095 &multibuffer,
4096 &mut snapshot,
4097 &mut subscription,
4098 cx,
4099 indoc! {"
4100 - new base
4101 "},
4102 );
4103}
4104
4105#[track_caller]
4106fn assert_excerpts_match(
4107 multibuffer: &Entity<MultiBuffer>,
4108 cx: &mut TestAppContext,
4109 expected: &str,
4110) {
4111 let mut output = String::new();
4112 multibuffer.read_with(cx, |multibuffer, cx| {
4113 for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
4114 output.push_str("-----\n");
4115 output.extend(buffer.text_for_range(range.context));
4116 if !output.ends_with('\n') {
4117 output.push('\n');
4118 }
4119 }
4120 });
4121 assert_eq!(output, expected);
4122}
4123
4124#[track_caller]
4125fn assert_new_snapshot(
4126 multibuffer: &Entity<MultiBuffer>,
4127 snapshot: &mut MultiBufferSnapshot,
4128 subscription: &mut Subscription<MultiBufferOffset>,
4129 cx: &mut TestAppContext,
4130 expected_diff: &str,
4131) {
4132 let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4133 let actual_text = new_snapshot.text();
4134 let line_infos = new_snapshot
4135 .row_infos(MultiBufferRow(0))
4136 .collect::<Vec<_>>();
4137 let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
4138 pretty_assertions::assert_eq!(actual_diff, expected_diff);
4139 check_edits(
4140 snapshot,
4141 &new_snapshot,
4142 &subscription.consume().into_inner(),
4143 );
4144 *snapshot = new_snapshot;
4145}
4146
4147#[track_caller]
4148fn check_edits(
4149 old_snapshot: &MultiBufferSnapshot,
4150 new_snapshot: &MultiBufferSnapshot,
4151 edits: &[Edit<MultiBufferOffset>],
4152) {
4153 let mut text = old_snapshot.text();
4154 let new_text = new_snapshot.text();
4155 for edit in edits.iter().rev() {
4156 if !text.is_char_boundary(edit.old.start.0)
4157 || !text.is_char_boundary(edit.old.end.0)
4158 || !new_text.is_char_boundary(edit.new.start.0)
4159 || !new_text.is_char_boundary(edit.new.end.0)
4160 {
4161 panic!(
4162 "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
4163 edits, text, new_text
4164 );
4165 }
4166
4167 text.replace_range(
4168 edit.old.start.0..edit.old.end.0,
4169 &new_text[edit.new.start.0..edit.new.end.0],
4170 );
4171 }
4172
4173 pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
4174}
4175
4176#[track_caller]
4177fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
4178 let full_text = snapshot.text();
4179 for ix in 0..full_text.len() {
4180 let mut chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4181 chunks.seek(MultiBufferOffset(ix)..snapshot.len());
4182 let tail = chunks.map(|chunk| chunk.text).collect::<String>();
4183 assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
4184 }
4185}
4186
4187#[track_caller]
4188fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
4189 let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
4190 for start_row in 1..all_line_numbers.len() {
4191 let line_numbers = snapshot
4192 .row_infos(MultiBufferRow(start_row as u32))
4193 .collect::<Vec<_>>();
4194 assert_eq!(
4195 line_numbers,
4196 all_line_numbers[start_row..],
4197 "start_row: {start_row}"
4198 );
4199 }
4200}
4201
4202#[track_caller]
4203fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
4204 let text = Rope::from(snapshot.text());
4205
4206 let mut left_anchors = Vec::new();
4207 let mut right_anchors = Vec::new();
4208 let mut offsets = Vec::new();
4209 let mut points = Vec::new();
4210 for offset in 0..=text.len() + 1 {
4211 let offset = MultiBufferOffset(offset);
4212 let clipped_left = snapshot.clip_offset(offset, Bias::Left);
4213 let clipped_right = snapshot.clip_offset(offset, Bias::Right);
4214 assert_eq!(
4215 clipped_left.0,
4216 text.clip_offset(offset.0, Bias::Left),
4217 "clip_offset({offset:?}, Left)"
4218 );
4219 assert_eq!(
4220 clipped_right.0,
4221 text.clip_offset(offset.0, Bias::Right),
4222 "clip_offset({offset:?}, Right)"
4223 );
4224 assert_eq!(
4225 snapshot.offset_to_point(clipped_left),
4226 text.offset_to_point(clipped_left.0),
4227 "offset_to_point({})",
4228 clipped_left.0
4229 );
4230 assert_eq!(
4231 snapshot.offset_to_point(clipped_right),
4232 text.offset_to_point(clipped_right.0),
4233 "offset_to_point({})",
4234 clipped_right.0
4235 );
4236 let anchor_after = snapshot.anchor_after(clipped_left);
4237 assert_eq!(
4238 anchor_after.to_offset(snapshot),
4239 clipped_left,
4240 "anchor_after({}).to_offset {anchor_after:?}",
4241 clipped_left.0
4242 );
4243 let anchor_before = snapshot.anchor_before(clipped_left);
4244 assert_eq!(
4245 anchor_before.to_offset(snapshot),
4246 clipped_left,
4247 "anchor_before({}).to_offset",
4248 clipped_left.0
4249 );
4250 left_anchors.push(anchor_before);
4251 right_anchors.push(anchor_after);
4252 offsets.push(clipped_left);
4253 points.push(text.offset_to_point(clipped_left.0));
4254 }
4255
4256 for row in 0..text.max_point().row {
4257 for column in 0..text.line_len(row) + 1 {
4258 let point = Point { row, column };
4259 let clipped_left = snapshot.clip_point(point, Bias::Left);
4260 let clipped_right = snapshot.clip_point(point, Bias::Right);
4261 assert_eq!(
4262 clipped_left,
4263 text.clip_point(point, Bias::Left),
4264 "clip_point({point:?}, Left)"
4265 );
4266 assert_eq!(
4267 clipped_right,
4268 text.clip_point(point, Bias::Right),
4269 "clip_point({point:?}, Right)"
4270 );
4271 assert_eq!(
4272 snapshot.point_to_offset(clipped_left).0,
4273 text.point_to_offset(clipped_left),
4274 "point_to_offset({clipped_left:?})"
4275 );
4276 assert_eq!(
4277 snapshot.point_to_offset(clipped_right).0,
4278 text.point_to_offset(clipped_right),
4279 "point_to_offset({clipped_right:?})"
4280 );
4281 }
4282 }
4283
4284 assert_eq!(
4285 snapshot.summaries_for_anchors::<MultiBufferOffset, _>(&left_anchors),
4286 offsets,
4287 "left_anchors <-> offsets"
4288 );
4289 assert_eq!(
4290 snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
4291 points,
4292 "left_anchors <-> points"
4293 );
4294 assert_eq!(
4295 snapshot.summaries_for_anchors::<MultiBufferOffset, _>(&right_anchors),
4296 offsets,
4297 "right_anchors <-> offsets"
4298 );
4299 assert_eq!(
4300 snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
4301 points,
4302 "right_anchors <-> points"
4303 );
4304
4305 for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
4306 for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
4307 if ix > 0 && *offset == MultiBufferOffset(252) && offset > &offsets[ix - 1] {
4308 let prev_anchor = left_anchors[ix - 1];
4309 assert!(
4310 anchor.cmp(&prev_anchor, snapshot).is_gt(),
4311 "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
4312 offsets[ix],
4313 offsets[ix - 1],
4314 );
4315 assert!(
4316 prev_anchor.cmp(anchor, snapshot).is_lt(),
4317 "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
4318 offsets[ix - 1],
4319 offsets[ix],
4320 );
4321 }
4322 }
4323 }
4324
4325 if let Some((buffer, offset)) = snapshot.point_to_buffer_offset(snapshot.max_point()) {
4326 assert!(offset.0 <= buffer.len());
4327 }
4328 if let Some((buffer, point, _)) = snapshot.point_to_buffer_point(snapshot.max_point()) {
4329 assert!(point <= buffer.max_point());
4330 }
4331}
4332
4333fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
4334 let max_row = snapshot.max_point().row;
4335 let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
4336 let text = text::Buffer::new(ReplicaId::LOCAL, buffer_id, snapshot.text());
4337 let mut line_indents = text
4338 .line_indents_in_row_range(0..max_row + 1)
4339 .collect::<Vec<_>>();
4340 for start_row in 0..snapshot.max_point().row {
4341 pretty_assertions::assert_eq!(
4342 snapshot
4343 .line_indents(MultiBufferRow(start_row), |_| true)
4344 .map(|(row, indent, _)| (row.0, indent))
4345 .collect::<Vec<_>>(),
4346 &line_indents[(start_row as usize)..],
4347 "line_indents({start_row})"
4348 );
4349 }
4350
4351 line_indents.reverse();
4352 pretty_assertions::assert_eq!(
4353 snapshot
4354 .reversed_line_indents(MultiBufferRow(max_row), |_| true)
4355 .map(|(row, indent, _)| (row.0, indent))
4356 .collect::<Vec<_>>(),
4357 &line_indents[..],
4358 "reversed_line_indents({max_row})"
4359 );
4360}
4361
4362#[gpui::test]
4363fn test_new_empty_buffer_uses_untitled_title(cx: &mut App) {
4364 let buffer = cx.new(|cx| Buffer::local("", cx));
4365 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4366
4367 assert_eq!(multibuffer.read(cx).title(cx), "untitled");
4368}
4369
4370#[gpui::test]
4371fn test_new_empty_buffer_uses_untitled_title_when_only_contains_whitespace(cx: &mut App) {
4372 let buffer = cx.new(|cx| Buffer::local("\n ", cx));
4373 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4374
4375 assert_eq!(multibuffer.read(cx).title(cx), "untitled");
4376}
4377
4378#[gpui::test]
4379fn test_new_empty_buffer_takes_first_line_for_title(cx: &mut App) {
4380 let buffer = cx.new(|cx| Buffer::local("Hello World\nSecond line", cx));
4381 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4382
4383 assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
4384}
4385
4386#[gpui::test]
4387fn test_new_empty_buffer_takes_trimmed_first_line_for_title(cx: &mut App) {
4388 let buffer = cx.new(|cx| Buffer::local("\nHello, World ", cx));
4389 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4390
4391 assert_eq!(multibuffer.read(cx).title(cx), "Hello, World");
4392}
4393
4394#[gpui::test]
4395fn test_new_empty_buffer_uses_truncated_first_line_for_title(cx: &mut App) {
4396 let title = "aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeee";
4397 let title_after = "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd";
4398 let buffer = cx.new(|cx| Buffer::local(title, cx));
4399 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4400
4401 assert_eq!(multibuffer.read(cx).title(cx), title_after);
4402}
4403
4404#[gpui::test]
4405fn test_new_empty_buffer_uses_truncated_first_line_for_title_after_merging_adjacent_spaces(
4406 cx: &mut App,
4407) {
4408 let title = "aaaaaaaaaabbbbbbbbbb ccccccccccddddddddddeeeeeeeeee";
4409 let title_after = "aaaaaaaaaabbbbbbbbbb ccccccccccddddddddd";
4410 let buffer = cx.new(|cx| Buffer::local(title, cx));
4411 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4412
4413 assert_eq!(multibuffer.read(cx).title(cx), title_after);
4414}
4415
4416#[gpui::test]
4417fn test_new_empty_buffers_title_can_be_set(cx: &mut App) {
4418 let buffer = cx.new(|cx| Buffer::local("Hello World", cx));
4419 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4420 assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
4421
4422 multibuffer.update(cx, |multibuffer, cx| {
4423 multibuffer.set_title("Hey".into(), cx)
4424 });
4425 assert_eq!(multibuffer.read(cx).title(cx), "Hey");
4426}
4427
4428#[gpui::test(iterations = 100)]
4429fn test_random_chunk_bitmaps(cx: &mut App, mut rng: StdRng) {
4430 let multibuffer = if rng.random() {
4431 let len = rng.random_range(0..10000);
4432 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
4433 let buffer = cx.new(|cx| Buffer::local(text, cx));
4434 cx.new(|cx| MultiBuffer::singleton(buffer, cx))
4435 } else {
4436 MultiBuffer::build_random(&mut rng, cx)
4437 };
4438
4439 let snapshot = multibuffer.read(cx).snapshot(cx);
4440
4441 let chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4442
4443 for chunk in chunks {
4444 let chunk_text = chunk.text;
4445 let chars_bitmap = chunk.chars;
4446 let tabs_bitmap = chunk.tabs;
4447
4448 if chunk_text.is_empty() {
4449 assert_eq!(
4450 chars_bitmap, 0,
4451 "Empty chunk should have empty chars bitmap"
4452 );
4453 assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
4454 continue;
4455 }
4456
4457 assert!(
4458 chunk_text.len() <= 128,
4459 "Chunk text length {} exceeds 128 bytes",
4460 chunk_text.len()
4461 );
4462
4463 // Verify chars bitmap
4464 let char_indices = chunk_text
4465 .char_indices()
4466 .map(|(i, _)| i)
4467 .collect::<Vec<_>>();
4468
4469 for byte_idx in 0..chunk_text.len() {
4470 let should_have_bit = char_indices.contains(&byte_idx);
4471 let has_bit = chars_bitmap & (1 << byte_idx) != 0;
4472
4473 if has_bit != should_have_bit {
4474 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4475 eprintln!("Char indices: {:?}", char_indices);
4476 eprintln!("Chars bitmap: {:#b}", chars_bitmap);
4477 }
4478
4479 assert_eq!(
4480 has_bit, should_have_bit,
4481 "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
4482 byte_idx, chunk_text, should_have_bit, has_bit
4483 );
4484 }
4485
4486 for (byte_idx, byte) in chunk_text.bytes().enumerate() {
4487 let is_tab = byte == b'\t';
4488 let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
4489
4490 if has_bit != is_tab {
4491 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4492 eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
4493 assert_eq!(
4494 has_bit, is_tab,
4495 "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
4496 byte_idx, chunk_text, byte as char, is_tab, has_bit
4497 );
4498 }
4499 }
4500 }
4501}
4502
4503#[gpui::test(iterations = 10)]
4504fn test_random_chunk_bitmaps_with_diffs(cx: &mut App, mut rng: StdRng) {
4505 let settings_store = SettingsStore::test(cx);
4506 cx.set_global(settings_store);
4507 use buffer_diff::BufferDiff;
4508 use util::RandomCharIter;
4509
4510 let multibuffer = if rng.random() {
4511 let len = rng.random_range(100..10000);
4512 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
4513 let buffer = cx.new(|cx| Buffer::local(text, cx));
4514 cx.new(|cx| MultiBuffer::singleton(buffer, cx))
4515 } else {
4516 MultiBuffer::build_random(&mut rng, cx)
4517 };
4518
4519 let _diff_count = rng.random_range(1..5);
4520 let mut diffs = Vec::new();
4521
4522 multibuffer.update(cx, |multibuffer, cx| {
4523 for buffer_id in multibuffer.excerpt_buffer_ids() {
4524 if rng.random_bool(0.7) {
4525 if let Some(buffer_handle) = multibuffer.buffer(buffer_id) {
4526 let buffer_text = buffer_handle.read(cx).text();
4527 let mut base_text = String::new();
4528
4529 for line in buffer_text.lines() {
4530 if rng.random_bool(0.3) {
4531 continue;
4532 } else if rng.random_bool(0.3) {
4533 let line_len = rng.random_range(0..50);
4534 let modified_line = RandomCharIter::new(&mut rng)
4535 .take(line_len)
4536 .collect::<String>();
4537 base_text.push_str(&modified_line);
4538 base_text.push('\n');
4539 } else {
4540 base_text.push_str(line);
4541 base_text.push('\n');
4542 }
4543 }
4544
4545 if rng.random_bool(0.5) {
4546 let extra_lines = rng.random_range(1..5);
4547 for _ in 0..extra_lines {
4548 let line_len = rng.random_range(0..50);
4549 let extra_line = RandomCharIter::new(&mut rng)
4550 .take(line_len)
4551 .collect::<String>();
4552 base_text.push_str(&extra_line);
4553 base_text.push('\n');
4554 }
4555 }
4556
4557 let diff = cx.new(|cx| {
4558 BufferDiff::new_with_base_text(
4559 &base_text,
4560 &buffer_handle.read(cx).text_snapshot(),
4561 cx,
4562 )
4563 });
4564 diffs.push(diff.clone());
4565 multibuffer.add_diff(diff, cx);
4566 }
4567 }
4568 }
4569 });
4570
4571 multibuffer.update(cx, |multibuffer, cx| {
4572 if rng.random_bool(0.5) {
4573 multibuffer.set_all_diff_hunks_expanded(cx);
4574 } else {
4575 let snapshot = multibuffer.snapshot(cx);
4576 let text = snapshot.text();
4577
4578 let mut ranges = Vec::new();
4579 for _ in 0..rng.random_range(1..5) {
4580 if snapshot.len().0 == 0 {
4581 break;
4582 }
4583
4584 let diff_size = rng.random_range(5..1000);
4585 let mut start = rng.random_range(0..snapshot.len().0);
4586
4587 while !text.is_char_boundary(start) {
4588 start = start.saturating_sub(1);
4589 }
4590
4591 let mut end = rng.random_range(start..snapshot.len().0.min(start + diff_size));
4592
4593 while !text.is_char_boundary(end) {
4594 end = end.saturating_add(1);
4595 }
4596 let start_anchor = snapshot.anchor_after(MultiBufferOffset(start));
4597 let end_anchor = snapshot.anchor_before(MultiBufferOffset(end));
4598 ranges.push(start_anchor..end_anchor);
4599 }
4600 multibuffer.expand_diff_hunks(ranges, cx);
4601 }
4602 });
4603
4604 let snapshot = multibuffer.read(cx).snapshot(cx);
4605
4606 let chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4607
4608 for chunk in chunks {
4609 let chunk_text = chunk.text;
4610 let chars_bitmap = chunk.chars;
4611 let tabs_bitmap = chunk.tabs;
4612
4613 if chunk_text.is_empty() {
4614 assert_eq!(
4615 chars_bitmap, 0,
4616 "Empty chunk should have empty chars bitmap"
4617 );
4618 assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
4619 continue;
4620 }
4621
4622 assert!(
4623 chunk_text.len() <= 128,
4624 "Chunk text length {} exceeds 128 bytes",
4625 chunk_text.len()
4626 );
4627
4628 let char_indices = chunk_text
4629 .char_indices()
4630 .map(|(i, _)| i)
4631 .collect::<Vec<_>>();
4632
4633 for byte_idx in 0..chunk_text.len() {
4634 let should_have_bit = char_indices.contains(&byte_idx);
4635 let has_bit = chars_bitmap & (1 << byte_idx) != 0;
4636
4637 if has_bit != should_have_bit {
4638 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4639 eprintln!("Char indices: {:?}", char_indices);
4640 eprintln!("Chars bitmap: {:#b}", chars_bitmap);
4641 }
4642
4643 assert_eq!(
4644 has_bit, should_have_bit,
4645 "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
4646 byte_idx, chunk_text, should_have_bit, has_bit
4647 );
4648 }
4649
4650 for (byte_idx, byte) in chunk_text.bytes().enumerate() {
4651 let is_tab = byte == b'\t';
4652 let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
4653
4654 if has_bit != is_tab {
4655 eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4656 eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
4657 assert_eq!(
4658 has_bit, is_tab,
4659 "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
4660 byte_idx, chunk_text, byte as char, is_tab, has_bit
4661 );
4662 }
4663 }
4664 }
4665}
4666
4667fn collect_word_diffs(
4668 base_text: &str,
4669 modified_text: &str,
4670 cx: &mut TestAppContext,
4671) -> Vec<String> {
4672 let buffer = cx.new(|cx| Buffer::local(modified_text, cx));
4673 let diff = cx
4674 .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
4675 cx.run_until_parked();
4676
4677 let multibuffer = cx.new(|cx| {
4678 let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
4679 multibuffer.add_diff(diff.clone(), cx);
4680 multibuffer
4681 });
4682
4683 multibuffer.update(cx, |multibuffer, cx| {
4684 multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
4685 });
4686
4687 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4688 let text = snapshot.text();
4689
4690 snapshot
4691 .diff_hunks()
4692 .flat_map(|hunk| hunk.word_diffs)
4693 .map(|range| text[range.start.0..range.end.0].to_string())
4694 .collect()
4695}
4696
4697#[gpui::test]
4698async fn test_word_diff_simple_replacement(cx: &mut TestAppContext) {
4699 let settings_store = cx.update(|cx| SettingsStore::test(cx));
4700 cx.set_global(settings_store);
4701
4702 let base_text = "hello world foo bar\n";
4703 let modified_text = "hello WORLD foo BAR\n";
4704
4705 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4706
4707 assert_eq!(word_diffs, vec!["world", "bar", "WORLD", "BAR"]);
4708}
4709
4710#[gpui::test]
4711async fn test_word_diff_white_space(cx: &mut TestAppContext) {
4712 let settings_store = cx.update(|cx| SettingsStore::test(cx));
4713 cx.set_global(settings_store);
4714
4715 let base_text = "hello world foo bar\n";
4716 let modified_text = " hello world foo bar\n";
4717
4718 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4719
4720 assert_eq!(word_diffs, vec![" "]);
4721}
4722
4723#[gpui::test]
4724async fn test_word_diff_consecutive_modified_lines(cx: &mut TestAppContext) {
4725 let settings_store = cx.update(|cx| SettingsStore::test(cx));
4726 cx.set_global(settings_store);
4727
4728 let base_text = "aaa bbb\nccc ddd\n";
4729 let modified_text = "aaa BBB\nccc DDD\n";
4730
4731 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4732
4733 assert_eq!(
4734 word_diffs,
4735 vec!["bbb", "ddd", "BBB", "DDD"],
4736 "consecutive modified lines should produce word diffs when line counts match"
4737 );
4738}
4739
4740#[gpui::test]
4741async fn test_word_diff_modified_lines_with_deletion_between(cx: &mut TestAppContext) {
4742 let settings_store = cx.update(|cx| SettingsStore::test(cx));
4743 cx.set_global(settings_store);
4744
4745 let base_text = "aaa bbb\ndeleted line\nccc ddd\n";
4746 let modified_text = "aaa BBB\nccc DDD\n";
4747
4748 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4749
4750 assert_eq!(
4751 word_diffs,
4752 Vec::<String>::new(),
4753 "modified lines with a deleted line between should not produce word diffs"
4754 );
4755}
4756
4757#[gpui::test]
4758async fn test_word_diff_disabled(cx: &mut TestAppContext) {
4759 let settings_store = cx.update(|cx| {
4760 let mut settings_store = SettingsStore::test(cx);
4761 settings_store.update_user_settings(cx, |settings| {
4762 settings.project.all_languages.defaults.word_diff_enabled = Some(false);
4763 });
4764 settings_store
4765 });
4766 cx.set_global(settings_store);
4767
4768 let base_text = "hello world\n";
4769 let modified_text = "hello WORLD\n";
4770
4771 let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4772
4773 assert_eq!(
4774 word_diffs,
4775 Vec::<String>::new(),
4776 "word diffs should be empty when disabled"
4777 );
4778}
4779
4780/// Tests `excerpt_containing` and `excerpts_for_range` (functions mapping multi-buffer text-coordinates to excerpts)
4781#[gpui::test]
4782fn test_excerpts_containment_functions(cx: &mut App) {
4783 // Multibuffer content for these tests:
4784 // 0123
4785 // 0: aa0
4786 // 1: aa1
4787 // -----
4788 // 2: bb0
4789 // 3: bb1
4790 // -----MultiBufferOffset(0)..
4791 // 4: cc0
4792
4793 let buffer_1 = cx.new(|cx| Buffer::local("aa0\naa1", cx));
4794 let buffer_2 = cx.new(|cx| Buffer::local("bb0\nbb1", cx));
4795 let buffer_3 = cx.new(|cx| Buffer::local("cc0", cx));
4796
4797 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
4798
4799 let (excerpt_1_id, excerpt_2_id, excerpt_3_id) = multibuffer.update(cx, |multibuffer, cx| {
4800 let excerpt_1_id = multibuffer.push_excerpts(
4801 buffer_1.clone(),
4802 [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4803 cx,
4804 )[0];
4805
4806 let excerpt_2_id = multibuffer.push_excerpts(
4807 buffer_2.clone(),
4808 [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4809 cx,
4810 )[0];
4811
4812 let excerpt_3_id = multibuffer.push_excerpts(
4813 buffer_3.clone(),
4814 [ExcerptRange::new(Point::new(0, 0)..Point::new(0, 3))],
4815 cx,
4816 )[0];
4817
4818 (excerpt_1_id, excerpt_2_id, excerpt_3_id)
4819 });
4820
4821 let snapshot = multibuffer.read(cx).snapshot(cx);
4822
4823 assert_eq!(snapshot.text(), "aa0\naa1\nbb0\nbb1\ncc0");
4824
4825 //// Test `excerpts_for_range`
4826
4827 let p00 = snapshot.point_to_offset(Point::new(0, 0));
4828 let p10 = snapshot.point_to_offset(Point::new(1, 0));
4829 let p20 = snapshot.point_to_offset(Point::new(2, 0));
4830 let p23 = snapshot.point_to_offset(Point::new(2, 3));
4831 let p13 = snapshot.point_to_offset(Point::new(1, 3));
4832 let p40 = snapshot.point_to_offset(Point::new(4, 0));
4833 let p43 = snapshot.point_to_offset(Point::new(4, 3));
4834
4835 let excerpts: Vec<_> = snapshot.excerpts_for_range(p00..p00).collect();
4836 assert_eq!(excerpts.len(), 1);
4837 assert_eq!(excerpts[0].id, excerpt_1_id);
4838
4839 // Cursor at very end of excerpt 3
4840 let excerpts: Vec<_> = snapshot.excerpts_for_range(p43..p43).collect();
4841 assert_eq!(excerpts.len(), 1);
4842 assert_eq!(excerpts[0].id, excerpt_3_id);
4843
4844 let excerpts: Vec<_> = snapshot.excerpts_for_range(p00..p23).collect();
4845 assert_eq!(excerpts.len(), 2);
4846 assert_eq!(excerpts[0].id, excerpt_1_id);
4847 assert_eq!(excerpts[1].id, excerpt_2_id);
4848
4849 // This range represent an selection with end-point just inside excerpt_2
4850 // Today we only expand the first excerpt, but another interpretation that
4851 // we could consider is expanding both here
4852 let excerpts: Vec<_> = snapshot.excerpts_for_range(p10..p20).collect();
4853 assert_eq!(excerpts.len(), 1);
4854 assert_eq!(excerpts[0].id, excerpt_1_id);
4855
4856 //// Test that `excerpts_for_range` and `excerpt_containing` agree for all single offsets (cursor positions)
4857 for offset in 0..=snapshot.len().0 {
4858 let offset = MultiBufferOffset(offset);
4859 let excerpts_for_range: Vec<_> = snapshot.excerpts_for_range(offset..offset).collect();
4860 assert_eq!(
4861 excerpts_for_range.len(),
4862 1,
4863 "Expected exactly one excerpt for offset {offset}",
4864 );
4865
4866 let excerpt_containing = snapshot.excerpt_containing(offset..offset);
4867 assert!(
4868 excerpt_containing.is_some(),
4869 "Expected excerpt_containing to find excerpt for offset {offset}",
4870 );
4871
4872 assert_eq!(
4873 excerpts_for_range[0].id,
4874 excerpt_containing.unwrap().id(),
4875 "excerpts_for_range and excerpt_containing should agree for offset {offset}",
4876 );
4877 }
4878
4879 //// Test `excerpt_containing` behavior with ranges:
4880
4881 // Ranges intersecting a single-excerpt
4882 let containing = snapshot.excerpt_containing(p00..p13);
4883 assert!(containing.is_some());
4884 assert_eq!(containing.unwrap().id(), excerpt_1_id);
4885
4886 // Ranges intersecting multiple excerpts (should return None)
4887 let containing = snapshot.excerpt_containing(p20..p40);
4888 assert!(
4889 containing.is_none(),
4890 "excerpt_containing should return None for ranges spanning multiple excerpts"
4891 );
4892}