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