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