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