1mod anchor;
2
3pub use anchor::{Anchor, AnchorRangeExt, Offset};
4use anyhow::{anyhow, Result};
5use clock::ReplicaId;
6use collections::{BTreeMap, Bound, HashMap, HashSet};
7use futures::{channel::mpsc, SinkExt};
8use git::diff::DiffHunk;
9use gpui::{AppContext, EntityId, EventEmitter, Model, ModelContext};
10use itertools::Itertools;
11use language::{
12 char_kind,
13 language_settings::{language_settings, LanguageSettings},
14 AutoindentMode, Buffer, BufferChunks, BufferRow, BufferSnapshot, Capability, CharKind, Chunk,
15 CursorShape, DiagnosticEntry, File, IndentGuide, IndentSize, Language, LanguageScope,
16 OffsetRangeExt, OffsetUtf16, Outline, OutlineItem, Point, PointUtf16, Selection, TextDimension,
17 ToOffset as _, ToOffsetUtf16 as _, ToPoint as _, ToPointUtf16 as _, TransactionId, Unclipped,
18};
19use smallvec::SmallVec;
20use std::{
21 any::type_name,
22 borrow::Cow,
23 cell::{Ref, RefCell},
24 cmp, fmt,
25 future::Future,
26 io,
27 iter::{self, FromIterator},
28 mem,
29 ops::{Range, RangeBounds, Sub},
30 str,
31 sync::Arc,
32 time::{Duration, Instant},
33};
34use sum_tree::{Bias, Cursor, SumTree};
35use text::{
36 locator::Locator,
37 subscription::{Subscription, Topic},
38 BufferId, Edit, TextSummary,
39};
40use theme::SyntaxTheme;
41
42use util::post_inc;
43
44#[cfg(any(test, feature = "test-support"))]
45use gpui::Context;
46
47const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize];
48
49#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
50pub struct ExcerptId(usize);
51
52impl From<ExcerptId> for EntityId {
53 fn from(id: ExcerptId) -> Self {
54 EntityId::from(id.0 as u64)
55 }
56}
57
58/// One or more [`Buffers`](Buffer) being edited in a single view.
59///
60/// See <https://zed.dev/features#multi-buffers>
61pub struct MultiBuffer {
62 /// A snapshot of the [`Excerpt`]s in the MultiBuffer.
63 /// Use [`MultiBuffer::snapshot`] to get a up-to-date snapshot.
64 snapshot: RefCell<MultiBufferSnapshot>,
65 /// Contains the state of the buffers being edited
66 buffers: RefCell<HashMap<BufferId, BufferState>>,
67 subscriptions: Topic,
68 /// If true, the multi-buffer only contains a single [`Buffer`] and a single [`Excerpt`]
69 singleton: bool,
70 replica_id: ReplicaId,
71 history: History,
72 title: Option<String>,
73 capability: Capability,
74}
75
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub enum Event {
78 ExcerptsAdded {
79 buffer: Model<Buffer>,
80 predecessor: ExcerptId,
81 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
82 },
83 ExcerptsRemoved {
84 ids: Vec<ExcerptId>,
85 },
86 ExcerptsExpanded {
87 ids: Vec<ExcerptId>,
88 },
89 ExcerptsEdited {
90 ids: Vec<ExcerptId>,
91 },
92 Edited {
93 singleton_buffer_edited: bool,
94 },
95 TransactionUndone {
96 transaction_id: TransactionId,
97 },
98 Reloaded,
99 DiffBaseChanged,
100 DiffUpdated {
101 buffer: Model<Buffer>,
102 },
103 LanguageChanged(BufferId),
104 CapabilityChanged,
105 Reparsed(BufferId),
106 Saved,
107 FileHandleChanged,
108 Closed,
109 DirtyChanged,
110 DiagnosticsUpdated,
111}
112
113pub type MultiBufferPoint = Point;
114
115#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq, serde::Deserialize)]
116#[serde(transparent)]
117pub struct MultiBufferRow(pub u32);
118
119impl MultiBufferRow {
120 pub const MIN: Self = Self(0);
121 pub const MAX: Self = Self(u32::MAX);
122}
123
124#[derive(Clone)]
125struct History {
126 next_transaction_id: TransactionId,
127 undo_stack: Vec<Transaction>,
128 redo_stack: Vec<Transaction>,
129 transaction_depth: usize,
130 group_interval: Duration,
131}
132
133#[derive(Clone)]
134struct Transaction {
135 id: TransactionId,
136 buffer_transactions: HashMap<BufferId, text::TransactionId>,
137 first_edit_at: Instant,
138 last_edit_at: Instant,
139 suppress_grouping: bool,
140}
141
142pub trait ToOffset: 'static + fmt::Debug {
143 fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
144}
145
146pub trait ToOffsetUtf16: 'static + fmt::Debug {
147 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16;
148}
149
150pub trait ToPoint: 'static + fmt::Debug {
151 fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
152}
153
154pub trait ToPointUtf16: 'static + fmt::Debug {
155 fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16;
156}
157
158struct BufferState {
159 buffer: Model<Buffer>,
160 last_version: clock::Global,
161 last_non_text_state_update_count: usize,
162 excerpts: Vec<Locator>,
163 _subscriptions: [gpui::Subscription; 2],
164}
165
166/// The contents of a [`MultiBuffer`] at a single point in time.
167#[derive(Clone, Default)]
168pub struct MultiBufferSnapshot {
169 singleton: bool,
170 excerpts: SumTree<Excerpt>,
171 excerpt_ids: SumTree<ExcerptIdMapping>,
172 trailing_excerpt_update_count: usize,
173 non_text_state_update_count: usize,
174 edit_count: usize,
175 is_dirty: bool,
176 has_conflict: bool,
177 show_headers: bool,
178}
179
180pub struct ExcerptInfo {
181 pub id: ExcerptId,
182 pub buffer: BufferSnapshot,
183 pub buffer_id: BufferId,
184 pub range: ExcerptRange<text::Anchor>,
185}
186
187impl std::fmt::Debug for ExcerptInfo {
188 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189 f.debug_struct(type_name::<Self>())
190 .field("id", &self.id)
191 .field("buffer_id", &self.buffer_id)
192 .field("range", &self.range)
193 .finish()
194 }
195}
196
197/// A boundary between [`Excerpt`]s in a [`MultiBuffer`]
198#[derive(Debug)]
199pub struct ExcerptBoundary {
200 pub prev: Option<ExcerptInfo>,
201 pub next: Option<ExcerptInfo>,
202 /// The row in the `MultiBuffer` where the boundary is located
203 pub row: MultiBufferRow,
204}
205
206impl ExcerptBoundary {
207 pub fn starts_new_buffer(&self) -> bool {
208 match (self.prev.as_ref(), self.next.as_ref()) {
209 (None, _) => true,
210 (Some(_), None) => false,
211 (Some(prev), Some(next)) => prev.buffer_id != next.buffer_id,
212 }
213 }
214}
215
216/// A slice into a [`Buffer`] that is being edited in a [`MultiBuffer`].
217#[derive(Clone)]
218struct Excerpt {
219 /// The unique identifier for this excerpt
220 id: ExcerptId,
221 /// The location of the excerpt in the [`MultiBuffer`]
222 locator: Locator,
223 /// The buffer being excerpted
224 buffer_id: BufferId,
225 /// A snapshot of the buffer being excerpted
226 buffer: BufferSnapshot,
227 /// The range of the buffer to be shown in the excerpt
228 range: ExcerptRange<text::Anchor>,
229 /// The last row in the excerpted slice of the buffer
230 max_buffer_row: BufferRow,
231 /// A summary of the text in the excerpt
232 text_summary: TextSummary,
233 has_trailing_newline: bool,
234}
235
236/// A public view into an [`Excerpt`] in a [`MultiBuffer`].
237///
238/// Contains methods for getting the [`Buffer`] of the excerpt,
239/// as well as mapping offsets to/from buffer and multibuffer coordinates.
240#[derive(Clone)]
241pub struct MultiBufferExcerpt<'a> {
242 excerpt: &'a Excerpt,
243 excerpt_offset: usize,
244}
245
246#[derive(Clone, Debug)]
247struct ExcerptIdMapping {
248 id: ExcerptId,
249 locator: Locator,
250}
251
252/// A range of text from a single [`Buffer`], to be shown as an [`Excerpt`].
253/// These ranges are relative to the buffer itself
254#[derive(Clone, Debug, Eq, PartialEq)]
255pub struct ExcerptRange<T> {
256 /// The full range of text to be shown in the excerpt.
257 pub context: Range<T>,
258 /// The primary range of text to be highlighted in the excerpt.
259 /// In a multi-buffer search, this would be the text that matched the search
260 pub primary: Option<Range<T>>,
261}
262
263#[derive(Clone, Debug, Default)]
264struct ExcerptSummary {
265 excerpt_id: ExcerptId,
266 /// The location of the last [`Excerpt`] being summarized
267 excerpt_locator: Locator,
268 /// The maximum row of the [`Excerpt`]s being summarized
269 max_buffer_row: MultiBufferRow,
270 text: TextSummary,
271}
272
273#[derive(Clone)]
274pub struct MultiBufferRows<'a> {
275 buffer_row_range: Range<u32>,
276 excerpts: Cursor<'a, Excerpt, Point>,
277}
278
279pub struct MultiBufferChunks<'a> {
280 range: Range<usize>,
281 excerpts: Cursor<'a, Excerpt, usize>,
282 excerpt_chunks: Option<ExcerptChunks<'a>>,
283 language_aware: bool,
284}
285
286pub struct MultiBufferBytes<'a> {
287 range: Range<usize>,
288 excerpts: Cursor<'a, Excerpt, usize>,
289 excerpt_bytes: Option<ExcerptBytes<'a>>,
290 chunk: &'a [u8],
291}
292
293pub struct ReversedMultiBufferBytes<'a> {
294 range: Range<usize>,
295 excerpts: Cursor<'a, Excerpt, usize>,
296 excerpt_bytes: Option<ExcerptBytes<'a>>,
297 chunk: &'a [u8],
298}
299
300struct ExcerptChunks<'a> {
301 content_chunks: BufferChunks<'a>,
302 footer_height: usize,
303}
304
305struct ExcerptBytes<'a> {
306 content_bytes: text::Bytes<'a>,
307 padding_height: usize,
308 reversed: bool,
309}
310
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
312pub enum ExpandExcerptDirection {
313 Up,
314 Down,
315 UpAndDown,
316}
317
318impl ExpandExcerptDirection {
319 pub fn should_expand_up(&self) -> bool {
320 match self {
321 ExpandExcerptDirection::Up => true,
322 ExpandExcerptDirection::Down => false,
323 ExpandExcerptDirection::UpAndDown => true,
324 }
325 }
326
327 pub fn should_expand_down(&self) -> bool {
328 match self {
329 ExpandExcerptDirection::Up => false,
330 ExpandExcerptDirection::Down => true,
331 ExpandExcerptDirection::UpAndDown => true,
332 }
333 }
334}
335
336#[derive(Clone, Debug, PartialEq)]
337pub struct MultiBufferIndentGuide {
338 pub multibuffer_row_range: Range<MultiBufferRow>,
339 pub buffer: IndentGuide,
340}
341
342impl std::ops::Deref for MultiBufferIndentGuide {
343 type Target = IndentGuide;
344
345 fn deref(&self) -> &Self::Target {
346 &self.buffer
347 }
348}
349
350impl MultiBuffer {
351 pub fn new(replica_id: ReplicaId, capability: Capability) -> Self {
352 Self {
353 snapshot: RefCell::new(MultiBufferSnapshot {
354 show_headers: true,
355 ..MultiBufferSnapshot::default()
356 }),
357 buffers: RefCell::default(),
358 subscriptions: Topic::default(),
359 singleton: false,
360 capability,
361 replica_id,
362 title: None,
363 history: History {
364 next_transaction_id: clock::Lamport::default(),
365 undo_stack: Vec::new(),
366 redo_stack: Vec::new(),
367 transaction_depth: 0,
368 group_interval: Duration::from_millis(300),
369 },
370 }
371 }
372
373 pub fn without_headers(replica_id: ReplicaId, capability: Capability) -> Self {
374 Self {
375 snapshot: Default::default(),
376 buffers: Default::default(),
377 subscriptions: Default::default(),
378 singleton: false,
379 capability,
380 replica_id,
381 history: History {
382 next_transaction_id: Default::default(),
383 undo_stack: Default::default(),
384 redo_stack: Default::default(),
385 transaction_depth: 0,
386 group_interval: Duration::from_millis(300),
387 },
388 title: Default::default(),
389 }
390 }
391
392 pub fn clone(&self, new_cx: &mut ModelContext<Self>) -> Self {
393 let mut buffers = HashMap::default();
394 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
395 buffers.insert(
396 *buffer_id,
397 BufferState {
398 buffer: buffer_state.buffer.clone(),
399 last_version: buffer_state.last_version.clone(),
400 last_non_text_state_update_count: buffer_state.last_non_text_state_update_count,
401 excerpts: buffer_state.excerpts.clone(),
402 _subscriptions: [
403 new_cx.observe(&buffer_state.buffer, |_, _, cx| cx.notify()),
404 new_cx.subscribe(&buffer_state.buffer, Self::on_buffer_event),
405 ],
406 },
407 );
408 }
409 Self {
410 snapshot: RefCell::new(self.snapshot.borrow().clone()),
411 buffers: RefCell::new(buffers),
412 subscriptions: Default::default(),
413 singleton: self.singleton,
414 capability: self.capability,
415 replica_id: self.replica_id,
416 history: self.history.clone(),
417 title: self.title.clone(),
418 }
419 }
420
421 pub fn with_title(mut self, title: String) -> Self {
422 self.title = Some(title);
423 self
424 }
425
426 pub fn read_only(&self) -> bool {
427 self.capability == Capability::ReadOnly
428 }
429
430 pub fn singleton(buffer: Model<Buffer>, cx: &mut ModelContext<Self>) -> Self {
431 let mut this = Self::new(buffer.read(cx).replica_id(), buffer.read(cx).capability());
432 this.singleton = true;
433 this.push_excerpts(
434 buffer,
435 [ExcerptRange {
436 context: text::Anchor::MIN..text::Anchor::MAX,
437 primary: None,
438 }],
439 cx,
440 );
441 this.snapshot.borrow_mut().singleton = true;
442 this
443 }
444
445 pub fn replica_id(&self) -> ReplicaId {
446 self.replica_id
447 }
448
449 /// Returns an up-to-date snapshot of the MultiBuffer.
450 pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
451 self.sync(cx);
452 self.snapshot.borrow().clone()
453 }
454
455 pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
456 self.sync(cx);
457 self.snapshot.borrow()
458 }
459
460 pub fn as_singleton(&self) -> Option<Model<Buffer>> {
461 if self.singleton {
462 return Some(
463 self.buffers
464 .borrow()
465 .values()
466 .next()
467 .unwrap()
468 .buffer
469 .clone(),
470 );
471 } else {
472 None
473 }
474 }
475
476 pub fn is_singleton(&self) -> bool {
477 self.singleton
478 }
479
480 pub fn subscribe(&mut self) -> Subscription {
481 self.subscriptions.subscribe()
482 }
483
484 pub fn is_dirty(&self, cx: &AppContext) -> bool {
485 self.read(cx).is_dirty()
486 }
487
488 pub fn has_conflict(&self, cx: &AppContext) -> bool {
489 self.read(cx).has_conflict()
490 }
491
492 // The `is_empty` signature doesn't match what clippy expects
493 #[allow(clippy::len_without_is_empty)]
494 pub fn len(&self, cx: &AppContext) -> usize {
495 self.read(cx).len()
496 }
497
498 pub fn is_empty(&self, cx: &AppContext) -> bool {
499 self.len(cx) != 0
500 }
501
502 pub fn symbols_containing<T: ToOffset>(
503 &self,
504 offset: T,
505 theme: Option<&SyntaxTheme>,
506 cx: &AppContext,
507 ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
508 self.read(cx).symbols_containing(offset, theme)
509 }
510
511 pub fn edit<I, S, T>(
512 &mut self,
513 edits: I,
514 mut autoindent_mode: Option<AutoindentMode>,
515 cx: &mut ModelContext<Self>,
516 ) where
517 I: IntoIterator<Item = (Range<S>, T)>,
518 S: ToOffset,
519 T: Into<Arc<str>>,
520 {
521 if self.read_only() {
522 return;
523 }
524 if self.buffers.borrow().is_empty() {
525 return;
526 }
527
528 let snapshot = self.read(cx);
529 let edits = edits.into_iter().map(|(range, new_text)| {
530 let mut range = range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot);
531 if range.start > range.end {
532 mem::swap(&mut range.start, &mut range.end);
533 }
534 (range, new_text)
535 });
536
537 if let Some(buffer) = self.as_singleton() {
538 buffer.update(cx, |buffer, cx| {
539 buffer.edit(edits, autoindent_mode, cx);
540 });
541 cx.emit(Event::ExcerptsEdited {
542 ids: self.excerpt_ids(),
543 });
544 return;
545 }
546
547 let original_indent_columns = match &mut autoindent_mode {
548 Some(AutoindentMode::Block {
549 original_indent_columns,
550 }) => mem::take(original_indent_columns),
551 _ => Default::default(),
552 };
553
554 struct BufferEdit {
555 range: Range<usize>,
556 new_text: Arc<str>,
557 is_insertion: bool,
558 original_indent_column: u32,
559 }
560 let mut buffer_edits: HashMap<BufferId, Vec<BufferEdit>> = Default::default();
561 let mut edited_excerpt_ids = Vec::new();
562 let mut cursor = snapshot.excerpts.cursor::<usize>();
563 for (ix, (range, new_text)) in edits.enumerate() {
564 let new_text: Arc<str> = new_text.into();
565 let original_indent_column = original_indent_columns.get(ix).copied().unwrap_or(0);
566 cursor.seek(&range.start, Bias::Right, &());
567 if cursor.item().is_none() && range.start == *cursor.start() {
568 cursor.prev(&());
569 }
570 let start_excerpt = cursor.item().expect("start offset out of bounds");
571 let start_overshoot = range.start - cursor.start();
572 let buffer_start = start_excerpt
573 .range
574 .context
575 .start
576 .to_offset(&start_excerpt.buffer)
577 + start_overshoot;
578 edited_excerpt_ids.push(start_excerpt.id);
579
580 cursor.seek(&range.end, Bias::Right, &());
581 if cursor.item().is_none() && range.end == *cursor.start() {
582 cursor.prev(&());
583 }
584 let end_excerpt = cursor.item().expect("end offset out of bounds");
585 let end_overshoot = range.end - cursor.start();
586 let buffer_end = end_excerpt
587 .range
588 .context
589 .start
590 .to_offset(&end_excerpt.buffer)
591 + end_overshoot;
592
593 if start_excerpt.id == end_excerpt.id {
594 buffer_edits
595 .entry(start_excerpt.buffer_id)
596 .or_insert(Vec::new())
597 .push(BufferEdit {
598 range: buffer_start..buffer_end,
599 new_text,
600 is_insertion: true,
601 original_indent_column,
602 });
603 } else {
604 edited_excerpt_ids.push(end_excerpt.id);
605 let start_excerpt_range = buffer_start
606 ..start_excerpt
607 .range
608 .context
609 .end
610 .to_offset(&start_excerpt.buffer);
611 let end_excerpt_range = end_excerpt
612 .range
613 .context
614 .start
615 .to_offset(&end_excerpt.buffer)
616 ..buffer_end;
617 buffer_edits
618 .entry(start_excerpt.buffer_id)
619 .or_insert(Vec::new())
620 .push(BufferEdit {
621 range: start_excerpt_range,
622 new_text: new_text.clone(),
623 is_insertion: true,
624 original_indent_column,
625 });
626 buffer_edits
627 .entry(end_excerpt.buffer_id)
628 .or_insert(Vec::new())
629 .push(BufferEdit {
630 range: end_excerpt_range,
631 new_text: new_text.clone(),
632 is_insertion: false,
633 original_indent_column,
634 });
635
636 cursor.seek(&range.start, Bias::Right, &());
637 cursor.next(&());
638 while let Some(excerpt) = cursor.item() {
639 if excerpt.id == end_excerpt.id {
640 break;
641 }
642 buffer_edits
643 .entry(excerpt.buffer_id)
644 .or_insert(Vec::new())
645 .push(BufferEdit {
646 range: excerpt.range.context.to_offset(&excerpt.buffer),
647 new_text: new_text.clone(),
648 is_insertion: false,
649 original_indent_column,
650 });
651 edited_excerpt_ids.push(excerpt.id);
652 cursor.next(&());
653 }
654 }
655 }
656
657 drop(cursor);
658 drop(snapshot);
659 // Non-generic part of edit, hoisted out to avoid blowing up LLVM IR.
660 fn tail(
661 this: &mut MultiBuffer,
662 buffer_edits: HashMap<BufferId, Vec<BufferEdit>>,
663 autoindent_mode: Option<AutoindentMode>,
664 edited_excerpt_ids: Vec<ExcerptId>,
665 cx: &mut ModelContext<MultiBuffer>,
666 ) {
667 for (buffer_id, mut edits) in buffer_edits {
668 edits.sort_unstable_by_key(|edit| edit.range.start);
669 this.buffers.borrow()[&buffer_id]
670 .buffer
671 .update(cx, |buffer, cx| {
672 let mut edits = edits.into_iter().peekable();
673 let mut insertions = Vec::new();
674 let mut original_indent_columns = Vec::new();
675 let mut deletions = Vec::new();
676 let empty_str: Arc<str> = "".into();
677 while let Some(BufferEdit {
678 mut range,
679 new_text,
680 mut is_insertion,
681 original_indent_column,
682 }) = edits.next()
683 {
684 while let Some(BufferEdit {
685 range: next_range,
686 is_insertion: next_is_insertion,
687 ..
688 }) = edits.peek()
689 {
690 if range.end >= next_range.start {
691 range.end = cmp::max(next_range.end, range.end);
692 is_insertion |= *next_is_insertion;
693 edits.next();
694 } else {
695 break;
696 }
697 }
698
699 if is_insertion {
700 original_indent_columns.push(original_indent_column);
701 insertions.push((
702 buffer.anchor_before(range.start)
703 ..buffer.anchor_before(range.end),
704 new_text.clone(),
705 ));
706 } else if !range.is_empty() {
707 deletions.push((
708 buffer.anchor_before(range.start)
709 ..buffer.anchor_before(range.end),
710 empty_str.clone(),
711 ));
712 }
713 }
714
715 let deletion_autoindent_mode =
716 if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
717 Some(AutoindentMode::Block {
718 original_indent_columns: Default::default(),
719 })
720 } else {
721 None
722 };
723 let insertion_autoindent_mode =
724 if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
725 Some(AutoindentMode::Block {
726 original_indent_columns,
727 })
728 } else {
729 None
730 };
731
732 buffer.edit(deletions, deletion_autoindent_mode, cx);
733 buffer.edit(insertions, insertion_autoindent_mode, cx);
734 })
735 }
736
737 cx.emit(Event::ExcerptsEdited {
738 ids: edited_excerpt_ids,
739 });
740 }
741 tail(self, buffer_edits, autoindent_mode, edited_excerpt_ids, cx);
742 }
743
744 pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
745 self.start_transaction_at(Instant::now(), cx)
746 }
747
748 pub fn start_transaction_at(
749 &mut self,
750 now: Instant,
751 cx: &mut ModelContext<Self>,
752 ) -> Option<TransactionId> {
753 if let Some(buffer) = self.as_singleton() {
754 return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
755 }
756
757 for BufferState { buffer, .. } in self.buffers.borrow().values() {
758 buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
759 }
760 self.history.start_transaction(now)
761 }
762
763 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
764 self.end_transaction_at(Instant::now(), cx)
765 }
766
767 pub fn end_transaction_at(
768 &mut self,
769 now: Instant,
770 cx: &mut ModelContext<Self>,
771 ) -> Option<TransactionId> {
772 if let Some(buffer) = self.as_singleton() {
773 return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
774 }
775
776 let mut buffer_transactions = HashMap::default();
777 for BufferState { buffer, .. } in self.buffers.borrow().values() {
778 if let Some(transaction_id) =
779 buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
780 {
781 buffer_transactions.insert(buffer.read(cx).remote_id(), transaction_id);
782 }
783 }
784
785 if self.history.end_transaction(now, buffer_transactions) {
786 let transaction_id = self.history.group().unwrap();
787 Some(transaction_id)
788 } else {
789 None
790 }
791 }
792
793 pub fn edited_ranges_for_transaction<D>(
794 &self,
795 transaction_id: TransactionId,
796 cx: &AppContext,
797 ) -> Vec<Range<D>>
798 where
799 D: TextDimension + Ord + Sub<D, Output = D>,
800 {
801 if let Some(buffer) = self.as_singleton() {
802 return buffer
803 .read(cx)
804 .edited_ranges_for_transaction_id(transaction_id)
805 .collect::<Vec<_>>();
806 }
807
808 let Some(transaction) = self.history.transaction(transaction_id) else {
809 return Vec::new();
810 };
811
812 let mut ranges = Vec::new();
813 let snapshot = self.read(cx);
814 let buffers = self.buffers.borrow();
815 let mut cursor = snapshot.excerpts.cursor::<ExcerptSummary>();
816
817 for (buffer_id, buffer_transaction) in &transaction.buffer_transactions {
818 let Some(buffer_state) = buffers.get(&buffer_id) else {
819 continue;
820 };
821
822 let buffer = buffer_state.buffer.read(cx);
823 for range in buffer.edited_ranges_for_transaction_id::<D>(*buffer_transaction) {
824 for excerpt_id in &buffer_state.excerpts {
825 cursor.seek(excerpt_id, Bias::Left, &());
826 if let Some(excerpt) = cursor.item() {
827 if excerpt.locator == *excerpt_id {
828 let excerpt_buffer_start =
829 excerpt.range.context.start.summary::<D>(buffer);
830 let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(buffer);
831 let excerpt_range = excerpt_buffer_start.clone()..excerpt_buffer_end;
832 if excerpt_range.contains(&range.start)
833 && excerpt_range.contains(&range.end)
834 {
835 let excerpt_start = D::from_text_summary(&cursor.start().text);
836
837 let mut start = excerpt_start.clone();
838 start.add_assign(&(range.start - excerpt_buffer_start.clone()));
839 let mut end = excerpt_start;
840 end.add_assign(&(range.end - excerpt_buffer_start));
841
842 ranges.push(start..end);
843 break;
844 }
845 }
846 }
847 }
848 }
849 }
850
851 ranges.sort_by_key(|range| range.start.clone());
852 ranges
853 }
854
855 pub fn merge_transactions(
856 &mut self,
857 transaction: TransactionId,
858 destination: TransactionId,
859 cx: &mut ModelContext<Self>,
860 ) {
861 if let Some(buffer) = self.as_singleton() {
862 buffer.update(cx, |buffer, _| {
863 buffer.merge_transactions(transaction, destination)
864 });
865 } else {
866 if let Some(transaction) = self.history.forget(transaction) {
867 if let Some(destination) = self.history.transaction_mut(destination) {
868 for (buffer_id, buffer_transaction_id) in transaction.buffer_transactions {
869 if let Some(destination_buffer_transaction_id) =
870 destination.buffer_transactions.get(&buffer_id)
871 {
872 if let Some(state) = self.buffers.borrow().get(&buffer_id) {
873 state.buffer.update(cx, |buffer, _| {
874 buffer.merge_transactions(
875 buffer_transaction_id,
876 *destination_buffer_transaction_id,
877 )
878 });
879 }
880 } else {
881 destination
882 .buffer_transactions
883 .insert(buffer_id, buffer_transaction_id);
884 }
885 }
886 }
887 }
888 }
889 }
890
891 pub fn finalize_last_transaction(&mut self, cx: &mut ModelContext<Self>) {
892 self.history.finalize_last_transaction();
893 for BufferState { buffer, .. } in self.buffers.borrow().values() {
894 buffer.update(cx, |buffer, _| {
895 buffer.finalize_last_transaction();
896 });
897 }
898 }
899
900 pub fn push_transaction<'a, T>(&mut self, buffer_transactions: T, cx: &mut ModelContext<Self>)
901 where
902 T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
903 {
904 self.history
905 .push_transaction(buffer_transactions, Instant::now(), cx);
906 self.history.finalize_last_transaction();
907 }
908
909 pub fn group_until_transaction(
910 &mut self,
911 transaction_id: TransactionId,
912 cx: &mut ModelContext<Self>,
913 ) {
914 if let Some(buffer) = self.as_singleton() {
915 buffer.update(cx, |buffer, _| {
916 buffer.group_until_transaction(transaction_id)
917 });
918 } else {
919 self.history.group_until(transaction_id);
920 }
921 }
922
923 pub fn set_active_selections(
924 &mut self,
925 selections: &[Selection<Anchor>],
926 line_mode: bool,
927 cursor_shape: CursorShape,
928 cx: &mut ModelContext<Self>,
929 ) {
930 let mut selections_by_buffer: HashMap<BufferId, Vec<Selection<text::Anchor>>> =
931 Default::default();
932 let snapshot = self.read(cx);
933 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
934 for selection in selections {
935 let start_locator = snapshot.excerpt_locator_for_id(selection.start.excerpt_id);
936 let end_locator = snapshot.excerpt_locator_for_id(selection.end.excerpt_id);
937
938 cursor.seek(&Some(start_locator), Bias::Left, &());
939 while let Some(excerpt) = cursor.item() {
940 if excerpt.locator > *end_locator {
941 break;
942 }
943
944 let mut start = excerpt.range.context.start;
945 let mut end = excerpt.range.context.end;
946 if excerpt.id == selection.start.excerpt_id {
947 start = selection.start.text_anchor;
948 }
949 if excerpt.id == selection.end.excerpt_id {
950 end = selection.end.text_anchor;
951 }
952 selections_by_buffer
953 .entry(excerpt.buffer_id)
954 .or_default()
955 .push(Selection {
956 id: selection.id,
957 start,
958 end,
959 reversed: selection.reversed,
960 goal: selection.goal,
961 });
962
963 cursor.next(&());
964 }
965 }
966
967 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
968 if !selections_by_buffer.contains_key(buffer_id) {
969 buffer_state
970 .buffer
971 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
972 }
973 }
974
975 for (buffer_id, mut selections) in selections_by_buffer {
976 self.buffers.borrow()[&buffer_id]
977 .buffer
978 .update(cx, |buffer, cx| {
979 selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer));
980 let mut selections = selections.into_iter().peekable();
981 let merged_selections = Arc::from_iter(iter::from_fn(|| {
982 let mut selection = selections.next()?;
983 while let Some(next_selection) = selections.peek() {
984 if selection.end.cmp(&next_selection.start, buffer).is_ge() {
985 let next_selection = selections.next().unwrap();
986 if next_selection.end.cmp(&selection.end, buffer).is_ge() {
987 selection.end = next_selection.end;
988 }
989 } else {
990 break;
991 }
992 }
993 Some(selection)
994 }));
995 buffer.set_active_selections(merged_selections, line_mode, cursor_shape, cx);
996 });
997 }
998 }
999
1000 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1001 for buffer in self.buffers.borrow().values() {
1002 buffer
1003 .buffer
1004 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
1005 }
1006 }
1007
1008 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1009 let mut transaction_id = None;
1010 if let Some(buffer) = self.as_singleton() {
1011 transaction_id = buffer.update(cx, |buffer, cx| buffer.undo(cx));
1012 } else {
1013 while let Some(transaction) = self.history.pop_undo() {
1014 let mut undone = false;
1015 for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
1016 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
1017 undone |= buffer.update(cx, |buffer, cx| {
1018 let undo_to = *buffer_transaction_id;
1019 if let Some(entry) = buffer.peek_undo_stack() {
1020 *buffer_transaction_id = entry.transaction_id();
1021 }
1022 buffer.undo_to_transaction(undo_to, cx)
1023 });
1024 }
1025 }
1026
1027 if undone {
1028 transaction_id = Some(transaction.id);
1029 break;
1030 }
1031 }
1032 }
1033
1034 if let Some(transaction_id) = transaction_id {
1035 cx.emit(Event::TransactionUndone { transaction_id });
1036 }
1037
1038 transaction_id
1039 }
1040
1041 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1042 if let Some(buffer) = self.as_singleton() {
1043 return buffer.update(cx, |buffer, cx| buffer.redo(cx));
1044 }
1045
1046 while let Some(transaction) = self.history.pop_redo() {
1047 let mut redone = false;
1048 for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
1049 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
1050 redone |= buffer.update(cx, |buffer, cx| {
1051 let redo_to = *buffer_transaction_id;
1052 if let Some(entry) = buffer.peek_redo_stack() {
1053 *buffer_transaction_id = entry.transaction_id();
1054 }
1055 buffer.redo_to_transaction(redo_to, cx)
1056 });
1057 }
1058 }
1059
1060 if redone {
1061 return Some(transaction.id);
1062 }
1063 }
1064
1065 None
1066 }
1067
1068 pub fn undo_transaction(&mut self, transaction_id: TransactionId, cx: &mut ModelContext<Self>) {
1069 if let Some(buffer) = self.as_singleton() {
1070 buffer.update(cx, |buffer, cx| buffer.undo_transaction(transaction_id, cx));
1071 } else if let Some(transaction) = self.history.remove_from_undo(transaction_id) {
1072 for (buffer_id, transaction_id) in &transaction.buffer_transactions {
1073 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
1074 buffer.update(cx, |buffer, cx| {
1075 buffer.undo_transaction(*transaction_id, cx)
1076 });
1077 }
1078 }
1079 }
1080 }
1081
1082 pub fn stream_excerpts_with_context_lines(
1083 &mut self,
1084 buffer: Model<Buffer>,
1085 ranges: Vec<Range<text::Anchor>>,
1086 context_line_count: u32,
1087 cx: &mut ModelContext<Self>,
1088 ) -> mpsc::Receiver<Range<Anchor>> {
1089 let (buffer_id, buffer_snapshot) =
1090 buffer.update(cx, |buffer, _| (buffer.remote_id(), buffer.snapshot()));
1091
1092 let (mut tx, rx) = mpsc::channel(256);
1093 cx.spawn(move |this, mut cx| async move {
1094 let mut excerpt_ranges = Vec::new();
1095 let mut range_counts = Vec::new();
1096 cx.background_executor()
1097 .scoped(|scope| {
1098 scope.spawn(async {
1099 let (ranges, counts) =
1100 build_excerpt_ranges(&buffer_snapshot, &ranges, context_line_count);
1101 excerpt_ranges = ranges;
1102 range_counts = counts;
1103 });
1104 })
1105 .await;
1106
1107 let mut ranges = ranges.into_iter();
1108 let mut range_counts = range_counts.into_iter();
1109 for excerpt_ranges in excerpt_ranges.chunks(100) {
1110 let excerpt_ids = match this.update(&mut cx, |this, cx| {
1111 this.push_excerpts(buffer.clone(), excerpt_ranges.iter().cloned(), cx)
1112 }) {
1113 Ok(excerpt_ids) => excerpt_ids,
1114 Err(_) => return,
1115 };
1116
1117 for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(range_counts.by_ref())
1118 {
1119 for range in ranges.by_ref().take(range_count) {
1120 let start = Anchor {
1121 buffer_id: Some(buffer_id),
1122 excerpt_id,
1123 text_anchor: range.start,
1124 };
1125 let end = Anchor {
1126 buffer_id: Some(buffer_id),
1127 excerpt_id,
1128 text_anchor: range.end,
1129 };
1130 if tx.send(start..end).await.is_err() {
1131 break;
1132 }
1133 }
1134 }
1135 }
1136 })
1137 .detach();
1138
1139 rx
1140 }
1141
1142 pub fn push_excerpts<O>(
1143 &mut self,
1144 buffer: Model<Buffer>,
1145 ranges: impl IntoIterator<Item = ExcerptRange<O>>,
1146 cx: &mut ModelContext<Self>,
1147 ) -> Vec<ExcerptId>
1148 where
1149 O: text::ToOffset,
1150 {
1151 self.insert_excerpts_after(ExcerptId::max(), buffer, ranges, cx)
1152 }
1153
1154 pub fn push_excerpts_with_context_lines<O>(
1155 &mut self,
1156 buffer: Model<Buffer>,
1157 ranges: Vec<Range<O>>,
1158 context_line_count: u32,
1159 cx: &mut ModelContext<Self>,
1160 ) -> Vec<Range<Anchor>>
1161 where
1162 O: text::ToPoint + text::ToOffset,
1163 {
1164 let buffer_id = buffer.read(cx).remote_id();
1165 let buffer_snapshot = buffer.read(cx).snapshot();
1166 let (excerpt_ranges, range_counts) =
1167 build_excerpt_ranges(&buffer_snapshot, &ranges, context_line_count);
1168
1169 let excerpt_ids = self.push_excerpts(buffer, excerpt_ranges, cx);
1170
1171 let mut anchor_ranges = Vec::new();
1172 let mut ranges = ranges.into_iter();
1173 for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(range_counts.into_iter()) {
1174 anchor_ranges.extend(ranges.by_ref().take(range_count).map(|range| {
1175 let start = Anchor {
1176 buffer_id: Some(buffer_id),
1177 excerpt_id,
1178 text_anchor: buffer_snapshot.anchor_after(range.start),
1179 };
1180 let end = Anchor {
1181 buffer_id: Some(buffer_id),
1182 excerpt_id,
1183 text_anchor: buffer_snapshot.anchor_after(range.end),
1184 };
1185 start..end
1186 }))
1187 }
1188 anchor_ranges
1189 }
1190
1191 pub fn insert_excerpts_after<O>(
1192 &mut self,
1193 prev_excerpt_id: ExcerptId,
1194 buffer: Model<Buffer>,
1195 ranges: impl IntoIterator<Item = ExcerptRange<O>>,
1196 cx: &mut ModelContext<Self>,
1197 ) -> Vec<ExcerptId>
1198 where
1199 O: text::ToOffset,
1200 {
1201 let mut ids = Vec::new();
1202 let mut next_excerpt_id =
1203 if let Some(last_entry) = self.snapshot.borrow().excerpt_ids.last() {
1204 last_entry.id.0 + 1
1205 } else {
1206 1
1207 };
1208 self.insert_excerpts_with_ids_after(
1209 prev_excerpt_id,
1210 buffer,
1211 ranges.into_iter().map(|range| {
1212 let id = ExcerptId(post_inc(&mut next_excerpt_id));
1213 ids.push(id);
1214 (id, range)
1215 }),
1216 cx,
1217 );
1218 ids
1219 }
1220
1221 pub fn insert_excerpts_with_ids_after<O>(
1222 &mut self,
1223 prev_excerpt_id: ExcerptId,
1224 buffer: Model<Buffer>,
1225 ranges: impl IntoIterator<Item = (ExcerptId, ExcerptRange<O>)>,
1226 cx: &mut ModelContext<Self>,
1227 ) where
1228 O: text::ToOffset,
1229 {
1230 assert_eq!(self.history.transaction_depth, 0);
1231 let mut ranges = ranges.into_iter().peekable();
1232 if ranges.peek().is_none() {
1233 return Default::default();
1234 }
1235
1236 self.sync(cx);
1237
1238 let buffer_id = buffer.read(cx).remote_id();
1239 let buffer_snapshot = buffer.read(cx).snapshot();
1240
1241 let mut buffers = self.buffers.borrow_mut();
1242 let buffer_state = buffers.entry(buffer_id).or_insert_with(|| BufferState {
1243 last_version: buffer_snapshot.version().clone(),
1244 last_non_text_state_update_count: buffer_snapshot.non_text_state_update_count(),
1245 excerpts: Default::default(),
1246 _subscriptions: [
1247 cx.observe(&buffer, |_, _, cx| cx.notify()),
1248 cx.subscribe(&buffer, Self::on_buffer_event),
1249 ],
1250 buffer: buffer.clone(),
1251 });
1252
1253 let mut snapshot = self.snapshot.borrow_mut();
1254
1255 let mut prev_locator = snapshot.excerpt_locator_for_id(prev_excerpt_id).clone();
1256 let mut new_excerpt_ids = mem::take(&mut snapshot.excerpt_ids);
1257 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
1258 let mut new_excerpts = cursor.slice(&prev_locator, Bias::Right, &());
1259 prev_locator = cursor.start().unwrap_or(Locator::min_ref()).clone();
1260
1261 let edit_start = new_excerpts.summary().text.len;
1262 new_excerpts.update_last(
1263 |excerpt| {
1264 excerpt.has_trailing_newline = true;
1265 },
1266 &(),
1267 );
1268
1269 let next_locator = if let Some(excerpt) = cursor.item() {
1270 excerpt.locator.clone()
1271 } else {
1272 Locator::max()
1273 };
1274
1275 let mut excerpts = Vec::new();
1276 while let Some((id, range)) = ranges.next() {
1277 let locator = Locator::between(&prev_locator, &next_locator);
1278 if let Err(ix) = buffer_state.excerpts.binary_search(&locator) {
1279 buffer_state.excerpts.insert(ix, locator.clone());
1280 }
1281 let range = ExcerptRange {
1282 context: buffer_snapshot.anchor_before(&range.context.start)
1283 ..buffer_snapshot.anchor_after(&range.context.end),
1284 primary: range.primary.map(|primary| {
1285 buffer_snapshot.anchor_before(&primary.start)
1286 ..buffer_snapshot.anchor_after(&primary.end)
1287 }),
1288 };
1289 excerpts.push((id, range.clone()));
1290 let excerpt = Excerpt::new(
1291 id,
1292 locator.clone(),
1293 buffer_id,
1294 buffer_snapshot.clone(),
1295 range,
1296 ranges.peek().is_some() || cursor.item().is_some(),
1297 );
1298 new_excerpts.push(excerpt, &());
1299 prev_locator = locator.clone();
1300
1301 if let Some(last_mapping_entry) = new_excerpt_ids.last() {
1302 assert!(id > last_mapping_entry.id, "excerpt ids must be increasing");
1303 }
1304 new_excerpt_ids.push(ExcerptIdMapping { id, locator }, &());
1305 }
1306
1307 let edit_end = new_excerpts.summary().text.len;
1308
1309 let suffix = cursor.suffix(&());
1310 let changed_trailing_excerpt = suffix.is_empty();
1311 new_excerpts.append(suffix, &());
1312 drop(cursor);
1313 snapshot.excerpts = new_excerpts;
1314 snapshot.excerpt_ids = new_excerpt_ids;
1315 if changed_trailing_excerpt {
1316 snapshot.trailing_excerpt_update_count += 1;
1317 }
1318
1319 self.subscriptions.publish_mut([Edit {
1320 old: edit_start..edit_start,
1321 new: edit_start..edit_end,
1322 }]);
1323 cx.emit(Event::Edited {
1324 singleton_buffer_edited: false,
1325 });
1326 cx.emit(Event::ExcerptsAdded {
1327 buffer,
1328 predecessor: prev_excerpt_id,
1329 excerpts,
1330 });
1331 cx.notify();
1332 }
1333
1334 pub fn clear(&mut self, cx: &mut ModelContext<Self>) {
1335 self.sync(cx);
1336 let ids = self.excerpt_ids();
1337 self.buffers.borrow_mut().clear();
1338 let mut snapshot = self.snapshot.borrow_mut();
1339 let prev_len = snapshot.len();
1340 snapshot.excerpts = Default::default();
1341 snapshot.trailing_excerpt_update_count += 1;
1342 snapshot.is_dirty = false;
1343 snapshot.has_conflict = false;
1344
1345 self.subscriptions.publish_mut([Edit {
1346 old: 0..prev_len,
1347 new: 0..0,
1348 }]);
1349 cx.emit(Event::Edited {
1350 singleton_buffer_edited: false,
1351 });
1352 cx.emit(Event::ExcerptsRemoved { ids });
1353 cx.notify();
1354 }
1355
1356 pub fn excerpts_for_buffer(
1357 &self,
1358 buffer: &Model<Buffer>,
1359 cx: &AppContext,
1360 ) -> Vec<(ExcerptId, ExcerptRange<text::Anchor>)> {
1361 let mut excerpts = Vec::new();
1362 let snapshot = self.read(cx);
1363 let buffers = self.buffers.borrow();
1364 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
1365 for locator in buffers
1366 .get(&buffer.read(cx).remote_id())
1367 .map(|state| &state.excerpts)
1368 .into_iter()
1369 .flatten()
1370 {
1371 cursor.seek_forward(&Some(locator), Bias::Left, &());
1372 if let Some(excerpt) = cursor.item() {
1373 if excerpt.locator == *locator {
1374 excerpts.push((excerpt.id, excerpt.range.clone()));
1375 }
1376 }
1377 }
1378
1379 excerpts
1380 }
1381
1382 pub fn excerpt_buffer_ids(&self) -> Vec<BufferId> {
1383 self.snapshot
1384 .borrow()
1385 .excerpts
1386 .iter()
1387 .map(|entry| entry.buffer_id)
1388 .collect()
1389 }
1390
1391 pub fn excerpt_ids(&self) -> Vec<ExcerptId> {
1392 self.snapshot
1393 .borrow()
1394 .excerpts
1395 .iter()
1396 .map(|entry| entry.id)
1397 .collect()
1398 }
1399
1400 pub fn excerpt_containing(
1401 &self,
1402 position: impl ToOffset,
1403 cx: &AppContext,
1404 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1405 let snapshot = self.read(cx);
1406 let position = position.to_offset(&snapshot);
1407
1408 let mut cursor = snapshot.excerpts.cursor::<usize>();
1409 cursor.seek(&position, Bias::Right, &());
1410 cursor
1411 .item()
1412 .or_else(|| snapshot.excerpts.last())
1413 .map(|excerpt| {
1414 (
1415 excerpt.id,
1416 self.buffers
1417 .borrow()
1418 .get(&excerpt.buffer_id)
1419 .unwrap()
1420 .buffer
1421 .clone(),
1422 excerpt.range.context.clone(),
1423 )
1424 })
1425 }
1426
1427 // If point is at the end of the buffer, the last excerpt is returned
1428 pub fn point_to_buffer_offset<T: ToOffset>(
1429 &self,
1430 point: T,
1431 cx: &AppContext,
1432 ) -> Option<(Model<Buffer>, usize, ExcerptId)> {
1433 let snapshot = self.read(cx);
1434 let offset = point.to_offset(&snapshot);
1435 let mut cursor = snapshot.excerpts.cursor::<usize>();
1436 cursor.seek(&offset, Bias::Right, &());
1437 if cursor.item().is_none() {
1438 cursor.prev(&());
1439 }
1440
1441 cursor.item().map(|excerpt| {
1442 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1443 let buffer_point = excerpt_start + offset - *cursor.start();
1444 let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1445
1446 (buffer, buffer_point, excerpt.id)
1447 })
1448 }
1449
1450 pub fn range_to_buffer_ranges<T: ToOffset>(
1451 &self,
1452 range: Range<T>,
1453 cx: &AppContext,
1454 ) -> Vec<(Model<Buffer>, Range<usize>, ExcerptId)> {
1455 let snapshot = self.read(cx);
1456 let start = range.start.to_offset(&snapshot);
1457 let end = range.end.to_offset(&snapshot);
1458
1459 let mut result = Vec::new();
1460 let mut cursor = snapshot.excerpts.cursor::<usize>();
1461 cursor.seek(&start, Bias::Right, &());
1462 if cursor.item().is_none() {
1463 cursor.prev(&());
1464 }
1465
1466 while let Some(excerpt) = cursor.item() {
1467 if *cursor.start() > end {
1468 break;
1469 }
1470
1471 let mut end_before_newline = cursor.end(&());
1472 if excerpt.has_trailing_newline {
1473 end_before_newline -= 1;
1474 }
1475 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1476 let start = excerpt_start + (cmp::max(start, *cursor.start()) - *cursor.start());
1477 let end = excerpt_start + (cmp::min(end, end_before_newline) - *cursor.start());
1478 let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1479 result.push((buffer, start..end, excerpt.id));
1480 cursor.next(&());
1481 }
1482
1483 result
1484 }
1485
1486 pub fn remove_excerpts(
1487 &mut self,
1488 excerpt_ids: impl IntoIterator<Item = ExcerptId>,
1489 cx: &mut ModelContext<Self>,
1490 ) {
1491 self.sync(cx);
1492 let ids = excerpt_ids.into_iter().collect::<Vec<_>>();
1493 if ids.is_empty() {
1494 return;
1495 }
1496
1497 let mut buffers = self.buffers.borrow_mut();
1498 let mut snapshot = self.snapshot.borrow_mut();
1499 let mut new_excerpts = SumTree::new();
1500 let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1501 let mut edits = Vec::new();
1502 let mut excerpt_ids = ids.iter().copied().peekable();
1503
1504 while let Some(excerpt_id) = excerpt_ids.next() {
1505 // Seek to the next excerpt to remove, preserving any preceding excerpts.
1506 let locator = snapshot.excerpt_locator_for_id(excerpt_id);
1507 new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
1508
1509 if let Some(mut excerpt) = cursor.item() {
1510 if excerpt.id != excerpt_id {
1511 continue;
1512 }
1513 let mut old_start = cursor.start().1;
1514
1515 // Skip over the removed excerpt.
1516 'remove_excerpts: loop {
1517 if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
1518 buffer_state.excerpts.retain(|l| l != &excerpt.locator);
1519 if buffer_state.excerpts.is_empty() {
1520 buffers.remove(&excerpt.buffer_id);
1521 }
1522 }
1523 cursor.next(&());
1524
1525 // Skip over any subsequent excerpts that are also removed.
1526 if let Some(&next_excerpt_id) = excerpt_ids.peek() {
1527 let next_locator = snapshot.excerpt_locator_for_id(next_excerpt_id);
1528 if let Some(next_excerpt) = cursor.item() {
1529 if next_excerpt.locator == *next_locator {
1530 excerpt_ids.next();
1531 excerpt = next_excerpt;
1532 continue 'remove_excerpts;
1533 }
1534 }
1535 }
1536
1537 break;
1538 }
1539
1540 // When removing the last excerpt, remove the trailing newline from
1541 // the previous excerpt.
1542 if cursor.item().is_none() && old_start > 0 {
1543 old_start -= 1;
1544 new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
1545 }
1546
1547 // Push an edit for the removal of this run of excerpts.
1548 let old_end = cursor.start().1;
1549 let new_start = new_excerpts.summary().text.len;
1550 edits.push(Edit {
1551 old: old_start..old_end,
1552 new: new_start..new_start,
1553 });
1554 }
1555 }
1556 let suffix = cursor.suffix(&());
1557 let changed_trailing_excerpt = suffix.is_empty();
1558 new_excerpts.append(suffix, &());
1559 drop(cursor);
1560 snapshot.excerpts = new_excerpts;
1561
1562 if changed_trailing_excerpt {
1563 snapshot.trailing_excerpt_update_count += 1;
1564 }
1565
1566 self.subscriptions.publish_mut(edits);
1567 cx.emit(Event::Edited {
1568 singleton_buffer_edited: false,
1569 });
1570 cx.emit(Event::ExcerptsRemoved { ids });
1571 cx.notify();
1572 }
1573
1574 pub fn wait_for_anchors<'a>(
1575 &self,
1576 anchors: impl 'a + Iterator<Item = Anchor>,
1577 cx: &mut ModelContext<Self>,
1578 ) -> impl 'static + Future<Output = Result<()>> {
1579 let borrow = self.buffers.borrow();
1580 let mut error = None;
1581 let mut futures = Vec::new();
1582 for anchor in anchors {
1583 if let Some(buffer_id) = anchor.buffer_id {
1584 if let Some(buffer) = borrow.get(&buffer_id) {
1585 buffer.buffer.update(cx, |buffer, _| {
1586 futures.push(buffer.wait_for_anchors([anchor.text_anchor]))
1587 });
1588 } else {
1589 error = Some(anyhow!(
1590 "buffer {buffer_id} is not part of this multi-buffer"
1591 ));
1592 break;
1593 }
1594 }
1595 }
1596 async move {
1597 if let Some(error) = error {
1598 Err(error)?;
1599 }
1600 for future in futures {
1601 future.await?;
1602 }
1603 Ok(())
1604 }
1605 }
1606
1607 pub fn text_anchor_for_position<T: ToOffset>(
1608 &self,
1609 position: T,
1610 cx: &AppContext,
1611 ) -> Option<(Model<Buffer>, language::Anchor)> {
1612 let snapshot = self.read(cx);
1613 let anchor = snapshot.anchor_before(position);
1614 let buffer = self
1615 .buffers
1616 .borrow()
1617 .get(&anchor.buffer_id?)?
1618 .buffer
1619 .clone();
1620 Some((buffer, anchor.text_anchor))
1621 }
1622
1623 fn on_buffer_event(
1624 &mut self,
1625 buffer: Model<Buffer>,
1626 event: &language::Event,
1627 cx: &mut ModelContext<Self>,
1628 ) {
1629 cx.emit(match event {
1630 language::Event::Edited => Event::Edited {
1631 singleton_buffer_edited: true,
1632 },
1633 language::Event::DirtyChanged => Event::DirtyChanged,
1634 language::Event::Saved => Event::Saved,
1635 language::Event::FileHandleChanged => Event::FileHandleChanged,
1636 language::Event::Reloaded => Event::Reloaded,
1637 language::Event::DiffBaseChanged => Event::DiffBaseChanged,
1638 language::Event::DiffUpdated => Event::DiffUpdated { buffer },
1639 language::Event::LanguageChanged => Event::LanguageChanged(buffer.read(cx).remote_id()),
1640 language::Event::Reparsed => Event::Reparsed(buffer.read(cx).remote_id()),
1641 language::Event::DiagnosticsUpdated => Event::DiagnosticsUpdated,
1642 language::Event::Closed => Event::Closed,
1643 language::Event::CapabilityChanged => {
1644 self.capability = buffer.read(cx).capability();
1645 Event::CapabilityChanged
1646 }
1647
1648 //
1649 language::Event::Operation(_) => return,
1650 });
1651 }
1652
1653 pub fn all_buffers(&self) -> HashSet<Model<Buffer>> {
1654 self.buffers
1655 .borrow()
1656 .values()
1657 .map(|state| state.buffer.clone())
1658 .collect()
1659 }
1660
1661 pub fn buffer(&self, buffer_id: BufferId) -> Option<Model<Buffer>> {
1662 self.buffers
1663 .borrow()
1664 .get(&buffer_id)
1665 .map(|state| state.buffer.clone())
1666 }
1667
1668 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1669 self.point_to_buffer_offset(point, cx)
1670 .and_then(|(buffer, offset, _)| buffer.read(cx).language_at(offset))
1671 }
1672
1673 pub fn settings_at<'a, T: ToOffset>(
1674 &self,
1675 point: T,
1676 cx: &'a AppContext,
1677 ) -> &'a LanguageSettings {
1678 let mut language = None;
1679 let mut file = None;
1680 if let Some((buffer, offset, _)) = self.point_to_buffer_offset(point, cx) {
1681 let buffer = buffer.read(cx);
1682 language = buffer.language_at(offset);
1683 file = buffer.file();
1684 }
1685 language_settings(language.as_ref(), file, cx)
1686 }
1687
1688 pub fn for_each_buffer(&self, mut f: impl FnMut(&Model<Buffer>)) {
1689 self.buffers
1690 .borrow()
1691 .values()
1692 .for_each(|state| f(&state.buffer))
1693 }
1694
1695 pub fn title<'a>(&'a self, cx: &'a AppContext) -> Cow<'a, str> {
1696 if let Some(title) = self.title.as_ref() {
1697 return title.into();
1698 }
1699
1700 if let Some(buffer) = self.as_singleton() {
1701 if let Some(file) = buffer.read(cx).file() {
1702 return file.file_name(cx).to_string_lossy();
1703 }
1704 }
1705
1706 "untitled".into()
1707 }
1708
1709 pub fn set_title(&mut self, title: String, cx: &mut ModelContext<Self>) {
1710 self.title = Some(title);
1711 cx.notify();
1712 }
1713
1714 #[cfg(any(test, feature = "test-support"))]
1715 pub fn is_parsing(&self, cx: &AppContext) -> bool {
1716 self.as_singleton().unwrap().read(cx).is_parsing()
1717 }
1718
1719 pub fn expand_excerpts(
1720 &mut self,
1721 ids: impl IntoIterator<Item = ExcerptId>,
1722 line_count: u32,
1723 direction: ExpandExcerptDirection,
1724 cx: &mut ModelContext<Self>,
1725 ) {
1726 if line_count == 0 {
1727 return;
1728 }
1729 self.sync(cx);
1730
1731 let ids = ids.into_iter().collect::<Vec<_>>();
1732 let snapshot = self.snapshot(cx);
1733 let locators = snapshot.excerpt_locators_for_ids(ids.iter().copied());
1734 let mut new_excerpts = SumTree::new();
1735 let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1736 let mut edits = Vec::<Edit<usize>>::new();
1737
1738 for locator in &locators {
1739 let prefix = cursor.slice(&Some(locator), Bias::Left, &());
1740 new_excerpts.append(prefix, &());
1741
1742 let mut excerpt = cursor.item().unwrap().clone();
1743 let old_text_len = excerpt.text_summary.len;
1744
1745 let up_line_count = if direction.should_expand_up() {
1746 line_count
1747 } else {
1748 0
1749 };
1750
1751 let start_row = excerpt
1752 .range
1753 .context
1754 .start
1755 .to_point(&excerpt.buffer)
1756 .row
1757 .saturating_sub(up_line_count);
1758 let start_point = Point::new(start_row, 0);
1759 excerpt.range.context.start = excerpt.buffer.anchor_before(start_point);
1760
1761 let down_line_count = if direction.should_expand_down() {
1762 line_count
1763 } else {
1764 0
1765 };
1766
1767 let mut end_point = excerpt.buffer.clip_point(
1768 excerpt.range.context.end.to_point(&excerpt.buffer)
1769 + Point::new(down_line_count, 0),
1770 Bias::Left,
1771 );
1772 end_point.column = excerpt.buffer.line_len(end_point.row);
1773 excerpt.range.context.end = excerpt.buffer.anchor_after(end_point);
1774 excerpt.max_buffer_row = end_point.row;
1775
1776 excerpt.text_summary = excerpt
1777 .buffer
1778 .text_summary_for_range(excerpt.range.context.clone());
1779
1780 let new_start_offset = new_excerpts.summary().text.len;
1781 let old_start_offset = cursor.start().1;
1782 let edit = Edit {
1783 old: old_start_offset..old_start_offset + old_text_len,
1784 new: new_start_offset..new_start_offset + excerpt.text_summary.len,
1785 };
1786
1787 if let Some(last_edit) = edits.last_mut() {
1788 if last_edit.old.end == edit.old.start {
1789 last_edit.old.end = edit.old.end;
1790 last_edit.new.end = edit.new.end;
1791 } else {
1792 edits.push(edit);
1793 }
1794 } else {
1795 edits.push(edit);
1796 }
1797
1798 new_excerpts.push(excerpt, &());
1799
1800 cursor.next(&());
1801 }
1802
1803 new_excerpts.append(cursor.suffix(&()), &());
1804
1805 drop(cursor);
1806 self.snapshot.borrow_mut().excerpts = new_excerpts;
1807
1808 self.subscriptions.publish_mut(edits);
1809 cx.emit(Event::Edited {
1810 singleton_buffer_edited: false,
1811 });
1812 cx.emit(Event::ExcerptsExpanded { ids });
1813 cx.notify();
1814 }
1815
1816 fn sync(&self, cx: &AppContext) {
1817 let mut snapshot = self.snapshot.borrow_mut();
1818 let mut excerpts_to_edit = Vec::new();
1819 let mut non_text_state_updated = false;
1820 let mut is_dirty = false;
1821 let mut has_conflict = false;
1822 let mut edited = false;
1823 let mut buffers = self.buffers.borrow_mut();
1824 for buffer_state in buffers.values_mut() {
1825 let buffer = buffer_state.buffer.read(cx);
1826 let version = buffer.version();
1827 let non_text_state_update_count = buffer.non_text_state_update_count();
1828
1829 let buffer_edited = version.changed_since(&buffer_state.last_version);
1830 let buffer_non_text_state_updated =
1831 non_text_state_update_count > buffer_state.last_non_text_state_update_count;
1832 if buffer_edited || buffer_non_text_state_updated {
1833 buffer_state.last_version = version;
1834 buffer_state.last_non_text_state_update_count = non_text_state_update_count;
1835 excerpts_to_edit.extend(
1836 buffer_state
1837 .excerpts
1838 .iter()
1839 .map(|locator| (locator, buffer_state.buffer.clone(), buffer_edited)),
1840 );
1841 }
1842
1843 edited |= buffer_edited;
1844 non_text_state_updated |= buffer_non_text_state_updated;
1845 is_dirty |= buffer.is_dirty();
1846 has_conflict |= buffer.has_conflict();
1847 }
1848 if edited {
1849 snapshot.edit_count += 1;
1850 }
1851 if non_text_state_updated {
1852 snapshot.non_text_state_update_count += 1;
1853 }
1854 snapshot.is_dirty = is_dirty;
1855 snapshot.has_conflict = has_conflict;
1856
1857 excerpts_to_edit.sort_unstable_by_key(|(locator, _, _)| *locator);
1858
1859 let mut edits = Vec::new();
1860 let mut new_excerpts = SumTree::new();
1861 let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1862
1863 for (locator, buffer, buffer_edited) in excerpts_to_edit {
1864 new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
1865 let old_excerpt = cursor.item().unwrap();
1866 let buffer = buffer.read(cx);
1867 let buffer_id = buffer.remote_id();
1868
1869 let mut new_excerpt;
1870 if buffer_edited {
1871 edits.extend(
1872 buffer
1873 .edits_since_in_range::<usize>(
1874 old_excerpt.buffer.version(),
1875 old_excerpt.range.context.clone(),
1876 )
1877 .map(|mut edit| {
1878 let excerpt_old_start = cursor.start().1;
1879 let excerpt_new_start = new_excerpts.summary().text.len;
1880 edit.old.start += excerpt_old_start;
1881 edit.old.end += excerpt_old_start;
1882 edit.new.start += excerpt_new_start;
1883 edit.new.end += excerpt_new_start;
1884 edit
1885 }),
1886 );
1887
1888 new_excerpt = Excerpt::new(
1889 old_excerpt.id,
1890 locator.clone(),
1891 buffer_id,
1892 buffer.snapshot(),
1893 old_excerpt.range.clone(),
1894 old_excerpt.has_trailing_newline,
1895 );
1896 } else {
1897 new_excerpt = old_excerpt.clone();
1898 new_excerpt.buffer = buffer.snapshot();
1899 }
1900
1901 new_excerpts.push(new_excerpt, &());
1902 cursor.next(&());
1903 }
1904 new_excerpts.append(cursor.suffix(&()), &());
1905
1906 drop(cursor);
1907 snapshot.excerpts = new_excerpts;
1908
1909 self.subscriptions.publish(edits);
1910 }
1911}
1912
1913#[cfg(any(test, feature = "test-support"))]
1914impl MultiBuffer {
1915 pub fn build_simple(text: &str, cx: &mut gpui::AppContext) -> Model<Self> {
1916 let buffer = cx.new_model(|cx| Buffer::local(text, cx));
1917 cx.new_model(|cx| Self::singleton(buffer, cx))
1918 }
1919
1920 pub fn build_multi<const COUNT: usize>(
1921 excerpts: [(&str, Vec<Range<Point>>); COUNT],
1922 cx: &mut gpui::AppContext,
1923 ) -> Model<Self> {
1924 let multi = cx.new_model(|_| Self::new(0, Capability::ReadWrite));
1925 for (text, ranges) in excerpts {
1926 let buffer = cx.new_model(|cx| Buffer::local(text, cx));
1927 let excerpt_ranges = ranges.into_iter().map(|range| ExcerptRange {
1928 context: range,
1929 primary: None,
1930 });
1931 multi.update(cx, |multi, cx| {
1932 multi.push_excerpts(buffer, excerpt_ranges, cx)
1933 });
1934 }
1935
1936 multi
1937 }
1938
1939 pub fn build_from_buffer(buffer: Model<Buffer>, cx: &mut gpui::AppContext) -> Model<Self> {
1940 cx.new_model(|cx| Self::singleton(buffer, cx))
1941 }
1942
1943 pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> Model<Self> {
1944 cx.new_model(|cx| {
1945 let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
1946 let mutation_count = rng.gen_range(1..=5);
1947 multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1948 multibuffer
1949 })
1950 }
1951
1952 pub fn randomly_edit(
1953 &mut self,
1954 rng: &mut impl rand::Rng,
1955 edit_count: usize,
1956 cx: &mut ModelContext<Self>,
1957 ) {
1958 use util::RandomCharIter;
1959
1960 let snapshot = self.read(cx);
1961 let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1962 let mut last_end = None;
1963 for _ in 0..edit_count {
1964 if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1965 break;
1966 }
1967
1968 let new_start = last_end.map_or(0, |last_end| last_end + 1);
1969 let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1970 let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1971 last_end = Some(end);
1972
1973 let mut range = start..end;
1974 if rng.gen_bool(0.2) {
1975 mem::swap(&mut range.start, &mut range.end);
1976 }
1977
1978 let new_text_len = rng.gen_range(0..10);
1979 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1980
1981 edits.push((range, new_text.into()));
1982 }
1983 log::info!("mutating multi-buffer with {:?}", edits);
1984 drop(snapshot);
1985
1986 self.edit(edits, None, cx);
1987 }
1988
1989 pub fn randomly_edit_excerpts(
1990 &mut self,
1991 rng: &mut impl rand::Rng,
1992 mutation_count: usize,
1993 cx: &mut ModelContext<Self>,
1994 ) {
1995 use rand::prelude::*;
1996 use std::env;
1997 use util::RandomCharIter;
1998
1999 let max_excerpts = env::var("MAX_EXCERPTS")
2000 .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
2001 .unwrap_or(5);
2002
2003 let mut buffers = Vec::new();
2004 for _ in 0..mutation_count {
2005 if rng.gen_bool(0.05) {
2006 log::info!("Clearing multi-buffer");
2007 self.clear(cx);
2008 continue;
2009 } else if rng.gen_bool(0.1) && !self.excerpt_ids().is_empty() {
2010 let ids = self.excerpt_ids();
2011 let mut excerpts = HashSet::default();
2012 for _ in 0..rng.gen_range(0..ids.len()) {
2013 excerpts.extend(ids.choose(rng).copied());
2014 }
2015
2016 let line_count = rng.gen_range(0..5);
2017
2018 log::info!("Expanding excerpts {excerpts:?} by {line_count} lines");
2019
2020 self.expand_excerpts(
2021 excerpts.iter().cloned(),
2022 line_count,
2023 ExpandExcerptDirection::UpAndDown,
2024 cx,
2025 );
2026 continue;
2027 }
2028
2029 let excerpt_ids = self.excerpt_ids();
2030 if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
2031 let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
2032 let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
2033 buffers.push(cx.new_model(|cx| Buffer::local(text, cx)));
2034 let buffer = buffers.last().unwrap().read(cx);
2035 log::info!(
2036 "Creating new buffer {} with text: {:?}",
2037 buffer.remote_id(),
2038 buffer.text()
2039 );
2040 buffers.last().unwrap().clone()
2041 } else {
2042 self.buffers
2043 .borrow()
2044 .values()
2045 .choose(rng)
2046 .unwrap()
2047 .buffer
2048 .clone()
2049 };
2050
2051 let buffer = buffer_handle.read(cx);
2052 let buffer_text = buffer.text();
2053 let ranges = (0..rng.gen_range(0..5))
2054 .map(|_| {
2055 let end_ix =
2056 buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
2057 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2058 ExcerptRange {
2059 context: start_ix..end_ix,
2060 primary: None,
2061 }
2062 })
2063 .collect::<Vec<_>>();
2064 log::info!(
2065 "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
2066 buffer_handle.read(cx).remote_id(),
2067 ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
2068 ranges
2069 .iter()
2070 .map(|r| &buffer_text[r.context.clone()])
2071 .collect::<Vec<_>>()
2072 );
2073
2074 let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
2075 log::info!("Inserted with ids: {:?}", excerpt_id);
2076 } else {
2077 let remove_count = rng.gen_range(1..=excerpt_ids.len());
2078 let mut excerpts_to_remove = excerpt_ids
2079 .choose_multiple(rng, remove_count)
2080 .cloned()
2081 .collect::<Vec<_>>();
2082 let snapshot = self.snapshot.borrow();
2083 excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2084 drop(snapshot);
2085 log::info!("Removing excerpts {:?}", excerpts_to_remove);
2086 self.remove_excerpts(excerpts_to_remove, cx);
2087 }
2088 }
2089 }
2090
2091 pub fn randomly_mutate(
2092 &mut self,
2093 rng: &mut impl rand::Rng,
2094 mutation_count: usize,
2095 cx: &mut ModelContext<Self>,
2096 ) {
2097 use rand::prelude::*;
2098
2099 if rng.gen_bool(0.7) || self.singleton {
2100 let buffer = self
2101 .buffers
2102 .borrow()
2103 .values()
2104 .choose(rng)
2105 .map(|state| state.buffer.clone());
2106
2107 if let Some(buffer) = buffer {
2108 buffer.update(cx, |buffer, cx| {
2109 if rng.gen() {
2110 buffer.randomly_edit(rng, mutation_count, cx);
2111 } else {
2112 buffer.randomly_undo_redo(rng, cx);
2113 }
2114 });
2115 } else {
2116 self.randomly_edit(rng, mutation_count, cx);
2117 }
2118 } else {
2119 self.randomly_edit_excerpts(rng, mutation_count, cx);
2120 }
2121
2122 self.check_invariants(cx);
2123 }
2124
2125 fn check_invariants(&self, cx: &mut ModelContext<Self>) {
2126 let snapshot = self.read(cx);
2127 let excerpts = snapshot.excerpts.items(&());
2128 let excerpt_ids = snapshot.excerpt_ids.items(&());
2129
2130 for (ix, excerpt) in excerpts.iter().enumerate() {
2131 if ix == 0 {
2132 if excerpt.locator <= Locator::min() {
2133 panic!("invalid first excerpt locator {:?}", excerpt.locator);
2134 }
2135 } else {
2136 if excerpt.locator <= excerpts[ix - 1].locator {
2137 panic!("excerpts are out-of-order: {:?}", excerpts);
2138 }
2139 }
2140 }
2141
2142 for (ix, entry) in excerpt_ids.iter().enumerate() {
2143 if ix == 0 {
2144 if entry.id.cmp(&ExcerptId::min(), &snapshot).is_le() {
2145 panic!("invalid first excerpt id {:?}", entry.id);
2146 }
2147 } else {
2148 if entry.id <= excerpt_ids[ix - 1].id {
2149 panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
2150 }
2151 }
2152 }
2153 }
2154}
2155
2156impl EventEmitter<Event> for MultiBuffer {}
2157
2158impl MultiBufferSnapshot {
2159 pub fn text(&self) -> String {
2160 self.chunks(0..self.len(), false)
2161 .map(|chunk| chunk.text)
2162 .collect()
2163 }
2164
2165 pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
2166 let mut offset = position.to_offset(self);
2167 let mut cursor = self.excerpts.cursor::<usize>();
2168 cursor.seek(&offset, Bias::Left, &());
2169 let mut excerpt_chunks = cursor.item().map(|excerpt| {
2170 let end_before_footer = cursor.start() + excerpt.text_summary.len;
2171 let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2172 let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
2173 excerpt.buffer.reversed_chunks_in_range(start..end)
2174 });
2175 iter::from_fn(move || {
2176 if offset == *cursor.start() {
2177 cursor.prev(&());
2178 let excerpt = cursor.item()?;
2179 excerpt_chunks = Some(
2180 excerpt
2181 .buffer
2182 .reversed_chunks_in_range(excerpt.range.context.clone()),
2183 );
2184 }
2185
2186 let excerpt = cursor.item().unwrap();
2187 if offset == cursor.end(&()) && excerpt.has_trailing_newline {
2188 offset -= 1;
2189 Some("\n")
2190 } else {
2191 let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
2192 offset -= chunk.len();
2193 Some(chunk)
2194 }
2195 })
2196 .flat_map(|c| c.chars().rev())
2197 }
2198
2199 pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
2200 let offset = position.to_offset(self);
2201 self.text_for_range(offset..self.len())
2202 .flat_map(|chunk| chunk.chars())
2203 }
2204
2205 pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
2206 self.chunks(range, false).map(|chunk| chunk.text)
2207 }
2208
2209 pub fn is_line_blank(&self, row: MultiBufferRow) -> bool {
2210 self.text_for_range(Point::new(row.0, 0)..Point::new(row.0, self.line_len(row)))
2211 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
2212 }
2213
2214 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
2215 where
2216 T: ToOffset,
2217 {
2218 let position = position.to_offset(self);
2219 position == self.clip_offset(position, Bias::Left)
2220 && self
2221 .bytes_in_range(position..self.len())
2222 .flatten()
2223 .copied()
2224 .take(needle.len())
2225 .eq(needle.bytes())
2226 }
2227
2228 pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2229 let mut start = start.to_offset(self);
2230 let mut end = start;
2231 let mut next_chars = self.chars_at(start).peekable();
2232 let mut prev_chars = self.reversed_chars_at(start).peekable();
2233
2234 let scope = self.language_scope_at(start);
2235 let kind = |c| char_kind(&scope, c);
2236 let word_kind = cmp::max(
2237 prev_chars.peek().copied().map(kind),
2238 next_chars.peek().copied().map(kind),
2239 );
2240
2241 for ch in prev_chars {
2242 if Some(kind(ch)) == word_kind && ch != '\n' {
2243 start -= ch.len_utf8();
2244 } else {
2245 break;
2246 }
2247 }
2248
2249 for ch in next_chars {
2250 if Some(kind(ch)) == word_kind && ch != '\n' {
2251 end += ch.len_utf8();
2252 } else {
2253 break;
2254 }
2255 }
2256
2257 (start..end, word_kind)
2258 }
2259
2260 pub fn as_singleton(&self) -> Option<(&ExcerptId, BufferId, &BufferSnapshot)> {
2261 if self.singleton {
2262 self.excerpts
2263 .iter()
2264 .next()
2265 .map(|e| (&e.id, e.buffer_id, &e.buffer))
2266 } else {
2267 None
2268 }
2269 }
2270
2271 pub fn len(&self) -> usize {
2272 self.excerpts.summary().text.len
2273 }
2274
2275 pub fn is_empty(&self) -> bool {
2276 self.excerpts.summary().text.len == 0
2277 }
2278
2279 pub fn max_buffer_row(&self) -> MultiBufferRow {
2280 self.excerpts.summary().max_buffer_row
2281 }
2282
2283 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
2284 if let Some((_, _, buffer)) = self.as_singleton() {
2285 return buffer.clip_offset(offset, bias);
2286 }
2287
2288 let mut cursor = self.excerpts.cursor::<usize>();
2289 cursor.seek(&offset, Bias::Right, &());
2290 let overshoot = if let Some(excerpt) = cursor.item() {
2291 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2292 let buffer_offset = excerpt
2293 .buffer
2294 .clip_offset(excerpt_start + (offset - cursor.start()), bias);
2295 buffer_offset.saturating_sub(excerpt_start)
2296 } else {
2297 0
2298 };
2299 cursor.start() + overshoot
2300 }
2301
2302 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
2303 if let Some((_, _, buffer)) = self.as_singleton() {
2304 return buffer.clip_point(point, bias);
2305 }
2306
2307 let mut cursor = self.excerpts.cursor::<Point>();
2308 cursor.seek(&point, Bias::Right, &());
2309 let overshoot = if let Some(excerpt) = cursor.item() {
2310 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2311 let buffer_point = excerpt
2312 .buffer
2313 .clip_point(excerpt_start + (point - cursor.start()), bias);
2314 buffer_point.saturating_sub(excerpt_start)
2315 } else {
2316 Point::zero()
2317 };
2318 *cursor.start() + overshoot
2319 }
2320
2321 pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
2322 if let Some((_, _, buffer)) = self.as_singleton() {
2323 return buffer.clip_offset_utf16(offset, bias);
2324 }
2325
2326 let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
2327 cursor.seek(&offset, Bias::Right, &());
2328 let overshoot = if let Some(excerpt) = cursor.item() {
2329 let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2330 let buffer_offset = excerpt
2331 .buffer
2332 .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
2333 OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
2334 } else {
2335 OffsetUtf16(0)
2336 };
2337 *cursor.start() + overshoot
2338 }
2339
2340 pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
2341 if let Some((_, _, buffer)) = self.as_singleton() {
2342 return buffer.clip_point_utf16(point, bias);
2343 }
2344
2345 let mut cursor = self.excerpts.cursor::<PointUtf16>();
2346 cursor.seek(&point.0, Bias::Right, &());
2347 let overshoot = if let Some(excerpt) = cursor.item() {
2348 let excerpt_start = excerpt
2349 .buffer
2350 .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2351 let buffer_point = excerpt
2352 .buffer
2353 .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
2354 buffer_point.saturating_sub(excerpt_start)
2355 } else {
2356 PointUtf16::zero()
2357 };
2358 *cursor.start() + overshoot
2359 }
2360
2361 pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
2362 let range = range.start.to_offset(self)..range.end.to_offset(self);
2363 let mut excerpts = self.excerpts.cursor::<usize>();
2364 excerpts.seek(&range.start, Bias::Right, &());
2365
2366 let mut chunk = &[][..];
2367 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2368 let mut excerpt_bytes = excerpt
2369 .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
2370 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2371 Some(excerpt_bytes)
2372 } else {
2373 None
2374 };
2375 MultiBufferBytes {
2376 range,
2377 excerpts,
2378 excerpt_bytes,
2379 chunk,
2380 }
2381 }
2382
2383 pub fn reversed_bytes_in_range<T: ToOffset>(
2384 &self,
2385 range: Range<T>,
2386 ) -> ReversedMultiBufferBytes {
2387 let range = range.start.to_offset(self)..range.end.to_offset(self);
2388 let mut excerpts = self.excerpts.cursor::<usize>();
2389 excerpts.seek(&range.end, Bias::Left, &());
2390
2391 let mut chunk = &[][..];
2392 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2393 let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
2394 range.start.saturating_sub(*excerpts.start())..range.end - *excerpts.start(),
2395 );
2396 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2397 Some(excerpt_bytes)
2398 } else {
2399 None
2400 };
2401
2402 ReversedMultiBufferBytes {
2403 range,
2404 excerpts,
2405 excerpt_bytes,
2406 chunk,
2407 }
2408 }
2409
2410 pub fn buffer_rows(&self, start_row: MultiBufferRow) -> MultiBufferRows {
2411 let mut result = MultiBufferRows {
2412 buffer_row_range: 0..0,
2413 excerpts: self.excerpts.cursor(),
2414 };
2415 result.seek(start_row);
2416 result
2417 }
2418
2419 pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
2420 let range = range.start.to_offset(self)..range.end.to_offset(self);
2421 let mut chunks = MultiBufferChunks {
2422 range: range.clone(),
2423 excerpts: self.excerpts.cursor(),
2424 excerpt_chunks: None,
2425 language_aware,
2426 };
2427 chunks.seek(range.start);
2428 chunks
2429 }
2430
2431 pub fn offset_to_point(&self, offset: usize) -> Point {
2432 if let Some((_, _, buffer)) = self.as_singleton() {
2433 return buffer.offset_to_point(offset);
2434 }
2435
2436 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2437 cursor.seek(&offset, Bias::Right, &());
2438 if let Some(excerpt) = cursor.item() {
2439 let (start_offset, start_point) = cursor.start();
2440 let overshoot = offset - start_offset;
2441 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2442 let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2443 let buffer_point = excerpt
2444 .buffer
2445 .offset_to_point(excerpt_start_offset + overshoot);
2446 *start_point + (buffer_point - excerpt_start_point)
2447 } else {
2448 self.excerpts.summary().text.lines
2449 }
2450 }
2451
2452 pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
2453 if let Some((_, _, buffer)) = self.as_singleton() {
2454 return buffer.offset_to_point_utf16(offset);
2455 }
2456
2457 let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
2458 cursor.seek(&offset, Bias::Right, &());
2459 if let Some(excerpt) = cursor.item() {
2460 let (start_offset, start_point) = cursor.start();
2461 let overshoot = offset - start_offset;
2462 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2463 let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2464 let buffer_point = excerpt
2465 .buffer
2466 .offset_to_point_utf16(excerpt_start_offset + overshoot);
2467 *start_point + (buffer_point - excerpt_start_point)
2468 } else {
2469 self.excerpts.summary().text.lines_utf16()
2470 }
2471 }
2472
2473 pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
2474 if let Some((_, _, buffer)) = self.as_singleton() {
2475 return buffer.point_to_point_utf16(point);
2476 }
2477
2478 let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
2479 cursor.seek(&point, Bias::Right, &());
2480 if let Some(excerpt) = cursor.item() {
2481 let (start_offset, start_point) = cursor.start();
2482 let overshoot = point - start_offset;
2483 let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2484 let excerpt_start_point_utf16 =
2485 excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2486 let buffer_point = excerpt
2487 .buffer
2488 .point_to_point_utf16(excerpt_start_point + overshoot);
2489 *start_point + (buffer_point - excerpt_start_point_utf16)
2490 } else {
2491 self.excerpts.summary().text.lines_utf16()
2492 }
2493 }
2494
2495 pub fn point_to_offset(&self, point: Point) -> usize {
2496 if let Some((_, _, buffer)) = self.as_singleton() {
2497 return buffer.point_to_offset(point);
2498 }
2499
2500 let mut cursor = self.excerpts.cursor::<(Point, usize)>();
2501 cursor.seek(&point, Bias::Right, &());
2502 if let Some(excerpt) = cursor.item() {
2503 let (start_point, start_offset) = cursor.start();
2504 let overshoot = point - start_point;
2505 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2506 let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2507 let buffer_offset = excerpt
2508 .buffer
2509 .point_to_offset(excerpt_start_point + overshoot);
2510 *start_offset + buffer_offset - excerpt_start_offset
2511 } else {
2512 self.excerpts.summary().text.len
2513 }
2514 }
2515
2516 pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2517 if let Some((_, _, buffer)) = self.as_singleton() {
2518 return buffer.offset_utf16_to_offset(offset_utf16);
2519 }
2520
2521 let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2522 cursor.seek(&offset_utf16, Bias::Right, &());
2523 if let Some(excerpt) = cursor.item() {
2524 let (start_offset_utf16, start_offset) = cursor.start();
2525 let overshoot = offset_utf16 - start_offset_utf16;
2526 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2527 let excerpt_start_offset_utf16 =
2528 excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2529 let buffer_offset = excerpt
2530 .buffer
2531 .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2532 *start_offset + (buffer_offset - excerpt_start_offset)
2533 } else {
2534 self.excerpts.summary().text.len
2535 }
2536 }
2537
2538 pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2539 if let Some((_, _, buffer)) = self.as_singleton() {
2540 return buffer.offset_to_offset_utf16(offset);
2541 }
2542
2543 let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2544 cursor.seek(&offset, Bias::Right, &());
2545 if let Some(excerpt) = cursor.item() {
2546 let (start_offset, start_offset_utf16) = cursor.start();
2547 let overshoot = offset - start_offset;
2548 let excerpt_start_offset_utf16 =
2549 excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2550 let excerpt_start_offset = excerpt
2551 .buffer
2552 .offset_utf16_to_offset(excerpt_start_offset_utf16);
2553 let buffer_offset_utf16 = excerpt
2554 .buffer
2555 .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2556 *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2557 } else {
2558 self.excerpts.summary().text.len_utf16
2559 }
2560 }
2561
2562 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2563 if let Some((_, _, buffer)) = self.as_singleton() {
2564 return buffer.point_utf16_to_offset(point);
2565 }
2566
2567 let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2568 cursor.seek(&point, Bias::Right, &());
2569 if let Some(excerpt) = cursor.item() {
2570 let (start_point, start_offset) = cursor.start();
2571 let overshoot = point - start_point;
2572 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2573 let excerpt_start_point = excerpt
2574 .buffer
2575 .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2576 let buffer_offset = excerpt
2577 .buffer
2578 .point_utf16_to_offset(excerpt_start_point + overshoot);
2579 *start_offset + (buffer_offset - excerpt_start_offset)
2580 } else {
2581 self.excerpts.summary().text.len
2582 }
2583 }
2584
2585 pub fn point_to_buffer_offset<T: ToOffset>(
2586 &self,
2587 point: T,
2588 ) -> Option<(&BufferSnapshot, usize)> {
2589 let offset = point.to_offset(self);
2590 let mut cursor = self.excerpts.cursor::<usize>();
2591 cursor.seek(&offset, Bias::Right, &());
2592 if cursor.item().is_none() {
2593 cursor.prev(&());
2594 }
2595
2596 cursor.item().map(|excerpt| {
2597 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2598 let buffer_point = excerpt_start + offset - *cursor.start();
2599 (&excerpt.buffer, buffer_point)
2600 })
2601 }
2602
2603 pub fn suggested_indents(
2604 &self,
2605 rows: impl IntoIterator<Item = u32>,
2606 cx: &AppContext,
2607 ) -> BTreeMap<MultiBufferRow, IndentSize> {
2608 let mut result = BTreeMap::new();
2609
2610 let mut rows_for_excerpt = Vec::new();
2611 let mut cursor = self.excerpts.cursor::<Point>();
2612 let mut rows = rows.into_iter().peekable();
2613 let mut prev_row = u32::MAX;
2614 let mut prev_language_indent_size = IndentSize::default();
2615
2616 while let Some(row) = rows.next() {
2617 cursor.seek(&Point::new(row, 0), Bias::Right, &());
2618 let excerpt = match cursor.item() {
2619 Some(excerpt) => excerpt,
2620 _ => continue,
2621 };
2622
2623 // Retrieve the language and indent size once for each disjoint region being indented.
2624 let single_indent_size = if row.saturating_sub(1) == prev_row {
2625 prev_language_indent_size
2626 } else {
2627 excerpt
2628 .buffer
2629 .language_indent_size_at(Point::new(row, 0), cx)
2630 };
2631 prev_language_indent_size = single_indent_size;
2632 prev_row = row;
2633
2634 let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2635 let start_multibuffer_row = cursor.start().row;
2636
2637 rows_for_excerpt.push(row);
2638 while let Some(next_row) = rows.peek().copied() {
2639 if cursor.end(&()).row > next_row {
2640 rows_for_excerpt.push(next_row);
2641 rows.next();
2642 } else {
2643 break;
2644 }
2645 }
2646
2647 let buffer_rows = rows_for_excerpt
2648 .drain(..)
2649 .map(|row| start_buffer_row + row - start_multibuffer_row);
2650 let buffer_indents = excerpt
2651 .buffer
2652 .suggested_indents(buffer_rows, single_indent_size);
2653 let multibuffer_indents = buffer_indents.into_iter().map(|(row, indent)| {
2654 (
2655 MultiBufferRow(start_multibuffer_row + row - start_buffer_row),
2656 indent,
2657 )
2658 });
2659 result.extend(multibuffer_indents);
2660 }
2661
2662 result
2663 }
2664
2665 pub fn indent_size_for_line(&self, row: MultiBufferRow) -> IndentSize {
2666 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2667 let mut size = buffer.indent_size_for_line(range.start.row);
2668 size.len = size
2669 .len
2670 .min(range.end.column)
2671 .saturating_sub(range.start.column);
2672 size
2673 } else {
2674 IndentSize::spaces(0)
2675 }
2676 }
2677
2678 pub fn prev_non_blank_row(&self, mut row: MultiBufferRow) -> Option<MultiBufferRow> {
2679 while row.0 > 0 {
2680 row.0 -= 1;
2681 if !self.is_line_blank(row) {
2682 return Some(row);
2683 }
2684 }
2685 None
2686 }
2687
2688 pub fn line_len(&self, row: MultiBufferRow) -> u32 {
2689 if let Some((_, range)) = self.buffer_line_for_row(row) {
2690 range.end.column - range.start.column
2691 } else {
2692 0
2693 }
2694 }
2695
2696 pub fn buffer_line_for_row(
2697 &self,
2698 row: MultiBufferRow,
2699 ) -> Option<(&BufferSnapshot, Range<Point>)> {
2700 let mut cursor = self.excerpts.cursor::<Point>();
2701 let point = Point::new(row.0, 0);
2702 cursor.seek(&point, Bias::Right, &());
2703 if cursor.item().is_none() && *cursor.start() == point {
2704 cursor.prev(&());
2705 }
2706 if let Some(excerpt) = cursor.item() {
2707 let overshoot = row.0 - cursor.start().row;
2708 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2709 let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2710 let buffer_row = excerpt_start.row + overshoot;
2711 let line_start = Point::new(buffer_row, 0);
2712 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2713 return Some((
2714 &excerpt.buffer,
2715 line_start.max(excerpt_start)..line_end.min(excerpt_end),
2716 ));
2717 }
2718 None
2719 }
2720
2721 pub fn max_point(&self) -> Point {
2722 self.text_summary().lines
2723 }
2724
2725 pub fn text_summary(&self) -> TextSummary {
2726 self.excerpts.summary().text.clone()
2727 }
2728
2729 pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2730 where
2731 D: TextDimension,
2732 O: ToOffset,
2733 {
2734 let mut summary = D::default();
2735 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2736 let mut cursor = self.excerpts.cursor::<usize>();
2737 cursor.seek(&range.start, Bias::Right, &());
2738 if let Some(excerpt) = cursor.item() {
2739 let mut end_before_newline = cursor.end(&());
2740 if excerpt.has_trailing_newline {
2741 end_before_newline -= 1;
2742 }
2743
2744 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2745 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2746 let end_in_excerpt =
2747 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2748 summary.add_assign(
2749 &excerpt
2750 .buffer
2751 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2752 );
2753
2754 if range.end > end_before_newline {
2755 summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2756 }
2757
2758 cursor.next(&());
2759 }
2760
2761 if range.end > *cursor.start() {
2762 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2763 &range.end,
2764 Bias::Right,
2765 &(),
2766 )));
2767 if let Some(excerpt) = cursor.item() {
2768 range.end = cmp::max(*cursor.start(), range.end);
2769
2770 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2771 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2772 summary.add_assign(
2773 &excerpt
2774 .buffer
2775 .text_summary_for_range(excerpt_start..end_in_excerpt),
2776 );
2777 }
2778 }
2779
2780 summary
2781 }
2782
2783 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2784 where
2785 D: TextDimension + Ord + Sub<D, Output = D>,
2786 {
2787 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2788 let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2789
2790 cursor.seek(locator, Bias::Left, &());
2791 if cursor.item().is_none() {
2792 cursor.next(&());
2793 }
2794
2795 let mut position = D::from_text_summary(&cursor.start().text);
2796 if let Some(excerpt) = cursor.item() {
2797 if excerpt.id == anchor.excerpt_id {
2798 let excerpt_buffer_start =
2799 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2800 let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2801 let buffer_position = cmp::min(
2802 excerpt_buffer_end,
2803 anchor.text_anchor.summary::<D>(&excerpt.buffer),
2804 );
2805 if buffer_position > excerpt_buffer_start {
2806 position.add_assign(&(buffer_position - excerpt_buffer_start));
2807 }
2808 }
2809 }
2810 position
2811 }
2812
2813 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2814 where
2815 D: TextDimension + Ord + Sub<D, Output = D>,
2816 I: 'a + IntoIterator<Item = &'a Anchor>,
2817 {
2818 if let Some((_, _, buffer)) = self.as_singleton() {
2819 return buffer
2820 .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2821 .collect();
2822 }
2823
2824 let mut anchors = anchors.into_iter().peekable();
2825 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2826 let mut summaries = Vec::new();
2827 while let Some(anchor) = anchors.peek() {
2828 let excerpt_id = anchor.excerpt_id;
2829 let excerpt_anchors = iter::from_fn(|| {
2830 let anchor = anchors.peek()?;
2831 if anchor.excerpt_id == excerpt_id {
2832 Some(&anchors.next().unwrap().text_anchor)
2833 } else {
2834 None
2835 }
2836 });
2837
2838 let locator = self.excerpt_locator_for_id(excerpt_id);
2839 cursor.seek_forward(locator, Bias::Left, &());
2840 if cursor.item().is_none() {
2841 cursor.next(&());
2842 }
2843
2844 let position = D::from_text_summary(&cursor.start().text);
2845 if let Some(excerpt) = cursor.item() {
2846 if excerpt.id == excerpt_id {
2847 let excerpt_buffer_start =
2848 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2849 let excerpt_buffer_end =
2850 excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2851 summaries.extend(
2852 excerpt
2853 .buffer
2854 .summaries_for_anchors::<D, _>(excerpt_anchors)
2855 .map(move |summary| {
2856 let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2857 let mut position = position.clone();
2858 let excerpt_buffer_start = excerpt_buffer_start.clone();
2859 if summary > excerpt_buffer_start {
2860 position.add_assign(&(summary - excerpt_buffer_start));
2861 }
2862 position
2863 }),
2864 );
2865 continue;
2866 }
2867 }
2868
2869 summaries.extend(excerpt_anchors.map(|_| position.clone()));
2870 }
2871
2872 summaries
2873 }
2874
2875 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2876 where
2877 I: 'a + IntoIterator<Item = &'a Anchor>,
2878 {
2879 let mut anchors = anchors.into_iter().enumerate().peekable();
2880 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2881 cursor.next(&());
2882
2883 let mut result = Vec::new();
2884
2885 while let Some((_, anchor)) = anchors.peek() {
2886 let old_excerpt_id = anchor.excerpt_id;
2887
2888 // Find the location where this anchor's excerpt should be.
2889 let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2890 cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2891
2892 if cursor.item().is_none() {
2893 cursor.next(&());
2894 }
2895
2896 let next_excerpt = cursor.item();
2897 let prev_excerpt = cursor.prev_item();
2898
2899 // Process all of the anchors for this excerpt.
2900 while let Some((_, anchor)) = anchors.peek() {
2901 if anchor.excerpt_id != old_excerpt_id {
2902 break;
2903 }
2904 let (anchor_ix, anchor) = anchors.next().unwrap();
2905 let mut anchor = *anchor;
2906
2907 // Leave min and max anchors unchanged if invalid or
2908 // if the old excerpt still exists at this location
2909 let mut kept_position = next_excerpt
2910 .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2911 || old_excerpt_id == ExcerptId::max()
2912 || old_excerpt_id == ExcerptId::min();
2913
2914 // If the old excerpt no longer exists at this location, then attempt to
2915 // find an equivalent position for this anchor in an adjacent excerpt.
2916 if !kept_position {
2917 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2918 if excerpt.contains(&anchor) {
2919 anchor.excerpt_id = excerpt.id;
2920 kept_position = true;
2921 break;
2922 }
2923 }
2924 }
2925
2926 // If there's no adjacent excerpt that contains the anchor's position,
2927 // then report that the anchor has lost its position.
2928 if !kept_position {
2929 anchor = if let Some(excerpt) = next_excerpt {
2930 let mut text_anchor = excerpt
2931 .range
2932 .context
2933 .start
2934 .bias(anchor.text_anchor.bias, &excerpt.buffer);
2935 if text_anchor
2936 .cmp(&excerpt.range.context.end, &excerpt.buffer)
2937 .is_gt()
2938 {
2939 text_anchor = excerpt.range.context.end;
2940 }
2941 Anchor {
2942 buffer_id: Some(excerpt.buffer_id),
2943 excerpt_id: excerpt.id,
2944 text_anchor,
2945 }
2946 } else if let Some(excerpt) = prev_excerpt {
2947 let mut text_anchor = excerpt
2948 .range
2949 .context
2950 .end
2951 .bias(anchor.text_anchor.bias, &excerpt.buffer);
2952 if text_anchor
2953 .cmp(&excerpt.range.context.start, &excerpt.buffer)
2954 .is_lt()
2955 {
2956 text_anchor = excerpt.range.context.start;
2957 }
2958 Anchor {
2959 buffer_id: Some(excerpt.buffer_id),
2960 excerpt_id: excerpt.id,
2961 text_anchor,
2962 }
2963 } else if anchor.text_anchor.bias == Bias::Left {
2964 Anchor::min()
2965 } else {
2966 Anchor::max()
2967 };
2968 }
2969
2970 result.push((anchor_ix, anchor, kept_position));
2971 }
2972 }
2973 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2974 result
2975 }
2976
2977 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2978 self.anchor_at(position, Bias::Left)
2979 }
2980
2981 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2982 self.anchor_at(position, Bias::Right)
2983 }
2984
2985 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2986 let offset = position.to_offset(self);
2987 if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2988 return Anchor {
2989 buffer_id: Some(buffer_id),
2990 excerpt_id: *excerpt_id,
2991 text_anchor: buffer.anchor_at(offset, bias),
2992 };
2993 }
2994
2995 let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2996 cursor.seek(&offset, Bias::Right, &());
2997 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2998 cursor.prev(&());
2999 }
3000 if let Some(excerpt) = cursor.item() {
3001 let mut overshoot = offset.saturating_sub(cursor.start().0);
3002 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
3003 overshoot -= 1;
3004 bias = Bias::Right;
3005 }
3006
3007 let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3008 let text_anchor =
3009 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
3010 Anchor {
3011 buffer_id: Some(excerpt.buffer_id),
3012 excerpt_id: excerpt.id,
3013 text_anchor,
3014 }
3015 } else if offset == 0 && bias == Bias::Left {
3016 Anchor::min()
3017 } else {
3018 Anchor::max()
3019 }
3020 }
3021
3022 /// Returns an anchor for the given excerpt and text anchor,
3023 /// returns None if the excerpt_id is no longer valid.
3024 pub fn anchor_in_excerpt(
3025 &self,
3026 excerpt_id: ExcerptId,
3027 text_anchor: text::Anchor,
3028 ) -> Option<Anchor> {
3029 let locator = self.excerpt_locator_for_id(excerpt_id);
3030 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3031 cursor.seek(locator, Bias::Left, &());
3032 if let Some(excerpt) = cursor.item() {
3033 if excerpt.id == excerpt_id {
3034 let text_anchor = excerpt.clip_anchor(text_anchor);
3035 drop(cursor);
3036 return Some(Anchor {
3037 buffer_id: Some(excerpt.buffer_id),
3038 excerpt_id,
3039 text_anchor,
3040 });
3041 }
3042 }
3043 None
3044 }
3045
3046 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
3047 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
3048 true
3049 } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
3050 excerpt.buffer.can_resolve(&anchor.text_anchor)
3051 } else {
3052 false
3053 }
3054 }
3055
3056 pub fn excerpts(
3057 &self,
3058 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
3059 self.excerpts
3060 .iter()
3061 .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
3062 }
3063
3064 fn excerpts_for_range<T: ToOffset>(
3065 &self,
3066 range: Range<T>,
3067 ) -> impl Iterator<Item = (&Excerpt, usize)> + '_ {
3068 let range = range.start.to_offset(self)..range.end.to_offset(self);
3069
3070 let mut cursor = self.excerpts.cursor::<usize>();
3071 cursor.seek(&range.start, Bias::Right, &());
3072 cursor.prev(&());
3073
3074 iter::from_fn(move || {
3075 cursor.next(&());
3076 if cursor.start() < &range.end {
3077 cursor.item().map(|item| (item, *cursor.start()))
3078 } else {
3079 None
3080 }
3081 })
3082 }
3083
3084 pub fn excerpt_boundaries_in_range<R, T>(
3085 &self,
3086 range: R,
3087 ) -> impl Iterator<Item = ExcerptBoundary> + '_
3088 where
3089 R: RangeBounds<T>,
3090 T: ToOffset,
3091 {
3092 let start_offset;
3093 let start = match range.start_bound() {
3094 Bound::Included(start) => {
3095 start_offset = start.to_offset(self);
3096 Bound::Included(start_offset)
3097 }
3098 Bound::Excluded(start) => {
3099 start_offset = start.to_offset(self);
3100 Bound::Excluded(start_offset)
3101 }
3102 Bound::Unbounded => {
3103 start_offset = 0;
3104 Bound::Unbounded
3105 }
3106 };
3107 let end = match range.end_bound() {
3108 Bound::Included(end) => Bound::Included(end.to_offset(self)),
3109 Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
3110 Bound::Unbounded => Bound::Unbounded,
3111 };
3112 let bounds = (start, end);
3113
3114 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
3115 cursor.seek(&start_offset, Bias::Right, &());
3116 if cursor.item().is_none() {
3117 cursor.prev(&());
3118 }
3119 if !bounds.contains(&cursor.start().0) {
3120 cursor.next(&());
3121 }
3122
3123 let mut visited_end = false;
3124 std::iter::from_fn(move || {
3125 if self.singleton {
3126 None
3127 } else if bounds.contains(&cursor.start().0) {
3128 let next = cursor.item().map(|excerpt| ExcerptInfo {
3129 id: excerpt.id,
3130 buffer: excerpt.buffer.clone(),
3131 buffer_id: excerpt.buffer_id,
3132 range: excerpt.range.clone(),
3133 });
3134
3135 if next.is_none() {
3136 if visited_end {
3137 return None;
3138 } else {
3139 visited_end = true;
3140 }
3141 }
3142
3143 let prev = cursor.prev_item().map(|prev_excerpt| ExcerptInfo {
3144 id: prev_excerpt.id,
3145 buffer: prev_excerpt.buffer.clone(),
3146 buffer_id: prev_excerpt.buffer_id,
3147 range: prev_excerpt.range.clone(),
3148 });
3149 let row = MultiBufferRow(cursor.start().1.row);
3150
3151 cursor.next(&());
3152
3153 Some(ExcerptBoundary { row, prev, next })
3154 } else {
3155 None
3156 }
3157 })
3158 }
3159
3160 pub fn edit_count(&self) -> usize {
3161 self.edit_count
3162 }
3163
3164 pub fn non_text_state_update_count(&self) -> usize {
3165 self.non_text_state_update_count
3166 }
3167
3168 /// Returns the smallest enclosing bracket ranges containing the given range or
3169 /// None if no brackets contain range or the range is not contained in a single
3170 /// excerpt
3171 ///
3172 /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3173 pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3174 &self,
3175 range: Range<T>,
3176 range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3177 ) -> Option<(Range<usize>, Range<usize>)> {
3178 let range = range.start.to_offset(self)..range.end.to_offset(self);
3179 let excerpt = self.excerpt_containing(range.clone())?;
3180
3181 // Filter to ranges contained in the excerpt
3182 let range_filter = |open: Range<usize>, close: Range<usize>| -> bool {
3183 excerpt.contains_buffer_range(open.start..close.end)
3184 && range_filter.map_or(true, |filter| {
3185 filter(
3186 excerpt.map_range_from_buffer(open),
3187 excerpt.map_range_from_buffer(close),
3188 )
3189 })
3190 };
3191
3192 let (open, close) = excerpt.buffer().innermost_enclosing_bracket_ranges(
3193 excerpt.map_range_to_buffer(range),
3194 Some(&range_filter),
3195 )?;
3196
3197 Some((
3198 excerpt.map_range_from_buffer(open),
3199 excerpt.map_range_from_buffer(close),
3200 ))
3201 }
3202
3203 /// Returns enclosing bracket ranges containing the given range or returns None if the range is
3204 /// not contained in a single excerpt
3205 pub fn enclosing_bracket_ranges<T: ToOffset>(
3206 &self,
3207 range: Range<T>,
3208 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
3209 let range = range.start.to_offset(self)..range.end.to_offset(self);
3210 let excerpt = self.excerpt_containing(range.clone())?;
3211
3212 Some(
3213 excerpt
3214 .buffer()
3215 .enclosing_bracket_ranges(excerpt.map_range_to_buffer(range))
3216 .filter_map(move |(open, close)| {
3217 if excerpt.contains_buffer_range(open.start..close.end) {
3218 Some((
3219 excerpt.map_range_from_buffer(open),
3220 excerpt.map_range_from_buffer(close),
3221 ))
3222 } else {
3223 None
3224 }
3225 }),
3226 )
3227 }
3228
3229 /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
3230 /// not contained in a single excerpt
3231 pub fn bracket_ranges<T: ToOffset>(
3232 &self,
3233 range: Range<T>,
3234 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
3235 let range = range.start.to_offset(self)..range.end.to_offset(self);
3236 let excerpt = self.excerpt_containing(range.clone())?;
3237
3238 Some(
3239 excerpt
3240 .buffer()
3241 .bracket_ranges(excerpt.map_range_to_buffer(range))
3242 .filter_map(move |(start_bracket_range, close_bracket_range)| {
3243 let buffer_range = start_bracket_range.start..close_bracket_range.end;
3244 if excerpt.contains_buffer_range(buffer_range) {
3245 Some((
3246 excerpt.map_range_from_buffer(start_bracket_range),
3247 excerpt.map_range_from_buffer(close_bracket_range),
3248 ))
3249 } else {
3250 None
3251 }
3252 }),
3253 )
3254 }
3255
3256 pub fn redacted_ranges<'a, T: ToOffset>(
3257 &'a self,
3258 range: Range<T>,
3259 redaction_enabled: impl Fn(Option<&Arc<dyn File>>) -> bool + 'a,
3260 ) -> impl Iterator<Item = Range<usize>> + 'a {
3261 let range = range.start.to_offset(self)..range.end.to_offset(self);
3262 self.excerpts_for_range(range.clone())
3263 .filter_map(move |(excerpt, excerpt_offset)| {
3264 redaction_enabled(excerpt.buffer.file()).then(move || {
3265 let excerpt_buffer_start =
3266 excerpt.range.context.start.to_offset(&excerpt.buffer);
3267
3268 excerpt
3269 .buffer
3270 .redacted_ranges(excerpt.range.context.clone())
3271 .map(move |mut redacted_range| {
3272 // Re-base onto the excerpts coordinates in the multibuffer
3273 redacted_range.start = excerpt_offset
3274 + redacted_range.start.saturating_sub(excerpt_buffer_start);
3275 redacted_range.end = excerpt_offset
3276 + redacted_range.end.saturating_sub(excerpt_buffer_start);
3277
3278 redacted_range
3279 })
3280 .skip_while(move |redacted_range| redacted_range.end < range.start)
3281 .take_while(move |redacted_range| redacted_range.start < range.end)
3282 })
3283 })
3284 .flatten()
3285 }
3286
3287 pub fn runnable_ranges(
3288 &self,
3289 range: Range<Anchor>,
3290 ) -> impl Iterator<Item = language::RunnableRange> + '_ {
3291 let range = range.start.to_offset(self)..range.end.to_offset(self);
3292 self.excerpts_for_range(range.clone())
3293 .flat_map(move |(excerpt, excerpt_offset)| {
3294 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3295
3296 excerpt
3297 .buffer
3298 .runnable_ranges(excerpt.range.context.clone())
3299 .filter_map(move |mut runnable| {
3300 // Re-base onto the excerpts coordinates in the multibuffer
3301 //
3302 // The node matching our runnables query might partially overlap with
3303 // the provided range. If the run indicator is outside of excerpt bounds, do not actually show it.
3304 if runnable.run_range.start < excerpt_buffer_start {
3305 return None;
3306 }
3307 if language::ToPoint::to_point(&runnable.run_range.end, &excerpt.buffer).row
3308 > excerpt.max_buffer_row
3309 {
3310 return None;
3311 }
3312 runnable.run_range.start =
3313 excerpt_offset + runnable.run_range.start - excerpt_buffer_start;
3314 runnable.run_range.end =
3315 excerpt_offset + runnable.run_range.end - excerpt_buffer_start;
3316 Some(runnable)
3317 })
3318 .skip_while(move |runnable| runnable.run_range.end < range.start)
3319 .take_while(move |runnable| runnable.run_range.start < range.end)
3320 })
3321 }
3322
3323 pub fn indent_guides_in_range(
3324 &self,
3325 range: Range<Anchor>,
3326 ignore_disabled_for_language: bool,
3327 cx: &AppContext,
3328 ) -> Vec<MultiBufferIndentGuide> {
3329 // Fast path for singleton buffers, we can skip the conversion between offsets.
3330 if let Some((_, _, snapshot)) = self.as_singleton() {
3331 return snapshot
3332 .indent_guides_in_range(
3333 range.start.text_anchor..range.end.text_anchor,
3334 ignore_disabled_for_language,
3335 cx,
3336 )
3337 .into_iter()
3338 .map(|guide| MultiBufferIndentGuide {
3339 multibuffer_row_range: MultiBufferRow(guide.start_row)
3340 ..MultiBufferRow(guide.end_row),
3341 buffer: guide,
3342 })
3343 .collect();
3344 }
3345
3346 let range = range.start.to_offset(self)..range.end.to_offset(self);
3347
3348 self.excerpts_for_range(range.clone())
3349 .flat_map(move |(excerpt, excerpt_offset)| {
3350 let excerpt_buffer_start_row =
3351 excerpt.range.context.start.to_point(&excerpt.buffer).row;
3352 let excerpt_offset_row = crate::ToPoint::to_point(&excerpt_offset, self).row;
3353
3354 excerpt
3355 .buffer
3356 .indent_guides_in_range(
3357 excerpt.range.context.clone(),
3358 ignore_disabled_for_language,
3359 cx,
3360 )
3361 .into_iter()
3362 .map(move |indent_guide| {
3363 let start_row = excerpt_offset_row
3364 + (indent_guide.start_row - excerpt_buffer_start_row);
3365 let end_row =
3366 excerpt_offset_row + (indent_guide.end_row - excerpt_buffer_start_row);
3367
3368 MultiBufferIndentGuide {
3369 multibuffer_row_range: MultiBufferRow(start_row)
3370 ..MultiBufferRow(end_row),
3371 buffer: indent_guide,
3372 }
3373 })
3374 })
3375 .collect()
3376 }
3377
3378 pub fn trailing_excerpt_update_count(&self) -> usize {
3379 self.trailing_excerpt_update_count
3380 }
3381
3382 pub fn file_at<T: ToOffset>(&self, point: T) -> Option<&Arc<dyn File>> {
3383 self.point_to_buffer_offset(point)
3384 .and_then(|(buffer, _)| buffer.file())
3385 }
3386
3387 pub fn language_at<T: ToOffset>(&self, point: T) -> Option<&Arc<Language>> {
3388 self.point_to_buffer_offset(point)
3389 .and_then(|(buffer, offset)| buffer.language_at(offset))
3390 }
3391
3392 pub fn settings_at<'a, T: ToOffset>(
3393 &'a self,
3394 point: T,
3395 cx: &'a AppContext,
3396 ) -> &'a LanguageSettings {
3397 let mut language = None;
3398 let mut file = None;
3399 if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
3400 language = buffer.language_at(offset);
3401 file = buffer.file();
3402 }
3403 language_settings(language, file, cx)
3404 }
3405
3406 pub fn language_scope_at<T: ToOffset>(&self, point: T) -> Option<LanguageScope> {
3407 self.point_to_buffer_offset(point)
3408 .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
3409 }
3410
3411 pub fn language_indent_size_at<T: ToOffset>(
3412 &self,
3413 position: T,
3414 cx: &AppContext,
3415 ) -> Option<IndentSize> {
3416 let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
3417 Some(buffer_snapshot.language_indent_size_at(offset, cx))
3418 }
3419
3420 pub fn is_dirty(&self) -> bool {
3421 self.is_dirty
3422 }
3423
3424 pub fn has_conflict(&self) -> bool {
3425 self.has_conflict
3426 }
3427
3428 pub fn has_diagnostics(&self) -> bool {
3429 self.excerpts
3430 .iter()
3431 .any(|excerpt| excerpt.buffer.has_diagnostics())
3432 }
3433
3434 pub fn diagnostic_group<'a, O>(
3435 &'a self,
3436 group_id: usize,
3437 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3438 where
3439 O: text::FromAnchor + 'a,
3440 {
3441 self.as_singleton()
3442 .into_iter()
3443 .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
3444 }
3445
3446 pub fn diagnostics_in_range<'a, T, O>(
3447 &'a self,
3448 range: Range<T>,
3449 reversed: bool,
3450 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3451 where
3452 T: 'a + ToOffset,
3453 O: 'a + text::FromAnchor + Ord,
3454 {
3455 self.as_singleton()
3456 .into_iter()
3457 .flat_map(move |(_, _, buffer)| {
3458 buffer.diagnostics_in_range(
3459 range.start.to_offset(self)..range.end.to_offset(self),
3460 reversed,
3461 )
3462 })
3463 }
3464
3465 pub fn has_git_diffs(&self) -> bool {
3466 for excerpt in self.excerpts.iter() {
3467 if excerpt.buffer.has_git_diff() {
3468 return true;
3469 }
3470 }
3471 false
3472 }
3473
3474 pub fn git_diff_hunks_in_range_rev(
3475 &self,
3476 row_range: Range<MultiBufferRow>,
3477 ) -> impl Iterator<Item = DiffHunk<MultiBufferRow>> + '_ {
3478 let mut cursor = self.excerpts.cursor::<Point>();
3479
3480 cursor.seek(&Point::new(row_range.end.0, 0), Bias::Left, &());
3481 if cursor.item().is_none() {
3482 cursor.prev(&());
3483 }
3484
3485 std::iter::from_fn(move || {
3486 let excerpt = cursor.item()?;
3487 let multibuffer_start = *cursor.start();
3488 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3489 if multibuffer_start.row >= row_range.end.0 {
3490 return None;
3491 }
3492
3493 let mut buffer_start = excerpt.range.context.start;
3494 let mut buffer_end = excerpt.range.context.end;
3495 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3496 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3497
3498 if row_range.start.0 > multibuffer_start.row {
3499 let buffer_start_point =
3500 excerpt_start_point + Point::new(row_range.start.0 - multibuffer_start.row, 0);
3501 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3502 }
3503
3504 if row_range.end.0 < multibuffer_end.row {
3505 let buffer_end_point =
3506 excerpt_start_point + Point::new(row_range.end.0 - multibuffer_start.row, 0);
3507 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3508 }
3509
3510 let buffer_hunks = excerpt
3511 .buffer
3512 .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
3513 .map(move |hunk| {
3514 let start = multibuffer_start.row
3515 + hunk
3516 .associated_range
3517 .start
3518 .saturating_sub(excerpt_start_point.row);
3519 let end = multibuffer_start.row
3520 + hunk
3521 .associated_range
3522 .end
3523 .min(excerpt_end_point.row + 1)
3524 .saturating_sub(excerpt_start_point.row);
3525
3526 DiffHunk {
3527 associated_range: MultiBufferRow(start)..MultiBufferRow(end),
3528 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3529 buffer_range: hunk.buffer_range.clone(),
3530 buffer_id: hunk.buffer_id,
3531 }
3532 });
3533
3534 cursor.prev(&());
3535
3536 Some(buffer_hunks)
3537 })
3538 .flatten()
3539 }
3540
3541 pub fn git_diff_hunks_in_range(
3542 &self,
3543 row_range: Range<MultiBufferRow>,
3544 ) -> impl Iterator<Item = DiffHunk<MultiBufferRow>> + '_ {
3545 let mut cursor = self.excerpts.cursor::<Point>();
3546
3547 cursor.seek(&Point::new(row_range.start.0, 0), Bias::Left, &());
3548
3549 std::iter::from_fn(move || {
3550 let excerpt = cursor.item()?;
3551 let multibuffer_start = *cursor.start();
3552 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3553 let mut buffer_start = excerpt.range.context.start;
3554 let mut buffer_end = excerpt.range.context.end;
3555
3556 let excerpt_rows = match multibuffer_start.row.cmp(&row_range.end.0) {
3557 cmp::Ordering::Less => {
3558 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3559 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3560
3561 if row_range.start.0 > multibuffer_start.row {
3562 let buffer_start_point = excerpt_start_point
3563 + Point::new(row_range.start.0 - multibuffer_start.row, 0);
3564 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3565 }
3566
3567 if row_range.end.0 < multibuffer_end.row {
3568 let buffer_end_point = excerpt_start_point
3569 + Point::new(row_range.end.0 - multibuffer_start.row, 0);
3570 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3571 }
3572 excerpt_start_point.row..excerpt_end_point.row
3573 }
3574 cmp::Ordering::Equal if row_range.end.0 == 0 => {
3575 buffer_end = buffer_start;
3576 0..0
3577 }
3578 cmp::Ordering::Greater | cmp::Ordering::Equal => return None,
3579 };
3580
3581 let buffer_hunks = excerpt
3582 .buffer
3583 .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3584 .map(move |hunk| {
3585 let buffer_range = if excerpt_rows.start == 0 && excerpt_rows.end == 0 {
3586 MultiBufferRow(0)..MultiBufferRow(1)
3587 } else {
3588 let start = multibuffer_start.row
3589 + hunk
3590 .associated_range
3591 .start
3592 .saturating_sub(excerpt_rows.start);
3593 let end = multibuffer_start.row
3594 + hunk
3595 .associated_range
3596 .end
3597 .min(excerpt_rows.end + 1)
3598 .saturating_sub(excerpt_rows.start);
3599 MultiBufferRow(start)..MultiBufferRow(end)
3600 };
3601 DiffHunk {
3602 associated_range: buffer_range,
3603 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3604 buffer_range: hunk.buffer_range.clone(),
3605 buffer_id: hunk.buffer_id,
3606 }
3607 });
3608
3609 cursor.next(&());
3610
3611 Some(buffer_hunks)
3612 })
3613 .flatten()
3614 }
3615
3616 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3617 let range = range.start.to_offset(self)..range.end.to_offset(self);
3618 let excerpt = self.excerpt_containing(range.clone())?;
3619
3620 let ancestor_buffer_range = excerpt
3621 .buffer()
3622 .range_for_syntax_ancestor(excerpt.map_range_to_buffer(range))?;
3623
3624 Some(excerpt.map_range_from_buffer(ancestor_buffer_range))
3625 }
3626
3627 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3628 let (excerpt_id, _, buffer) = self.as_singleton()?;
3629 let outline = buffer.outline(theme)?;
3630 Some(Outline::new(
3631 outline
3632 .items
3633 .into_iter()
3634 .flat_map(|item| {
3635 Some(OutlineItem {
3636 depth: item.depth,
3637 range: self.anchor_in_excerpt(*excerpt_id, item.range.start)?
3638 ..self.anchor_in_excerpt(*excerpt_id, item.range.end)?,
3639 text: item.text,
3640 highlight_ranges: item.highlight_ranges,
3641 name_ranges: item.name_ranges,
3642 body_range: item.body_range.and_then(|body_range| {
3643 Some(
3644 self.anchor_in_excerpt(*excerpt_id, body_range.start)?
3645 ..self.anchor_in_excerpt(*excerpt_id, body_range.end)?,
3646 )
3647 }),
3648 })
3649 })
3650 .collect(),
3651 ))
3652 }
3653
3654 pub fn symbols_containing<T: ToOffset>(
3655 &self,
3656 offset: T,
3657 theme: Option<&SyntaxTheme>,
3658 ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
3659 let anchor = self.anchor_before(offset);
3660 let excerpt_id = anchor.excerpt_id;
3661 let excerpt = self.excerpt(excerpt_id)?;
3662 Some((
3663 excerpt.buffer_id,
3664 excerpt
3665 .buffer
3666 .symbols_containing(anchor.text_anchor, theme)
3667 .into_iter()
3668 .flatten()
3669 .flat_map(|item| {
3670 Some(OutlineItem {
3671 depth: item.depth,
3672 range: self.anchor_in_excerpt(excerpt_id, item.range.start)?
3673 ..self.anchor_in_excerpt(excerpt_id, item.range.end)?,
3674 text: item.text,
3675 highlight_ranges: item.highlight_ranges,
3676 name_ranges: item.name_ranges,
3677 body_range: item.body_range.and_then(|body_range| {
3678 Some(
3679 self.anchor_in_excerpt(excerpt_id, body_range.start)?
3680 ..self.anchor_in_excerpt(excerpt_id, body_range.end)?,
3681 )
3682 }),
3683 })
3684 })
3685 .collect(),
3686 ))
3687 }
3688
3689 fn excerpt_locator_for_id(&self, id: ExcerptId) -> &Locator {
3690 if id == ExcerptId::min() {
3691 Locator::min_ref()
3692 } else if id == ExcerptId::max() {
3693 Locator::max_ref()
3694 } else {
3695 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3696 cursor.seek(&id, Bias::Left, &());
3697 if let Some(entry) = cursor.item() {
3698 if entry.id == id {
3699 return &entry.locator;
3700 }
3701 }
3702 panic!("invalid excerpt id {:?}", id)
3703 }
3704 }
3705
3706 // Returns the locators referenced by the given excerpt ids, sorted by locator.
3707 fn excerpt_locators_for_ids(
3708 &self,
3709 ids: impl IntoIterator<Item = ExcerptId>,
3710 ) -> SmallVec<[Locator; 1]> {
3711 let mut sorted_ids = ids.into_iter().collect::<SmallVec<[_; 1]>>();
3712 sorted_ids.sort_unstable();
3713 let mut locators = SmallVec::new();
3714
3715 while sorted_ids.last() == Some(&ExcerptId::max()) {
3716 sorted_ids.pop();
3717 locators.push(Locator::max());
3718 }
3719
3720 let mut sorted_ids = sorted_ids.into_iter().dedup().peekable();
3721 if sorted_ids.peek() == Some(&ExcerptId::min()) {
3722 sorted_ids.next();
3723 locators.push(Locator::min());
3724 }
3725
3726 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3727 for id in sorted_ids {
3728 if cursor.seek_forward(&id, Bias::Left, &()) {
3729 locators.push(cursor.item().unwrap().locator.clone());
3730 } else {
3731 panic!("invalid excerpt id {:?}", id);
3732 }
3733 }
3734
3735 locators.sort_unstable();
3736 locators
3737 }
3738
3739 pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<BufferId> {
3740 Some(self.excerpt(excerpt_id)?.buffer_id)
3741 }
3742
3743 pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3744 Some(&self.excerpt(excerpt_id)?.buffer)
3745 }
3746
3747 fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
3748 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3749 let locator = self.excerpt_locator_for_id(excerpt_id);
3750 cursor.seek(&Some(locator), Bias::Left, &());
3751 if let Some(excerpt) = cursor.item() {
3752 if excerpt.id == excerpt_id {
3753 return Some(excerpt);
3754 }
3755 }
3756 None
3757 }
3758
3759 /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3760 pub fn excerpt_containing<T: ToOffset>(&self, range: Range<T>) -> Option<MultiBufferExcerpt> {
3761 let range = range.start.to_offset(self)..range.end.to_offset(self);
3762
3763 let mut cursor = self.excerpts.cursor::<usize>();
3764 cursor.seek(&range.start, Bias::Right, &());
3765 let start_excerpt = cursor.item()?;
3766
3767 if range.start == range.end {
3768 return Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()));
3769 }
3770
3771 cursor.seek(&range.end, Bias::Right, &());
3772 let end_excerpt = cursor.item()?;
3773
3774 if start_excerpt.id == end_excerpt.id {
3775 Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()))
3776 } else {
3777 None
3778 }
3779 }
3780
3781 /// Returns excerpts overlapping the given ranges. If range spans multiple excerpts returns one range for each excerpt
3782 pub fn excerpts_in_ranges(
3783 &self,
3784 ranges: impl IntoIterator<Item = Range<Anchor>>,
3785 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, Range<usize>)> {
3786 let mut ranges = ranges.into_iter().map(|range| range.to_offset(self));
3787 let mut cursor = self.excerpts.cursor::<usize>();
3788 cursor.next(&());
3789 let mut current_range = ranges.next();
3790 iter::from_fn(move || {
3791 let range = current_range.clone()?;
3792 if range.start >= cursor.end(&()) {
3793 cursor.seek_forward(&range.start, Bias::Right, &());
3794 if range.start == self.len() {
3795 cursor.prev(&());
3796 }
3797 }
3798
3799 let excerpt = cursor.item()?;
3800 let range_start_in_excerpt = cmp::max(range.start, *cursor.start());
3801 let range_end_in_excerpt = if excerpt.has_trailing_newline {
3802 cmp::min(range.end, cursor.end(&()) - 1)
3803 } else {
3804 cmp::min(range.end, cursor.end(&()))
3805 };
3806 let buffer_range = MultiBufferExcerpt::new(excerpt, *cursor.start())
3807 .map_range_to_buffer(range_start_in_excerpt..range_end_in_excerpt);
3808
3809 if range.end > cursor.end(&()) {
3810 cursor.next(&());
3811 } else {
3812 current_range = ranges.next();
3813 }
3814
3815 Some((excerpt.id, &excerpt.buffer, buffer_range))
3816 })
3817 }
3818
3819 pub fn selections_in_range<'a>(
3820 &'a self,
3821 range: &'a Range<Anchor>,
3822 include_local: bool,
3823 ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3824 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3825 let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3826 let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3827 cursor.seek(start_locator, Bias::Left, &());
3828 cursor
3829 .take_while(move |excerpt| excerpt.locator <= *end_locator)
3830 .flat_map(move |excerpt| {
3831 let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3832 if excerpt.id == range.start.excerpt_id {
3833 query_range.start = range.start.text_anchor;
3834 }
3835 if excerpt.id == range.end.excerpt_id {
3836 query_range.end = range.end.text_anchor;
3837 }
3838
3839 excerpt
3840 .buffer
3841 .selections_in_range(query_range, include_local)
3842 .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3843 selections.map(move |selection| {
3844 let mut start = Anchor {
3845 buffer_id: Some(excerpt.buffer_id),
3846 excerpt_id: excerpt.id,
3847 text_anchor: selection.start,
3848 };
3849 let mut end = Anchor {
3850 buffer_id: Some(excerpt.buffer_id),
3851 excerpt_id: excerpt.id,
3852 text_anchor: selection.end,
3853 };
3854 if range.start.cmp(&start, self).is_gt() {
3855 start = range.start;
3856 }
3857 if range.end.cmp(&end, self).is_lt() {
3858 end = range.end;
3859 }
3860
3861 (
3862 replica_id,
3863 line_mode,
3864 cursor_shape,
3865 Selection {
3866 id: selection.id,
3867 start,
3868 end,
3869 reversed: selection.reversed,
3870 goal: selection.goal,
3871 },
3872 )
3873 })
3874 })
3875 })
3876 }
3877
3878 pub fn show_headers(&self) -> bool {
3879 self.show_headers
3880 }
3881}
3882
3883#[cfg(any(test, feature = "test-support"))]
3884impl MultiBufferSnapshot {
3885 pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3886 let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3887 let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3888 start..end
3889 }
3890}
3891
3892impl History {
3893 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3894 self.transaction_depth += 1;
3895 if self.transaction_depth == 1 {
3896 let id = self.next_transaction_id.tick();
3897 self.undo_stack.push(Transaction {
3898 id,
3899 buffer_transactions: Default::default(),
3900 first_edit_at: now,
3901 last_edit_at: now,
3902 suppress_grouping: false,
3903 });
3904 Some(id)
3905 } else {
3906 None
3907 }
3908 }
3909
3910 fn end_transaction(
3911 &mut self,
3912 now: Instant,
3913 buffer_transactions: HashMap<BufferId, TransactionId>,
3914 ) -> bool {
3915 assert_ne!(self.transaction_depth, 0);
3916 self.transaction_depth -= 1;
3917 if self.transaction_depth == 0 {
3918 if buffer_transactions.is_empty() {
3919 self.undo_stack.pop();
3920 false
3921 } else {
3922 self.redo_stack.clear();
3923 let transaction = self.undo_stack.last_mut().unwrap();
3924 transaction.last_edit_at = now;
3925 for (buffer_id, transaction_id) in buffer_transactions {
3926 transaction
3927 .buffer_transactions
3928 .entry(buffer_id)
3929 .or_insert(transaction_id);
3930 }
3931 true
3932 }
3933 } else {
3934 false
3935 }
3936 }
3937
3938 fn push_transaction<'a, T>(
3939 &mut self,
3940 buffer_transactions: T,
3941 now: Instant,
3942 cx: &mut ModelContext<MultiBuffer>,
3943 ) where
3944 T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
3945 {
3946 assert_eq!(self.transaction_depth, 0);
3947 let transaction = Transaction {
3948 id: self.next_transaction_id.tick(),
3949 buffer_transactions: buffer_transactions
3950 .into_iter()
3951 .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3952 .collect(),
3953 first_edit_at: now,
3954 last_edit_at: now,
3955 suppress_grouping: false,
3956 };
3957 if !transaction.buffer_transactions.is_empty() {
3958 self.undo_stack.push(transaction);
3959 self.redo_stack.clear();
3960 }
3961 }
3962
3963 fn finalize_last_transaction(&mut self) {
3964 if let Some(transaction) = self.undo_stack.last_mut() {
3965 transaction.suppress_grouping = true;
3966 }
3967 }
3968
3969 fn forget(&mut self, transaction_id: TransactionId) -> Option<Transaction> {
3970 if let Some(ix) = self
3971 .undo_stack
3972 .iter()
3973 .rposition(|transaction| transaction.id == transaction_id)
3974 {
3975 Some(self.undo_stack.remove(ix))
3976 } else if let Some(ix) = self
3977 .redo_stack
3978 .iter()
3979 .rposition(|transaction| transaction.id == transaction_id)
3980 {
3981 Some(self.redo_stack.remove(ix))
3982 } else {
3983 None
3984 }
3985 }
3986
3987 fn transaction(&self, transaction_id: TransactionId) -> Option<&Transaction> {
3988 self.undo_stack
3989 .iter()
3990 .find(|transaction| transaction.id == transaction_id)
3991 .or_else(|| {
3992 self.redo_stack
3993 .iter()
3994 .find(|transaction| transaction.id == transaction_id)
3995 })
3996 }
3997
3998 fn transaction_mut(&mut self, transaction_id: TransactionId) -> Option<&mut Transaction> {
3999 self.undo_stack
4000 .iter_mut()
4001 .find(|transaction| transaction.id == transaction_id)
4002 .or_else(|| {
4003 self.redo_stack
4004 .iter_mut()
4005 .find(|transaction| transaction.id == transaction_id)
4006 })
4007 }
4008
4009 fn pop_undo(&mut self) -> Option<&mut Transaction> {
4010 assert_eq!(self.transaction_depth, 0);
4011 if let Some(transaction) = self.undo_stack.pop() {
4012 self.redo_stack.push(transaction);
4013 self.redo_stack.last_mut()
4014 } else {
4015 None
4016 }
4017 }
4018
4019 fn pop_redo(&mut self) -> Option<&mut Transaction> {
4020 assert_eq!(self.transaction_depth, 0);
4021 if let Some(transaction) = self.redo_stack.pop() {
4022 self.undo_stack.push(transaction);
4023 self.undo_stack.last_mut()
4024 } else {
4025 None
4026 }
4027 }
4028
4029 fn remove_from_undo(&mut self, transaction_id: TransactionId) -> Option<&Transaction> {
4030 let ix = self
4031 .undo_stack
4032 .iter()
4033 .rposition(|transaction| transaction.id == transaction_id)?;
4034 let transaction = self.undo_stack.remove(ix);
4035 self.redo_stack.push(transaction);
4036 self.redo_stack.last()
4037 }
4038
4039 fn group(&mut self) -> Option<TransactionId> {
4040 let mut count = 0;
4041 let mut transactions = self.undo_stack.iter();
4042 if let Some(mut transaction) = transactions.next_back() {
4043 while let Some(prev_transaction) = transactions.next_back() {
4044 if !prev_transaction.suppress_grouping
4045 && transaction.first_edit_at - prev_transaction.last_edit_at
4046 <= self.group_interval
4047 {
4048 transaction = prev_transaction;
4049 count += 1;
4050 } else {
4051 break;
4052 }
4053 }
4054 }
4055 self.group_trailing(count)
4056 }
4057
4058 fn group_until(&mut self, transaction_id: TransactionId) {
4059 let mut count = 0;
4060 for transaction in self.undo_stack.iter().rev() {
4061 if transaction.id == transaction_id {
4062 self.group_trailing(count);
4063 break;
4064 } else if transaction.suppress_grouping {
4065 break;
4066 } else {
4067 count += 1;
4068 }
4069 }
4070 }
4071
4072 fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
4073 let new_len = self.undo_stack.len() - n;
4074 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
4075 if let Some(last_transaction) = transactions_to_keep.last_mut() {
4076 if let Some(transaction) = transactions_to_merge.last() {
4077 last_transaction.last_edit_at = transaction.last_edit_at;
4078 }
4079 for to_merge in transactions_to_merge {
4080 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
4081 last_transaction
4082 .buffer_transactions
4083 .entry(*buffer_id)
4084 .or_insert(*transaction_id);
4085 }
4086 }
4087 }
4088
4089 self.undo_stack.truncate(new_len);
4090 self.undo_stack.last().map(|t| t.id)
4091 }
4092}
4093
4094impl Excerpt {
4095 fn new(
4096 id: ExcerptId,
4097 locator: Locator,
4098 buffer_id: BufferId,
4099 buffer: BufferSnapshot,
4100 range: ExcerptRange<text::Anchor>,
4101 has_trailing_newline: bool,
4102 ) -> Self {
4103 Excerpt {
4104 id,
4105 locator,
4106 max_buffer_row: range.context.end.to_point(&buffer).row,
4107 text_summary: buffer
4108 .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
4109 buffer_id,
4110 buffer,
4111 range,
4112 has_trailing_newline,
4113 }
4114 }
4115
4116 fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
4117 let content_start = self.range.context.start.to_offset(&self.buffer);
4118 let chunks_start = content_start + range.start;
4119 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
4120
4121 let footer_height = if self.has_trailing_newline
4122 && range.start <= self.text_summary.len
4123 && range.end > self.text_summary.len
4124 {
4125 1
4126 } else {
4127 0
4128 };
4129
4130 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
4131
4132 ExcerptChunks {
4133 content_chunks,
4134 footer_height,
4135 }
4136 }
4137
4138 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
4139 let content_start = self.range.context.start.to_offset(&self.buffer);
4140 let bytes_start = content_start + range.start;
4141 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
4142 let footer_height = if self.has_trailing_newline
4143 && range.start <= self.text_summary.len
4144 && range.end > self.text_summary.len
4145 {
4146 1
4147 } else {
4148 0
4149 };
4150 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
4151
4152 ExcerptBytes {
4153 content_bytes,
4154 padding_height: footer_height,
4155 reversed: false,
4156 }
4157 }
4158
4159 fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
4160 let content_start = self.range.context.start.to_offset(&self.buffer);
4161 let bytes_start = content_start + range.start;
4162 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
4163 let footer_height = if self.has_trailing_newline
4164 && range.start <= self.text_summary.len
4165 && range.end > self.text_summary.len
4166 {
4167 1
4168 } else {
4169 0
4170 };
4171 let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
4172
4173 ExcerptBytes {
4174 content_bytes,
4175 padding_height: footer_height,
4176 reversed: true,
4177 }
4178 }
4179
4180 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
4181 if text_anchor
4182 .cmp(&self.range.context.start, &self.buffer)
4183 .is_lt()
4184 {
4185 self.range.context.start
4186 } else if text_anchor
4187 .cmp(&self.range.context.end, &self.buffer)
4188 .is_gt()
4189 {
4190 self.range.context.end
4191 } else {
4192 text_anchor
4193 }
4194 }
4195
4196 fn contains(&self, anchor: &Anchor) -> bool {
4197 Some(self.buffer_id) == anchor.buffer_id
4198 && self
4199 .range
4200 .context
4201 .start
4202 .cmp(&anchor.text_anchor, &self.buffer)
4203 .is_le()
4204 && self
4205 .range
4206 .context
4207 .end
4208 .cmp(&anchor.text_anchor, &self.buffer)
4209 .is_ge()
4210 }
4211
4212 /// The [`Excerpt`]'s start offset in its [`Buffer`]
4213 fn buffer_start_offset(&self) -> usize {
4214 self.range.context.start.to_offset(&self.buffer)
4215 }
4216
4217 /// The [`Excerpt`]'s end offset in its [`Buffer`]
4218 fn buffer_end_offset(&self) -> usize {
4219 self.buffer_start_offset() + self.text_summary.len
4220 }
4221}
4222
4223impl<'a> MultiBufferExcerpt<'a> {
4224 fn new(excerpt: &'a Excerpt, excerpt_offset: usize) -> Self {
4225 MultiBufferExcerpt {
4226 excerpt,
4227 excerpt_offset,
4228 }
4229 }
4230
4231 pub fn buffer(&self) -> &'a BufferSnapshot {
4232 &self.excerpt.buffer
4233 }
4234
4235 /// Maps an offset within the [`MultiBuffer`] to an offset within the [`Buffer`]
4236 pub fn map_offset_to_buffer(&self, offset: usize) -> usize {
4237 self.excerpt.buffer_start_offset() + offset.saturating_sub(self.excerpt_offset)
4238 }
4239
4240 /// Maps a range within the [`MultiBuffer`] to a range within the [`Buffer`]
4241 pub fn map_range_to_buffer(&self, range: Range<usize>) -> Range<usize> {
4242 self.map_offset_to_buffer(range.start)..self.map_offset_to_buffer(range.end)
4243 }
4244
4245 /// Map an offset within the [`Buffer`] to an offset within the [`MultiBuffer`]
4246 pub fn map_offset_from_buffer(&self, buffer_offset: usize) -> usize {
4247 let mut buffer_offset_in_excerpt =
4248 buffer_offset.saturating_sub(self.excerpt.buffer_start_offset());
4249 buffer_offset_in_excerpt =
4250 cmp::min(buffer_offset_in_excerpt, self.excerpt.text_summary.len);
4251
4252 self.excerpt_offset + buffer_offset_in_excerpt
4253 }
4254
4255 /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
4256 pub fn map_range_from_buffer(&self, buffer_range: Range<usize>) -> Range<usize> {
4257 self.map_offset_from_buffer(buffer_range.start)
4258 ..self.map_offset_from_buffer(buffer_range.end)
4259 }
4260
4261 /// Returns true if the entirety of the given range is in the buffer's excerpt
4262 pub fn contains_buffer_range(&self, range: Range<usize>) -> bool {
4263 range.start >= self.excerpt.buffer_start_offset()
4264 && range.end <= self.excerpt.buffer_end_offset()
4265 }
4266}
4267
4268impl ExcerptId {
4269 pub fn min() -> Self {
4270 Self(0)
4271 }
4272
4273 pub fn max() -> Self {
4274 Self(usize::MAX)
4275 }
4276
4277 pub fn to_proto(&self) -> u64 {
4278 self.0 as _
4279 }
4280
4281 pub fn from_proto(proto: u64) -> Self {
4282 Self(proto as _)
4283 }
4284
4285 pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
4286 let a = snapshot.excerpt_locator_for_id(*self);
4287 let b = snapshot.excerpt_locator_for_id(*other);
4288 a.cmp(b).then_with(|| self.0.cmp(&other.0))
4289 }
4290}
4291
4292impl Into<usize> for ExcerptId {
4293 fn into(self) -> usize {
4294 self.0
4295 }
4296}
4297
4298impl fmt::Debug for Excerpt {
4299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4300 f.debug_struct("Excerpt")
4301 .field("id", &self.id)
4302 .field("locator", &self.locator)
4303 .field("buffer_id", &self.buffer_id)
4304 .field("range", &self.range)
4305 .field("text_summary", &self.text_summary)
4306 .field("has_trailing_newline", &self.has_trailing_newline)
4307 .finish()
4308 }
4309}
4310
4311impl sum_tree::Item for Excerpt {
4312 type Summary = ExcerptSummary;
4313
4314 fn summary(&self) -> Self::Summary {
4315 let mut text = self.text_summary.clone();
4316 if self.has_trailing_newline {
4317 text += TextSummary::from("\n");
4318 }
4319 ExcerptSummary {
4320 excerpt_id: self.id,
4321 excerpt_locator: self.locator.clone(),
4322 max_buffer_row: MultiBufferRow(self.max_buffer_row),
4323 text,
4324 }
4325 }
4326}
4327
4328impl sum_tree::Item for ExcerptIdMapping {
4329 type Summary = ExcerptId;
4330
4331 fn summary(&self) -> Self::Summary {
4332 self.id
4333 }
4334}
4335
4336impl sum_tree::KeyedItem for ExcerptIdMapping {
4337 type Key = ExcerptId;
4338
4339 fn key(&self) -> Self::Key {
4340 self.id
4341 }
4342}
4343
4344impl sum_tree::Summary for ExcerptId {
4345 type Context = ();
4346
4347 fn add_summary(&mut self, other: &Self, _: &()) {
4348 *self = *other;
4349 }
4350}
4351
4352impl sum_tree::Summary for ExcerptSummary {
4353 type Context = ();
4354
4355 fn add_summary(&mut self, summary: &Self, _: &()) {
4356 debug_assert!(summary.excerpt_locator > self.excerpt_locator);
4357 self.excerpt_locator = summary.excerpt_locator.clone();
4358 self.text.add_summary(&summary.text, &());
4359 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
4360 }
4361}
4362
4363impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
4364 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4365 *self += &summary.text;
4366 }
4367}
4368
4369impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
4370 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4371 *self += summary.text.len;
4372 }
4373}
4374
4375impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
4376 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4377 Ord::cmp(self, &cursor_location.text.len)
4378 }
4379}
4380
4381impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
4382 fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
4383 Ord::cmp(&Some(self), cursor_location)
4384 }
4385}
4386
4387impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
4388 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4389 Ord::cmp(self, &cursor_location.excerpt_locator)
4390 }
4391}
4392
4393impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
4394 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4395 *self += summary.text.len_utf16;
4396 }
4397}
4398
4399impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
4400 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4401 *self += summary.text.lines;
4402 }
4403}
4404
4405impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
4406 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4407 *self += summary.text.lines_utf16()
4408 }
4409}
4410
4411impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
4412 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4413 *self = Some(&summary.excerpt_locator);
4414 }
4415}
4416
4417impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
4418 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4419 *self = Some(summary.excerpt_id);
4420 }
4421}
4422
4423impl<'a> MultiBufferRows<'a> {
4424 pub fn seek(&mut self, row: MultiBufferRow) {
4425 self.buffer_row_range = 0..0;
4426
4427 self.excerpts
4428 .seek_forward(&Point::new(row.0, 0), Bias::Right, &());
4429 if self.excerpts.item().is_none() {
4430 self.excerpts.prev(&());
4431
4432 if self.excerpts.item().is_none() && row.0 == 0 {
4433 self.buffer_row_range = 0..1;
4434 return;
4435 }
4436 }
4437
4438 if let Some(excerpt) = self.excerpts.item() {
4439 let overshoot = row.0 - self.excerpts.start().row;
4440 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4441 self.buffer_row_range.start = excerpt_start + overshoot;
4442 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
4443 }
4444 }
4445}
4446
4447impl<'a> Iterator for MultiBufferRows<'a> {
4448 type Item = Option<u32>;
4449
4450 fn next(&mut self) -> Option<Self::Item> {
4451 loop {
4452 if !self.buffer_row_range.is_empty() {
4453 let row = Some(self.buffer_row_range.start);
4454 self.buffer_row_range.start += 1;
4455 return Some(row);
4456 }
4457 self.excerpts.item()?;
4458 self.excerpts.next(&());
4459 let excerpt = self.excerpts.item()?;
4460 self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4461 self.buffer_row_range.end =
4462 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
4463 }
4464 }
4465}
4466
4467impl<'a> MultiBufferChunks<'a> {
4468 pub fn offset(&self) -> usize {
4469 self.range.start
4470 }
4471
4472 pub fn seek(&mut self, offset: usize) {
4473 self.range.start = offset;
4474 self.excerpts.seek(&offset, Bias::Right, &());
4475 if let Some(excerpt) = self.excerpts.item() {
4476 self.excerpt_chunks = Some(excerpt.chunks_in_range(
4477 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
4478 self.language_aware,
4479 ));
4480 } else {
4481 self.excerpt_chunks = None;
4482 }
4483 }
4484}
4485
4486impl<'a> Iterator for MultiBufferChunks<'a> {
4487 type Item = Chunk<'a>;
4488
4489 fn next(&mut self) -> Option<Self::Item> {
4490 if self.range.is_empty() {
4491 None
4492 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
4493 self.range.start += chunk.text.len();
4494 Some(chunk)
4495 } else {
4496 self.excerpts.next(&());
4497 let excerpt = self.excerpts.item()?;
4498 self.excerpt_chunks = Some(excerpt.chunks_in_range(
4499 0..self.range.end - self.excerpts.start(),
4500 self.language_aware,
4501 ));
4502 self.next()
4503 }
4504 }
4505}
4506
4507impl<'a> MultiBufferBytes<'a> {
4508 fn consume(&mut self, len: usize) {
4509 self.range.start += len;
4510 self.chunk = &self.chunk[len..];
4511
4512 if !self.range.is_empty() && self.chunk.is_empty() {
4513 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4514 self.chunk = chunk;
4515 } else {
4516 self.excerpts.next(&());
4517 if let Some(excerpt) = self.excerpts.item() {
4518 let mut excerpt_bytes =
4519 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
4520 self.chunk = excerpt_bytes.next().unwrap();
4521 self.excerpt_bytes = Some(excerpt_bytes);
4522 }
4523 }
4524 }
4525 }
4526}
4527
4528impl<'a> Iterator for MultiBufferBytes<'a> {
4529 type Item = &'a [u8];
4530
4531 fn next(&mut self) -> Option<Self::Item> {
4532 let chunk = self.chunk;
4533 if chunk.is_empty() {
4534 None
4535 } else {
4536 self.consume(chunk.len());
4537 Some(chunk)
4538 }
4539 }
4540}
4541
4542impl<'a> io::Read for MultiBufferBytes<'a> {
4543 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4544 let len = cmp::min(buf.len(), self.chunk.len());
4545 buf[..len].copy_from_slice(&self.chunk[..len]);
4546 if len > 0 {
4547 self.consume(len);
4548 }
4549 Ok(len)
4550 }
4551}
4552
4553impl<'a> ReversedMultiBufferBytes<'a> {
4554 fn consume(&mut self, len: usize) {
4555 self.range.end -= len;
4556 self.chunk = &self.chunk[..self.chunk.len() - len];
4557
4558 if !self.range.is_empty() && self.chunk.is_empty() {
4559 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4560 self.chunk = chunk;
4561 } else {
4562 self.excerpts.prev(&());
4563 if let Some(excerpt) = self.excerpts.item() {
4564 let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
4565 self.range.start.saturating_sub(*self.excerpts.start())..usize::MAX,
4566 );
4567 self.chunk = excerpt_bytes.next().unwrap();
4568 self.excerpt_bytes = Some(excerpt_bytes);
4569 }
4570 }
4571 } else {
4572 }
4573 }
4574}
4575
4576impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
4577 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4578 let len = cmp::min(buf.len(), self.chunk.len());
4579 buf[..len].copy_from_slice(&self.chunk[..len]);
4580 buf[..len].reverse();
4581 if len > 0 {
4582 self.consume(len);
4583 }
4584 Ok(len)
4585 }
4586}
4587impl<'a> Iterator for ExcerptBytes<'a> {
4588 type Item = &'a [u8];
4589
4590 fn next(&mut self) -> Option<Self::Item> {
4591 if self.reversed && self.padding_height > 0 {
4592 let result = &NEWLINES[..self.padding_height];
4593 self.padding_height = 0;
4594 return Some(result);
4595 }
4596
4597 if let Some(chunk) = self.content_bytes.next() {
4598 if !chunk.is_empty() {
4599 return Some(chunk);
4600 }
4601 }
4602
4603 if self.padding_height > 0 {
4604 let result = &NEWLINES[..self.padding_height];
4605 self.padding_height = 0;
4606 return Some(result);
4607 }
4608
4609 None
4610 }
4611}
4612
4613impl<'a> Iterator for ExcerptChunks<'a> {
4614 type Item = Chunk<'a>;
4615
4616 fn next(&mut self) -> Option<Self::Item> {
4617 if let Some(chunk) = self.content_chunks.next() {
4618 return Some(chunk);
4619 }
4620
4621 if self.footer_height > 0 {
4622 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
4623 self.footer_height = 0;
4624 return Some(Chunk {
4625 text,
4626 ..Default::default()
4627 });
4628 }
4629
4630 None
4631 }
4632}
4633
4634impl ToOffset for Point {
4635 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4636 snapshot.point_to_offset(*self)
4637 }
4638}
4639
4640impl ToOffset for usize {
4641 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4642 assert!(*self <= snapshot.len(), "offset is out of range");
4643 *self
4644 }
4645}
4646
4647impl ToOffset for OffsetUtf16 {
4648 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4649 snapshot.offset_utf16_to_offset(*self)
4650 }
4651}
4652
4653impl ToOffset for PointUtf16 {
4654 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4655 snapshot.point_utf16_to_offset(*self)
4656 }
4657}
4658
4659impl ToOffsetUtf16 for OffsetUtf16 {
4660 fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4661 *self
4662 }
4663}
4664
4665impl ToOffsetUtf16 for usize {
4666 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4667 snapshot.offset_to_offset_utf16(*self)
4668 }
4669}
4670
4671impl ToPoint for usize {
4672 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
4673 snapshot.offset_to_point(*self)
4674 }
4675}
4676
4677impl ToPoint for Point {
4678 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
4679 *self
4680 }
4681}
4682
4683impl ToPointUtf16 for usize {
4684 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4685 snapshot.offset_to_point_utf16(*self)
4686 }
4687}
4688
4689impl ToPointUtf16 for Point {
4690 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4691 snapshot.point_to_point_utf16(*self)
4692 }
4693}
4694
4695impl ToPointUtf16 for PointUtf16 {
4696 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
4697 *self
4698 }
4699}
4700
4701pub fn build_excerpt_ranges<T>(
4702 buffer: &BufferSnapshot,
4703 ranges: &[Range<T>],
4704 context_line_count: u32,
4705) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
4706where
4707 T: text::ToPoint,
4708{
4709 let max_point = buffer.max_point();
4710 let mut range_counts = Vec::new();
4711 let mut excerpt_ranges = Vec::new();
4712 let mut range_iter = ranges
4713 .iter()
4714 .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
4715 .peekable();
4716 while let Some(range) = range_iter.next() {
4717 let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
4718 let row = (range.end.row + context_line_count).min(max_point.row);
4719 let mut excerpt_end = Point::new(row, buffer.line_len(row));
4720
4721 let mut ranges_in_excerpt = 1;
4722
4723 while let Some(next_range) = range_iter.peek() {
4724 if next_range.start.row <= excerpt_end.row + context_line_count {
4725 let row = (next_range.end.row + context_line_count).min(max_point.row);
4726 excerpt_end = Point::new(row, buffer.line_len(row));
4727
4728 ranges_in_excerpt += 1;
4729 range_iter.next();
4730 } else {
4731 break;
4732 }
4733 }
4734
4735 excerpt_ranges.push(ExcerptRange {
4736 context: excerpt_start..excerpt_end,
4737 primary: Some(range),
4738 });
4739 range_counts.push(ranges_in_excerpt);
4740 }
4741
4742 (excerpt_ranges, range_counts)
4743}
4744
4745#[cfg(test)]
4746mod tests {
4747 use super::*;
4748 use futures::StreamExt;
4749 use gpui::{AppContext, Context, TestAppContext};
4750 use language::{Buffer, Rope};
4751 use parking_lot::RwLock;
4752 use rand::prelude::*;
4753 use settings::SettingsStore;
4754 use std::env;
4755 use util::test::sample_text;
4756
4757 #[ctor::ctor]
4758 fn init_logger() {
4759 if std::env::var("RUST_LOG").is_ok() {
4760 env_logger::init();
4761 }
4762 }
4763
4764 #[gpui::test]
4765 fn test_singleton(cx: &mut AppContext) {
4766 let buffer = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4767 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4768
4769 let snapshot = multibuffer.read(cx).snapshot(cx);
4770 assert_eq!(snapshot.text(), buffer.read(cx).text());
4771
4772 assert_eq!(
4773 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4774 (0..buffer.read(cx).row_count())
4775 .map(Some)
4776 .collect::<Vec<_>>()
4777 );
4778
4779 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4780 let snapshot = multibuffer.read(cx).snapshot(cx);
4781
4782 assert_eq!(snapshot.text(), buffer.read(cx).text());
4783 assert_eq!(
4784 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4785 (0..buffer.read(cx).row_count())
4786 .map(Some)
4787 .collect::<Vec<_>>()
4788 );
4789 }
4790
4791 #[gpui::test]
4792 fn test_remote(cx: &mut AppContext) {
4793 let host_buffer = cx.new_model(|cx| Buffer::local("a", cx));
4794 let guest_buffer = cx.new_model(|cx| {
4795 let state = host_buffer.read(cx).to_proto();
4796 let ops = cx
4797 .background_executor()
4798 .block(host_buffer.read(cx).serialize_ops(None, cx));
4799 let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
4800 buffer
4801 .apply_ops(
4802 ops.into_iter()
4803 .map(|op| language::proto::deserialize_operation(op).unwrap()),
4804 cx,
4805 )
4806 .unwrap();
4807 buffer
4808 });
4809 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4810 let snapshot = multibuffer.read(cx).snapshot(cx);
4811 assert_eq!(snapshot.text(), "a");
4812
4813 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4814 let snapshot = multibuffer.read(cx).snapshot(cx);
4815 assert_eq!(snapshot.text(), "ab");
4816
4817 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4818 let snapshot = multibuffer.read(cx).snapshot(cx);
4819 assert_eq!(snapshot.text(), "abc");
4820 }
4821
4822 #[gpui::test]
4823 fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4824 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4825 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
4826 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4827
4828 let events = Arc::new(RwLock::new(Vec::<Event>::new()));
4829 multibuffer.update(cx, |_, cx| {
4830 let events = events.clone();
4831 cx.subscribe(&multibuffer, move |_, _, event, _| {
4832 if let Event::Edited { .. } = event {
4833 events.write().push(event.clone())
4834 }
4835 })
4836 .detach();
4837 });
4838
4839 let subscription = multibuffer.update(cx, |multibuffer, cx| {
4840 let subscription = multibuffer.subscribe();
4841 multibuffer.push_excerpts(
4842 buffer_1.clone(),
4843 [ExcerptRange {
4844 context: Point::new(1, 2)..Point::new(2, 5),
4845 primary: None,
4846 }],
4847 cx,
4848 );
4849 assert_eq!(
4850 subscription.consume().into_inner(),
4851 [Edit {
4852 old: 0..0,
4853 new: 0..10
4854 }]
4855 );
4856
4857 multibuffer.push_excerpts(
4858 buffer_1.clone(),
4859 [ExcerptRange {
4860 context: Point::new(3, 3)..Point::new(4, 4),
4861 primary: None,
4862 }],
4863 cx,
4864 );
4865 multibuffer.push_excerpts(
4866 buffer_2.clone(),
4867 [ExcerptRange {
4868 context: Point::new(3, 1)..Point::new(3, 3),
4869 primary: None,
4870 }],
4871 cx,
4872 );
4873 assert_eq!(
4874 subscription.consume().into_inner(),
4875 [Edit {
4876 old: 10..10,
4877 new: 10..22
4878 }]
4879 );
4880
4881 subscription
4882 });
4883
4884 // Adding excerpts emits an edited event.
4885 assert_eq!(
4886 events.read().as_slice(),
4887 &[
4888 Event::Edited {
4889 singleton_buffer_edited: false
4890 },
4891 Event::Edited {
4892 singleton_buffer_edited: false
4893 },
4894 Event::Edited {
4895 singleton_buffer_edited: false
4896 }
4897 ]
4898 );
4899
4900 let snapshot = multibuffer.read(cx).snapshot(cx);
4901 assert_eq!(
4902 snapshot.text(),
4903 concat!(
4904 "bbbb\n", // Preserve newlines
4905 "ccccc\n", //
4906 "ddd\n", //
4907 "eeee\n", //
4908 "jj" //
4909 )
4910 );
4911 assert_eq!(
4912 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4913 [Some(1), Some(2), Some(3), Some(4), Some(3)]
4914 );
4915 assert_eq!(
4916 snapshot.buffer_rows(MultiBufferRow(2)).collect::<Vec<_>>(),
4917 [Some(3), Some(4), Some(3)]
4918 );
4919 assert_eq!(
4920 snapshot.buffer_rows(MultiBufferRow(4)).collect::<Vec<_>>(),
4921 [Some(3)]
4922 );
4923 assert_eq!(
4924 snapshot.buffer_rows(MultiBufferRow(5)).collect::<Vec<_>>(),
4925 []
4926 );
4927
4928 assert_eq!(
4929 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4930 &[
4931 (MultiBufferRow(0), "bbbb\nccccc".to_string(), true),
4932 (MultiBufferRow(2), "ddd\neeee".to_string(), false),
4933 (MultiBufferRow(4), "jj".to_string(), true),
4934 ]
4935 );
4936 assert_eq!(
4937 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4938 &[(MultiBufferRow(0), "bbbb\nccccc".to_string(), true)]
4939 );
4940 assert_eq!(
4941 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4942 &[]
4943 );
4944 assert_eq!(
4945 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4946 &[]
4947 );
4948 assert_eq!(
4949 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4950 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4951 );
4952 assert_eq!(
4953 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4954 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4955 );
4956 assert_eq!(
4957 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4958 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4959 );
4960 assert_eq!(
4961 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4962 &[(MultiBufferRow(4), "jj".to_string(), true)]
4963 );
4964 assert_eq!(
4965 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4966 &[]
4967 );
4968
4969 buffer_1.update(cx, |buffer, cx| {
4970 let text = "\n";
4971 buffer.edit(
4972 [
4973 (Point::new(0, 0)..Point::new(0, 0), text),
4974 (Point::new(2, 1)..Point::new(2, 3), text),
4975 ],
4976 None,
4977 cx,
4978 );
4979 });
4980
4981 let snapshot = multibuffer.read(cx).snapshot(cx);
4982 assert_eq!(
4983 snapshot.text(),
4984 concat!(
4985 "bbbb\n", // Preserve newlines
4986 "c\n", //
4987 "cc\n", //
4988 "ddd\n", //
4989 "eeee\n", //
4990 "jj" //
4991 )
4992 );
4993
4994 assert_eq!(
4995 subscription.consume().into_inner(),
4996 [Edit {
4997 old: 6..8,
4998 new: 6..7
4999 }]
5000 );
5001
5002 let snapshot = multibuffer.read(cx).snapshot(cx);
5003 assert_eq!(
5004 snapshot.clip_point(Point::new(0, 5), Bias::Left),
5005 Point::new(0, 4)
5006 );
5007 assert_eq!(
5008 snapshot.clip_point(Point::new(0, 5), Bias::Right),
5009 Point::new(0, 4)
5010 );
5011 assert_eq!(
5012 snapshot.clip_point(Point::new(5, 1), Bias::Right),
5013 Point::new(5, 1)
5014 );
5015 assert_eq!(
5016 snapshot.clip_point(Point::new(5, 2), Bias::Right),
5017 Point::new(5, 2)
5018 );
5019 assert_eq!(
5020 snapshot.clip_point(Point::new(5, 3), Bias::Right),
5021 Point::new(5, 2)
5022 );
5023
5024 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
5025 let (buffer_2_excerpt_id, _) =
5026 multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
5027 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
5028 multibuffer.snapshot(cx)
5029 });
5030
5031 assert_eq!(
5032 snapshot.text(),
5033 concat!(
5034 "bbbb\n", // Preserve newlines
5035 "c\n", //
5036 "cc\n", //
5037 "ddd\n", //
5038 "eeee", //
5039 )
5040 );
5041
5042 fn boundaries_in_range(
5043 range: Range<Point>,
5044 snapshot: &MultiBufferSnapshot,
5045 ) -> Vec<(MultiBufferRow, String, bool)> {
5046 snapshot
5047 .excerpt_boundaries_in_range(range)
5048 .filter_map(|boundary| {
5049 let starts_new_buffer = boundary.starts_new_buffer();
5050 boundary.next.map(|next| {
5051 (
5052 boundary.row,
5053 next.buffer
5054 .text_for_range(next.range.context)
5055 .collect::<String>(),
5056 starts_new_buffer,
5057 )
5058 })
5059 })
5060 .collect::<Vec<_>>()
5061 }
5062 }
5063
5064 #[gpui::test]
5065 fn test_excerpt_events(cx: &mut AppContext) {
5066 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
5067 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
5068
5069 let leader_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5070 let follower_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5071 let follower_edit_event_count = Arc::new(RwLock::new(0));
5072
5073 follower_multibuffer.update(cx, |_, cx| {
5074 let follower_edit_event_count = follower_edit_event_count.clone();
5075 cx.subscribe(
5076 &leader_multibuffer,
5077 move |follower, _, event, cx| match event.clone() {
5078 Event::ExcerptsAdded {
5079 buffer,
5080 predecessor,
5081 excerpts,
5082 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
5083 Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
5084 Event::Edited { .. } => {
5085 *follower_edit_event_count.write() += 1;
5086 }
5087 _ => {}
5088 },
5089 )
5090 .detach();
5091 });
5092
5093 leader_multibuffer.update(cx, |leader, cx| {
5094 leader.push_excerpts(
5095 buffer_1.clone(),
5096 [
5097 ExcerptRange {
5098 context: 0..8,
5099 primary: None,
5100 },
5101 ExcerptRange {
5102 context: 12..16,
5103 primary: None,
5104 },
5105 ],
5106 cx,
5107 );
5108 leader.insert_excerpts_after(
5109 leader.excerpt_ids()[0],
5110 buffer_2.clone(),
5111 [
5112 ExcerptRange {
5113 context: 0..5,
5114 primary: None,
5115 },
5116 ExcerptRange {
5117 context: 10..15,
5118 primary: None,
5119 },
5120 ],
5121 cx,
5122 )
5123 });
5124 assert_eq!(
5125 leader_multibuffer.read(cx).snapshot(cx).text(),
5126 follower_multibuffer.read(cx).snapshot(cx).text(),
5127 );
5128 assert_eq!(*follower_edit_event_count.read(), 2);
5129
5130 leader_multibuffer.update(cx, |leader, cx| {
5131 let excerpt_ids = leader.excerpt_ids();
5132 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
5133 });
5134 assert_eq!(
5135 leader_multibuffer.read(cx).snapshot(cx).text(),
5136 follower_multibuffer.read(cx).snapshot(cx).text(),
5137 );
5138 assert_eq!(*follower_edit_event_count.read(), 3);
5139
5140 // Removing an empty set of excerpts is a noop.
5141 leader_multibuffer.update(cx, |leader, cx| {
5142 leader.remove_excerpts([], cx);
5143 });
5144 assert_eq!(
5145 leader_multibuffer.read(cx).snapshot(cx).text(),
5146 follower_multibuffer.read(cx).snapshot(cx).text(),
5147 );
5148 assert_eq!(*follower_edit_event_count.read(), 3);
5149
5150 // Adding an empty set of excerpts is a noop.
5151 leader_multibuffer.update(cx, |leader, cx| {
5152 leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
5153 });
5154 assert_eq!(
5155 leader_multibuffer.read(cx).snapshot(cx).text(),
5156 follower_multibuffer.read(cx).snapshot(cx).text(),
5157 );
5158 assert_eq!(*follower_edit_event_count.read(), 3);
5159
5160 leader_multibuffer.update(cx, |leader, cx| {
5161 leader.clear(cx);
5162 });
5163 assert_eq!(
5164 leader_multibuffer.read(cx).snapshot(cx).text(),
5165 follower_multibuffer.read(cx).snapshot(cx).text(),
5166 );
5167 assert_eq!(*follower_edit_event_count.read(), 4);
5168 }
5169
5170 #[gpui::test]
5171 fn test_expand_excerpts(cx: &mut AppContext) {
5172 let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5173 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5174
5175 multibuffer.update(cx, |multibuffer, cx| {
5176 multibuffer.push_excerpts_with_context_lines(
5177 buffer.clone(),
5178 vec![
5179 // Note that in this test, this first excerpt
5180 // does not contain a new line
5181 Point::new(3, 2)..Point::new(3, 3),
5182 Point::new(7, 1)..Point::new(7, 3),
5183 Point::new(15, 0)..Point::new(15, 0),
5184 ],
5185 1,
5186 cx,
5187 )
5188 });
5189
5190 let snapshot = multibuffer.read(cx).snapshot(cx);
5191
5192 assert_eq!(
5193 snapshot.text(),
5194 concat!(
5195 "ccc\n", //
5196 "ddd\n", //
5197 "eee", //
5198 "\n", // End of excerpt
5199 "ggg\n", //
5200 "hhh\n", //
5201 "iii", //
5202 "\n", // End of excerpt
5203 "ooo\n", //
5204 "ppp\n", //
5205 "qqq", // End of excerpt
5206 )
5207 );
5208 drop(snapshot);
5209
5210 multibuffer.update(cx, |multibuffer, cx| {
5211 multibuffer.expand_excerpts(
5212 multibuffer.excerpt_ids(),
5213 1,
5214 ExpandExcerptDirection::UpAndDown,
5215 cx,
5216 )
5217 });
5218
5219 let snapshot = multibuffer.read(cx).snapshot(cx);
5220
5221 // Expanding context lines causes the line containing 'fff' to appear in two different excerpts.
5222 // We don't attempt to merge them, because removing the excerpt could create inconsistency with other layers
5223 // that are tracking excerpt ids.
5224 assert_eq!(
5225 snapshot.text(),
5226 concat!(
5227 "bbb\n", //
5228 "ccc\n", //
5229 "ddd\n", //
5230 "eee\n", //
5231 "fff\n", // End of excerpt
5232 "fff\n", //
5233 "ggg\n", //
5234 "hhh\n", //
5235 "iii\n", //
5236 "jjj\n", // End of excerpt
5237 "nnn\n", //
5238 "ooo\n", //
5239 "ppp\n", //
5240 "qqq\n", //
5241 "rrr", // End of excerpt
5242 )
5243 );
5244 }
5245
5246 #[gpui::test]
5247 fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
5248 let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5249 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5250 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5251 multibuffer.push_excerpts_with_context_lines(
5252 buffer.clone(),
5253 vec![
5254 // Note that in this test, this first excerpt
5255 // does contain a new line
5256 Point::new(3, 2)..Point::new(4, 2),
5257 Point::new(7, 1)..Point::new(7, 3),
5258 Point::new(15, 0)..Point::new(15, 0),
5259 ],
5260 2,
5261 cx,
5262 )
5263 });
5264
5265 let snapshot = multibuffer.read(cx).snapshot(cx);
5266 assert_eq!(
5267 snapshot.text(),
5268 concat!(
5269 "bbb\n", // Preserve newlines
5270 "ccc\n", //
5271 "ddd\n", //
5272 "eee\n", //
5273 "fff\n", //
5274 "ggg\n", //
5275 "hhh\n", //
5276 "iii\n", //
5277 "jjj\n", //
5278 "nnn\n", //
5279 "ooo\n", //
5280 "ppp\n", //
5281 "qqq\n", //
5282 "rrr", //
5283 )
5284 );
5285
5286 assert_eq!(
5287 anchor_ranges
5288 .iter()
5289 .map(|range| range.to_point(&snapshot))
5290 .collect::<Vec<_>>(),
5291 vec![
5292 Point::new(2, 2)..Point::new(3, 2),
5293 Point::new(6, 1)..Point::new(6, 3),
5294 Point::new(11, 0)..Point::new(11, 0)
5295 ]
5296 );
5297 }
5298
5299 #[gpui::test]
5300 async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
5301 let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5302 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5303 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5304 let snapshot = buffer.read(cx);
5305 let ranges = vec![
5306 snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
5307 snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
5308 snapshot.anchor_before(Point::new(15, 0))
5309 ..snapshot.anchor_before(Point::new(15, 0)),
5310 ];
5311 multibuffer.stream_excerpts_with_context_lines(buffer.clone(), ranges, 2, cx)
5312 });
5313
5314 let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
5315
5316 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
5317 assert_eq!(
5318 snapshot.text(),
5319 concat!(
5320 "bbb\n", //
5321 "ccc\n", //
5322 "ddd\n", //
5323 "eee\n", //
5324 "fff\n", //
5325 "ggg\n", //
5326 "hhh\n", //
5327 "iii\n", //
5328 "jjj\n", //
5329 "nnn\n", //
5330 "ooo\n", //
5331 "ppp\n", //
5332 "qqq\n", //
5333 "rrr", //
5334 )
5335 );
5336
5337 assert_eq!(
5338 anchor_ranges
5339 .iter()
5340 .map(|range| range.to_point(&snapshot))
5341 .collect::<Vec<_>>(),
5342 vec![
5343 Point::new(2, 2)..Point::new(3, 2),
5344 Point::new(6, 1)..Point::new(6, 3),
5345 Point::new(11, 0)..Point::new(11, 0)
5346 ]
5347 );
5348 }
5349
5350 #[gpui::test]
5351 fn test_empty_multibuffer(cx: &mut AppContext) {
5352 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5353
5354 let snapshot = multibuffer.read(cx).snapshot(cx);
5355 assert_eq!(snapshot.text(), "");
5356 assert_eq!(
5357 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5358 &[Some(0)]
5359 );
5360 assert_eq!(
5361 snapshot.buffer_rows(MultiBufferRow(1)).collect::<Vec<_>>(),
5362 &[]
5363 );
5364 }
5365
5366 #[gpui::test]
5367 fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
5368 let buffer = cx.new_model(|cx| Buffer::local("abcd", cx));
5369 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
5370 let old_snapshot = multibuffer.read(cx).snapshot(cx);
5371 buffer.update(cx, |buffer, cx| {
5372 buffer.edit([(0..0, "X")], None, cx);
5373 buffer.edit([(5..5, "Y")], None, cx);
5374 });
5375 let new_snapshot = multibuffer.read(cx).snapshot(cx);
5376
5377 assert_eq!(old_snapshot.text(), "abcd");
5378 assert_eq!(new_snapshot.text(), "XabcdY");
5379
5380 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5381 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5382 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
5383 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
5384 }
5385
5386 #[gpui::test]
5387 fn test_multibuffer_anchors(cx: &mut AppContext) {
5388 let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5389 let buffer_2 = cx.new_model(|cx| Buffer::local("efghi", cx));
5390 let multibuffer = cx.new_model(|cx| {
5391 let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
5392 multibuffer.push_excerpts(
5393 buffer_1.clone(),
5394 [ExcerptRange {
5395 context: 0..4,
5396 primary: None,
5397 }],
5398 cx,
5399 );
5400 multibuffer.push_excerpts(
5401 buffer_2.clone(),
5402 [ExcerptRange {
5403 context: 0..5,
5404 primary: None,
5405 }],
5406 cx,
5407 );
5408 multibuffer
5409 });
5410 let old_snapshot = multibuffer.read(cx).snapshot(cx);
5411
5412 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
5413 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
5414 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5415 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5416 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5417 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5418
5419 buffer_1.update(cx, |buffer, cx| {
5420 buffer.edit([(0..0, "W")], None, cx);
5421 buffer.edit([(5..5, "X")], None, cx);
5422 });
5423 buffer_2.update(cx, |buffer, cx| {
5424 buffer.edit([(0..0, "Y")], None, cx);
5425 buffer.edit([(6..6, "Z")], None, cx);
5426 });
5427 let new_snapshot = multibuffer.read(cx).snapshot(cx);
5428
5429 assert_eq!(old_snapshot.text(), "abcd\nefghi");
5430 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
5431
5432 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5433 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5434 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
5435 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
5436 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
5437 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
5438 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
5439 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
5440 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
5441 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
5442 }
5443
5444 #[gpui::test]
5445 fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
5446 let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5447 let buffer_2 = cx.new_model(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
5448 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5449
5450 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
5451 // Add an excerpt from buffer 1 that spans this new insertion.
5452 buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
5453 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
5454 multibuffer
5455 .push_excerpts(
5456 buffer_1.clone(),
5457 [ExcerptRange {
5458 context: 0..7,
5459 primary: None,
5460 }],
5461 cx,
5462 )
5463 .pop()
5464 .unwrap()
5465 });
5466
5467 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
5468 assert_eq!(snapshot_1.text(), "abcd123");
5469
5470 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
5471 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
5472 multibuffer.remove_excerpts([excerpt_id_1], cx);
5473 let mut ids = multibuffer
5474 .push_excerpts(
5475 buffer_2.clone(),
5476 [
5477 ExcerptRange {
5478 context: 0..4,
5479 primary: None,
5480 },
5481 ExcerptRange {
5482 context: 6..10,
5483 primary: None,
5484 },
5485 ExcerptRange {
5486 context: 12..16,
5487 primary: None,
5488 },
5489 ],
5490 cx,
5491 )
5492 .into_iter();
5493 (ids.next().unwrap(), ids.next().unwrap())
5494 });
5495 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
5496 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
5497
5498 // The old excerpt id doesn't get reused.
5499 assert_ne!(excerpt_id_2, excerpt_id_1);
5500
5501 // Resolve some anchors from the previous snapshot in the new snapshot.
5502 // The current excerpts are from a different buffer, so we don't attempt to
5503 // resolve the old text anchor in the new buffer.
5504 assert_eq!(
5505 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
5506 0
5507 );
5508 assert_eq!(
5509 snapshot_2.summaries_for_anchors::<usize, _>(&[
5510 snapshot_1.anchor_before(2),
5511 snapshot_1.anchor_after(3)
5512 ]),
5513 vec![0, 0]
5514 );
5515
5516 // Refresh anchors from the old snapshot. The return value indicates that both
5517 // anchors lost their original excerpt.
5518 let refresh =
5519 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
5520 assert_eq!(
5521 refresh,
5522 &[
5523 (0, snapshot_2.anchor_before(0), false),
5524 (1, snapshot_2.anchor_after(0), false),
5525 ]
5526 );
5527
5528 // Replace the middle excerpt with a smaller excerpt in buffer 2,
5529 // that intersects the old excerpt.
5530 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
5531 multibuffer.remove_excerpts([excerpt_id_3], cx);
5532 multibuffer
5533 .insert_excerpts_after(
5534 excerpt_id_2,
5535 buffer_2.clone(),
5536 [ExcerptRange {
5537 context: 5..8,
5538 primary: None,
5539 }],
5540 cx,
5541 )
5542 .pop()
5543 .unwrap()
5544 });
5545
5546 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
5547 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
5548 assert_ne!(excerpt_id_5, excerpt_id_3);
5549
5550 // Resolve some anchors from the previous snapshot in the new snapshot.
5551 // The third anchor can't be resolved, since its excerpt has been removed,
5552 // so it resolves to the same position as its predecessor.
5553 let anchors = [
5554 snapshot_2.anchor_before(0),
5555 snapshot_2.anchor_after(2),
5556 snapshot_2.anchor_after(6),
5557 snapshot_2.anchor_after(14),
5558 ];
5559 assert_eq!(
5560 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
5561 &[0, 2, 9, 13]
5562 );
5563
5564 let new_anchors = snapshot_3.refresh_anchors(&anchors);
5565 assert_eq!(
5566 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
5567 &[(0, true), (1, true), (2, true), (3, true)]
5568 );
5569 assert_eq!(
5570 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
5571 &[0, 2, 7, 13]
5572 );
5573 }
5574
5575 #[gpui::test(iterations = 100)]
5576 fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
5577 let operations = env::var("OPERATIONS")
5578 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
5579 .unwrap_or(10);
5580
5581 let mut buffers: Vec<Model<Buffer>> = Vec::new();
5582 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5583 let mut excerpt_ids = Vec::<ExcerptId>::new();
5584 let mut expected_excerpts = Vec::<(Model<Buffer>, Range<text::Anchor>)>::new();
5585 let mut anchors = Vec::new();
5586 let mut old_versions = Vec::new();
5587
5588 for _ in 0..operations {
5589 match rng.gen_range(0..100) {
5590 0..=14 if !buffers.is_empty() => {
5591 let buffer = buffers.choose(&mut rng).unwrap();
5592 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
5593 }
5594 15..=19 if !expected_excerpts.is_empty() => {
5595 multibuffer.update(cx, |multibuffer, cx| {
5596 let ids = multibuffer.excerpt_ids();
5597 let mut excerpts = HashSet::default();
5598 for _ in 0..rng.gen_range(0..ids.len()) {
5599 excerpts.extend(ids.choose(&mut rng).copied());
5600 }
5601
5602 let line_count = rng.gen_range(0..5);
5603
5604 let excerpt_ixs = excerpts
5605 .iter()
5606 .map(|id| excerpt_ids.iter().position(|i| i == id).unwrap())
5607 .collect::<Vec<_>>();
5608 log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
5609 multibuffer.expand_excerpts(
5610 excerpts.iter().cloned(),
5611 line_count,
5612 ExpandExcerptDirection::UpAndDown,
5613 cx,
5614 );
5615
5616 if line_count > 0 {
5617 for id in excerpts {
5618 let excerpt_ix = excerpt_ids.iter().position(|&i| i == id).unwrap();
5619 let (buffer, range) = &mut expected_excerpts[excerpt_ix];
5620 let snapshot = buffer.read(cx).snapshot();
5621 let mut point_range = range.to_point(&snapshot);
5622 point_range.start =
5623 Point::new(point_range.start.row.saturating_sub(line_count), 0);
5624 point_range.end = snapshot.clip_point(
5625 Point::new(point_range.end.row + line_count, 0),
5626 Bias::Left,
5627 );
5628 point_range.end.column = snapshot.line_len(point_range.end.row);
5629 *range = snapshot.anchor_before(point_range.start)
5630 ..snapshot.anchor_after(point_range.end);
5631 }
5632 }
5633 });
5634 }
5635 20..=29 if !expected_excerpts.is_empty() => {
5636 let mut ids_to_remove = vec![];
5637 for _ in 0..rng.gen_range(1..=3) {
5638 if expected_excerpts.is_empty() {
5639 break;
5640 }
5641
5642 let ix = rng.gen_range(0..expected_excerpts.len());
5643 ids_to_remove.push(excerpt_ids.remove(ix));
5644 let (buffer, range) = expected_excerpts.remove(ix);
5645 let buffer = buffer.read(cx);
5646 log::info!(
5647 "Removing excerpt {}: {:?}",
5648 ix,
5649 buffer
5650 .text_for_range(range.to_offset(buffer))
5651 .collect::<String>(),
5652 );
5653 }
5654 let snapshot = multibuffer.read(cx).read(cx);
5655 ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
5656 drop(snapshot);
5657 multibuffer.update(cx, |multibuffer, cx| {
5658 multibuffer.remove_excerpts(ids_to_remove, cx)
5659 });
5660 }
5661 30..=39 if !expected_excerpts.is_empty() => {
5662 let multibuffer = multibuffer.read(cx).read(cx);
5663 let offset =
5664 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
5665 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
5666 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
5667 anchors.push(multibuffer.anchor_at(offset, bias));
5668 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
5669 }
5670 40..=44 if !anchors.is_empty() => {
5671 let multibuffer = multibuffer.read(cx).read(cx);
5672 let prev_len = anchors.len();
5673 anchors = multibuffer
5674 .refresh_anchors(&anchors)
5675 .into_iter()
5676 .map(|a| a.1)
5677 .collect();
5678
5679 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
5680 // overshoot its boundaries.
5681 assert_eq!(anchors.len(), prev_len);
5682 for anchor in &anchors {
5683 if anchor.excerpt_id == ExcerptId::min()
5684 || anchor.excerpt_id == ExcerptId::max()
5685 {
5686 continue;
5687 }
5688
5689 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
5690 assert_eq!(excerpt.id, anchor.excerpt_id);
5691 assert!(excerpt.contains(anchor));
5692 }
5693 }
5694 _ => {
5695 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
5696 let base_text = util::RandomCharIter::new(&mut rng)
5697 .take(25)
5698 .collect::<String>();
5699
5700 buffers.push(cx.new_model(|cx| Buffer::local(base_text, cx)));
5701 buffers.last().unwrap()
5702 } else {
5703 buffers.choose(&mut rng).unwrap()
5704 };
5705
5706 let buffer = buffer_handle.read(cx);
5707 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
5708 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5709 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
5710 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
5711 let prev_excerpt_id = excerpt_ids
5712 .get(prev_excerpt_ix)
5713 .cloned()
5714 .unwrap_or_else(ExcerptId::max);
5715 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
5716
5717 log::info!(
5718 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
5719 excerpt_ix,
5720 expected_excerpts.len(),
5721 buffer_handle.read(cx).remote_id(),
5722 buffer.text(),
5723 start_ix..end_ix,
5724 &buffer.text()[start_ix..end_ix]
5725 );
5726
5727 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
5728 multibuffer
5729 .insert_excerpts_after(
5730 prev_excerpt_id,
5731 buffer_handle.clone(),
5732 [ExcerptRange {
5733 context: start_ix..end_ix,
5734 primary: None,
5735 }],
5736 cx,
5737 )
5738 .pop()
5739 .unwrap()
5740 });
5741
5742 excerpt_ids.insert(excerpt_ix, excerpt_id);
5743 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
5744 }
5745 }
5746
5747 if rng.gen_bool(0.3) {
5748 multibuffer.update(cx, |multibuffer, cx| {
5749 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
5750 })
5751 }
5752
5753 let snapshot = multibuffer.read(cx).snapshot(cx);
5754
5755 let mut excerpt_starts = Vec::new();
5756 let mut expected_text = String::new();
5757 let mut expected_buffer_rows = Vec::new();
5758 for (buffer, range) in &expected_excerpts {
5759 let buffer = buffer.read(cx);
5760 let buffer_range = range.to_offset(buffer);
5761
5762 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5763 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5764 expected_text.push('\n');
5765
5766 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5767 ..=buffer.offset_to_point(buffer_range.end).row;
5768 for row in buffer_row_range {
5769 expected_buffer_rows.push(Some(row));
5770 }
5771 }
5772 // Remove final trailing newline.
5773 if !expected_excerpts.is_empty() {
5774 expected_text.pop();
5775 }
5776
5777 // Always report one buffer row
5778 if expected_buffer_rows.is_empty() {
5779 expected_buffer_rows.push(Some(0));
5780 }
5781
5782 assert_eq!(snapshot.text(), expected_text);
5783 log::info!("MultiBuffer text: {:?}", expected_text);
5784
5785 assert_eq!(
5786 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5787 expected_buffer_rows,
5788 );
5789
5790 for _ in 0..5 {
5791 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5792 assert_eq!(
5793 snapshot
5794 .buffer_rows(MultiBufferRow(start_row as u32))
5795 .collect::<Vec<_>>(),
5796 &expected_buffer_rows[start_row..],
5797 "buffer_rows({})",
5798 start_row
5799 );
5800 }
5801
5802 assert_eq!(
5803 snapshot.max_buffer_row().0,
5804 expected_buffer_rows.into_iter().flatten().max().unwrap()
5805 );
5806
5807 let mut excerpt_starts = excerpt_starts.into_iter();
5808 for (buffer, range) in &expected_excerpts {
5809 let buffer = buffer.read(cx);
5810 let buffer_id = buffer.remote_id();
5811 let buffer_range = range.to_offset(buffer);
5812 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5813 let buffer_start_point_utf16 =
5814 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5815
5816 let excerpt_start = excerpt_starts.next().unwrap();
5817 let mut offset = excerpt_start.len;
5818 let mut buffer_offset = buffer_range.start;
5819 let mut point = excerpt_start.lines;
5820 let mut buffer_point = buffer_start_point;
5821 let mut point_utf16 = excerpt_start.lines_utf16();
5822 let mut buffer_point_utf16 = buffer_start_point_utf16;
5823 for ch in buffer
5824 .snapshot()
5825 .chunks(buffer_range.clone(), false)
5826 .flat_map(|c| c.text.chars())
5827 {
5828 for _ in 0..ch.len_utf8() {
5829 let left_offset = snapshot.clip_offset(offset, Bias::Left);
5830 let right_offset = snapshot.clip_offset(offset, Bias::Right);
5831 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5832 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5833 assert_eq!(
5834 left_offset,
5835 excerpt_start.len + (buffer_left_offset - buffer_range.start),
5836 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5837 offset,
5838 buffer_id,
5839 buffer_offset,
5840 );
5841 assert_eq!(
5842 right_offset,
5843 excerpt_start.len + (buffer_right_offset - buffer_range.start),
5844 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5845 offset,
5846 buffer_id,
5847 buffer_offset,
5848 );
5849
5850 let left_point = snapshot.clip_point(point, Bias::Left);
5851 let right_point = snapshot.clip_point(point, Bias::Right);
5852 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5853 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5854 assert_eq!(
5855 left_point,
5856 excerpt_start.lines + (buffer_left_point - buffer_start_point),
5857 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5858 point,
5859 buffer_id,
5860 buffer_point,
5861 );
5862 assert_eq!(
5863 right_point,
5864 excerpt_start.lines + (buffer_right_point - buffer_start_point),
5865 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5866 point,
5867 buffer_id,
5868 buffer_point,
5869 );
5870
5871 assert_eq!(
5872 snapshot.point_to_offset(left_point),
5873 left_offset,
5874 "point_to_offset({:?})",
5875 left_point,
5876 );
5877 assert_eq!(
5878 snapshot.offset_to_point(left_offset),
5879 left_point,
5880 "offset_to_point({:?})",
5881 left_offset,
5882 );
5883
5884 offset += 1;
5885 buffer_offset += 1;
5886 if ch == '\n' {
5887 point += Point::new(1, 0);
5888 buffer_point += Point::new(1, 0);
5889 } else {
5890 point += Point::new(0, 1);
5891 buffer_point += Point::new(0, 1);
5892 }
5893 }
5894
5895 for _ in 0..ch.len_utf16() {
5896 let left_point_utf16 =
5897 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5898 let right_point_utf16 =
5899 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5900 let buffer_left_point_utf16 =
5901 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5902 let buffer_right_point_utf16 =
5903 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5904 assert_eq!(
5905 left_point_utf16,
5906 excerpt_start.lines_utf16()
5907 + (buffer_left_point_utf16 - buffer_start_point_utf16),
5908 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5909 point_utf16,
5910 buffer_id,
5911 buffer_point_utf16,
5912 );
5913 assert_eq!(
5914 right_point_utf16,
5915 excerpt_start.lines_utf16()
5916 + (buffer_right_point_utf16 - buffer_start_point_utf16),
5917 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5918 point_utf16,
5919 buffer_id,
5920 buffer_point_utf16,
5921 );
5922
5923 if ch == '\n' {
5924 point_utf16 += PointUtf16::new(1, 0);
5925 buffer_point_utf16 += PointUtf16::new(1, 0);
5926 } else {
5927 point_utf16 += PointUtf16::new(0, 1);
5928 buffer_point_utf16 += PointUtf16::new(0, 1);
5929 }
5930 }
5931 }
5932 }
5933
5934 for (row, line) in expected_text.split('\n').enumerate() {
5935 assert_eq!(
5936 snapshot.line_len(MultiBufferRow(row as u32)),
5937 line.len() as u32,
5938 "line_len({}).",
5939 row
5940 );
5941 }
5942
5943 let text_rope = Rope::from(expected_text.as_str());
5944 for _ in 0..10 {
5945 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5946 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5947
5948 let text_for_range = snapshot
5949 .text_for_range(start_ix..end_ix)
5950 .collect::<String>();
5951 assert_eq!(
5952 text_for_range,
5953 &expected_text[start_ix..end_ix],
5954 "incorrect text for range {:?}",
5955 start_ix..end_ix
5956 );
5957
5958 let excerpted_buffer_ranges = multibuffer
5959 .read(cx)
5960 .range_to_buffer_ranges(start_ix..end_ix, cx);
5961 let excerpted_buffers_text = excerpted_buffer_ranges
5962 .iter()
5963 .map(|(buffer, buffer_range, _)| {
5964 buffer
5965 .read(cx)
5966 .text_for_range(buffer_range.clone())
5967 .collect::<String>()
5968 })
5969 .collect::<Vec<_>>()
5970 .join("\n");
5971 assert_eq!(excerpted_buffers_text, text_for_range);
5972 if !expected_excerpts.is_empty() {
5973 assert!(!excerpted_buffer_ranges.is_empty());
5974 }
5975
5976 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5977 assert_eq!(
5978 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5979 expected_summary,
5980 "incorrect summary for range {:?}",
5981 start_ix..end_ix
5982 );
5983 }
5984
5985 // Anchor resolution
5986 let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5987 assert_eq!(anchors.len(), summaries.len());
5988 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5989 assert!(resolved_offset <= snapshot.len());
5990 assert_eq!(
5991 snapshot.summary_for_anchor::<usize>(anchor),
5992 resolved_offset
5993 );
5994 }
5995
5996 for _ in 0..10 {
5997 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5998 assert_eq!(
5999 snapshot.reversed_chars_at(end_ix).collect::<String>(),
6000 expected_text[..end_ix].chars().rev().collect::<String>(),
6001 );
6002 }
6003
6004 for _ in 0..10 {
6005 let end_ix = rng.gen_range(0..=text_rope.len());
6006 let start_ix = rng.gen_range(0..=end_ix);
6007 assert_eq!(
6008 snapshot
6009 .bytes_in_range(start_ix..end_ix)
6010 .flatten()
6011 .copied()
6012 .collect::<Vec<_>>(),
6013 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
6014 "bytes_in_range({:?})",
6015 start_ix..end_ix,
6016 );
6017 }
6018 }
6019
6020 let snapshot = multibuffer.read(cx).snapshot(cx);
6021 for (old_snapshot, subscription) in old_versions {
6022 let edits = subscription.consume().into_inner();
6023
6024 log::info!(
6025 "applying subscription edits to old text: {:?}: {:?}",
6026 old_snapshot.text(),
6027 edits,
6028 );
6029
6030 let mut text = old_snapshot.text();
6031 for edit in edits {
6032 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
6033 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
6034 }
6035 assert_eq!(text.to_string(), snapshot.text());
6036 }
6037 }
6038
6039 #[gpui::test]
6040 fn test_history(cx: &mut AppContext) {
6041 let test_settings = SettingsStore::test(cx);
6042 cx.set_global(test_settings);
6043
6044 let buffer_1 = cx.new_model(|cx| Buffer::local("1234", cx));
6045 let buffer_2 = cx.new_model(|cx| Buffer::local("5678", cx));
6046 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6047 let group_interval = multibuffer.read(cx).history.group_interval;
6048 multibuffer.update(cx, |multibuffer, cx| {
6049 multibuffer.push_excerpts(
6050 buffer_1.clone(),
6051 [ExcerptRange {
6052 context: 0..buffer_1.read(cx).len(),
6053 primary: None,
6054 }],
6055 cx,
6056 );
6057 multibuffer.push_excerpts(
6058 buffer_2.clone(),
6059 [ExcerptRange {
6060 context: 0..buffer_2.read(cx).len(),
6061 primary: None,
6062 }],
6063 cx,
6064 );
6065 });
6066
6067 let mut now = Instant::now();
6068
6069 multibuffer.update(cx, |multibuffer, cx| {
6070 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
6071 multibuffer.edit(
6072 [
6073 (Point::new(0, 0)..Point::new(0, 0), "A"),
6074 (Point::new(1, 0)..Point::new(1, 0), "A"),
6075 ],
6076 None,
6077 cx,
6078 );
6079 multibuffer.edit(
6080 [
6081 (Point::new(0, 1)..Point::new(0, 1), "B"),
6082 (Point::new(1, 1)..Point::new(1, 1), "B"),
6083 ],
6084 None,
6085 cx,
6086 );
6087 multibuffer.end_transaction_at(now, cx);
6088 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6089
6090 // Verify edited ranges for transaction 1
6091 assert_eq!(
6092 multibuffer.edited_ranges_for_transaction(transaction_1, cx),
6093 &[
6094 Point::new(0, 0)..Point::new(0, 2),
6095 Point::new(1, 0)..Point::new(1, 2)
6096 ]
6097 );
6098
6099 // Edit buffer 1 through the multibuffer
6100 now += 2 * group_interval;
6101 multibuffer.start_transaction_at(now, cx);
6102 multibuffer.edit([(2..2, "C")], None, cx);
6103 multibuffer.end_transaction_at(now, cx);
6104 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
6105
6106 // Edit buffer 1 independently
6107 buffer_1.update(cx, |buffer_1, cx| {
6108 buffer_1.start_transaction_at(now);
6109 buffer_1.edit([(3..3, "D")], None, cx);
6110 buffer_1.end_transaction_at(now, cx);
6111
6112 now += 2 * group_interval;
6113 buffer_1.start_transaction_at(now);
6114 buffer_1.edit([(4..4, "E")], None, cx);
6115 buffer_1.end_transaction_at(now, cx);
6116 });
6117 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
6118
6119 // An undo in the multibuffer undoes the multibuffer transaction
6120 // and also any individual buffer edits that have occurred since
6121 // that transaction.
6122 multibuffer.undo(cx);
6123 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6124
6125 multibuffer.undo(cx);
6126 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6127
6128 multibuffer.redo(cx);
6129 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6130
6131 multibuffer.redo(cx);
6132 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
6133
6134 // Undo buffer 2 independently.
6135 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
6136 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
6137
6138 // An undo in the multibuffer undoes the components of the
6139 // the last multibuffer transaction that are not already undone.
6140 multibuffer.undo(cx);
6141 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
6142
6143 multibuffer.undo(cx);
6144 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6145
6146 multibuffer.redo(cx);
6147 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6148
6149 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
6150 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
6151
6152 // Redo stack gets cleared after an edit.
6153 now += 2 * group_interval;
6154 multibuffer.start_transaction_at(now, cx);
6155 multibuffer.edit([(0..0, "X")], None, cx);
6156 multibuffer.end_transaction_at(now, cx);
6157 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6158 multibuffer.redo(cx);
6159 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6160 multibuffer.undo(cx);
6161 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
6162 multibuffer.undo(cx);
6163 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6164
6165 // Transactions can be grouped manually.
6166 multibuffer.redo(cx);
6167 multibuffer.redo(cx);
6168 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6169 multibuffer.group_until_transaction(transaction_1, cx);
6170 multibuffer.undo(cx);
6171 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6172 multibuffer.redo(cx);
6173 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6174 });
6175 }
6176
6177 #[gpui::test]
6178 fn test_excerpts_in_ranges_no_ranges(cx: &mut AppContext) {
6179 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6180 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6181 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6182 multibuffer.update(cx, |multibuffer, cx| {
6183 multibuffer.push_excerpts(
6184 buffer_1.clone(),
6185 [ExcerptRange {
6186 context: 0..buffer_1.read(cx).len(),
6187 primary: None,
6188 }],
6189 cx,
6190 );
6191 multibuffer.push_excerpts(
6192 buffer_2.clone(),
6193 [ExcerptRange {
6194 context: 0..buffer_2.read(cx).len(),
6195 primary: None,
6196 }],
6197 cx,
6198 );
6199 });
6200
6201 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
6202
6203 let mut excerpts = snapshot.excerpts_in_ranges(iter::from_fn(|| None));
6204
6205 assert!(excerpts.next().is_none());
6206 }
6207
6208 fn validate_excerpts(
6209 actual: &Vec<(ExcerptId, BufferId, Range<Anchor>)>,
6210 expected: &Vec<(ExcerptId, BufferId, Range<Anchor>)>,
6211 ) {
6212 assert_eq!(actual.len(), expected.len());
6213
6214 actual
6215 .into_iter()
6216 .zip(expected)
6217 .map(|(actual, expected)| {
6218 assert_eq!(actual.0, expected.0);
6219 assert_eq!(actual.1, expected.1);
6220 assert_eq!(actual.2.start, expected.2.start);
6221 assert_eq!(actual.2.end, expected.2.end);
6222 })
6223 .collect_vec();
6224 }
6225
6226 fn map_range_from_excerpt(
6227 snapshot: &MultiBufferSnapshot,
6228 excerpt_id: ExcerptId,
6229 excerpt_buffer: &BufferSnapshot,
6230 range: Range<usize>,
6231 ) -> Range<Anchor> {
6232 snapshot
6233 .anchor_in_excerpt(excerpt_id, excerpt_buffer.anchor_before(range.start))
6234 .unwrap()
6235 ..snapshot
6236 .anchor_in_excerpt(excerpt_id, excerpt_buffer.anchor_after(range.end))
6237 .unwrap()
6238 }
6239
6240 fn make_expected_excerpt_info(
6241 snapshot: &MultiBufferSnapshot,
6242 cx: &mut AppContext,
6243 excerpt_id: ExcerptId,
6244 buffer: &Model<Buffer>,
6245 range: Range<usize>,
6246 ) -> (ExcerptId, BufferId, Range<Anchor>) {
6247 (
6248 excerpt_id,
6249 buffer.read(cx).remote_id(),
6250 map_range_from_excerpt(&snapshot, excerpt_id, &buffer.read(cx).snapshot(), range),
6251 )
6252 }
6253
6254 #[gpui::test]
6255 fn test_excerpts_in_ranges_range_inside_the_excerpt(cx: &mut AppContext) {
6256 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6257 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6258 let buffer_len = buffer_1.read(cx).len();
6259 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6260 let mut expected_excerpt_id = ExcerptId(0);
6261
6262 multibuffer.update(cx, |multibuffer, cx| {
6263 expected_excerpt_id = multibuffer.push_excerpts(
6264 buffer_1.clone(),
6265 [ExcerptRange {
6266 context: 0..buffer_1.read(cx).len(),
6267 primary: None,
6268 }],
6269 cx,
6270 )[0];
6271 multibuffer.push_excerpts(
6272 buffer_2.clone(),
6273 [ExcerptRange {
6274 context: 0..buffer_2.read(cx).len(),
6275 primary: None,
6276 }],
6277 cx,
6278 );
6279 });
6280
6281 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
6282
6283 let range = snapshot
6284 .anchor_in_excerpt(expected_excerpt_id, buffer_1.read(cx).anchor_before(1))
6285 .unwrap()
6286 ..snapshot
6287 .anchor_in_excerpt(
6288 expected_excerpt_id,
6289 buffer_1.read(cx).anchor_after(buffer_len / 2),
6290 )
6291 .unwrap();
6292
6293 let expected_excerpts = vec![make_expected_excerpt_info(
6294 &snapshot,
6295 cx,
6296 expected_excerpt_id,
6297 &buffer_1,
6298 1..(buffer_len / 2),
6299 )];
6300
6301 let excerpts = snapshot
6302 .excerpts_in_ranges(vec![range.clone()].into_iter())
6303 .map(|(excerpt_id, buffer, actual_range)| {
6304 (
6305 excerpt_id,
6306 buffer.remote_id(),
6307 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6308 )
6309 })
6310 .collect_vec();
6311
6312 validate_excerpts(&excerpts, &expected_excerpts);
6313 }
6314
6315 #[gpui::test]
6316 fn test_excerpts_in_ranges_range_crosses_excerpts_boundary(cx: &mut AppContext) {
6317 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6318 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6319 let buffer_len = buffer_1.read(cx).len();
6320 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6321 let mut excerpt_1_id = ExcerptId(0);
6322 let mut excerpt_2_id = ExcerptId(0);
6323
6324 multibuffer.update(cx, |multibuffer, cx| {
6325 excerpt_1_id = multibuffer.push_excerpts(
6326 buffer_1.clone(),
6327 [ExcerptRange {
6328 context: 0..buffer_1.read(cx).len(),
6329 primary: None,
6330 }],
6331 cx,
6332 )[0];
6333 excerpt_2_id = multibuffer.push_excerpts(
6334 buffer_2.clone(),
6335 [ExcerptRange {
6336 context: 0..buffer_2.read(cx).len(),
6337 primary: None,
6338 }],
6339 cx,
6340 )[0];
6341 });
6342
6343 let snapshot = multibuffer.read(cx).snapshot(cx);
6344
6345 let expected_range = snapshot
6346 .anchor_in_excerpt(
6347 excerpt_1_id,
6348 buffer_1.read(cx).anchor_before(buffer_len / 2),
6349 )
6350 .unwrap()
6351 ..snapshot
6352 .anchor_in_excerpt(excerpt_2_id, buffer_2.read(cx).anchor_after(buffer_len / 2))
6353 .unwrap();
6354
6355 let expected_excerpts = vec![
6356 make_expected_excerpt_info(
6357 &snapshot,
6358 cx,
6359 excerpt_1_id,
6360 &buffer_1,
6361 (buffer_len / 2)..buffer_len,
6362 ),
6363 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, 0..buffer_len / 2),
6364 ];
6365
6366 let excerpts = snapshot
6367 .excerpts_in_ranges(vec![expected_range.clone()].into_iter())
6368 .map(|(excerpt_id, buffer, actual_range)| {
6369 (
6370 excerpt_id,
6371 buffer.remote_id(),
6372 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6373 )
6374 })
6375 .collect_vec();
6376
6377 validate_excerpts(&excerpts, &expected_excerpts);
6378 }
6379
6380 #[gpui::test]
6381 fn test_excerpts_in_ranges_range_encloses_excerpt(cx: &mut AppContext) {
6382 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6383 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6384 let buffer_3 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'r'), cx));
6385 let buffer_len = buffer_1.read(cx).len();
6386 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6387 let mut excerpt_1_id = ExcerptId(0);
6388 let mut excerpt_2_id = ExcerptId(0);
6389 let mut excerpt_3_id = ExcerptId(0);
6390
6391 multibuffer.update(cx, |multibuffer, cx| {
6392 excerpt_1_id = multibuffer.push_excerpts(
6393 buffer_1.clone(),
6394 [ExcerptRange {
6395 context: 0..buffer_1.read(cx).len(),
6396 primary: None,
6397 }],
6398 cx,
6399 )[0];
6400 excerpt_2_id = multibuffer.push_excerpts(
6401 buffer_2.clone(),
6402 [ExcerptRange {
6403 context: 0..buffer_2.read(cx).len(),
6404 primary: None,
6405 }],
6406 cx,
6407 )[0];
6408 excerpt_3_id = multibuffer.push_excerpts(
6409 buffer_3.clone(),
6410 [ExcerptRange {
6411 context: 0..buffer_3.read(cx).len(),
6412 primary: None,
6413 }],
6414 cx,
6415 )[0];
6416 });
6417
6418 let snapshot = multibuffer.read(cx).snapshot(cx);
6419
6420 let expected_range = snapshot
6421 .anchor_in_excerpt(
6422 excerpt_1_id,
6423 buffer_1.read(cx).anchor_before(buffer_len / 2),
6424 )
6425 .unwrap()
6426 ..snapshot
6427 .anchor_in_excerpt(excerpt_3_id, buffer_3.read(cx).anchor_after(buffer_len / 2))
6428 .unwrap();
6429
6430 let expected_excerpts = vec![
6431 make_expected_excerpt_info(
6432 &snapshot,
6433 cx,
6434 excerpt_1_id,
6435 &buffer_1,
6436 (buffer_len / 2)..buffer_len,
6437 ),
6438 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, 0..buffer_len),
6439 make_expected_excerpt_info(&snapshot, cx, excerpt_3_id, &buffer_3, 0..buffer_len / 2),
6440 ];
6441
6442 let excerpts = snapshot
6443 .excerpts_in_ranges(vec![expected_range.clone()].into_iter())
6444 .map(|(excerpt_id, buffer, actual_range)| {
6445 (
6446 excerpt_id,
6447 buffer.remote_id(),
6448 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6449 )
6450 })
6451 .collect_vec();
6452
6453 validate_excerpts(&excerpts, &expected_excerpts);
6454 }
6455
6456 #[gpui::test]
6457 fn test_excerpts_in_ranges_multiple_ranges(cx: &mut AppContext) {
6458 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6459 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6460 let buffer_len = buffer_1.read(cx).len();
6461 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6462 let mut excerpt_1_id = ExcerptId(0);
6463 let mut excerpt_2_id = ExcerptId(0);
6464
6465 multibuffer.update(cx, |multibuffer, cx| {
6466 excerpt_1_id = multibuffer.push_excerpts(
6467 buffer_1.clone(),
6468 [ExcerptRange {
6469 context: 0..buffer_1.read(cx).len(),
6470 primary: None,
6471 }],
6472 cx,
6473 )[0];
6474 excerpt_2_id = multibuffer.push_excerpts(
6475 buffer_2.clone(),
6476 [ExcerptRange {
6477 context: 0..buffer_2.read(cx).len(),
6478 primary: None,
6479 }],
6480 cx,
6481 )[0];
6482 });
6483
6484 let snapshot = multibuffer.read(cx).snapshot(cx);
6485
6486 let ranges = vec![
6487 1..(buffer_len / 4),
6488 (buffer_len / 3)..(buffer_len / 2),
6489 (buffer_len / 4 * 3)..(buffer_len),
6490 ];
6491
6492 let expected_excerpts = ranges
6493 .iter()
6494 .map(|range| {
6495 make_expected_excerpt_info(&snapshot, cx, excerpt_1_id, &buffer_1, range.clone())
6496 })
6497 .collect_vec();
6498
6499 let ranges = ranges.into_iter().map(|range| {
6500 map_range_from_excerpt(
6501 &snapshot,
6502 excerpt_1_id,
6503 &buffer_1.read(cx).snapshot(),
6504 range,
6505 )
6506 });
6507
6508 let excerpts = snapshot
6509 .excerpts_in_ranges(ranges)
6510 .map(|(excerpt_id, buffer, actual_range)| {
6511 (
6512 excerpt_id,
6513 buffer.remote_id(),
6514 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6515 )
6516 })
6517 .collect_vec();
6518
6519 validate_excerpts(&excerpts, &expected_excerpts);
6520 }
6521
6522 #[gpui::test]
6523 fn test_excerpts_in_ranges_range_ends_at_excerpt_end(cx: &mut AppContext) {
6524 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6525 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6526 let buffer_len = buffer_1.read(cx).len();
6527 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6528 let mut excerpt_1_id = ExcerptId(0);
6529 let mut excerpt_2_id = ExcerptId(0);
6530
6531 multibuffer.update(cx, |multibuffer, cx| {
6532 excerpt_1_id = multibuffer.push_excerpts(
6533 buffer_1.clone(),
6534 [ExcerptRange {
6535 context: 0..buffer_1.read(cx).len(),
6536 primary: None,
6537 }],
6538 cx,
6539 )[0];
6540 excerpt_2_id = multibuffer.push_excerpts(
6541 buffer_2.clone(),
6542 [ExcerptRange {
6543 context: 0..buffer_2.read(cx).len(),
6544 primary: None,
6545 }],
6546 cx,
6547 )[0];
6548 });
6549
6550 let snapshot = multibuffer.read(cx).snapshot(cx);
6551
6552 let ranges = [0..buffer_len, (buffer_len / 3)..(buffer_len / 2)];
6553
6554 let expected_excerpts = vec![
6555 make_expected_excerpt_info(&snapshot, cx, excerpt_1_id, &buffer_1, ranges[0].clone()),
6556 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, ranges[1].clone()),
6557 ];
6558
6559 let ranges = [
6560 map_range_from_excerpt(
6561 &snapshot,
6562 excerpt_1_id,
6563 &buffer_1.read(cx).snapshot(),
6564 ranges[0].clone(),
6565 ),
6566 map_range_from_excerpt(
6567 &snapshot,
6568 excerpt_2_id,
6569 &buffer_2.read(cx).snapshot(),
6570 ranges[1].clone(),
6571 ),
6572 ];
6573
6574 let excerpts = snapshot
6575 .excerpts_in_ranges(ranges.into_iter())
6576 .map(|(excerpt_id, buffer, actual_range)| {
6577 (
6578 excerpt_id,
6579 buffer.remote_id(),
6580 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6581 )
6582 })
6583 .collect_vec();
6584
6585 validate_excerpts(&excerpts, &expected_excerpts);
6586 }
6587}