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