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