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