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