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 })
3643 })
3644 .collect(),
3645 ))
3646 }
3647
3648 pub fn symbols_containing<T: ToOffset>(
3649 &self,
3650 offset: T,
3651 theme: Option<&SyntaxTheme>,
3652 ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
3653 let anchor = self.anchor_before(offset);
3654 let excerpt_id = anchor.excerpt_id;
3655 let excerpt = self.excerpt(excerpt_id)?;
3656 Some((
3657 excerpt.buffer_id,
3658 excerpt
3659 .buffer
3660 .symbols_containing(anchor.text_anchor, theme)
3661 .into_iter()
3662 .flatten()
3663 .flat_map(|item| {
3664 Some(OutlineItem {
3665 depth: item.depth,
3666 range: self.anchor_in_excerpt(excerpt_id, item.range.start)?
3667 ..self.anchor_in_excerpt(excerpt_id, item.range.end)?,
3668 text: item.text,
3669 highlight_ranges: item.highlight_ranges,
3670 name_ranges: item.name_ranges,
3671 })
3672 })
3673 .collect(),
3674 ))
3675 }
3676
3677 fn excerpt_locator_for_id(&self, id: ExcerptId) -> &Locator {
3678 if id == ExcerptId::min() {
3679 Locator::min_ref()
3680 } else if id == ExcerptId::max() {
3681 Locator::max_ref()
3682 } else {
3683 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3684 cursor.seek(&id, Bias::Left, &());
3685 if let Some(entry) = cursor.item() {
3686 if entry.id == id {
3687 return &entry.locator;
3688 }
3689 }
3690 panic!("invalid excerpt id {:?}", id)
3691 }
3692 }
3693
3694 // Returns the locators referenced by the given excerpt ids, sorted by locator.
3695 fn excerpt_locators_for_ids(
3696 &self,
3697 ids: impl IntoIterator<Item = ExcerptId>,
3698 ) -> SmallVec<[Locator; 1]> {
3699 let mut sorted_ids = ids.into_iter().collect::<SmallVec<[_; 1]>>();
3700 sorted_ids.sort_unstable();
3701 let mut locators = SmallVec::new();
3702
3703 while sorted_ids.last() == Some(&ExcerptId::max()) {
3704 sorted_ids.pop();
3705 locators.push(Locator::max());
3706 }
3707
3708 let mut sorted_ids = sorted_ids.into_iter().dedup().peekable();
3709 if sorted_ids.peek() == Some(&ExcerptId::min()) {
3710 sorted_ids.next();
3711 locators.push(Locator::min());
3712 }
3713
3714 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3715 for id in sorted_ids {
3716 if cursor.seek_forward(&id, Bias::Left, &()) {
3717 locators.push(cursor.item().unwrap().locator.clone());
3718 } else {
3719 panic!("invalid excerpt id {:?}", id);
3720 }
3721 }
3722
3723 locators.sort_unstable();
3724 locators
3725 }
3726
3727 pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<BufferId> {
3728 Some(self.excerpt(excerpt_id)?.buffer_id)
3729 }
3730
3731 pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3732 Some(&self.excerpt(excerpt_id)?.buffer)
3733 }
3734
3735 fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
3736 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3737 let locator = self.excerpt_locator_for_id(excerpt_id);
3738 cursor.seek(&Some(locator), Bias::Left, &());
3739 if let Some(excerpt) = cursor.item() {
3740 if excerpt.id == excerpt_id {
3741 return Some(excerpt);
3742 }
3743 }
3744 None
3745 }
3746
3747 /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3748 pub fn excerpt_containing<T: ToOffset>(&self, range: Range<T>) -> Option<MultiBufferExcerpt> {
3749 let range = range.start.to_offset(self)..range.end.to_offset(self);
3750
3751 let mut cursor = self.excerpts.cursor::<usize>();
3752 cursor.seek(&range.start, Bias::Right, &());
3753 let start_excerpt = cursor.item()?;
3754
3755 if range.start == range.end {
3756 return Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()));
3757 }
3758
3759 cursor.seek(&range.end, Bias::Right, &());
3760 let end_excerpt = cursor.item()?;
3761
3762 if start_excerpt.id == end_excerpt.id {
3763 Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()))
3764 } else {
3765 None
3766 }
3767 }
3768
3769 /// Returns excerpts overlapping the given ranges. If range spans multiple excerpts returns one range for each excerpt
3770 pub fn excerpts_in_ranges(
3771 &self,
3772 ranges: impl IntoIterator<Item = Range<Anchor>>,
3773 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, Range<usize>)> {
3774 let mut ranges = ranges.into_iter().map(|range| range.to_offset(self));
3775 let mut cursor = self.excerpts.cursor::<usize>();
3776 cursor.next(&());
3777 let mut current_range = ranges.next();
3778 iter::from_fn(move || {
3779 let range = current_range.clone()?;
3780 if range.start >= cursor.end(&()) {
3781 cursor.seek_forward(&range.start, Bias::Right, &());
3782 if range.start == self.len() {
3783 cursor.prev(&());
3784 }
3785 }
3786
3787 let excerpt = cursor.item()?;
3788 let range_start_in_excerpt = cmp::max(range.start, *cursor.start());
3789 let range_end_in_excerpt = if excerpt.has_trailing_newline {
3790 cmp::min(range.end, cursor.end(&()) - 1)
3791 } else {
3792 cmp::min(range.end, cursor.end(&()))
3793 };
3794 let buffer_range = MultiBufferExcerpt::new(excerpt, *cursor.start())
3795 .map_range_to_buffer(range_start_in_excerpt..range_end_in_excerpt);
3796
3797 if range.end > cursor.end(&()) {
3798 cursor.next(&());
3799 } else {
3800 current_range = ranges.next();
3801 }
3802
3803 Some((excerpt.id, &excerpt.buffer, buffer_range))
3804 })
3805 }
3806
3807 pub fn selections_in_range<'a>(
3808 &'a self,
3809 range: &'a Range<Anchor>,
3810 include_local: bool,
3811 ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3812 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3813 let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3814 let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3815 cursor.seek(start_locator, Bias::Left, &());
3816 cursor
3817 .take_while(move |excerpt| excerpt.locator <= *end_locator)
3818 .flat_map(move |excerpt| {
3819 let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3820 if excerpt.id == range.start.excerpt_id {
3821 query_range.start = range.start.text_anchor;
3822 }
3823 if excerpt.id == range.end.excerpt_id {
3824 query_range.end = range.end.text_anchor;
3825 }
3826
3827 excerpt
3828 .buffer
3829 .selections_in_range(query_range, include_local)
3830 .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3831 selections.map(move |selection| {
3832 let mut start = Anchor {
3833 buffer_id: Some(excerpt.buffer_id),
3834 excerpt_id: excerpt.id,
3835 text_anchor: selection.start,
3836 };
3837 let mut end = Anchor {
3838 buffer_id: Some(excerpt.buffer_id),
3839 excerpt_id: excerpt.id,
3840 text_anchor: selection.end,
3841 };
3842 if range.start.cmp(&start, self).is_gt() {
3843 start = range.start;
3844 }
3845 if range.end.cmp(&end, self).is_lt() {
3846 end = range.end;
3847 }
3848
3849 (
3850 replica_id,
3851 line_mode,
3852 cursor_shape,
3853 Selection {
3854 id: selection.id,
3855 start,
3856 end,
3857 reversed: selection.reversed,
3858 goal: selection.goal,
3859 },
3860 )
3861 })
3862 })
3863 })
3864 }
3865
3866 pub fn show_headers(&self) -> bool {
3867 self.show_headers
3868 }
3869}
3870
3871#[cfg(any(test, feature = "test-support"))]
3872impl MultiBufferSnapshot {
3873 pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3874 let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3875 let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3876 start..end
3877 }
3878}
3879
3880impl History {
3881 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3882 self.transaction_depth += 1;
3883 if self.transaction_depth == 1 {
3884 let id = self.next_transaction_id.tick();
3885 self.undo_stack.push(Transaction {
3886 id,
3887 buffer_transactions: Default::default(),
3888 first_edit_at: now,
3889 last_edit_at: now,
3890 suppress_grouping: false,
3891 });
3892 Some(id)
3893 } else {
3894 None
3895 }
3896 }
3897
3898 fn end_transaction(
3899 &mut self,
3900 now: Instant,
3901 buffer_transactions: HashMap<BufferId, TransactionId>,
3902 ) -> bool {
3903 assert_ne!(self.transaction_depth, 0);
3904 self.transaction_depth -= 1;
3905 if self.transaction_depth == 0 {
3906 if buffer_transactions.is_empty() {
3907 self.undo_stack.pop();
3908 false
3909 } else {
3910 self.redo_stack.clear();
3911 let transaction = self.undo_stack.last_mut().unwrap();
3912 transaction.last_edit_at = now;
3913 for (buffer_id, transaction_id) in buffer_transactions {
3914 transaction
3915 .buffer_transactions
3916 .entry(buffer_id)
3917 .or_insert(transaction_id);
3918 }
3919 true
3920 }
3921 } else {
3922 false
3923 }
3924 }
3925
3926 fn push_transaction<'a, T>(
3927 &mut self,
3928 buffer_transactions: T,
3929 now: Instant,
3930 cx: &mut ModelContext<MultiBuffer>,
3931 ) where
3932 T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
3933 {
3934 assert_eq!(self.transaction_depth, 0);
3935 let transaction = Transaction {
3936 id: self.next_transaction_id.tick(),
3937 buffer_transactions: buffer_transactions
3938 .into_iter()
3939 .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3940 .collect(),
3941 first_edit_at: now,
3942 last_edit_at: now,
3943 suppress_grouping: false,
3944 };
3945 if !transaction.buffer_transactions.is_empty() {
3946 self.undo_stack.push(transaction);
3947 self.redo_stack.clear();
3948 }
3949 }
3950
3951 fn finalize_last_transaction(&mut self) {
3952 if let Some(transaction) = self.undo_stack.last_mut() {
3953 transaction.suppress_grouping = true;
3954 }
3955 }
3956
3957 fn forget(&mut self, transaction_id: TransactionId) -> Option<Transaction> {
3958 if let Some(ix) = self
3959 .undo_stack
3960 .iter()
3961 .rposition(|transaction| transaction.id == transaction_id)
3962 {
3963 Some(self.undo_stack.remove(ix))
3964 } else if let Some(ix) = self
3965 .redo_stack
3966 .iter()
3967 .rposition(|transaction| transaction.id == transaction_id)
3968 {
3969 Some(self.redo_stack.remove(ix))
3970 } else {
3971 None
3972 }
3973 }
3974
3975 fn transaction(&self, transaction_id: TransactionId) -> Option<&Transaction> {
3976 self.undo_stack
3977 .iter()
3978 .find(|transaction| transaction.id == transaction_id)
3979 .or_else(|| {
3980 self.redo_stack
3981 .iter()
3982 .find(|transaction| transaction.id == transaction_id)
3983 })
3984 }
3985
3986 fn transaction_mut(&mut self, transaction_id: TransactionId) -> Option<&mut Transaction> {
3987 self.undo_stack
3988 .iter_mut()
3989 .find(|transaction| transaction.id == transaction_id)
3990 .or_else(|| {
3991 self.redo_stack
3992 .iter_mut()
3993 .find(|transaction| transaction.id == transaction_id)
3994 })
3995 }
3996
3997 fn pop_undo(&mut self) -> Option<&mut Transaction> {
3998 assert_eq!(self.transaction_depth, 0);
3999 if let Some(transaction) = self.undo_stack.pop() {
4000 self.redo_stack.push(transaction);
4001 self.redo_stack.last_mut()
4002 } else {
4003 None
4004 }
4005 }
4006
4007 fn pop_redo(&mut self) -> Option<&mut Transaction> {
4008 assert_eq!(self.transaction_depth, 0);
4009 if let Some(transaction) = self.redo_stack.pop() {
4010 self.undo_stack.push(transaction);
4011 self.undo_stack.last_mut()
4012 } else {
4013 None
4014 }
4015 }
4016
4017 fn remove_from_undo(&mut self, transaction_id: TransactionId) -> Option<&Transaction> {
4018 let ix = self
4019 .undo_stack
4020 .iter()
4021 .rposition(|transaction| transaction.id == transaction_id)?;
4022 let transaction = self.undo_stack.remove(ix);
4023 self.redo_stack.push(transaction);
4024 self.redo_stack.last()
4025 }
4026
4027 fn group(&mut self) -> Option<TransactionId> {
4028 let mut count = 0;
4029 let mut transactions = self.undo_stack.iter();
4030 if let Some(mut transaction) = transactions.next_back() {
4031 while let Some(prev_transaction) = transactions.next_back() {
4032 if !prev_transaction.suppress_grouping
4033 && transaction.first_edit_at - prev_transaction.last_edit_at
4034 <= self.group_interval
4035 {
4036 transaction = prev_transaction;
4037 count += 1;
4038 } else {
4039 break;
4040 }
4041 }
4042 }
4043 self.group_trailing(count)
4044 }
4045
4046 fn group_until(&mut self, transaction_id: TransactionId) {
4047 let mut count = 0;
4048 for transaction in self.undo_stack.iter().rev() {
4049 if transaction.id == transaction_id {
4050 self.group_trailing(count);
4051 break;
4052 } else if transaction.suppress_grouping {
4053 break;
4054 } else {
4055 count += 1;
4056 }
4057 }
4058 }
4059
4060 fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
4061 let new_len = self.undo_stack.len() - n;
4062 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
4063 if let Some(last_transaction) = transactions_to_keep.last_mut() {
4064 if let Some(transaction) = transactions_to_merge.last() {
4065 last_transaction.last_edit_at = transaction.last_edit_at;
4066 }
4067 for to_merge in transactions_to_merge {
4068 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
4069 last_transaction
4070 .buffer_transactions
4071 .entry(*buffer_id)
4072 .or_insert(*transaction_id);
4073 }
4074 }
4075 }
4076
4077 self.undo_stack.truncate(new_len);
4078 self.undo_stack.last().map(|t| t.id)
4079 }
4080}
4081
4082impl Excerpt {
4083 fn new(
4084 id: ExcerptId,
4085 locator: Locator,
4086 buffer_id: BufferId,
4087 buffer: BufferSnapshot,
4088 range: ExcerptRange<text::Anchor>,
4089 has_trailing_newline: bool,
4090 ) -> Self {
4091 Excerpt {
4092 id,
4093 locator,
4094 max_buffer_row: range.context.end.to_point(&buffer).row,
4095 text_summary: buffer
4096 .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
4097 buffer_id,
4098 buffer,
4099 range,
4100 has_trailing_newline,
4101 }
4102 }
4103
4104 fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
4105 let content_start = self.range.context.start.to_offset(&self.buffer);
4106 let chunks_start = content_start + range.start;
4107 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
4108
4109 let footer_height = if self.has_trailing_newline
4110 && range.start <= self.text_summary.len
4111 && range.end > self.text_summary.len
4112 {
4113 1
4114 } else {
4115 0
4116 };
4117
4118 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
4119
4120 ExcerptChunks {
4121 content_chunks,
4122 footer_height,
4123 }
4124 }
4125
4126 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
4127 let content_start = self.range.context.start.to_offset(&self.buffer);
4128 let bytes_start = content_start + range.start;
4129 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
4130 let footer_height = if self.has_trailing_newline
4131 && range.start <= self.text_summary.len
4132 && range.end > self.text_summary.len
4133 {
4134 1
4135 } else {
4136 0
4137 };
4138 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
4139
4140 ExcerptBytes {
4141 content_bytes,
4142 padding_height: footer_height,
4143 reversed: false,
4144 }
4145 }
4146
4147 fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
4148 let content_start = self.range.context.start.to_offset(&self.buffer);
4149 let bytes_start = content_start + range.start;
4150 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
4151 let footer_height = if self.has_trailing_newline
4152 && range.start <= self.text_summary.len
4153 && range.end > self.text_summary.len
4154 {
4155 1
4156 } else {
4157 0
4158 };
4159 let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
4160
4161 ExcerptBytes {
4162 content_bytes,
4163 padding_height: footer_height,
4164 reversed: true,
4165 }
4166 }
4167
4168 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
4169 if text_anchor
4170 .cmp(&self.range.context.start, &self.buffer)
4171 .is_lt()
4172 {
4173 self.range.context.start
4174 } else if text_anchor
4175 .cmp(&self.range.context.end, &self.buffer)
4176 .is_gt()
4177 {
4178 self.range.context.end
4179 } else {
4180 text_anchor
4181 }
4182 }
4183
4184 fn contains(&self, anchor: &Anchor) -> bool {
4185 Some(self.buffer_id) == anchor.buffer_id
4186 && self
4187 .range
4188 .context
4189 .start
4190 .cmp(&anchor.text_anchor, &self.buffer)
4191 .is_le()
4192 && self
4193 .range
4194 .context
4195 .end
4196 .cmp(&anchor.text_anchor, &self.buffer)
4197 .is_ge()
4198 }
4199
4200 /// The [`Excerpt`]'s start offset in its [`Buffer`]
4201 fn buffer_start_offset(&self) -> usize {
4202 self.range.context.start.to_offset(&self.buffer)
4203 }
4204
4205 /// The [`Excerpt`]'s end offset in its [`Buffer`]
4206 fn buffer_end_offset(&self) -> usize {
4207 self.buffer_start_offset() + self.text_summary.len
4208 }
4209}
4210
4211impl<'a> MultiBufferExcerpt<'a> {
4212 fn new(excerpt: &'a Excerpt, excerpt_offset: usize) -> Self {
4213 MultiBufferExcerpt {
4214 excerpt,
4215 excerpt_offset,
4216 }
4217 }
4218
4219 pub fn buffer(&self) -> &'a BufferSnapshot {
4220 &self.excerpt.buffer
4221 }
4222
4223 /// Maps an offset within the [`MultiBuffer`] to an offset within the [`Buffer`]
4224 pub fn map_offset_to_buffer(&self, offset: usize) -> usize {
4225 self.excerpt.buffer_start_offset() + offset.saturating_sub(self.excerpt_offset)
4226 }
4227
4228 /// Maps a range within the [`MultiBuffer`] to a range within the [`Buffer`]
4229 pub fn map_range_to_buffer(&self, range: Range<usize>) -> Range<usize> {
4230 self.map_offset_to_buffer(range.start)..self.map_offset_to_buffer(range.end)
4231 }
4232
4233 /// Map an offset within the [`Buffer`] to an offset within the [`MultiBuffer`]
4234 pub fn map_offset_from_buffer(&self, buffer_offset: usize) -> usize {
4235 let mut buffer_offset_in_excerpt =
4236 buffer_offset.saturating_sub(self.excerpt.buffer_start_offset());
4237 buffer_offset_in_excerpt =
4238 cmp::min(buffer_offset_in_excerpt, self.excerpt.text_summary.len);
4239
4240 self.excerpt_offset + buffer_offset_in_excerpt
4241 }
4242
4243 /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
4244 pub fn map_range_from_buffer(&self, buffer_range: Range<usize>) -> Range<usize> {
4245 self.map_offset_from_buffer(buffer_range.start)
4246 ..self.map_offset_from_buffer(buffer_range.end)
4247 }
4248
4249 /// Returns true if the entirety of the given range is in the buffer's excerpt
4250 pub fn contains_buffer_range(&self, range: Range<usize>) -> bool {
4251 range.start >= self.excerpt.buffer_start_offset()
4252 && range.end <= self.excerpt.buffer_end_offset()
4253 }
4254}
4255
4256impl ExcerptId {
4257 pub fn min() -> Self {
4258 Self(0)
4259 }
4260
4261 pub fn max() -> Self {
4262 Self(usize::MAX)
4263 }
4264
4265 pub fn to_proto(&self) -> u64 {
4266 self.0 as _
4267 }
4268
4269 pub fn from_proto(proto: u64) -> Self {
4270 Self(proto as _)
4271 }
4272
4273 pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
4274 let a = snapshot.excerpt_locator_for_id(*self);
4275 let b = snapshot.excerpt_locator_for_id(*other);
4276 a.cmp(b).then_with(|| self.0.cmp(&other.0))
4277 }
4278}
4279
4280impl Into<usize> for ExcerptId {
4281 fn into(self) -> usize {
4282 self.0
4283 }
4284}
4285
4286impl fmt::Debug for Excerpt {
4287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4288 f.debug_struct("Excerpt")
4289 .field("id", &self.id)
4290 .field("locator", &self.locator)
4291 .field("buffer_id", &self.buffer_id)
4292 .field("range", &self.range)
4293 .field("text_summary", &self.text_summary)
4294 .field("has_trailing_newline", &self.has_trailing_newline)
4295 .finish()
4296 }
4297}
4298
4299impl sum_tree::Item for Excerpt {
4300 type Summary = ExcerptSummary;
4301
4302 fn summary(&self) -> Self::Summary {
4303 let mut text = self.text_summary.clone();
4304 if self.has_trailing_newline {
4305 text += TextSummary::from("\n");
4306 }
4307 ExcerptSummary {
4308 excerpt_id: self.id,
4309 excerpt_locator: self.locator.clone(),
4310 max_buffer_row: MultiBufferRow(self.max_buffer_row),
4311 text,
4312 }
4313 }
4314}
4315
4316impl sum_tree::Item for ExcerptIdMapping {
4317 type Summary = ExcerptId;
4318
4319 fn summary(&self) -> Self::Summary {
4320 self.id
4321 }
4322}
4323
4324impl sum_tree::KeyedItem for ExcerptIdMapping {
4325 type Key = ExcerptId;
4326
4327 fn key(&self) -> Self::Key {
4328 self.id
4329 }
4330}
4331
4332impl sum_tree::Summary for ExcerptId {
4333 type Context = ();
4334
4335 fn add_summary(&mut self, other: &Self, _: &()) {
4336 *self = *other;
4337 }
4338}
4339
4340impl sum_tree::Summary for ExcerptSummary {
4341 type Context = ();
4342
4343 fn add_summary(&mut self, summary: &Self, _: &()) {
4344 debug_assert!(summary.excerpt_locator > self.excerpt_locator);
4345 self.excerpt_locator = summary.excerpt_locator.clone();
4346 self.text.add_summary(&summary.text, &());
4347 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
4348 }
4349}
4350
4351impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
4352 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4353 *self += &summary.text;
4354 }
4355}
4356
4357impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
4358 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4359 *self += summary.text.len;
4360 }
4361}
4362
4363impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
4364 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4365 Ord::cmp(self, &cursor_location.text.len)
4366 }
4367}
4368
4369impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
4370 fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
4371 Ord::cmp(&Some(self), cursor_location)
4372 }
4373}
4374
4375impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
4376 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4377 Ord::cmp(self, &cursor_location.excerpt_locator)
4378 }
4379}
4380
4381impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
4382 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4383 *self += summary.text.len_utf16;
4384 }
4385}
4386
4387impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
4388 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4389 *self += summary.text.lines;
4390 }
4391}
4392
4393impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
4394 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4395 *self += summary.text.lines_utf16()
4396 }
4397}
4398
4399impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
4400 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4401 *self = Some(&summary.excerpt_locator);
4402 }
4403}
4404
4405impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
4406 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4407 *self = Some(summary.excerpt_id);
4408 }
4409}
4410
4411impl<'a> MultiBufferRows<'a> {
4412 pub fn seek(&mut self, row: MultiBufferRow) {
4413 self.buffer_row_range = 0..0;
4414
4415 self.excerpts
4416 .seek_forward(&Point::new(row.0, 0), Bias::Right, &());
4417 if self.excerpts.item().is_none() {
4418 self.excerpts.prev(&());
4419
4420 if self.excerpts.item().is_none() && row.0 == 0 {
4421 self.buffer_row_range = 0..1;
4422 return;
4423 }
4424 }
4425
4426 if let Some(excerpt) = self.excerpts.item() {
4427 let overshoot = row.0 - self.excerpts.start().row;
4428 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4429 self.buffer_row_range.start = excerpt_start + overshoot;
4430 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
4431 }
4432 }
4433}
4434
4435impl<'a> Iterator for MultiBufferRows<'a> {
4436 type Item = Option<u32>;
4437
4438 fn next(&mut self) -> Option<Self::Item> {
4439 loop {
4440 if !self.buffer_row_range.is_empty() {
4441 let row = Some(self.buffer_row_range.start);
4442 self.buffer_row_range.start += 1;
4443 return Some(row);
4444 }
4445 self.excerpts.item()?;
4446 self.excerpts.next(&());
4447 let excerpt = self.excerpts.item()?;
4448 self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4449 self.buffer_row_range.end =
4450 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
4451 }
4452 }
4453}
4454
4455impl<'a> MultiBufferChunks<'a> {
4456 pub fn offset(&self) -> usize {
4457 self.range.start
4458 }
4459
4460 pub fn seek(&mut self, offset: usize) {
4461 self.range.start = offset;
4462 self.excerpts.seek(&offset, Bias::Right, &());
4463 if let Some(excerpt) = self.excerpts.item() {
4464 self.excerpt_chunks = Some(excerpt.chunks_in_range(
4465 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
4466 self.language_aware,
4467 ));
4468 } else {
4469 self.excerpt_chunks = None;
4470 }
4471 }
4472}
4473
4474impl<'a> Iterator for MultiBufferChunks<'a> {
4475 type Item = Chunk<'a>;
4476
4477 fn next(&mut self) -> Option<Self::Item> {
4478 if self.range.is_empty() {
4479 None
4480 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
4481 self.range.start += chunk.text.len();
4482 Some(chunk)
4483 } else {
4484 self.excerpts.next(&());
4485 let excerpt = self.excerpts.item()?;
4486 self.excerpt_chunks = Some(excerpt.chunks_in_range(
4487 0..self.range.end - self.excerpts.start(),
4488 self.language_aware,
4489 ));
4490 self.next()
4491 }
4492 }
4493}
4494
4495impl<'a> MultiBufferBytes<'a> {
4496 fn consume(&mut self, len: usize) {
4497 self.range.start += len;
4498 self.chunk = &self.chunk[len..];
4499
4500 if !self.range.is_empty() && self.chunk.is_empty() {
4501 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4502 self.chunk = chunk;
4503 } else {
4504 self.excerpts.next(&());
4505 if let Some(excerpt) = self.excerpts.item() {
4506 let mut excerpt_bytes =
4507 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
4508 self.chunk = excerpt_bytes.next().unwrap();
4509 self.excerpt_bytes = Some(excerpt_bytes);
4510 }
4511 }
4512 }
4513 }
4514}
4515
4516impl<'a> Iterator for MultiBufferBytes<'a> {
4517 type Item = &'a [u8];
4518
4519 fn next(&mut self) -> Option<Self::Item> {
4520 let chunk = self.chunk;
4521 if chunk.is_empty() {
4522 None
4523 } else {
4524 self.consume(chunk.len());
4525 Some(chunk)
4526 }
4527 }
4528}
4529
4530impl<'a> io::Read for MultiBufferBytes<'a> {
4531 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4532 let len = cmp::min(buf.len(), self.chunk.len());
4533 buf[..len].copy_from_slice(&self.chunk[..len]);
4534 if len > 0 {
4535 self.consume(len);
4536 }
4537 Ok(len)
4538 }
4539}
4540
4541impl<'a> ReversedMultiBufferBytes<'a> {
4542 fn consume(&mut self, len: usize) {
4543 self.range.end -= len;
4544 self.chunk = &self.chunk[..self.chunk.len() - len];
4545
4546 if !self.range.is_empty() && self.chunk.is_empty() {
4547 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4548 self.chunk = chunk;
4549 } else {
4550 self.excerpts.prev(&());
4551 if let Some(excerpt) = self.excerpts.item() {
4552 let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
4553 self.range.start.saturating_sub(*self.excerpts.start())..usize::MAX,
4554 );
4555 self.chunk = excerpt_bytes.next().unwrap();
4556 self.excerpt_bytes = Some(excerpt_bytes);
4557 }
4558 }
4559 } else {
4560 }
4561 }
4562}
4563
4564impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
4565 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4566 let len = cmp::min(buf.len(), self.chunk.len());
4567 buf[..len].copy_from_slice(&self.chunk[..len]);
4568 buf[..len].reverse();
4569 if len > 0 {
4570 self.consume(len);
4571 }
4572 Ok(len)
4573 }
4574}
4575impl<'a> Iterator for ExcerptBytes<'a> {
4576 type Item = &'a [u8];
4577
4578 fn next(&mut self) -> Option<Self::Item> {
4579 if self.reversed && self.padding_height > 0 {
4580 let result = &NEWLINES[..self.padding_height];
4581 self.padding_height = 0;
4582 return Some(result);
4583 }
4584
4585 if let Some(chunk) = self.content_bytes.next() {
4586 if !chunk.is_empty() {
4587 return Some(chunk);
4588 }
4589 }
4590
4591 if self.padding_height > 0 {
4592 let result = &NEWLINES[..self.padding_height];
4593 self.padding_height = 0;
4594 return Some(result);
4595 }
4596
4597 None
4598 }
4599}
4600
4601impl<'a> Iterator for ExcerptChunks<'a> {
4602 type Item = Chunk<'a>;
4603
4604 fn next(&mut self) -> Option<Self::Item> {
4605 if let Some(chunk) = self.content_chunks.next() {
4606 return Some(chunk);
4607 }
4608
4609 if self.footer_height > 0 {
4610 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
4611 self.footer_height = 0;
4612 return Some(Chunk {
4613 text,
4614 ..Default::default()
4615 });
4616 }
4617
4618 None
4619 }
4620}
4621
4622impl ToOffset for Point {
4623 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4624 snapshot.point_to_offset(*self)
4625 }
4626}
4627
4628impl ToOffset for usize {
4629 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4630 assert!(*self <= snapshot.len(), "offset is out of range");
4631 *self
4632 }
4633}
4634
4635impl ToOffset for OffsetUtf16 {
4636 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4637 snapshot.offset_utf16_to_offset(*self)
4638 }
4639}
4640
4641impl ToOffset for PointUtf16 {
4642 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4643 snapshot.point_utf16_to_offset(*self)
4644 }
4645}
4646
4647impl ToOffsetUtf16 for OffsetUtf16 {
4648 fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4649 *self
4650 }
4651}
4652
4653impl ToOffsetUtf16 for usize {
4654 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4655 snapshot.offset_to_offset_utf16(*self)
4656 }
4657}
4658
4659impl ToPoint for usize {
4660 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
4661 snapshot.offset_to_point(*self)
4662 }
4663}
4664
4665impl ToPoint for Point {
4666 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
4667 *self
4668 }
4669}
4670
4671impl ToPointUtf16 for usize {
4672 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4673 snapshot.offset_to_point_utf16(*self)
4674 }
4675}
4676
4677impl ToPointUtf16 for Point {
4678 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4679 snapshot.point_to_point_utf16(*self)
4680 }
4681}
4682
4683impl ToPointUtf16 for PointUtf16 {
4684 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
4685 *self
4686 }
4687}
4688
4689pub fn build_excerpt_ranges<T>(
4690 buffer: &BufferSnapshot,
4691 ranges: &[Range<T>],
4692 context_line_count: u32,
4693) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
4694where
4695 T: text::ToPoint,
4696{
4697 let max_point = buffer.max_point();
4698 let mut range_counts = Vec::new();
4699 let mut excerpt_ranges = Vec::new();
4700 let mut range_iter = ranges
4701 .iter()
4702 .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
4703 .peekable();
4704 while let Some(range) = range_iter.next() {
4705 let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
4706 let row = (range.end.row + context_line_count).min(max_point.row);
4707 let mut excerpt_end = Point::new(row, buffer.line_len(row));
4708
4709 let mut ranges_in_excerpt = 1;
4710
4711 while let Some(next_range) = range_iter.peek() {
4712 if next_range.start.row <= excerpt_end.row + context_line_count {
4713 let row = (next_range.end.row + context_line_count).min(max_point.row);
4714 excerpt_end = Point::new(row, buffer.line_len(row));
4715
4716 ranges_in_excerpt += 1;
4717 range_iter.next();
4718 } else {
4719 break;
4720 }
4721 }
4722
4723 excerpt_ranges.push(ExcerptRange {
4724 context: excerpt_start..excerpt_end,
4725 primary: Some(range),
4726 });
4727 range_counts.push(ranges_in_excerpt);
4728 }
4729
4730 (excerpt_ranges, range_counts)
4731}
4732
4733#[cfg(test)]
4734mod tests {
4735 use super::*;
4736 use futures::StreamExt;
4737 use gpui::{AppContext, Context, TestAppContext};
4738 use language::{Buffer, Rope};
4739 use parking_lot::RwLock;
4740 use rand::prelude::*;
4741 use settings::SettingsStore;
4742 use std::env;
4743 use util::test::sample_text;
4744
4745 #[ctor::ctor]
4746 fn init_logger() {
4747 if std::env::var("RUST_LOG").is_ok() {
4748 env_logger::init();
4749 }
4750 }
4751
4752 #[gpui::test]
4753 fn test_singleton(cx: &mut AppContext) {
4754 let buffer = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4755 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4756
4757 let snapshot = multibuffer.read(cx).snapshot(cx);
4758 assert_eq!(snapshot.text(), buffer.read(cx).text());
4759
4760 assert_eq!(
4761 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4762 (0..buffer.read(cx).row_count())
4763 .map(Some)
4764 .collect::<Vec<_>>()
4765 );
4766
4767 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4768 let snapshot = multibuffer.read(cx).snapshot(cx);
4769
4770 assert_eq!(snapshot.text(), buffer.read(cx).text());
4771 assert_eq!(
4772 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4773 (0..buffer.read(cx).row_count())
4774 .map(Some)
4775 .collect::<Vec<_>>()
4776 );
4777 }
4778
4779 #[gpui::test]
4780 fn test_remote(cx: &mut AppContext) {
4781 let host_buffer = cx.new_model(|cx| Buffer::local("a", cx));
4782 let guest_buffer = cx.new_model(|cx| {
4783 let state = host_buffer.read(cx).to_proto();
4784 let ops = cx
4785 .background_executor()
4786 .block(host_buffer.read(cx).serialize_ops(None, cx));
4787 let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
4788 buffer
4789 .apply_ops(
4790 ops.into_iter()
4791 .map(|op| language::proto::deserialize_operation(op).unwrap()),
4792 cx,
4793 )
4794 .unwrap();
4795 buffer
4796 });
4797 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4798 let snapshot = multibuffer.read(cx).snapshot(cx);
4799 assert_eq!(snapshot.text(), "a");
4800
4801 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4802 let snapshot = multibuffer.read(cx).snapshot(cx);
4803 assert_eq!(snapshot.text(), "ab");
4804
4805 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4806 let snapshot = multibuffer.read(cx).snapshot(cx);
4807 assert_eq!(snapshot.text(), "abc");
4808 }
4809
4810 #[gpui::test]
4811 fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4812 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4813 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
4814 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4815
4816 let events = Arc::new(RwLock::new(Vec::<Event>::new()));
4817 multibuffer.update(cx, |_, cx| {
4818 let events = events.clone();
4819 cx.subscribe(&multibuffer, move |_, _, event, _| {
4820 if let Event::Edited { .. } = event {
4821 events.write().push(event.clone())
4822 }
4823 })
4824 .detach();
4825 });
4826
4827 let subscription = multibuffer.update(cx, |multibuffer, cx| {
4828 let subscription = multibuffer.subscribe();
4829 multibuffer.push_excerpts(
4830 buffer_1.clone(),
4831 [ExcerptRange {
4832 context: Point::new(1, 2)..Point::new(2, 5),
4833 primary: None,
4834 }],
4835 cx,
4836 );
4837 assert_eq!(
4838 subscription.consume().into_inner(),
4839 [Edit {
4840 old: 0..0,
4841 new: 0..10
4842 }]
4843 );
4844
4845 multibuffer.push_excerpts(
4846 buffer_1.clone(),
4847 [ExcerptRange {
4848 context: Point::new(3, 3)..Point::new(4, 4),
4849 primary: None,
4850 }],
4851 cx,
4852 );
4853 multibuffer.push_excerpts(
4854 buffer_2.clone(),
4855 [ExcerptRange {
4856 context: Point::new(3, 1)..Point::new(3, 3),
4857 primary: None,
4858 }],
4859 cx,
4860 );
4861 assert_eq!(
4862 subscription.consume().into_inner(),
4863 [Edit {
4864 old: 10..10,
4865 new: 10..22
4866 }]
4867 );
4868
4869 subscription
4870 });
4871
4872 // Adding excerpts emits an edited event.
4873 assert_eq!(
4874 events.read().as_slice(),
4875 &[
4876 Event::Edited {
4877 singleton_buffer_edited: false
4878 },
4879 Event::Edited {
4880 singleton_buffer_edited: false
4881 },
4882 Event::Edited {
4883 singleton_buffer_edited: false
4884 }
4885 ]
4886 );
4887
4888 let snapshot = multibuffer.read(cx).snapshot(cx);
4889 assert_eq!(
4890 snapshot.text(),
4891 concat!(
4892 "bbbb\n", // Preserve newlines
4893 "ccccc\n", //
4894 "ddd\n", //
4895 "eeee\n", //
4896 "jj" //
4897 )
4898 );
4899 assert_eq!(
4900 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4901 [Some(1), Some(2), Some(3), Some(4), Some(3)]
4902 );
4903 assert_eq!(
4904 snapshot.buffer_rows(MultiBufferRow(2)).collect::<Vec<_>>(),
4905 [Some(3), Some(4), Some(3)]
4906 );
4907 assert_eq!(
4908 snapshot.buffer_rows(MultiBufferRow(4)).collect::<Vec<_>>(),
4909 [Some(3)]
4910 );
4911 assert_eq!(
4912 snapshot.buffer_rows(MultiBufferRow(5)).collect::<Vec<_>>(),
4913 []
4914 );
4915
4916 assert_eq!(
4917 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4918 &[
4919 (MultiBufferRow(0), "bbbb\nccccc".to_string(), true),
4920 (MultiBufferRow(2), "ddd\neeee".to_string(), false),
4921 (MultiBufferRow(4), "jj".to_string(), true),
4922 ]
4923 );
4924 assert_eq!(
4925 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4926 &[(MultiBufferRow(0), "bbbb\nccccc".to_string(), true)]
4927 );
4928 assert_eq!(
4929 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4930 &[]
4931 );
4932 assert_eq!(
4933 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4934 &[]
4935 );
4936 assert_eq!(
4937 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4938 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4939 );
4940 assert_eq!(
4941 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4942 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4943 );
4944 assert_eq!(
4945 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4946 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4947 );
4948 assert_eq!(
4949 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4950 &[(MultiBufferRow(4), "jj".to_string(), true)]
4951 );
4952 assert_eq!(
4953 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4954 &[]
4955 );
4956
4957 buffer_1.update(cx, |buffer, cx| {
4958 let text = "\n";
4959 buffer.edit(
4960 [
4961 (Point::new(0, 0)..Point::new(0, 0), text),
4962 (Point::new(2, 1)..Point::new(2, 3), text),
4963 ],
4964 None,
4965 cx,
4966 );
4967 });
4968
4969 let snapshot = multibuffer.read(cx).snapshot(cx);
4970 assert_eq!(
4971 snapshot.text(),
4972 concat!(
4973 "bbbb\n", // Preserve newlines
4974 "c\n", //
4975 "cc\n", //
4976 "ddd\n", //
4977 "eeee\n", //
4978 "jj" //
4979 )
4980 );
4981
4982 assert_eq!(
4983 subscription.consume().into_inner(),
4984 [Edit {
4985 old: 6..8,
4986 new: 6..7
4987 }]
4988 );
4989
4990 let snapshot = multibuffer.read(cx).snapshot(cx);
4991 assert_eq!(
4992 snapshot.clip_point(Point::new(0, 5), Bias::Left),
4993 Point::new(0, 4)
4994 );
4995 assert_eq!(
4996 snapshot.clip_point(Point::new(0, 5), Bias::Right),
4997 Point::new(0, 4)
4998 );
4999 assert_eq!(
5000 snapshot.clip_point(Point::new(5, 1), Bias::Right),
5001 Point::new(5, 1)
5002 );
5003 assert_eq!(
5004 snapshot.clip_point(Point::new(5, 2), Bias::Right),
5005 Point::new(5, 2)
5006 );
5007 assert_eq!(
5008 snapshot.clip_point(Point::new(5, 3), Bias::Right),
5009 Point::new(5, 2)
5010 );
5011
5012 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
5013 let (buffer_2_excerpt_id, _) =
5014 multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
5015 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
5016 multibuffer.snapshot(cx)
5017 });
5018
5019 assert_eq!(
5020 snapshot.text(),
5021 concat!(
5022 "bbbb\n", // Preserve newlines
5023 "c\n", //
5024 "cc\n", //
5025 "ddd\n", //
5026 "eeee", //
5027 )
5028 );
5029
5030 fn boundaries_in_range(
5031 range: Range<Point>,
5032 snapshot: &MultiBufferSnapshot,
5033 ) -> Vec<(MultiBufferRow, String, bool)> {
5034 snapshot
5035 .excerpt_boundaries_in_range(range)
5036 .filter_map(|boundary| {
5037 let starts_new_buffer = boundary.starts_new_buffer();
5038 boundary.next.map(|next| {
5039 (
5040 boundary.row,
5041 next.buffer
5042 .text_for_range(next.range.context)
5043 .collect::<String>(),
5044 starts_new_buffer,
5045 )
5046 })
5047 })
5048 .collect::<Vec<_>>()
5049 }
5050 }
5051
5052 #[gpui::test]
5053 fn test_excerpt_events(cx: &mut AppContext) {
5054 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
5055 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
5056
5057 let leader_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5058 let follower_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5059 let follower_edit_event_count = Arc::new(RwLock::new(0));
5060
5061 follower_multibuffer.update(cx, |_, cx| {
5062 let follower_edit_event_count = follower_edit_event_count.clone();
5063 cx.subscribe(
5064 &leader_multibuffer,
5065 move |follower, _, event, cx| match event.clone() {
5066 Event::ExcerptsAdded {
5067 buffer,
5068 predecessor,
5069 excerpts,
5070 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
5071 Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
5072 Event::Edited { .. } => {
5073 *follower_edit_event_count.write() += 1;
5074 }
5075 _ => {}
5076 },
5077 )
5078 .detach();
5079 });
5080
5081 leader_multibuffer.update(cx, |leader, cx| {
5082 leader.push_excerpts(
5083 buffer_1.clone(),
5084 [
5085 ExcerptRange {
5086 context: 0..8,
5087 primary: None,
5088 },
5089 ExcerptRange {
5090 context: 12..16,
5091 primary: None,
5092 },
5093 ],
5094 cx,
5095 );
5096 leader.insert_excerpts_after(
5097 leader.excerpt_ids()[0],
5098 buffer_2.clone(),
5099 [
5100 ExcerptRange {
5101 context: 0..5,
5102 primary: None,
5103 },
5104 ExcerptRange {
5105 context: 10..15,
5106 primary: None,
5107 },
5108 ],
5109 cx,
5110 )
5111 });
5112 assert_eq!(
5113 leader_multibuffer.read(cx).snapshot(cx).text(),
5114 follower_multibuffer.read(cx).snapshot(cx).text(),
5115 );
5116 assert_eq!(*follower_edit_event_count.read(), 2);
5117
5118 leader_multibuffer.update(cx, |leader, cx| {
5119 let excerpt_ids = leader.excerpt_ids();
5120 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
5121 });
5122 assert_eq!(
5123 leader_multibuffer.read(cx).snapshot(cx).text(),
5124 follower_multibuffer.read(cx).snapshot(cx).text(),
5125 );
5126 assert_eq!(*follower_edit_event_count.read(), 3);
5127
5128 // Removing an empty set of excerpts is a noop.
5129 leader_multibuffer.update(cx, |leader, cx| {
5130 leader.remove_excerpts([], cx);
5131 });
5132 assert_eq!(
5133 leader_multibuffer.read(cx).snapshot(cx).text(),
5134 follower_multibuffer.read(cx).snapshot(cx).text(),
5135 );
5136 assert_eq!(*follower_edit_event_count.read(), 3);
5137
5138 // Adding an empty set of excerpts is a noop.
5139 leader_multibuffer.update(cx, |leader, cx| {
5140 leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
5141 });
5142 assert_eq!(
5143 leader_multibuffer.read(cx).snapshot(cx).text(),
5144 follower_multibuffer.read(cx).snapshot(cx).text(),
5145 );
5146 assert_eq!(*follower_edit_event_count.read(), 3);
5147
5148 leader_multibuffer.update(cx, |leader, cx| {
5149 leader.clear(cx);
5150 });
5151 assert_eq!(
5152 leader_multibuffer.read(cx).snapshot(cx).text(),
5153 follower_multibuffer.read(cx).snapshot(cx).text(),
5154 );
5155 assert_eq!(*follower_edit_event_count.read(), 4);
5156 }
5157
5158 #[gpui::test]
5159 fn test_expand_excerpts(cx: &mut AppContext) {
5160 let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5161 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5162
5163 multibuffer.update(cx, |multibuffer, cx| {
5164 multibuffer.push_excerpts_with_context_lines(
5165 buffer.clone(),
5166 vec![
5167 // Note that in this test, this first excerpt
5168 // does not contain a new line
5169 Point::new(3, 2)..Point::new(3, 3),
5170 Point::new(7, 1)..Point::new(7, 3),
5171 Point::new(15, 0)..Point::new(15, 0),
5172 ],
5173 1,
5174 cx,
5175 )
5176 });
5177
5178 let snapshot = multibuffer.read(cx).snapshot(cx);
5179
5180 assert_eq!(
5181 snapshot.text(),
5182 concat!(
5183 "ccc\n", //
5184 "ddd\n", //
5185 "eee", //
5186 "\n", // End of excerpt
5187 "ggg\n", //
5188 "hhh\n", //
5189 "iii", //
5190 "\n", // End of excerpt
5191 "ooo\n", //
5192 "ppp\n", //
5193 "qqq", // End of excerpt
5194 )
5195 );
5196 drop(snapshot);
5197
5198 multibuffer.update(cx, |multibuffer, cx| {
5199 multibuffer.expand_excerpts(
5200 multibuffer.excerpt_ids(),
5201 1,
5202 ExpandExcerptDirection::UpAndDown,
5203 cx,
5204 )
5205 });
5206
5207 let snapshot = multibuffer.read(cx).snapshot(cx);
5208
5209 // Expanding context lines causes the line containing 'fff' to appear in two different excerpts.
5210 // We don't attempt to merge them, because removing the excerpt could create inconsistency with other layers
5211 // that are tracking excerpt ids.
5212 assert_eq!(
5213 snapshot.text(),
5214 concat!(
5215 "bbb\n", //
5216 "ccc\n", //
5217 "ddd\n", //
5218 "eee\n", //
5219 "fff\n", // End of excerpt
5220 "fff\n", //
5221 "ggg\n", //
5222 "hhh\n", //
5223 "iii\n", //
5224 "jjj\n", // End of excerpt
5225 "nnn\n", //
5226 "ooo\n", //
5227 "ppp\n", //
5228 "qqq\n", //
5229 "rrr", // End of excerpt
5230 )
5231 );
5232 }
5233
5234 #[gpui::test]
5235 fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
5236 let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5237 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5238 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5239 multibuffer.push_excerpts_with_context_lines(
5240 buffer.clone(),
5241 vec![
5242 // Note that in this test, this first excerpt
5243 // does contain a new line
5244 Point::new(3, 2)..Point::new(4, 2),
5245 Point::new(7, 1)..Point::new(7, 3),
5246 Point::new(15, 0)..Point::new(15, 0),
5247 ],
5248 2,
5249 cx,
5250 )
5251 });
5252
5253 let snapshot = multibuffer.read(cx).snapshot(cx);
5254 assert_eq!(
5255 snapshot.text(),
5256 concat!(
5257 "bbb\n", // Preserve newlines
5258 "ccc\n", //
5259 "ddd\n", //
5260 "eee\n", //
5261 "fff\n", //
5262 "ggg\n", //
5263 "hhh\n", //
5264 "iii\n", //
5265 "jjj\n", //
5266 "nnn\n", //
5267 "ooo\n", //
5268 "ppp\n", //
5269 "qqq\n", //
5270 "rrr", //
5271 )
5272 );
5273
5274 assert_eq!(
5275 anchor_ranges
5276 .iter()
5277 .map(|range| range.to_point(&snapshot))
5278 .collect::<Vec<_>>(),
5279 vec![
5280 Point::new(2, 2)..Point::new(3, 2),
5281 Point::new(6, 1)..Point::new(6, 3),
5282 Point::new(11, 0)..Point::new(11, 0)
5283 ]
5284 );
5285 }
5286
5287 #[gpui::test]
5288 async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
5289 let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5290 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5291 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5292 let snapshot = buffer.read(cx);
5293 let ranges = vec![
5294 snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
5295 snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
5296 snapshot.anchor_before(Point::new(15, 0))
5297 ..snapshot.anchor_before(Point::new(15, 0)),
5298 ];
5299 multibuffer.stream_excerpts_with_context_lines(buffer.clone(), ranges, 2, cx)
5300 });
5301
5302 let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
5303
5304 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
5305 assert_eq!(
5306 snapshot.text(),
5307 concat!(
5308 "bbb\n", //
5309 "ccc\n", //
5310 "ddd\n", //
5311 "eee\n", //
5312 "fff\n", //
5313 "ggg\n", //
5314 "hhh\n", //
5315 "iii\n", //
5316 "jjj\n", //
5317 "nnn\n", //
5318 "ooo\n", //
5319 "ppp\n", //
5320 "qqq\n", //
5321 "rrr", //
5322 )
5323 );
5324
5325 assert_eq!(
5326 anchor_ranges
5327 .iter()
5328 .map(|range| range.to_point(&snapshot))
5329 .collect::<Vec<_>>(),
5330 vec![
5331 Point::new(2, 2)..Point::new(3, 2),
5332 Point::new(6, 1)..Point::new(6, 3),
5333 Point::new(11, 0)..Point::new(11, 0)
5334 ]
5335 );
5336 }
5337
5338 #[gpui::test]
5339 fn test_empty_multibuffer(cx: &mut AppContext) {
5340 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5341
5342 let snapshot = multibuffer.read(cx).snapshot(cx);
5343 assert_eq!(snapshot.text(), "");
5344 assert_eq!(
5345 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5346 &[Some(0)]
5347 );
5348 assert_eq!(
5349 snapshot.buffer_rows(MultiBufferRow(1)).collect::<Vec<_>>(),
5350 &[]
5351 );
5352 }
5353
5354 #[gpui::test]
5355 fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
5356 let buffer = cx.new_model(|cx| Buffer::local("abcd", cx));
5357 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
5358 let old_snapshot = multibuffer.read(cx).snapshot(cx);
5359 buffer.update(cx, |buffer, cx| {
5360 buffer.edit([(0..0, "X")], None, cx);
5361 buffer.edit([(5..5, "Y")], None, cx);
5362 });
5363 let new_snapshot = multibuffer.read(cx).snapshot(cx);
5364
5365 assert_eq!(old_snapshot.text(), "abcd");
5366 assert_eq!(new_snapshot.text(), "XabcdY");
5367
5368 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5369 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5370 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
5371 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
5372 }
5373
5374 #[gpui::test]
5375 fn test_multibuffer_anchors(cx: &mut AppContext) {
5376 let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5377 let buffer_2 = cx.new_model(|cx| Buffer::local("efghi", cx));
5378 let multibuffer = cx.new_model(|cx| {
5379 let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
5380 multibuffer.push_excerpts(
5381 buffer_1.clone(),
5382 [ExcerptRange {
5383 context: 0..4,
5384 primary: None,
5385 }],
5386 cx,
5387 );
5388 multibuffer.push_excerpts(
5389 buffer_2.clone(),
5390 [ExcerptRange {
5391 context: 0..5,
5392 primary: None,
5393 }],
5394 cx,
5395 );
5396 multibuffer
5397 });
5398 let old_snapshot = multibuffer.read(cx).snapshot(cx);
5399
5400 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
5401 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
5402 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5403 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5404 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5405 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5406
5407 buffer_1.update(cx, |buffer, cx| {
5408 buffer.edit([(0..0, "W")], None, cx);
5409 buffer.edit([(5..5, "X")], None, cx);
5410 });
5411 buffer_2.update(cx, |buffer, cx| {
5412 buffer.edit([(0..0, "Y")], None, cx);
5413 buffer.edit([(6..6, "Z")], None, cx);
5414 });
5415 let new_snapshot = multibuffer.read(cx).snapshot(cx);
5416
5417 assert_eq!(old_snapshot.text(), "abcd\nefghi");
5418 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
5419
5420 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5421 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5422 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
5423 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
5424 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
5425 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
5426 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
5427 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
5428 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
5429 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
5430 }
5431
5432 #[gpui::test]
5433 fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
5434 let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5435 let buffer_2 = cx.new_model(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
5436 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5437
5438 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
5439 // Add an excerpt from buffer 1 that spans this new insertion.
5440 buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
5441 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
5442 multibuffer
5443 .push_excerpts(
5444 buffer_1.clone(),
5445 [ExcerptRange {
5446 context: 0..7,
5447 primary: None,
5448 }],
5449 cx,
5450 )
5451 .pop()
5452 .unwrap()
5453 });
5454
5455 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
5456 assert_eq!(snapshot_1.text(), "abcd123");
5457
5458 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
5459 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
5460 multibuffer.remove_excerpts([excerpt_id_1], cx);
5461 let mut ids = multibuffer
5462 .push_excerpts(
5463 buffer_2.clone(),
5464 [
5465 ExcerptRange {
5466 context: 0..4,
5467 primary: None,
5468 },
5469 ExcerptRange {
5470 context: 6..10,
5471 primary: None,
5472 },
5473 ExcerptRange {
5474 context: 12..16,
5475 primary: None,
5476 },
5477 ],
5478 cx,
5479 )
5480 .into_iter();
5481 (ids.next().unwrap(), ids.next().unwrap())
5482 });
5483 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
5484 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
5485
5486 // The old excerpt id doesn't get reused.
5487 assert_ne!(excerpt_id_2, excerpt_id_1);
5488
5489 // Resolve some anchors from the previous snapshot in the new snapshot.
5490 // The current excerpts are from a different buffer, so we don't attempt to
5491 // resolve the old text anchor in the new buffer.
5492 assert_eq!(
5493 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
5494 0
5495 );
5496 assert_eq!(
5497 snapshot_2.summaries_for_anchors::<usize, _>(&[
5498 snapshot_1.anchor_before(2),
5499 snapshot_1.anchor_after(3)
5500 ]),
5501 vec![0, 0]
5502 );
5503
5504 // Refresh anchors from the old snapshot. The return value indicates that both
5505 // anchors lost their original excerpt.
5506 let refresh =
5507 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
5508 assert_eq!(
5509 refresh,
5510 &[
5511 (0, snapshot_2.anchor_before(0), false),
5512 (1, snapshot_2.anchor_after(0), false),
5513 ]
5514 );
5515
5516 // Replace the middle excerpt with a smaller excerpt in buffer 2,
5517 // that intersects the old excerpt.
5518 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
5519 multibuffer.remove_excerpts([excerpt_id_3], cx);
5520 multibuffer
5521 .insert_excerpts_after(
5522 excerpt_id_2,
5523 buffer_2.clone(),
5524 [ExcerptRange {
5525 context: 5..8,
5526 primary: None,
5527 }],
5528 cx,
5529 )
5530 .pop()
5531 .unwrap()
5532 });
5533
5534 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
5535 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
5536 assert_ne!(excerpt_id_5, excerpt_id_3);
5537
5538 // Resolve some anchors from the previous snapshot in the new snapshot.
5539 // The third anchor can't be resolved, since its excerpt has been removed,
5540 // so it resolves to the same position as its predecessor.
5541 let anchors = [
5542 snapshot_2.anchor_before(0),
5543 snapshot_2.anchor_after(2),
5544 snapshot_2.anchor_after(6),
5545 snapshot_2.anchor_after(14),
5546 ];
5547 assert_eq!(
5548 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
5549 &[0, 2, 9, 13]
5550 );
5551
5552 let new_anchors = snapshot_3.refresh_anchors(&anchors);
5553 assert_eq!(
5554 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
5555 &[(0, true), (1, true), (2, true), (3, true)]
5556 );
5557 assert_eq!(
5558 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
5559 &[0, 2, 7, 13]
5560 );
5561 }
5562
5563 #[gpui::test(iterations = 100)]
5564 fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
5565 let operations = env::var("OPERATIONS")
5566 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
5567 .unwrap_or(10);
5568
5569 let mut buffers: Vec<Model<Buffer>> = Vec::new();
5570 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5571 let mut excerpt_ids = Vec::<ExcerptId>::new();
5572 let mut expected_excerpts = Vec::<(Model<Buffer>, Range<text::Anchor>)>::new();
5573 let mut anchors = Vec::new();
5574 let mut old_versions = Vec::new();
5575
5576 for _ in 0..operations {
5577 match rng.gen_range(0..100) {
5578 0..=14 if !buffers.is_empty() => {
5579 let buffer = buffers.choose(&mut rng).unwrap();
5580 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
5581 }
5582 15..=19 if !expected_excerpts.is_empty() => {
5583 multibuffer.update(cx, |multibuffer, cx| {
5584 let ids = multibuffer.excerpt_ids();
5585 let mut excerpts = HashSet::default();
5586 for _ in 0..rng.gen_range(0..ids.len()) {
5587 excerpts.extend(ids.choose(&mut rng).copied());
5588 }
5589
5590 let line_count = rng.gen_range(0..5);
5591
5592 let excerpt_ixs = excerpts
5593 .iter()
5594 .map(|id| excerpt_ids.iter().position(|i| i == id).unwrap())
5595 .collect::<Vec<_>>();
5596 log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
5597 multibuffer.expand_excerpts(
5598 excerpts.iter().cloned(),
5599 line_count,
5600 ExpandExcerptDirection::UpAndDown,
5601 cx,
5602 );
5603
5604 if line_count > 0 {
5605 for id in excerpts {
5606 let excerpt_ix = excerpt_ids.iter().position(|&i| i == id).unwrap();
5607 let (buffer, range) = &mut expected_excerpts[excerpt_ix];
5608 let snapshot = buffer.read(cx).snapshot();
5609 let mut point_range = range.to_point(&snapshot);
5610 point_range.start =
5611 Point::new(point_range.start.row.saturating_sub(line_count), 0);
5612 point_range.end = snapshot.clip_point(
5613 Point::new(point_range.end.row + line_count, 0),
5614 Bias::Left,
5615 );
5616 point_range.end.column = snapshot.line_len(point_range.end.row);
5617 *range = snapshot.anchor_before(point_range.start)
5618 ..snapshot.anchor_after(point_range.end);
5619 }
5620 }
5621 });
5622 }
5623 20..=29 if !expected_excerpts.is_empty() => {
5624 let mut ids_to_remove = vec![];
5625 for _ in 0..rng.gen_range(1..=3) {
5626 if expected_excerpts.is_empty() {
5627 break;
5628 }
5629
5630 let ix = rng.gen_range(0..expected_excerpts.len());
5631 ids_to_remove.push(excerpt_ids.remove(ix));
5632 let (buffer, range) = expected_excerpts.remove(ix);
5633 let buffer = buffer.read(cx);
5634 log::info!(
5635 "Removing excerpt {}: {:?}",
5636 ix,
5637 buffer
5638 .text_for_range(range.to_offset(buffer))
5639 .collect::<String>(),
5640 );
5641 }
5642 let snapshot = multibuffer.read(cx).read(cx);
5643 ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
5644 drop(snapshot);
5645 multibuffer.update(cx, |multibuffer, cx| {
5646 multibuffer.remove_excerpts(ids_to_remove, cx)
5647 });
5648 }
5649 30..=39 if !expected_excerpts.is_empty() => {
5650 let multibuffer = multibuffer.read(cx).read(cx);
5651 let offset =
5652 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
5653 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
5654 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
5655 anchors.push(multibuffer.anchor_at(offset, bias));
5656 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
5657 }
5658 40..=44 if !anchors.is_empty() => {
5659 let multibuffer = multibuffer.read(cx).read(cx);
5660 let prev_len = anchors.len();
5661 anchors = multibuffer
5662 .refresh_anchors(&anchors)
5663 .into_iter()
5664 .map(|a| a.1)
5665 .collect();
5666
5667 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
5668 // overshoot its boundaries.
5669 assert_eq!(anchors.len(), prev_len);
5670 for anchor in &anchors {
5671 if anchor.excerpt_id == ExcerptId::min()
5672 || anchor.excerpt_id == ExcerptId::max()
5673 {
5674 continue;
5675 }
5676
5677 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
5678 assert_eq!(excerpt.id, anchor.excerpt_id);
5679 assert!(excerpt.contains(anchor));
5680 }
5681 }
5682 _ => {
5683 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
5684 let base_text = util::RandomCharIter::new(&mut rng)
5685 .take(25)
5686 .collect::<String>();
5687
5688 buffers.push(cx.new_model(|cx| Buffer::local(base_text, cx)));
5689 buffers.last().unwrap()
5690 } else {
5691 buffers.choose(&mut rng).unwrap()
5692 };
5693
5694 let buffer = buffer_handle.read(cx);
5695 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
5696 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5697 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
5698 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
5699 let prev_excerpt_id = excerpt_ids
5700 .get(prev_excerpt_ix)
5701 .cloned()
5702 .unwrap_or_else(ExcerptId::max);
5703 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
5704
5705 log::info!(
5706 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
5707 excerpt_ix,
5708 expected_excerpts.len(),
5709 buffer_handle.read(cx).remote_id(),
5710 buffer.text(),
5711 start_ix..end_ix,
5712 &buffer.text()[start_ix..end_ix]
5713 );
5714
5715 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
5716 multibuffer
5717 .insert_excerpts_after(
5718 prev_excerpt_id,
5719 buffer_handle.clone(),
5720 [ExcerptRange {
5721 context: start_ix..end_ix,
5722 primary: None,
5723 }],
5724 cx,
5725 )
5726 .pop()
5727 .unwrap()
5728 });
5729
5730 excerpt_ids.insert(excerpt_ix, excerpt_id);
5731 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
5732 }
5733 }
5734
5735 if rng.gen_bool(0.3) {
5736 multibuffer.update(cx, |multibuffer, cx| {
5737 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
5738 })
5739 }
5740
5741 let snapshot = multibuffer.read(cx).snapshot(cx);
5742
5743 let mut excerpt_starts = Vec::new();
5744 let mut expected_text = String::new();
5745 let mut expected_buffer_rows = Vec::new();
5746 for (buffer, range) in &expected_excerpts {
5747 let buffer = buffer.read(cx);
5748 let buffer_range = range.to_offset(buffer);
5749
5750 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5751 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5752 expected_text.push('\n');
5753
5754 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5755 ..=buffer.offset_to_point(buffer_range.end).row;
5756 for row in buffer_row_range {
5757 expected_buffer_rows.push(Some(row));
5758 }
5759 }
5760 // Remove final trailing newline.
5761 if !expected_excerpts.is_empty() {
5762 expected_text.pop();
5763 }
5764
5765 // Always report one buffer row
5766 if expected_buffer_rows.is_empty() {
5767 expected_buffer_rows.push(Some(0));
5768 }
5769
5770 assert_eq!(snapshot.text(), expected_text);
5771 log::info!("MultiBuffer text: {:?}", expected_text);
5772
5773 assert_eq!(
5774 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5775 expected_buffer_rows,
5776 );
5777
5778 for _ in 0..5 {
5779 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5780 assert_eq!(
5781 snapshot
5782 .buffer_rows(MultiBufferRow(start_row as u32))
5783 .collect::<Vec<_>>(),
5784 &expected_buffer_rows[start_row..],
5785 "buffer_rows({})",
5786 start_row
5787 );
5788 }
5789
5790 assert_eq!(
5791 snapshot.max_buffer_row().0,
5792 expected_buffer_rows.into_iter().flatten().max().unwrap()
5793 );
5794
5795 let mut excerpt_starts = excerpt_starts.into_iter();
5796 for (buffer, range) in &expected_excerpts {
5797 let buffer = buffer.read(cx);
5798 let buffer_id = buffer.remote_id();
5799 let buffer_range = range.to_offset(buffer);
5800 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5801 let buffer_start_point_utf16 =
5802 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5803
5804 let excerpt_start = excerpt_starts.next().unwrap();
5805 let mut offset = excerpt_start.len;
5806 let mut buffer_offset = buffer_range.start;
5807 let mut point = excerpt_start.lines;
5808 let mut buffer_point = buffer_start_point;
5809 let mut point_utf16 = excerpt_start.lines_utf16();
5810 let mut buffer_point_utf16 = buffer_start_point_utf16;
5811 for ch in buffer
5812 .snapshot()
5813 .chunks(buffer_range.clone(), false)
5814 .flat_map(|c| c.text.chars())
5815 {
5816 for _ in 0..ch.len_utf8() {
5817 let left_offset = snapshot.clip_offset(offset, Bias::Left);
5818 let right_offset = snapshot.clip_offset(offset, Bias::Right);
5819 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5820 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5821 assert_eq!(
5822 left_offset,
5823 excerpt_start.len + (buffer_left_offset - buffer_range.start),
5824 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5825 offset,
5826 buffer_id,
5827 buffer_offset,
5828 );
5829 assert_eq!(
5830 right_offset,
5831 excerpt_start.len + (buffer_right_offset - buffer_range.start),
5832 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5833 offset,
5834 buffer_id,
5835 buffer_offset,
5836 );
5837
5838 let left_point = snapshot.clip_point(point, Bias::Left);
5839 let right_point = snapshot.clip_point(point, Bias::Right);
5840 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5841 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5842 assert_eq!(
5843 left_point,
5844 excerpt_start.lines + (buffer_left_point - buffer_start_point),
5845 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5846 point,
5847 buffer_id,
5848 buffer_point,
5849 );
5850 assert_eq!(
5851 right_point,
5852 excerpt_start.lines + (buffer_right_point - buffer_start_point),
5853 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5854 point,
5855 buffer_id,
5856 buffer_point,
5857 );
5858
5859 assert_eq!(
5860 snapshot.point_to_offset(left_point),
5861 left_offset,
5862 "point_to_offset({:?})",
5863 left_point,
5864 );
5865 assert_eq!(
5866 snapshot.offset_to_point(left_offset),
5867 left_point,
5868 "offset_to_point({:?})",
5869 left_offset,
5870 );
5871
5872 offset += 1;
5873 buffer_offset += 1;
5874 if ch == '\n' {
5875 point += Point::new(1, 0);
5876 buffer_point += Point::new(1, 0);
5877 } else {
5878 point += Point::new(0, 1);
5879 buffer_point += Point::new(0, 1);
5880 }
5881 }
5882
5883 for _ in 0..ch.len_utf16() {
5884 let left_point_utf16 =
5885 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5886 let right_point_utf16 =
5887 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5888 let buffer_left_point_utf16 =
5889 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5890 let buffer_right_point_utf16 =
5891 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5892 assert_eq!(
5893 left_point_utf16,
5894 excerpt_start.lines_utf16()
5895 + (buffer_left_point_utf16 - buffer_start_point_utf16),
5896 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5897 point_utf16,
5898 buffer_id,
5899 buffer_point_utf16,
5900 );
5901 assert_eq!(
5902 right_point_utf16,
5903 excerpt_start.lines_utf16()
5904 + (buffer_right_point_utf16 - buffer_start_point_utf16),
5905 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5906 point_utf16,
5907 buffer_id,
5908 buffer_point_utf16,
5909 );
5910
5911 if ch == '\n' {
5912 point_utf16 += PointUtf16::new(1, 0);
5913 buffer_point_utf16 += PointUtf16::new(1, 0);
5914 } else {
5915 point_utf16 += PointUtf16::new(0, 1);
5916 buffer_point_utf16 += PointUtf16::new(0, 1);
5917 }
5918 }
5919 }
5920 }
5921
5922 for (row, line) in expected_text.split('\n').enumerate() {
5923 assert_eq!(
5924 snapshot.line_len(MultiBufferRow(row as u32)),
5925 line.len() as u32,
5926 "line_len({}).",
5927 row
5928 );
5929 }
5930
5931 let text_rope = Rope::from(expected_text.as_str());
5932 for _ in 0..10 {
5933 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5934 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5935
5936 let text_for_range = snapshot
5937 .text_for_range(start_ix..end_ix)
5938 .collect::<String>();
5939 assert_eq!(
5940 text_for_range,
5941 &expected_text[start_ix..end_ix],
5942 "incorrect text for range {:?}",
5943 start_ix..end_ix
5944 );
5945
5946 let excerpted_buffer_ranges = multibuffer
5947 .read(cx)
5948 .range_to_buffer_ranges(start_ix..end_ix, cx);
5949 let excerpted_buffers_text = excerpted_buffer_ranges
5950 .iter()
5951 .map(|(buffer, buffer_range, _)| {
5952 buffer
5953 .read(cx)
5954 .text_for_range(buffer_range.clone())
5955 .collect::<String>()
5956 })
5957 .collect::<Vec<_>>()
5958 .join("\n");
5959 assert_eq!(excerpted_buffers_text, text_for_range);
5960 if !expected_excerpts.is_empty() {
5961 assert!(!excerpted_buffer_ranges.is_empty());
5962 }
5963
5964 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5965 assert_eq!(
5966 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5967 expected_summary,
5968 "incorrect summary for range {:?}",
5969 start_ix..end_ix
5970 );
5971 }
5972
5973 // Anchor resolution
5974 let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5975 assert_eq!(anchors.len(), summaries.len());
5976 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5977 assert!(resolved_offset <= snapshot.len());
5978 assert_eq!(
5979 snapshot.summary_for_anchor::<usize>(anchor),
5980 resolved_offset
5981 );
5982 }
5983
5984 for _ in 0..10 {
5985 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5986 assert_eq!(
5987 snapshot.reversed_chars_at(end_ix).collect::<String>(),
5988 expected_text[..end_ix].chars().rev().collect::<String>(),
5989 );
5990 }
5991
5992 for _ in 0..10 {
5993 let end_ix = rng.gen_range(0..=text_rope.len());
5994 let start_ix = rng.gen_range(0..=end_ix);
5995 assert_eq!(
5996 snapshot
5997 .bytes_in_range(start_ix..end_ix)
5998 .flatten()
5999 .copied()
6000 .collect::<Vec<_>>(),
6001 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
6002 "bytes_in_range({:?})",
6003 start_ix..end_ix,
6004 );
6005 }
6006 }
6007
6008 let snapshot = multibuffer.read(cx).snapshot(cx);
6009 for (old_snapshot, subscription) in old_versions {
6010 let edits = subscription.consume().into_inner();
6011
6012 log::info!(
6013 "applying subscription edits to old text: {:?}: {:?}",
6014 old_snapshot.text(),
6015 edits,
6016 );
6017
6018 let mut text = old_snapshot.text();
6019 for edit in edits {
6020 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
6021 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
6022 }
6023 assert_eq!(text.to_string(), snapshot.text());
6024 }
6025 }
6026
6027 #[gpui::test]
6028 fn test_history(cx: &mut AppContext) {
6029 let test_settings = SettingsStore::test(cx);
6030 cx.set_global(test_settings);
6031
6032 let buffer_1 = cx.new_model(|cx| Buffer::local("1234", cx));
6033 let buffer_2 = cx.new_model(|cx| Buffer::local("5678", cx));
6034 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6035 let group_interval = multibuffer.read(cx).history.group_interval;
6036 multibuffer.update(cx, |multibuffer, cx| {
6037 multibuffer.push_excerpts(
6038 buffer_1.clone(),
6039 [ExcerptRange {
6040 context: 0..buffer_1.read(cx).len(),
6041 primary: None,
6042 }],
6043 cx,
6044 );
6045 multibuffer.push_excerpts(
6046 buffer_2.clone(),
6047 [ExcerptRange {
6048 context: 0..buffer_2.read(cx).len(),
6049 primary: None,
6050 }],
6051 cx,
6052 );
6053 });
6054
6055 let mut now = Instant::now();
6056
6057 multibuffer.update(cx, |multibuffer, cx| {
6058 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
6059 multibuffer.edit(
6060 [
6061 (Point::new(0, 0)..Point::new(0, 0), "A"),
6062 (Point::new(1, 0)..Point::new(1, 0), "A"),
6063 ],
6064 None,
6065 cx,
6066 );
6067 multibuffer.edit(
6068 [
6069 (Point::new(0, 1)..Point::new(0, 1), "B"),
6070 (Point::new(1, 1)..Point::new(1, 1), "B"),
6071 ],
6072 None,
6073 cx,
6074 );
6075 multibuffer.end_transaction_at(now, cx);
6076 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6077
6078 // Verify edited ranges for transaction 1
6079 assert_eq!(
6080 multibuffer.edited_ranges_for_transaction(transaction_1, cx),
6081 &[
6082 Point::new(0, 0)..Point::new(0, 2),
6083 Point::new(1, 0)..Point::new(1, 2)
6084 ]
6085 );
6086
6087 // Edit buffer 1 through the multibuffer
6088 now += 2 * group_interval;
6089 multibuffer.start_transaction_at(now, cx);
6090 multibuffer.edit([(2..2, "C")], None, cx);
6091 multibuffer.end_transaction_at(now, cx);
6092 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
6093
6094 // Edit buffer 1 independently
6095 buffer_1.update(cx, |buffer_1, cx| {
6096 buffer_1.start_transaction_at(now);
6097 buffer_1.edit([(3..3, "D")], None, cx);
6098 buffer_1.end_transaction_at(now, cx);
6099
6100 now += 2 * group_interval;
6101 buffer_1.start_transaction_at(now);
6102 buffer_1.edit([(4..4, "E")], None, cx);
6103 buffer_1.end_transaction_at(now, cx);
6104 });
6105 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
6106
6107 // An undo in the multibuffer undoes the multibuffer transaction
6108 // and also any individual buffer edits that have occurred since
6109 // that transaction.
6110 multibuffer.undo(cx);
6111 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6112
6113 multibuffer.undo(cx);
6114 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6115
6116 multibuffer.redo(cx);
6117 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6118
6119 multibuffer.redo(cx);
6120 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
6121
6122 // Undo buffer 2 independently.
6123 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
6124 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
6125
6126 // An undo in the multibuffer undoes the components of the
6127 // the last multibuffer transaction that are not already undone.
6128 multibuffer.undo(cx);
6129 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
6130
6131 multibuffer.undo(cx);
6132 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6133
6134 multibuffer.redo(cx);
6135 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6136
6137 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
6138 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
6139
6140 // Redo stack gets cleared after an edit.
6141 now += 2 * group_interval;
6142 multibuffer.start_transaction_at(now, cx);
6143 multibuffer.edit([(0..0, "X")], None, cx);
6144 multibuffer.end_transaction_at(now, cx);
6145 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6146 multibuffer.redo(cx);
6147 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6148 multibuffer.undo(cx);
6149 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
6150 multibuffer.undo(cx);
6151 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6152
6153 // Transactions can be grouped manually.
6154 multibuffer.redo(cx);
6155 multibuffer.redo(cx);
6156 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6157 multibuffer.group_until_transaction(transaction_1, cx);
6158 multibuffer.undo(cx);
6159 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6160 multibuffer.redo(cx);
6161 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6162 });
6163 }
6164
6165 #[gpui::test]
6166 fn test_excerpts_in_ranges_no_ranges(cx: &mut AppContext) {
6167 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6168 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6169 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6170 multibuffer.update(cx, |multibuffer, cx| {
6171 multibuffer.push_excerpts(
6172 buffer_1.clone(),
6173 [ExcerptRange {
6174 context: 0..buffer_1.read(cx).len(),
6175 primary: None,
6176 }],
6177 cx,
6178 );
6179 multibuffer.push_excerpts(
6180 buffer_2.clone(),
6181 [ExcerptRange {
6182 context: 0..buffer_2.read(cx).len(),
6183 primary: None,
6184 }],
6185 cx,
6186 );
6187 });
6188
6189 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
6190
6191 let mut excerpts = snapshot.excerpts_in_ranges(iter::from_fn(|| None));
6192
6193 assert!(excerpts.next().is_none());
6194 }
6195
6196 fn validate_excerpts(
6197 actual: &Vec<(ExcerptId, BufferId, Range<Anchor>)>,
6198 expected: &Vec<(ExcerptId, BufferId, Range<Anchor>)>,
6199 ) {
6200 assert_eq!(actual.len(), expected.len());
6201
6202 actual
6203 .into_iter()
6204 .zip(expected)
6205 .map(|(actual, expected)| {
6206 assert_eq!(actual.0, expected.0);
6207 assert_eq!(actual.1, expected.1);
6208 assert_eq!(actual.2.start, expected.2.start);
6209 assert_eq!(actual.2.end, expected.2.end);
6210 })
6211 .collect_vec();
6212 }
6213
6214 fn map_range_from_excerpt(
6215 snapshot: &MultiBufferSnapshot,
6216 excerpt_id: ExcerptId,
6217 excerpt_buffer: &BufferSnapshot,
6218 range: Range<usize>,
6219 ) -> Range<Anchor> {
6220 snapshot
6221 .anchor_in_excerpt(excerpt_id, excerpt_buffer.anchor_before(range.start))
6222 .unwrap()
6223 ..snapshot
6224 .anchor_in_excerpt(excerpt_id, excerpt_buffer.anchor_after(range.end))
6225 .unwrap()
6226 }
6227
6228 fn make_expected_excerpt_info(
6229 snapshot: &MultiBufferSnapshot,
6230 cx: &mut AppContext,
6231 excerpt_id: ExcerptId,
6232 buffer: &Model<Buffer>,
6233 range: Range<usize>,
6234 ) -> (ExcerptId, BufferId, Range<Anchor>) {
6235 (
6236 excerpt_id,
6237 buffer.read(cx).remote_id(),
6238 map_range_from_excerpt(&snapshot, excerpt_id, &buffer.read(cx).snapshot(), range),
6239 )
6240 }
6241
6242 #[gpui::test]
6243 fn test_excerpts_in_ranges_range_inside_the_excerpt(cx: &mut AppContext) {
6244 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6245 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6246 let buffer_len = buffer_1.read(cx).len();
6247 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6248 let mut expected_excerpt_id = ExcerptId(0);
6249
6250 multibuffer.update(cx, |multibuffer, cx| {
6251 expected_excerpt_id = multibuffer.push_excerpts(
6252 buffer_1.clone(),
6253 [ExcerptRange {
6254 context: 0..buffer_1.read(cx).len(),
6255 primary: None,
6256 }],
6257 cx,
6258 )[0];
6259 multibuffer.push_excerpts(
6260 buffer_2.clone(),
6261 [ExcerptRange {
6262 context: 0..buffer_2.read(cx).len(),
6263 primary: None,
6264 }],
6265 cx,
6266 );
6267 });
6268
6269 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
6270
6271 let range = snapshot
6272 .anchor_in_excerpt(expected_excerpt_id, buffer_1.read(cx).anchor_before(1))
6273 .unwrap()
6274 ..snapshot
6275 .anchor_in_excerpt(
6276 expected_excerpt_id,
6277 buffer_1.read(cx).anchor_after(buffer_len / 2),
6278 )
6279 .unwrap();
6280
6281 let expected_excerpts = vec![make_expected_excerpt_info(
6282 &snapshot,
6283 cx,
6284 expected_excerpt_id,
6285 &buffer_1,
6286 1..(buffer_len / 2),
6287 )];
6288
6289 let excerpts = snapshot
6290 .excerpts_in_ranges(vec![range.clone()].into_iter())
6291 .map(|(excerpt_id, buffer, actual_range)| {
6292 (
6293 excerpt_id,
6294 buffer.remote_id(),
6295 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6296 )
6297 })
6298 .collect_vec();
6299
6300 validate_excerpts(&excerpts, &expected_excerpts);
6301 }
6302
6303 #[gpui::test]
6304 fn test_excerpts_in_ranges_range_crosses_excerpts_boundary(cx: &mut AppContext) {
6305 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6306 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6307 let buffer_len = buffer_1.read(cx).len();
6308 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6309 let mut excerpt_1_id = ExcerptId(0);
6310 let mut excerpt_2_id = ExcerptId(0);
6311
6312 multibuffer.update(cx, |multibuffer, cx| {
6313 excerpt_1_id = multibuffer.push_excerpts(
6314 buffer_1.clone(),
6315 [ExcerptRange {
6316 context: 0..buffer_1.read(cx).len(),
6317 primary: None,
6318 }],
6319 cx,
6320 )[0];
6321 excerpt_2_id = multibuffer.push_excerpts(
6322 buffer_2.clone(),
6323 [ExcerptRange {
6324 context: 0..buffer_2.read(cx).len(),
6325 primary: None,
6326 }],
6327 cx,
6328 )[0];
6329 });
6330
6331 let snapshot = multibuffer.read(cx).snapshot(cx);
6332
6333 let expected_range = snapshot
6334 .anchor_in_excerpt(
6335 excerpt_1_id,
6336 buffer_1.read(cx).anchor_before(buffer_len / 2),
6337 )
6338 .unwrap()
6339 ..snapshot
6340 .anchor_in_excerpt(excerpt_2_id, buffer_2.read(cx).anchor_after(buffer_len / 2))
6341 .unwrap();
6342
6343 let expected_excerpts = vec![
6344 make_expected_excerpt_info(
6345 &snapshot,
6346 cx,
6347 excerpt_1_id,
6348 &buffer_1,
6349 (buffer_len / 2)..buffer_len,
6350 ),
6351 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, 0..buffer_len / 2),
6352 ];
6353
6354 let excerpts = snapshot
6355 .excerpts_in_ranges(vec![expected_range.clone()].into_iter())
6356 .map(|(excerpt_id, buffer, actual_range)| {
6357 (
6358 excerpt_id,
6359 buffer.remote_id(),
6360 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6361 )
6362 })
6363 .collect_vec();
6364
6365 validate_excerpts(&excerpts, &expected_excerpts);
6366 }
6367
6368 #[gpui::test]
6369 fn test_excerpts_in_ranges_range_encloses_excerpt(cx: &mut AppContext) {
6370 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6371 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6372 let buffer_3 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'r'), cx));
6373 let buffer_len = buffer_1.read(cx).len();
6374 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6375 let mut excerpt_1_id = ExcerptId(0);
6376 let mut excerpt_2_id = ExcerptId(0);
6377 let mut excerpt_3_id = ExcerptId(0);
6378
6379 multibuffer.update(cx, |multibuffer, cx| {
6380 excerpt_1_id = multibuffer.push_excerpts(
6381 buffer_1.clone(),
6382 [ExcerptRange {
6383 context: 0..buffer_1.read(cx).len(),
6384 primary: None,
6385 }],
6386 cx,
6387 )[0];
6388 excerpt_2_id = multibuffer.push_excerpts(
6389 buffer_2.clone(),
6390 [ExcerptRange {
6391 context: 0..buffer_2.read(cx).len(),
6392 primary: None,
6393 }],
6394 cx,
6395 )[0];
6396 excerpt_3_id = multibuffer.push_excerpts(
6397 buffer_3.clone(),
6398 [ExcerptRange {
6399 context: 0..buffer_3.read(cx).len(),
6400 primary: None,
6401 }],
6402 cx,
6403 )[0];
6404 });
6405
6406 let snapshot = multibuffer.read(cx).snapshot(cx);
6407
6408 let expected_range = snapshot
6409 .anchor_in_excerpt(
6410 excerpt_1_id,
6411 buffer_1.read(cx).anchor_before(buffer_len / 2),
6412 )
6413 .unwrap()
6414 ..snapshot
6415 .anchor_in_excerpt(excerpt_3_id, buffer_3.read(cx).anchor_after(buffer_len / 2))
6416 .unwrap();
6417
6418 let expected_excerpts = vec![
6419 make_expected_excerpt_info(
6420 &snapshot,
6421 cx,
6422 excerpt_1_id,
6423 &buffer_1,
6424 (buffer_len / 2)..buffer_len,
6425 ),
6426 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, 0..buffer_len),
6427 make_expected_excerpt_info(&snapshot, cx, excerpt_3_id, &buffer_3, 0..buffer_len / 2),
6428 ];
6429
6430 let excerpts = snapshot
6431 .excerpts_in_ranges(vec![expected_range.clone()].into_iter())
6432 .map(|(excerpt_id, buffer, actual_range)| {
6433 (
6434 excerpt_id,
6435 buffer.remote_id(),
6436 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6437 )
6438 })
6439 .collect_vec();
6440
6441 validate_excerpts(&excerpts, &expected_excerpts);
6442 }
6443
6444 #[gpui::test]
6445 fn test_excerpts_in_ranges_multiple_ranges(cx: &mut AppContext) {
6446 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6447 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6448 let buffer_len = buffer_1.read(cx).len();
6449 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6450 let mut excerpt_1_id = ExcerptId(0);
6451 let mut excerpt_2_id = ExcerptId(0);
6452
6453 multibuffer.update(cx, |multibuffer, cx| {
6454 excerpt_1_id = multibuffer.push_excerpts(
6455 buffer_1.clone(),
6456 [ExcerptRange {
6457 context: 0..buffer_1.read(cx).len(),
6458 primary: None,
6459 }],
6460 cx,
6461 )[0];
6462 excerpt_2_id = multibuffer.push_excerpts(
6463 buffer_2.clone(),
6464 [ExcerptRange {
6465 context: 0..buffer_2.read(cx).len(),
6466 primary: None,
6467 }],
6468 cx,
6469 )[0];
6470 });
6471
6472 let snapshot = multibuffer.read(cx).snapshot(cx);
6473
6474 let ranges = vec![
6475 1..(buffer_len / 4),
6476 (buffer_len / 3)..(buffer_len / 2),
6477 (buffer_len / 4 * 3)..(buffer_len),
6478 ];
6479
6480 let expected_excerpts = ranges
6481 .iter()
6482 .map(|range| {
6483 make_expected_excerpt_info(&snapshot, cx, excerpt_1_id, &buffer_1, range.clone())
6484 })
6485 .collect_vec();
6486
6487 let ranges = ranges.into_iter().map(|range| {
6488 map_range_from_excerpt(
6489 &snapshot,
6490 excerpt_1_id,
6491 &buffer_1.read(cx).snapshot(),
6492 range,
6493 )
6494 });
6495
6496 let excerpts = snapshot
6497 .excerpts_in_ranges(ranges)
6498 .map(|(excerpt_id, buffer, actual_range)| {
6499 (
6500 excerpt_id,
6501 buffer.remote_id(),
6502 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6503 )
6504 })
6505 .collect_vec();
6506
6507 validate_excerpts(&excerpts, &expected_excerpts);
6508 }
6509
6510 #[gpui::test]
6511 fn test_excerpts_in_ranges_range_ends_at_excerpt_end(cx: &mut AppContext) {
6512 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6513 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6514 let buffer_len = buffer_1.read(cx).len();
6515 let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
6516 let mut excerpt_1_id = ExcerptId(0);
6517 let mut excerpt_2_id = ExcerptId(0);
6518
6519 multibuffer.update(cx, |multibuffer, cx| {
6520 excerpt_1_id = multibuffer.push_excerpts(
6521 buffer_1.clone(),
6522 [ExcerptRange {
6523 context: 0..buffer_1.read(cx).len(),
6524 primary: None,
6525 }],
6526 cx,
6527 )[0];
6528 excerpt_2_id = multibuffer.push_excerpts(
6529 buffer_2.clone(),
6530 [ExcerptRange {
6531 context: 0..buffer_2.read(cx).len(),
6532 primary: None,
6533 }],
6534 cx,
6535 )[0];
6536 });
6537
6538 let snapshot = multibuffer.read(cx).snapshot(cx);
6539
6540 let ranges = [0..buffer_len, (buffer_len / 3)..(buffer_len / 2)];
6541
6542 let expected_excerpts = vec![
6543 make_expected_excerpt_info(&snapshot, cx, excerpt_1_id, &buffer_1, ranges[0].clone()),
6544 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, ranges[1].clone()),
6545 ];
6546
6547 let ranges = [
6548 map_range_from_excerpt(
6549 &snapshot,
6550 excerpt_1_id,
6551 &buffer_1.read(cx).snapshot(),
6552 ranges[0].clone(),
6553 ),
6554 map_range_from_excerpt(
6555 &snapshot,
6556 excerpt_2_id,
6557 &buffer_2.read(cx).snapshot(),
6558 ranges[1].clone(),
6559 ),
6560 ];
6561
6562 let excerpts = snapshot
6563 .excerpts_in_ranges(ranges.into_iter())
6564 .map(|(excerpt_id, buffer, actual_range)| {
6565 (
6566 excerpt_id,
6567 buffer.remote_id(),
6568 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6569 )
6570 })
6571 .collect_vec();
6572
6573 validate_excerpts(&excerpts, &expected_excerpts);
6574 }
6575}