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