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 prev_non_blank_row(&self, mut row: MultiBufferRow) -> Option<MultiBufferRow> {
2866 while row.0 > 0 {
2867 row.0 -= 1;
2868 if !self.is_line_blank(row) {
2869 return Some(row);
2870 }
2871 }
2872 None
2873 }
2874
2875 pub fn line_len(&self, row: MultiBufferRow) -> u32 {
2876 if let Some((_, range)) = self.buffer_line_for_row(row) {
2877 range.end.column - range.start.column
2878 } else {
2879 0
2880 }
2881 }
2882
2883 pub fn buffer_line_for_row(
2884 &self,
2885 row: MultiBufferRow,
2886 ) -> Option<(&BufferSnapshot, Range<Point>)> {
2887 let mut cursor = self.excerpts.cursor::<Point>(&());
2888 let point = Point::new(row.0, 0);
2889 cursor.seek(&point, Bias::Right, &());
2890 if cursor.item().is_none() && *cursor.start() == point {
2891 cursor.prev(&());
2892 }
2893 if let Some(excerpt) = cursor.item() {
2894 let overshoot = row.0 - cursor.start().row;
2895 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2896 let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2897 let buffer_row = excerpt_start.row + overshoot;
2898 let line_start = Point::new(buffer_row, 0);
2899 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2900 return Some((
2901 &excerpt.buffer,
2902 line_start.max(excerpt_start)..line_end.min(excerpt_end),
2903 ));
2904 }
2905 None
2906 }
2907
2908 pub fn max_point(&self) -> Point {
2909 self.text_summary().lines
2910 }
2911
2912 pub fn text_summary(&self) -> TextSummary {
2913 self.excerpts.summary().text.clone()
2914 }
2915
2916 pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2917 where
2918 D: TextDimension,
2919 O: ToOffset,
2920 {
2921 let mut summary = D::zero(&());
2922 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2923 let mut cursor = self.excerpts.cursor::<usize>(&());
2924 cursor.seek(&range.start, Bias::Right, &());
2925 if let Some(excerpt) = cursor.item() {
2926 let mut end_before_newline = cursor.end(&());
2927 if excerpt.has_trailing_newline {
2928 end_before_newline -= 1;
2929 }
2930
2931 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2932 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2933 let end_in_excerpt =
2934 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2935 summary.add_assign(
2936 &excerpt
2937 .buffer
2938 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2939 );
2940
2941 if range.end > end_before_newline {
2942 summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2943 }
2944
2945 cursor.next(&());
2946 }
2947
2948 if range.end > *cursor.start() {
2949 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2950 &range.end,
2951 Bias::Right,
2952 &(),
2953 )));
2954 if let Some(excerpt) = cursor.item() {
2955 range.end = cmp::max(*cursor.start(), range.end);
2956
2957 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2958 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2959 summary.add_assign(
2960 &excerpt
2961 .buffer
2962 .text_summary_for_range(excerpt_start..end_in_excerpt),
2963 );
2964 }
2965 }
2966
2967 summary
2968 }
2969
2970 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2971 where
2972 D: TextDimension + Ord + Sub<D, Output = D>,
2973 {
2974 let mut cursor = self.excerpts.cursor::<ExcerptSummary>(&());
2975 let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2976
2977 cursor.seek(locator, Bias::Left, &());
2978 if cursor.item().is_none() {
2979 cursor.next(&());
2980 }
2981
2982 let mut position = D::from_text_summary(&cursor.start().text);
2983 if let Some(excerpt) = cursor.item() {
2984 if excerpt.id == anchor.excerpt_id {
2985 let excerpt_buffer_start =
2986 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2987 let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2988 let buffer_position = cmp::min(
2989 excerpt_buffer_end,
2990 anchor.text_anchor.summary::<D>(&excerpt.buffer),
2991 );
2992 if buffer_position > excerpt_buffer_start {
2993 position.add_assign(&(buffer_position - excerpt_buffer_start));
2994 }
2995 }
2996 }
2997 position
2998 }
2999
3000 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
3001 where
3002 D: TextDimension + Ord + Sub<D, Output = D>,
3003 I: 'a + IntoIterator<Item = &'a Anchor>,
3004 {
3005 if let Some((_, _, buffer)) = self.as_singleton() {
3006 return buffer
3007 .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
3008 .collect();
3009 }
3010
3011 let mut anchors = anchors.into_iter().peekable();
3012 let mut cursor = self.excerpts.cursor::<ExcerptSummary>(&());
3013 let mut summaries = Vec::new();
3014 while let Some(anchor) = anchors.peek() {
3015 let excerpt_id = anchor.excerpt_id;
3016 let excerpt_anchors = iter::from_fn(|| {
3017 let anchor = anchors.peek()?;
3018 if anchor.excerpt_id == excerpt_id {
3019 Some(&anchors.next().unwrap().text_anchor)
3020 } else {
3021 None
3022 }
3023 });
3024
3025 let locator = self.excerpt_locator_for_id(excerpt_id);
3026 cursor.seek_forward(locator, Bias::Left, &());
3027 if cursor.item().is_none() {
3028 cursor.next(&());
3029 }
3030
3031 let position = D::from_text_summary(&cursor.start().text);
3032 if let Some(excerpt) = cursor.item() {
3033 if excerpt.id == excerpt_id {
3034 let excerpt_buffer_start =
3035 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
3036 let excerpt_buffer_end =
3037 excerpt.range.context.end.summary::<D>(&excerpt.buffer);
3038 summaries.extend(
3039 excerpt
3040 .buffer
3041 .summaries_for_anchors::<D, _>(excerpt_anchors)
3042 .map(move |summary| {
3043 let summary = cmp::min(excerpt_buffer_end.clone(), summary);
3044 let mut position = position.clone();
3045 let excerpt_buffer_start = excerpt_buffer_start.clone();
3046 if summary > excerpt_buffer_start {
3047 position.add_assign(&(summary - excerpt_buffer_start));
3048 }
3049 position
3050 }),
3051 );
3052 continue;
3053 }
3054 }
3055
3056 summaries.extend(excerpt_anchors.map(|_| position.clone()));
3057 }
3058
3059 summaries
3060 }
3061
3062 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
3063 where
3064 I: 'a + IntoIterator<Item = &'a Anchor>,
3065 {
3066 let mut anchors = anchors.into_iter().enumerate().peekable();
3067 let mut cursor = self.excerpts.cursor::<Option<&Locator>>(&());
3068 cursor.next(&());
3069
3070 let mut result = Vec::new();
3071
3072 while let Some((_, anchor)) = anchors.peek() {
3073 let old_excerpt_id = anchor.excerpt_id;
3074
3075 // Find the location where this anchor's excerpt should be.
3076 let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
3077 cursor.seek_forward(&Some(old_locator), Bias::Left, &());
3078
3079 if cursor.item().is_none() {
3080 cursor.next(&());
3081 }
3082
3083 let next_excerpt = cursor.item();
3084 let prev_excerpt = cursor.prev_item();
3085
3086 // Process all of the anchors for this excerpt.
3087 while let Some((_, anchor)) = anchors.peek() {
3088 if anchor.excerpt_id != old_excerpt_id {
3089 break;
3090 }
3091 let (anchor_ix, anchor) = anchors.next().unwrap();
3092 let mut anchor = *anchor;
3093
3094 // Leave min and max anchors unchanged if invalid or
3095 // if the old excerpt still exists at this location
3096 let mut kept_position = next_excerpt
3097 .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
3098 || old_excerpt_id == ExcerptId::max()
3099 || old_excerpt_id == ExcerptId::min();
3100
3101 // If the old excerpt no longer exists at this location, then attempt to
3102 // find an equivalent position for this anchor in an adjacent excerpt.
3103 if !kept_position {
3104 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
3105 if excerpt.contains(&anchor) {
3106 anchor.excerpt_id = excerpt.id;
3107 kept_position = true;
3108 break;
3109 }
3110 }
3111 }
3112
3113 // If there's no adjacent excerpt that contains the anchor's position,
3114 // then report that the anchor has lost its position.
3115 if !kept_position {
3116 anchor = if let Some(excerpt) = next_excerpt {
3117 let mut text_anchor = excerpt
3118 .range
3119 .context
3120 .start
3121 .bias(anchor.text_anchor.bias, &excerpt.buffer);
3122 if text_anchor
3123 .cmp(&excerpt.range.context.end, &excerpt.buffer)
3124 .is_gt()
3125 {
3126 text_anchor = excerpt.range.context.end;
3127 }
3128 Anchor {
3129 buffer_id: Some(excerpt.buffer_id),
3130 excerpt_id: excerpt.id,
3131 text_anchor,
3132 }
3133 } else if let Some(excerpt) = prev_excerpt {
3134 let mut text_anchor = excerpt
3135 .range
3136 .context
3137 .end
3138 .bias(anchor.text_anchor.bias, &excerpt.buffer);
3139 if text_anchor
3140 .cmp(&excerpt.range.context.start, &excerpt.buffer)
3141 .is_lt()
3142 {
3143 text_anchor = excerpt.range.context.start;
3144 }
3145 Anchor {
3146 buffer_id: Some(excerpt.buffer_id),
3147 excerpt_id: excerpt.id,
3148 text_anchor,
3149 }
3150 } else if anchor.text_anchor.bias == Bias::Left {
3151 Anchor::min()
3152 } else {
3153 Anchor::max()
3154 };
3155 }
3156
3157 result.push((anchor_ix, anchor, kept_position));
3158 }
3159 }
3160 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
3161 result
3162 }
3163
3164 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
3165 self.anchor_at(position, Bias::Left)
3166 }
3167
3168 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
3169 self.anchor_at(position, Bias::Right)
3170 }
3171
3172 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
3173 let offset = position.to_offset(self);
3174 if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
3175 return Anchor {
3176 buffer_id: Some(buffer_id),
3177 excerpt_id: *excerpt_id,
3178 text_anchor: buffer.anchor_at(offset, bias),
3179 };
3180 }
3181
3182 let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>(&());
3183 cursor.seek(&offset, Bias::Right, &());
3184 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
3185 cursor.prev(&());
3186 }
3187 if let Some(excerpt) = cursor.item() {
3188 let mut overshoot = offset.saturating_sub(cursor.start().0);
3189 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
3190 overshoot -= 1;
3191 bias = Bias::Right;
3192 }
3193
3194 let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3195 let text_anchor =
3196 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
3197 Anchor {
3198 buffer_id: Some(excerpt.buffer_id),
3199 excerpt_id: excerpt.id,
3200 text_anchor,
3201 }
3202 } else if offset == 0 && bias == Bias::Left {
3203 Anchor::min()
3204 } else {
3205 Anchor::max()
3206 }
3207 }
3208
3209 /// Returns an anchor for the given excerpt and text anchor,
3210 /// returns None if the excerpt_id is no longer valid.
3211 pub fn anchor_in_excerpt(
3212 &self,
3213 excerpt_id: ExcerptId,
3214 text_anchor: text::Anchor,
3215 ) -> Option<Anchor> {
3216 let locator = self.excerpt_locator_for_id(excerpt_id);
3217 let mut cursor = self.excerpts.cursor::<Option<&Locator>>(&());
3218 cursor.seek(locator, Bias::Left, &());
3219 if let Some(excerpt) = cursor.item() {
3220 if excerpt.id == excerpt_id {
3221 let text_anchor = excerpt.clip_anchor(text_anchor);
3222 drop(cursor);
3223 return Some(Anchor {
3224 buffer_id: Some(excerpt.buffer_id),
3225 excerpt_id,
3226 text_anchor,
3227 });
3228 }
3229 }
3230 None
3231 }
3232
3233 pub fn context_range_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<Range<text::Anchor>> {
3234 Some(self.excerpt(excerpt_id)?.range.context.clone())
3235 }
3236
3237 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
3238 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
3239 true
3240 } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
3241 excerpt.buffer.can_resolve(&anchor.text_anchor)
3242 } else {
3243 false
3244 }
3245 }
3246
3247 pub fn excerpts(
3248 &self,
3249 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
3250 self.excerpts
3251 .iter()
3252 .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
3253 }
3254
3255 fn excerpts_for_range<T: ToOffset>(
3256 &self,
3257 range: Range<T>,
3258 ) -> impl Iterator<Item = (&Excerpt, usize)> + '_ {
3259 let range = range.start.to_offset(self)..range.end.to_offset(self);
3260
3261 let mut cursor = self.excerpts.cursor::<usize>(&());
3262 cursor.seek(&range.start, Bias::Right, &());
3263 cursor.prev(&());
3264
3265 iter::from_fn(move || {
3266 cursor.next(&());
3267 if cursor.start() < &range.end {
3268 cursor.item().map(|item| (item, *cursor.start()))
3269 } else {
3270 None
3271 }
3272 })
3273 }
3274
3275 pub fn excerpt_boundaries_in_range<R, T>(
3276 &self,
3277 range: R,
3278 ) -> impl Iterator<Item = ExcerptBoundary> + '_
3279 where
3280 R: RangeBounds<T>,
3281 T: ToOffset,
3282 {
3283 let start_offset;
3284 let start = match range.start_bound() {
3285 Bound::Included(start) => {
3286 start_offset = start.to_offset(self);
3287 Bound::Included(start_offset)
3288 }
3289 Bound::Excluded(start) => {
3290 start_offset = start.to_offset(self);
3291 Bound::Excluded(start_offset)
3292 }
3293 Bound::Unbounded => {
3294 start_offset = 0;
3295 Bound::Unbounded
3296 }
3297 };
3298 let end = match range.end_bound() {
3299 Bound::Included(end) => Bound::Included(end.to_offset(self)),
3300 Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
3301 Bound::Unbounded => Bound::Unbounded,
3302 };
3303 let bounds = (start, end);
3304
3305 let mut cursor = self.excerpts.cursor::<(usize, Point)>(&());
3306 cursor.seek(&start_offset, Bias::Right, &());
3307 if cursor.item().is_none() {
3308 cursor.prev(&());
3309 }
3310 if !bounds.contains(&cursor.start().0) {
3311 cursor.next(&());
3312 }
3313
3314 let mut visited_end = false;
3315 std::iter::from_fn(move || {
3316 if self.singleton {
3317 None
3318 } else if bounds.contains(&cursor.start().0) {
3319 let next = cursor.item().map(|excerpt| ExcerptInfo {
3320 id: excerpt.id,
3321 buffer: excerpt.buffer.clone(),
3322 buffer_id: excerpt.buffer_id,
3323 range: excerpt.range.clone(),
3324 });
3325
3326 if next.is_none() {
3327 if visited_end {
3328 return None;
3329 } else {
3330 visited_end = true;
3331 }
3332 }
3333
3334 let prev = cursor.prev_item().map(|prev_excerpt| ExcerptInfo {
3335 id: prev_excerpt.id,
3336 buffer: prev_excerpt.buffer.clone(),
3337 buffer_id: prev_excerpt.buffer_id,
3338 range: prev_excerpt.range.clone(),
3339 });
3340 let row = MultiBufferRow(cursor.start().1.row);
3341
3342 cursor.next(&());
3343
3344 Some(ExcerptBoundary { row, prev, next })
3345 } else {
3346 None
3347 }
3348 })
3349 }
3350
3351 pub fn edit_count(&self) -> usize {
3352 self.edit_count
3353 }
3354
3355 pub fn non_text_state_update_count(&self) -> usize {
3356 self.non_text_state_update_count
3357 }
3358
3359 /// Returns the smallest enclosing bracket ranges containing the given range or
3360 /// None if no brackets contain range or the range is not contained in a single
3361 /// excerpt
3362 ///
3363 /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3364 pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3365 &self,
3366 range: Range<T>,
3367 range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3368 ) -> Option<(Range<usize>, Range<usize>)> {
3369 let range = range.start.to_offset(self)..range.end.to_offset(self);
3370 let excerpt = self.excerpt_containing(range.clone())?;
3371
3372 // Filter to ranges contained in the excerpt
3373 let range_filter = |open: Range<usize>, close: Range<usize>| -> bool {
3374 excerpt.contains_buffer_range(open.start..close.end)
3375 && range_filter.map_or(true, |filter| {
3376 filter(
3377 excerpt.map_range_from_buffer(open),
3378 excerpt.map_range_from_buffer(close),
3379 )
3380 })
3381 };
3382
3383 let (open, close) = excerpt.buffer().innermost_enclosing_bracket_ranges(
3384 excerpt.map_range_to_buffer(range),
3385 Some(&range_filter),
3386 )?;
3387
3388 Some((
3389 excerpt.map_range_from_buffer(open),
3390 excerpt.map_range_from_buffer(close),
3391 ))
3392 }
3393
3394 /// Returns enclosing bracket ranges containing the given range or returns None if the range is
3395 /// not contained in a single excerpt
3396 pub fn enclosing_bracket_ranges<T: ToOffset>(
3397 &self,
3398 range: Range<T>,
3399 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
3400 let range = range.start.to_offset(self)..range.end.to_offset(self);
3401 let excerpt = self.excerpt_containing(range.clone())?;
3402
3403 Some(
3404 excerpt
3405 .buffer()
3406 .enclosing_bracket_ranges(excerpt.map_range_to_buffer(range))
3407 .filter_map(move |(open, close)| {
3408 if excerpt.contains_buffer_range(open.start..close.end) {
3409 Some((
3410 excerpt.map_range_from_buffer(open),
3411 excerpt.map_range_from_buffer(close),
3412 ))
3413 } else {
3414 None
3415 }
3416 }),
3417 )
3418 }
3419
3420 /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
3421 /// not contained in a single excerpt
3422 pub fn bracket_ranges<T: ToOffset>(
3423 &self,
3424 range: Range<T>,
3425 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
3426 let range = range.start.to_offset(self)..range.end.to_offset(self);
3427 let excerpt = self.excerpt_containing(range.clone())?;
3428
3429 Some(
3430 excerpt
3431 .buffer()
3432 .bracket_ranges(excerpt.map_range_to_buffer(range))
3433 .filter_map(move |(start_bracket_range, close_bracket_range)| {
3434 let buffer_range = start_bracket_range.start..close_bracket_range.end;
3435 if excerpt.contains_buffer_range(buffer_range) {
3436 Some((
3437 excerpt.map_range_from_buffer(start_bracket_range),
3438 excerpt.map_range_from_buffer(close_bracket_range),
3439 ))
3440 } else {
3441 None
3442 }
3443 }),
3444 )
3445 }
3446
3447 pub fn redacted_ranges<'a, T: ToOffset>(
3448 &'a self,
3449 range: Range<T>,
3450 redaction_enabled: impl Fn(Option<&Arc<dyn File>>) -> bool + 'a,
3451 ) -> impl Iterator<Item = Range<usize>> + 'a {
3452 let range = range.start.to_offset(self)..range.end.to_offset(self);
3453 self.excerpts_for_range(range.clone())
3454 .filter(move |&(excerpt, _)| redaction_enabled(excerpt.buffer.file()))
3455 .flat_map(move |(excerpt, excerpt_offset)| {
3456 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3457
3458 excerpt
3459 .buffer
3460 .redacted_ranges(excerpt.range.context.clone())
3461 .map(move |mut redacted_range| {
3462 // Re-base onto the excerpts coordinates in the multibuffer
3463 redacted_range.start = excerpt_offset
3464 + redacted_range.start.saturating_sub(excerpt_buffer_start);
3465 redacted_range.end = excerpt_offset
3466 + redacted_range.end.saturating_sub(excerpt_buffer_start);
3467
3468 redacted_range
3469 })
3470 .skip_while(move |redacted_range| redacted_range.end < range.start)
3471 .take_while(move |redacted_range| redacted_range.start < range.end)
3472 })
3473 }
3474
3475 pub fn runnable_ranges(
3476 &self,
3477 range: Range<Anchor>,
3478 ) -> impl Iterator<Item = language::RunnableRange> + '_ {
3479 let range = range.start.to_offset(self)..range.end.to_offset(self);
3480 self.excerpts_for_range(range.clone())
3481 .flat_map(move |(excerpt, excerpt_offset)| {
3482 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3483
3484 excerpt
3485 .buffer
3486 .runnable_ranges(excerpt.range.context.clone())
3487 .filter_map(move |mut runnable| {
3488 // Re-base onto the excerpts coordinates in the multibuffer
3489 //
3490 // The node matching our runnables query might partially overlap with
3491 // the provided range. If the run indicator is outside of excerpt bounds, do not actually show it.
3492 if runnable.run_range.start < excerpt_buffer_start {
3493 return None;
3494 }
3495 if language::ToPoint::to_point(&runnable.run_range.end, &excerpt.buffer).row
3496 > excerpt.max_buffer_row
3497 {
3498 return None;
3499 }
3500 runnable.run_range.start =
3501 excerpt_offset + runnable.run_range.start - excerpt_buffer_start;
3502 runnable.run_range.end =
3503 excerpt_offset + runnable.run_range.end - excerpt_buffer_start;
3504 Some(runnable)
3505 })
3506 .skip_while(move |runnable| runnable.run_range.end < range.start)
3507 .take_while(move |runnable| runnable.run_range.start < range.end)
3508 })
3509 }
3510
3511 pub fn indent_guides_in_range(
3512 &self,
3513 range: Range<Anchor>,
3514 ignore_disabled_for_language: bool,
3515 cx: &AppContext,
3516 ) -> Vec<MultiBufferIndentGuide> {
3517 // Fast path for singleton buffers, we can skip the conversion between offsets.
3518 if let Some((_, _, snapshot)) = self.as_singleton() {
3519 return snapshot
3520 .indent_guides_in_range(
3521 range.start.text_anchor..range.end.text_anchor,
3522 ignore_disabled_for_language,
3523 cx,
3524 )
3525 .into_iter()
3526 .map(|guide| MultiBufferIndentGuide {
3527 multibuffer_row_range: MultiBufferRow(guide.start_row)
3528 ..MultiBufferRow(guide.end_row),
3529 buffer: guide,
3530 })
3531 .collect();
3532 }
3533
3534 let range = range.start.to_offset(self)..range.end.to_offset(self);
3535
3536 self.excerpts_for_range(range.clone())
3537 .flat_map(move |(excerpt, excerpt_offset)| {
3538 let excerpt_buffer_start_row =
3539 excerpt.range.context.start.to_point(&excerpt.buffer).row;
3540 let excerpt_offset_row = crate::ToPoint::to_point(&excerpt_offset, self).row;
3541
3542 excerpt
3543 .buffer
3544 .indent_guides_in_range(
3545 excerpt.range.context.clone(),
3546 ignore_disabled_for_language,
3547 cx,
3548 )
3549 .into_iter()
3550 .map(move |indent_guide| {
3551 let start_row = excerpt_offset_row
3552 + (indent_guide.start_row - excerpt_buffer_start_row);
3553 let end_row =
3554 excerpt_offset_row + (indent_guide.end_row - excerpt_buffer_start_row);
3555
3556 MultiBufferIndentGuide {
3557 multibuffer_row_range: MultiBufferRow(start_row)
3558 ..MultiBufferRow(end_row),
3559 buffer: indent_guide,
3560 }
3561 })
3562 })
3563 .collect()
3564 }
3565
3566 pub fn trailing_excerpt_update_count(&self) -> usize {
3567 self.trailing_excerpt_update_count
3568 }
3569
3570 pub fn file_at<T: ToOffset>(&self, point: T) -> Option<&Arc<dyn File>> {
3571 self.point_to_buffer_offset(point)
3572 .and_then(|(buffer, _)| buffer.file())
3573 }
3574
3575 pub fn language_at<T: ToOffset>(&self, point: T) -> Option<&Arc<Language>> {
3576 self.point_to_buffer_offset(point)
3577 .and_then(|(buffer, offset)| buffer.language_at(offset))
3578 }
3579
3580 pub fn settings_at<'a, T: ToOffset>(
3581 &'a self,
3582 point: T,
3583 cx: &'a AppContext,
3584 ) -> Cow<'a, LanguageSettings> {
3585 let mut language = None;
3586 let mut file = None;
3587 if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
3588 language = buffer.language_at(offset);
3589 file = buffer.file();
3590 }
3591 language_settings(language.map(|l| l.name()), file, cx)
3592 }
3593
3594 pub fn language_scope_at<T: ToOffset>(&self, point: T) -> Option<LanguageScope> {
3595 self.point_to_buffer_offset(point)
3596 .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
3597 }
3598
3599 pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
3600 self.point_to_buffer_offset(point)
3601 .map(|(buffer, offset)| buffer.char_classifier_at(offset))
3602 .unwrap_or_default()
3603 }
3604
3605 pub fn language_indent_size_at<T: ToOffset>(
3606 &self,
3607 position: T,
3608 cx: &AppContext,
3609 ) -> Option<IndentSize> {
3610 let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
3611 Some(buffer_snapshot.language_indent_size_at(offset, cx))
3612 }
3613
3614 pub fn is_dirty(&self) -> bool {
3615 self.is_dirty
3616 }
3617
3618 pub fn has_conflict(&self) -> bool {
3619 self.has_conflict
3620 }
3621
3622 pub fn has_diagnostics(&self) -> bool {
3623 self.excerpts
3624 .iter()
3625 .any(|excerpt| excerpt.buffer.has_diagnostics())
3626 }
3627
3628 pub fn diagnostic_group<'a, O>(
3629 &'a self,
3630 group_id: usize,
3631 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3632 where
3633 O: text::FromAnchor + 'a,
3634 {
3635 self.as_singleton()
3636 .into_iter()
3637 .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
3638 }
3639
3640 pub fn diagnostics_in_range<'a, T, O>(
3641 &'a self,
3642 range: Range<T>,
3643 reversed: bool,
3644 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3645 where
3646 T: 'a + ToOffset,
3647 O: 'a + text::FromAnchor + Ord,
3648 {
3649 self.as_singleton()
3650 .into_iter()
3651 .flat_map(move |(_, _, buffer)| {
3652 buffer.diagnostics_in_range(
3653 range.start.to_offset(self)..range.end.to_offset(self),
3654 reversed,
3655 )
3656 })
3657 }
3658
3659 pub fn has_git_diffs(&self) -> bool {
3660 for excerpt in self.excerpts.iter() {
3661 if excerpt.buffer.has_git_diff() {
3662 return true;
3663 }
3664 }
3665 false
3666 }
3667
3668 pub fn git_diff_hunks_in_range_rev(
3669 &self,
3670 row_range: Range<MultiBufferRow>,
3671 ) -> impl Iterator<Item = MultiBufferDiffHunk> + '_ {
3672 let mut cursor = self.excerpts.cursor::<Point>(&());
3673
3674 cursor.seek(&Point::new(row_range.end.0, 0), Bias::Left, &());
3675 if cursor.item().is_none() {
3676 cursor.prev(&());
3677 }
3678
3679 std::iter::from_fn(move || {
3680 let excerpt = cursor.item()?;
3681 let multibuffer_start = *cursor.start();
3682 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3683 if multibuffer_start.row >= row_range.end.0 {
3684 return None;
3685 }
3686
3687 let mut buffer_start = excerpt.range.context.start;
3688 let mut buffer_end = excerpt.range.context.end;
3689 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3690 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3691
3692 if row_range.start.0 > multibuffer_start.row {
3693 let buffer_start_point =
3694 excerpt_start_point + Point::new(row_range.start.0 - multibuffer_start.row, 0);
3695 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3696 }
3697
3698 if row_range.end.0 < multibuffer_end.row {
3699 let buffer_end_point =
3700 excerpt_start_point + Point::new(row_range.end.0 - multibuffer_start.row, 0);
3701 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3702 }
3703
3704 let buffer_hunks = excerpt
3705 .buffer
3706 .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
3707 .map(move |hunk| {
3708 let start = multibuffer_start.row
3709 + hunk.row_range.start.saturating_sub(excerpt_start_point.row);
3710 let end = multibuffer_start.row
3711 + hunk
3712 .row_range
3713 .end
3714 .min(excerpt_end_point.row + 1)
3715 .saturating_sub(excerpt_start_point.row);
3716
3717 MultiBufferDiffHunk {
3718 row_range: MultiBufferRow(start)..MultiBufferRow(end),
3719 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3720 buffer_range: hunk.buffer_range.clone(),
3721 buffer_id: excerpt.buffer_id,
3722 }
3723 });
3724
3725 cursor.prev(&());
3726
3727 Some(buffer_hunks)
3728 })
3729 .flatten()
3730 }
3731
3732 pub fn git_diff_hunks_in_range(
3733 &self,
3734 row_range: Range<MultiBufferRow>,
3735 ) -> impl Iterator<Item = MultiBufferDiffHunk> + '_ {
3736 let mut cursor = self.excerpts.cursor::<Point>(&());
3737
3738 cursor.seek(&Point::new(row_range.start.0, 0), Bias::Left, &());
3739
3740 std::iter::from_fn(move || {
3741 let excerpt = cursor.item()?;
3742 let multibuffer_start = *cursor.start();
3743 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3744 let mut buffer_start = excerpt.range.context.start;
3745 let mut buffer_end = excerpt.range.context.end;
3746
3747 let excerpt_rows = match multibuffer_start.row.cmp(&row_range.end.0) {
3748 cmp::Ordering::Less => {
3749 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3750 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3751
3752 if row_range.start.0 > multibuffer_start.row {
3753 let buffer_start_point = excerpt_start_point
3754 + Point::new(row_range.start.0 - multibuffer_start.row, 0);
3755 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3756 }
3757
3758 if row_range.end.0 < multibuffer_end.row {
3759 let buffer_end_point = excerpt_start_point
3760 + Point::new(row_range.end.0 - multibuffer_start.row, 0);
3761 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3762 }
3763 excerpt_start_point.row..excerpt_end_point.row
3764 }
3765 cmp::Ordering::Equal if row_range.end.0 == 0 => {
3766 buffer_end = buffer_start;
3767 0..0
3768 }
3769 cmp::Ordering::Greater | cmp::Ordering::Equal => return None,
3770 };
3771
3772 let buffer_hunks = excerpt
3773 .buffer
3774 .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3775 .map(move |hunk| {
3776 let buffer_range = if excerpt_rows.start == 0 && excerpt_rows.end == 0 {
3777 MultiBufferRow(0)..MultiBufferRow(1)
3778 } else {
3779 let start = multibuffer_start.row
3780 + hunk.row_range.start.saturating_sub(excerpt_rows.start);
3781 let end = multibuffer_start.row
3782 + hunk
3783 .row_range
3784 .end
3785 .min(excerpt_rows.end + 1)
3786 .saturating_sub(excerpt_rows.start);
3787 MultiBufferRow(start)..MultiBufferRow(end)
3788 };
3789 MultiBufferDiffHunk {
3790 row_range: buffer_range,
3791 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3792 buffer_range: hunk.buffer_range.clone(),
3793 buffer_id: excerpt.buffer_id,
3794 }
3795 });
3796
3797 cursor.next(&());
3798
3799 Some(buffer_hunks)
3800 })
3801 .flatten()
3802 }
3803
3804 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3805 let range = range.start.to_offset(self)..range.end.to_offset(self);
3806 let excerpt = self.excerpt_containing(range.clone())?;
3807
3808 let ancestor_buffer_range = excerpt
3809 .buffer()
3810 .range_for_syntax_ancestor(excerpt.map_range_to_buffer(range))?;
3811
3812 Some(excerpt.map_range_from_buffer(ancestor_buffer_range))
3813 }
3814
3815 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3816 let (excerpt_id, _, buffer) = self.as_singleton()?;
3817 let outline = buffer.outline(theme)?;
3818 Some(Outline::new(
3819 outline
3820 .items
3821 .into_iter()
3822 .flat_map(|item| {
3823 Some(OutlineItem {
3824 depth: item.depth,
3825 range: self.anchor_in_excerpt(*excerpt_id, item.range.start)?
3826 ..self.anchor_in_excerpt(*excerpt_id, item.range.end)?,
3827 text: item.text,
3828 highlight_ranges: item.highlight_ranges,
3829 name_ranges: item.name_ranges,
3830 body_range: item.body_range.and_then(|body_range| {
3831 Some(
3832 self.anchor_in_excerpt(*excerpt_id, body_range.start)?
3833 ..self.anchor_in_excerpt(*excerpt_id, body_range.end)?,
3834 )
3835 }),
3836 annotation_range: item.annotation_range.and_then(|annotation_range| {
3837 Some(
3838 self.anchor_in_excerpt(*excerpt_id, annotation_range.start)?
3839 ..self.anchor_in_excerpt(*excerpt_id, annotation_range.end)?,
3840 )
3841 }),
3842 })
3843 })
3844 .collect(),
3845 ))
3846 }
3847
3848 pub fn symbols_containing<T: ToOffset>(
3849 &self,
3850 offset: T,
3851 theme: Option<&SyntaxTheme>,
3852 ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
3853 let anchor = self.anchor_before(offset);
3854 let excerpt_id = anchor.excerpt_id;
3855 let excerpt = self.excerpt(excerpt_id)?;
3856 Some((
3857 excerpt.buffer_id,
3858 excerpt
3859 .buffer
3860 .symbols_containing(anchor.text_anchor, theme)
3861 .into_iter()
3862 .flatten()
3863 .flat_map(|item| {
3864 Some(OutlineItem {
3865 depth: item.depth,
3866 range: self.anchor_in_excerpt(excerpt_id, item.range.start)?
3867 ..self.anchor_in_excerpt(excerpt_id, item.range.end)?,
3868 text: item.text,
3869 highlight_ranges: item.highlight_ranges,
3870 name_ranges: item.name_ranges,
3871 body_range: item.body_range.and_then(|body_range| {
3872 Some(
3873 self.anchor_in_excerpt(excerpt_id, body_range.start)?
3874 ..self.anchor_in_excerpt(excerpt_id, body_range.end)?,
3875 )
3876 }),
3877 annotation_range: item.annotation_range.and_then(|body_range| {
3878 Some(
3879 self.anchor_in_excerpt(excerpt_id, body_range.start)?
3880 ..self.anchor_in_excerpt(excerpt_id, body_range.end)?,
3881 )
3882 }),
3883 })
3884 })
3885 .collect(),
3886 ))
3887 }
3888
3889 fn excerpt_locator_for_id(&self, id: ExcerptId) -> &Locator {
3890 if id == ExcerptId::min() {
3891 Locator::min_ref()
3892 } else if id == ExcerptId::max() {
3893 Locator::max_ref()
3894 } else {
3895 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>(&());
3896 cursor.seek(&id, Bias::Left, &());
3897 if let Some(entry) = cursor.item() {
3898 if entry.id == id {
3899 return &entry.locator;
3900 }
3901 }
3902 panic!("invalid excerpt id {:?}", id)
3903 }
3904 }
3905
3906 /// Returns the locators referenced by the given excerpt IDs, sorted by locator.
3907 fn excerpt_locators_for_ids(
3908 &self,
3909 ids: impl IntoIterator<Item = ExcerptId>,
3910 ) -> SmallVec<[Locator; 1]> {
3911 let mut sorted_ids = ids.into_iter().collect::<SmallVec<[_; 1]>>();
3912 sorted_ids.sort_unstable();
3913 let mut locators = SmallVec::new();
3914
3915 while sorted_ids.last() == Some(&ExcerptId::max()) {
3916 sorted_ids.pop();
3917 if let Some(mapping) = self.excerpt_ids.last() {
3918 locators.push(mapping.locator.clone());
3919 }
3920 }
3921
3922 let mut sorted_ids = sorted_ids.into_iter().dedup().peekable();
3923 if sorted_ids.peek() == Some(&ExcerptId::min()) {
3924 sorted_ids.next();
3925 if let Some(mapping) = self.excerpt_ids.first() {
3926 locators.push(mapping.locator.clone());
3927 }
3928 }
3929
3930 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>(&());
3931 for id in sorted_ids {
3932 if cursor.seek_forward(&id, Bias::Left, &()) {
3933 locators.push(cursor.item().unwrap().locator.clone());
3934 } else {
3935 panic!("invalid excerpt id {:?}", id);
3936 }
3937 }
3938
3939 locators.sort_unstable();
3940 locators
3941 }
3942
3943 pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<BufferId> {
3944 Some(self.excerpt(excerpt_id)?.buffer_id)
3945 }
3946
3947 pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3948 Some(&self.excerpt(excerpt_id)?.buffer)
3949 }
3950
3951 pub fn range_for_excerpt<'a, T: sum_tree::Dimension<'a, ExcerptSummary>>(
3952 &'a self,
3953 excerpt_id: ExcerptId,
3954 ) -> Option<Range<T>> {
3955 let mut cursor = self.excerpts.cursor::<(Option<&Locator>, T)>(&());
3956 let locator = self.excerpt_locator_for_id(excerpt_id);
3957 if cursor.seek(&Some(locator), Bias::Left, &()) {
3958 let start = cursor.start().1.clone();
3959 let end = cursor.end(&()).1;
3960 Some(start..end)
3961 } else {
3962 None
3963 }
3964 }
3965
3966 fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
3967 let mut cursor = self.excerpts.cursor::<Option<&Locator>>(&());
3968 let locator = self.excerpt_locator_for_id(excerpt_id);
3969 cursor.seek(&Some(locator), Bias::Left, &());
3970 if let Some(excerpt) = cursor.item() {
3971 if excerpt.id == excerpt_id {
3972 return Some(excerpt);
3973 }
3974 }
3975 None
3976 }
3977
3978 /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3979 pub fn excerpt_containing<T: ToOffset>(&self, range: Range<T>) -> Option<MultiBufferExcerpt> {
3980 let range = range.start.to_offset(self)..range.end.to_offset(self);
3981
3982 let mut cursor = self.excerpts.cursor::<usize>(&());
3983 cursor.seek(&range.start, Bias::Right, &());
3984 let start_excerpt = cursor.item()?;
3985
3986 if range.start == range.end {
3987 return Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()));
3988 }
3989
3990 cursor.seek(&range.end, Bias::Right, &());
3991 let end_excerpt = cursor.item()?;
3992
3993 if start_excerpt.id == end_excerpt.id {
3994 Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()))
3995 } else {
3996 None
3997 }
3998 }
3999
4000 // Takes an iterator over anchor ranges and returns a new iterator over anchor ranges that don't
4001 // span across excerpt boundaries.
4002 pub fn split_ranges<'a, I>(&'a self, ranges: I) -> impl Iterator<Item = Range<Anchor>> + 'a
4003 where
4004 I: IntoIterator<Item = Range<Anchor>> + 'a,
4005 {
4006 let mut ranges = ranges.into_iter().map(|range| range.to_offset(self));
4007 let mut cursor = self.excerpts.cursor::<usize>(&());
4008 cursor.next(&());
4009 let mut current_range = ranges.next();
4010 iter::from_fn(move || {
4011 let range = current_range.clone()?;
4012 if range.start >= cursor.end(&()) {
4013 cursor.seek_forward(&range.start, Bias::Right, &());
4014 if range.start == self.len() {
4015 cursor.prev(&());
4016 }
4017 }
4018
4019 let excerpt = cursor.item()?;
4020 let range_start_in_excerpt = cmp::max(range.start, *cursor.start());
4021 let range_end_in_excerpt = if excerpt.has_trailing_newline {
4022 cmp::min(range.end, cursor.end(&()) - 1)
4023 } else {
4024 cmp::min(range.end, cursor.end(&()))
4025 };
4026 let buffer_range = MultiBufferExcerpt::new(excerpt, *cursor.start())
4027 .map_range_to_buffer(range_start_in_excerpt..range_end_in_excerpt);
4028
4029 let subrange_start_anchor = Anchor {
4030 buffer_id: Some(excerpt.buffer_id),
4031 excerpt_id: excerpt.id,
4032 text_anchor: excerpt.buffer.anchor_before(buffer_range.start),
4033 };
4034 let subrange_end_anchor = Anchor {
4035 buffer_id: Some(excerpt.buffer_id),
4036 excerpt_id: excerpt.id,
4037 text_anchor: excerpt.buffer.anchor_after(buffer_range.end),
4038 };
4039
4040 if range.end > cursor.end(&()) {
4041 cursor.next(&());
4042 } else {
4043 current_range = ranges.next();
4044 }
4045
4046 Some(subrange_start_anchor..subrange_end_anchor)
4047 })
4048 }
4049
4050 /// Returns excerpts overlapping the given ranges. If range spans multiple excerpts returns one range for each excerpt
4051 ///
4052 /// The ranges are specified in the coordinate space of the multibuffer, not the individual excerpted buffers.
4053 /// Each returned excerpt's range is in the coordinate space of its source buffer.
4054 pub fn excerpts_in_ranges(
4055 &self,
4056 ranges: impl IntoIterator<Item = Range<Anchor>>,
4057 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, Range<usize>)> {
4058 let mut ranges = ranges.into_iter().map(|range| range.to_offset(self));
4059 let mut cursor = self.excerpts.cursor::<usize>(&());
4060 cursor.next(&());
4061 let mut current_range = ranges.next();
4062 iter::from_fn(move || {
4063 let range = current_range.clone()?;
4064 if range.start >= cursor.end(&()) {
4065 cursor.seek_forward(&range.start, Bias::Right, &());
4066 if range.start == self.len() {
4067 cursor.prev(&());
4068 }
4069 }
4070
4071 let excerpt = cursor.item()?;
4072 let range_start_in_excerpt = cmp::max(range.start, *cursor.start());
4073 let range_end_in_excerpt = if excerpt.has_trailing_newline {
4074 cmp::min(range.end, cursor.end(&()) - 1)
4075 } else {
4076 cmp::min(range.end, cursor.end(&()))
4077 };
4078 let buffer_range = MultiBufferExcerpt::new(excerpt, *cursor.start())
4079 .map_range_to_buffer(range_start_in_excerpt..range_end_in_excerpt);
4080
4081 if range.end > cursor.end(&()) {
4082 cursor.next(&());
4083 } else {
4084 current_range = ranges.next();
4085 }
4086
4087 Some((excerpt.id, &excerpt.buffer, buffer_range))
4088 })
4089 }
4090
4091 pub fn selections_in_range<'a>(
4092 &'a self,
4093 range: &'a Range<Anchor>,
4094 include_local: bool,
4095 ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
4096 let mut cursor = self.excerpts.cursor::<ExcerptSummary>(&());
4097 let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
4098 let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
4099 cursor.seek(start_locator, Bias::Left, &());
4100 cursor
4101 .take_while(move |excerpt| excerpt.locator <= *end_locator)
4102 .flat_map(move |excerpt| {
4103 let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
4104 if excerpt.id == range.start.excerpt_id {
4105 query_range.start = range.start.text_anchor;
4106 }
4107 if excerpt.id == range.end.excerpt_id {
4108 query_range.end = range.end.text_anchor;
4109 }
4110
4111 excerpt
4112 .buffer
4113 .selections_in_range(query_range, include_local)
4114 .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
4115 selections.map(move |selection| {
4116 let mut start = Anchor {
4117 buffer_id: Some(excerpt.buffer_id),
4118 excerpt_id: excerpt.id,
4119 text_anchor: selection.start,
4120 };
4121 let mut end = Anchor {
4122 buffer_id: Some(excerpt.buffer_id),
4123 excerpt_id: excerpt.id,
4124 text_anchor: selection.end,
4125 };
4126 if range.start.cmp(&start, self).is_gt() {
4127 start = range.start;
4128 }
4129 if range.end.cmp(&end, self).is_lt() {
4130 end = range.end;
4131 }
4132
4133 (
4134 replica_id,
4135 line_mode,
4136 cursor_shape,
4137 Selection {
4138 id: selection.id,
4139 start,
4140 end,
4141 reversed: selection.reversed,
4142 goal: selection.goal,
4143 },
4144 )
4145 })
4146 })
4147 })
4148 }
4149
4150 pub fn show_headers(&self) -> bool {
4151 self.show_headers
4152 }
4153}
4154
4155#[cfg(any(test, feature = "test-support"))]
4156impl MultiBufferSnapshot {
4157 pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
4158 let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
4159 let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
4160 start..end
4161 }
4162}
4163
4164impl History {
4165 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
4166 self.transaction_depth += 1;
4167 if self.transaction_depth == 1 {
4168 let id = self.next_transaction_id.tick();
4169 self.undo_stack.push(Transaction {
4170 id,
4171 buffer_transactions: Default::default(),
4172 first_edit_at: now,
4173 last_edit_at: now,
4174 suppress_grouping: false,
4175 });
4176 Some(id)
4177 } else {
4178 None
4179 }
4180 }
4181
4182 fn end_transaction(
4183 &mut self,
4184 now: Instant,
4185 buffer_transactions: HashMap<BufferId, TransactionId>,
4186 ) -> bool {
4187 assert_ne!(self.transaction_depth, 0);
4188 self.transaction_depth -= 1;
4189 if self.transaction_depth == 0 {
4190 if buffer_transactions.is_empty() {
4191 self.undo_stack.pop();
4192 false
4193 } else {
4194 self.redo_stack.clear();
4195 let transaction = self.undo_stack.last_mut().unwrap();
4196 transaction.last_edit_at = now;
4197 for (buffer_id, transaction_id) in buffer_transactions {
4198 transaction
4199 .buffer_transactions
4200 .entry(buffer_id)
4201 .or_insert(transaction_id);
4202 }
4203 true
4204 }
4205 } else {
4206 false
4207 }
4208 }
4209
4210 fn push_transaction<'a, T>(
4211 &mut self,
4212 buffer_transactions: T,
4213 now: Instant,
4214 cx: &ModelContext<MultiBuffer>,
4215 ) where
4216 T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
4217 {
4218 assert_eq!(self.transaction_depth, 0);
4219 let transaction = Transaction {
4220 id: self.next_transaction_id.tick(),
4221 buffer_transactions: buffer_transactions
4222 .into_iter()
4223 .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
4224 .collect(),
4225 first_edit_at: now,
4226 last_edit_at: now,
4227 suppress_grouping: false,
4228 };
4229 if !transaction.buffer_transactions.is_empty() {
4230 self.undo_stack.push(transaction);
4231 self.redo_stack.clear();
4232 }
4233 }
4234
4235 fn finalize_last_transaction(&mut self) {
4236 if let Some(transaction) = self.undo_stack.last_mut() {
4237 transaction.suppress_grouping = true;
4238 }
4239 }
4240
4241 fn forget(&mut self, transaction_id: TransactionId) -> Option<Transaction> {
4242 if let Some(ix) = self
4243 .undo_stack
4244 .iter()
4245 .rposition(|transaction| transaction.id == transaction_id)
4246 {
4247 Some(self.undo_stack.remove(ix))
4248 } else if let Some(ix) = self
4249 .redo_stack
4250 .iter()
4251 .rposition(|transaction| transaction.id == transaction_id)
4252 {
4253 Some(self.redo_stack.remove(ix))
4254 } else {
4255 None
4256 }
4257 }
4258
4259 fn transaction(&self, transaction_id: TransactionId) -> Option<&Transaction> {
4260 self.undo_stack
4261 .iter()
4262 .find(|transaction| transaction.id == transaction_id)
4263 .or_else(|| {
4264 self.redo_stack
4265 .iter()
4266 .find(|transaction| transaction.id == transaction_id)
4267 })
4268 }
4269
4270 fn transaction_mut(&mut self, transaction_id: TransactionId) -> Option<&mut Transaction> {
4271 self.undo_stack
4272 .iter_mut()
4273 .find(|transaction| transaction.id == transaction_id)
4274 .or_else(|| {
4275 self.redo_stack
4276 .iter_mut()
4277 .find(|transaction| transaction.id == transaction_id)
4278 })
4279 }
4280
4281 fn pop_undo(&mut self) -> Option<&mut Transaction> {
4282 assert_eq!(self.transaction_depth, 0);
4283 if let Some(transaction) = self.undo_stack.pop() {
4284 self.redo_stack.push(transaction);
4285 self.redo_stack.last_mut()
4286 } else {
4287 None
4288 }
4289 }
4290
4291 fn pop_redo(&mut self) -> Option<&mut Transaction> {
4292 assert_eq!(self.transaction_depth, 0);
4293 if let Some(transaction) = self.redo_stack.pop() {
4294 self.undo_stack.push(transaction);
4295 self.undo_stack.last_mut()
4296 } else {
4297 None
4298 }
4299 }
4300
4301 fn remove_from_undo(&mut self, transaction_id: TransactionId) -> Option<&Transaction> {
4302 let ix = self
4303 .undo_stack
4304 .iter()
4305 .rposition(|transaction| transaction.id == transaction_id)?;
4306 let transaction = self.undo_stack.remove(ix);
4307 self.redo_stack.push(transaction);
4308 self.redo_stack.last()
4309 }
4310
4311 fn group(&mut self) -> Option<TransactionId> {
4312 let mut count = 0;
4313 let mut transactions = self.undo_stack.iter();
4314 if let Some(mut transaction) = transactions.next_back() {
4315 while let Some(prev_transaction) = transactions.next_back() {
4316 if !prev_transaction.suppress_grouping
4317 && transaction.first_edit_at - prev_transaction.last_edit_at
4318 <= self.group_interval
4319 {
4320 transaction = prev_transaction;
4321 count += 1;
4322 } else {
4323 break;
4324 }
4325 }
4326 }
4327 self.group_trailing(count)
4328 }
4329
4330 fn group_until(&mut self, transaction_id: TransactionId) {
4331 let mut count = 0;
4332 for transaction in self.undo_stack.iter().rev() {
4333 if transaction.id == transaction_id {
4334 self.group_trailing(count);
4335 break;
4336 } else if transaction.suppress_grouping {
4337 break;
4338 } else {
4339 count += 1;
4340 }
4341 }
4342 }
4343
4344 fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
4345 let new_len = self.undo_stack.len() - n;
4346 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
4347 if let Some(last_transaction) = transactions_to_keep.last_mut() {
4348 if let Some(transaction) = transactions_to_merge.last() {
4349 last_transaction.last_edit_at = transaction.last_edit_at;
4350 }
4351 for to_merge in transactions_to_merge {
4352 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
4353 last_transaction
4354 .buffer_transactions
4355 .entry(*buffer_id)
4356 .or_insert(*transaction_id);
4357 }
4358 }
4359 }
4360
4361 self.undo_stack.truncate(new_len);
4362 self.undo_stack.last().map(|t| t.id)
4363 }
4364}
4365
4366impl Excerpt {
4367 fn new(
4368 id: ExcerptId,
4369 locator: Locator,
4370 buffer_id: BufferId,
4371 buffer: BufferSnapshot,
4372 range: ExcerptRange<text::Anchor>,
4373 has_trailing_newline: bool,
4374 ) -> Self {
4375 Excerpt {
4376 id,
4377 locator,
4378 max_buffer_row: range.context.end.to_point(&buffer).row,
4379 text_summary: buffer
4380 .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
4381 buffer_id,
4382 buffer,
4383 range,
4384 has_trailing_newline,
4385 }
4386 }
4387
4388 fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
4389 let content_start = self.range.context.start.to_offset(&self.buffer);
4390 let chunks_start = content_start + range.start;
4391 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
4392
4393 let footer_height = if self.has_trailing_newline
4394 && range.start <= self.text_summary.len
4395 && range.end > self.text_summary.len
4396 {
4397 1
4398 } else {
4399 0
4400 };
4401
4402 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
4403
4404 ExcerptChunks {
4405 excerpt_id: self.id,
4406 content_chunks,
4407 footer_height,
4408 }
4409 }
4410
4411 fn seek_chunks(&self, excerpt_chunks: &mut ExcerptChunks, range: Range<usize>) {
4412 let content_start = self.range.context.start.to_offset(&self.buffer);
4413 let chunks_start = content_start + range.start;
4414 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
4415 excerpt_chunks.content_chunks.seek(chunks_start..chunks_end);
4416 excerpt_chunks.footer_height = if self.has_trailing_newline
4417 && range.start <= self.text_summary.len
4418 && range.end > self.text_summary.len
4419 {
4420 1
4421 } else {
4422 0
4423 };
4424 }
4425
4426 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
4427 let content_start = self.range.context.start.to_offset(&self.buffer);
4428 let bytes_start = content_start + range.start;
4429 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
4430 let footer_height = if self.has_trailing_newline
4431 && range.start <= self.text_summary.len
4432 && range.end > self.text_summary.len
4433 {
4434 1
4435 } else {
4436 0
4437 };
4438 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
4439
4440 ExcerptBytes {
4441 content_bytes,
4442 padding_height: footer_height,
4443 reversed: false,
4444 }
4445 }
4446
4447 fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
4448 let content_start = self.range.context.start.to_offset(&self.buffer);
4449 let bytes_start = content_start + range.start;
4450 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
4451 let footer_height = if self.has_trailing_newline
4452 && range.start <= self.text_summary.len
4453 && range.end > self.text_summary.len
4454 {
4455 1
4456 } else {
4457 0
4458 };
4459 let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
4460
4461 ExcerptBytes {
4462 content_bytes,
4463 padding_height: footer_height,
4464 reversed: true,
4465 }
4466 }
4467
4468 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
4469 if text_anchor
4470 .cmp(&self.range.context.start, &self.buffer)
4471 .is_lt()
4472 {
4473 self.range.context.start
4474 } else if text_anchor
4475 .cmp(&self.range.context.end, &self.buffer)
4476 .is_gt()
4477 {
4478 self.range.context.end
4479 } else {
4480 text_anchor
4481 }
4482 }
4483
4484 fn contains(&self, anchor: &Anchor) -> bool {
4485 Some(self.buffer_id) == anchor.buffer_id
4486 && self
4487 .range
4488 .context
4489 .start
4490 .cmp(&anchor.text_anchor, &self.buffer)
4491 .is_le()
4492 && self
4493 .range
4494 .context
4495 .end
4496 .cmp(&anchor.text_anchor, &self.buffer)
4497 .is_ge()
4498 }
4499
4500 /// The [`Excerpt`]'s start offset in its [`Buffer`]
4501 fn buffer_start_offset(&self) -> usize {
4502 self.range.context.start.to_offset(&self.buffer)
4503 }
4504
4505 /// The [`Excerpt`]'s end offset in its [`Buffer`]
4506 fn buffer_end_offset(&self) -> usize {
4507 self.buffer_start_offset() + self.text_summary.len
4508 }
4509}
4510
4511impl<'a> MultiBufferExcerpt<'a> {
4512 fn new(excerpt: &'a Excerpt, excerpt_offset: usize) -> Self {
4513 MultiBufferExcerpt {
4514 excerpt,
4515 excerpt_offset,
4516 }
4517 }
4518
4519 pub fn buffer(&self) -> &'a BufferSnapshot {
4520 &self.excerpt.buffer
4521 }
4522
4523 /// Maps an offset within the [`MultiBuffer`] to an offset within the [`Buffer`]
4524 pub fn map_offset_to_buffer(&self, offset: usize) -> usize {
4525 self.excerpt.buffer_start_offset() + offset.saturating_sub(self.excerpt_offset)
4526 }
4527
4528 /// Maps a range within the [`MultiBuffer`] to a range within the [`Buffer`]
4529 pub fn map_range_to_buffer(&self, range: Range<usize>) -> Range<usize> {
4530 self.map_offset_to_buffer(range.start)..self.map_offset_to_buffer(range.end)
4531 }
4532
4533 /// Map an offset within the [`Buffer`] to an offset within the [`MultiBuffer`]
4534 pub fn map_offset_from_buffer(&self, buffer_offset: usize) -> usize {
4535 let mut buffer_offset_in_excerpt =
4536 buffer_offset.saturating_sub(self.excerpt.buffer_start_offset());
4537 buffer_offset_in_excerpt =
4538 cmp::min(buffer_offset_in_excerpt, self.excerpt.text_summary.len);
4539
4540 self.excerpt_offset + buffer_offset_in_excerpt
4541 }
4542
4543 /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
4544 pub fn map_range_from_buffer(&self, buffer_range: Range<usize>) -> Range<usize> {
4545 self.map_offset_from_buffer(buffer_range.start)
4546 ..self.map_offset_from_buffer(buffer_range.end)
4547 }
4548
4549 /// Returns true if the entirety of the given range is in the buffer's excerpt
4550 pub fn contains_buffer_range(&self, range: Range<usize>) -> bool {
4551 range.start >= self.excerpt.buffer_start_offset()
4552 && range.end <= self.excerpt.buffer_end_offset()
4553 }
4554}
4555
4556impl ExcerptId {
4557 pub fn min() -> Self {
4558 Self(0)
4559 }
4560
4561 pub fn max() -> Self {
4562 Self(usize::MAX)
4563 }
4564
4565 pub fn to_proto(&self) -> u64 {
4566 self.0 as _
4567 }
4568
4569 pub fn from_proto(proto: u64) -> Self {
4570 Self(proto as _)
4571 }
4572
4573 pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
4574 let a = snapshot.excerpt_locator_for_id(*self);
4575 let b = snapshot.excerpt_locator_for_id(*other);
4576 a.cmp(b).then_with(|| self.0.cmp(&other.0))
4577 }
4578}
4579
4580impl From<ExcerptId> for usize {
4581 fn from(val: ExcerptId) -> Self {
4582 val.0
4583 }
4584}
4585
4586impl fmt::Debug for Excerpt {
4587 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4588 f.debug_struct("Excerpt")
4589 .field("id", &self.id)
4590 .field("locator", &self.locator)
4591 .field("buffer_id", &self.buffer_id)
4592 .field("range", &self.range)
4593 .field("text_summary", &self.text_summary)
4594 .field("has_trailing_newline", &self.has_trailing_newline)
4595 .finish()
4596 }
4597}
4598
4599impl sum_tree::Item for Excerpt {
4600 type Summary = ExcerptSummary;
4601
4602 fn summary(&self, _cx: &()) -> Self::Summary {
4603 let mut text = self.text_summary.clone();
4604 if self.has_trailing_newline {
4605 text += TextSummary::from("\n");
4606 }
4607 ExcerptSummary {
4608 excerpt_id: self.id,
4609 excerpt_locator: self.locator.clone(),
4610 max_buffer_row: MultiBufferRow(self.max_buffer_row),
4611 text,
4612 }
4613 }
4614}
4615
4616impl sum_tree::Item for ExcerptIdMapping {
4617 type Summary = ExcerptId;
4618
4619 fn summary(&self, _cx: &()) -> Self::Summary {
4620 self.id
4621 }
4622}
4623
4624impl sum_tree::KeyedItem for ExcerptIdMapping {
4625 type Key = ExcerptId;
4626
4627 fn key(&self) -> Self::Key {
4628 self.id
4629 }
4630}
4631
4632impl sum_tree::Summary for ExcerptId {
4633 type Context = ();
4634
4635 fn zero(_cx: &()) -> Self {
4636 Default::default()
4637 }
4638
4639 fn add_summary(&mut self, other: &Self, _: &()) {
4640 *self = *other;
4641 }
4642}
4643
4644impl sum_tree::Summary for ExcerptSummary {
4645 type Context = ();
4646
4647 fn zero(_cx: &()) -> Self {
4648 Default::default()
4649 }
4650
4651 fn add_summary(&mut self, summary: &Self, _: &()) {
4652 debug_assert!(summary.excerpt_locator > self.excerpt_locator);
4653 self.excerpt_locator = summary.excerpt_locator.clone();
4654 self.text.add_summary(&summary.text, &());
4655 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
4656 }
4657}
4658
4659impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
4660 fn zero(_cx: &()) -> Self {
4661 Default::default()
4662 }
4663
4664 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4665 *self += &summary.text;
4666 }
4667}
4668
4669impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
4670 fn zero(_cx: &()) -> Self {
4671 Default::default()
4672 }
4673
4674 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4675 *self += summary.text.len;
4676 }
4677}
4678
4679impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
4680 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4681 Ord::cmp(self, &cursor_location.text.len)
4682 }
4683}
4684
4685impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
4686 fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
4687 Ord::cmp(&Some(self), cursor_location)
4688 }
4689}
4690
4691impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
4692 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4693 Ord::cmp(self, &cursor_location.excerpt_locator)
4694 }
4695}
4696
4697impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
4698 fn zero(_cx: &()) -> Self {
4699 Default::default()
4700 }
4701
4702 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4703 *self += summary.text.len_utf16;
4704 }
4705}
4706
4707impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
4708 fn zero(_cx: &()) -> Self {
4709 Default::default()
4710 }
4711
4712 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4713 *self += summary.text.lines;
4714 }
4715}
4716
4717impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
4718 fn zero(_cx: &()) -> Self {
4719 Default::default()
4720 }
4721
4722 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4723 *self += summary.text.lines_utf16()
4724 }
4725}
4726
4727impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
4728 fn zero(_cx: &()) -> Self {
4729 Default::default()
4730 }
4731
4732 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4733 *self = Some(&summary.excerpt_locator);
4734 }
4735}
4736
4737impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
4738 fn zero(_cx: &()) -> Self {
4739 Default::default()
4740 }
4741
4742 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4743 *self = Some(summary.excerpt_id);
4744 }
4745}
4746
4747impl<'a> MultiBufferRows<'a> {
4748 pub fn seek(&mut self, row: MultiBufferRow) {
4749 self.buffer_row_range = 0..0;
4750
4751 self.excerpts
4752 .seek_forward(&Point::new(row.0, 0), Bias::Right, &());
4753 if self.excerpts.item().is_none() {
4754 self.excerpts.prev(&());
4755
4756 if self.excerpts.item().is_none() && row.0 == 0 {
4757 self.buffer_row_range = 0..1;
4758 return;
4759 }
4760 }
4761
4762 if let Some(excerpt) = self.excerpts.item() {
4763 let overshoot = row.0 - self.excerpts.start().row;
4764 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4765 self.buffer_row_range.start = excerpt_start + overshoot;
4766 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
4767 }
4768 }
4769}
4770
4771impl<'a> Iterator for MultiBufferRows<'a> {
4772 type Item = Option<u32>;
4773
4774 fn next(&mut self) -> Option<Self::Item> {
4775 loop {
4776 if !self.buffer_row_range.is_empty() {
4777 let row = Some(self.buffer_row_range.start);
4778 self.buffer_row_range.start += 1;
4779 return Some(row);
4780 }
4781 self.excerpts.item()?;
4782 self.excerpts.next(&());
4783 let excerpt = self.excerpts.item()?;
4784 self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4785 self.buffer_row_range.end =
4786 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
4787 }
4788 }
4789}
4790
4791impl<'a> MultiBufferChunks<'a> {
4792 pub fn offset(&self) -> usize {
4793 self.range.start
4794 }
4795
4796 pub fn seek(&mut self, new_range: Range<usize>) {
4797 self.range = new_range.clone();
4798 self.excerpts.seek(&new_range.start, Bias::Right, &());
4799 if let Some(excerpt) = self.excerpts.item() {
4800 let excerpt_start = self.excerpts.start();
4801 if let Some(excerpt_chunks) = self
4802 .excerpt_chunks
4803 .as_mut()
4804 .filter(|chunks| excerpt.id == chunks.excerpt_id)
4805 {
4806 excerpt.seek_chunks(
4807 excerpt_chunks,
4808 self.range.start - excerpt_start..self.range.end - excerpt_start,
4809 );
4810 } else {
4811 self.excerpt_chunks = Some(excerpt.chunks_in_range(
4812 self.range.start - excerpt_start..self.range.end - excerpt_start,
4813 self.language_aware,
4814 ));
4815 }
4816 } else {
4817 self.excerpt_chunks = None;
4818 }
4819 }
4820}
4821
4822impl<'a> Iterator for MultiBufferChunks<'a> {
4823 type Item = Chunk<'a>;
4824
4825 fn next(&mut self) -> Option<Self::Item> {
4826 if self.range.is_empty() {
4827 None
4828 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
4829 self.range.start += chunk.text.len();
4830 Some(chunk)
4831 } else {
4832 self.excerpts.next(&());
4833 let excerpt = self.excerpts.item()?;
4834 self.excerpt_chunks = Some(excerpt.chunks_in_range(
4835 0..self.range.end - self.excerpts.start(),
4836 self.language_aware,
4837 ));
4838 self.next()
4839 }
4840 }
4841}
4842
4843impl<'a> MultiBufferBytes<'a> {
4844 fn consume(&mut self, len: usize) {
4845 self.range.start += len;
4846 self.chunk = &self.chunk[len..];
4847
4848 if !self.range.is_empty() && self.chunk.is_empty() {
4849 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4850 self.chunk = chunk;
4851 } else {
4852 self.excerpts.next(&());
4853 if let Some(excerpt) = self.excerpts.item() {
4854 let mut excerpt_bytes =
4855 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
4856 self.chunk = excerpt_bytes.next().unwrap();
4857 self.excerpt_bytes = Some(excerpt_bytes);
4858 }
4859 }
4860 }
4861 }
4862}
4863
4864impl<'a> Iterator for MultiBufferBytes<'a> {
4865 type Item = &'a [u8];
4866
4867 fn next(&mut self) -> Option<Self::Item> {
4868 let chunk = self.chunk;
4869 if chunk.is_empty() {
4870 None
4871 } else {
4872 self.consume(chunk.len());
4873 Some(chunk)
4874 }
4875 }
4876}
4877
4878impl<'a> io::Read for MultiBufferBytes<'a> {
4879 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4880 let len = cmp::min(buf.len(), self.chunk.len());
4881 buf[..len].copy_from_slice(&self.chunk[..len]);
4882 if len > 0 {
4883 self.consume(len);
4884 }
4885 Ok(len)
4886 }
4887}
4888
4889impl<'a> ReversedMultiBufferBytes<'a> {
4890 fn consume(&mut self, len: usize) {
4891 self.range.end -= len;
4892 self.chunk = &self.chunk[..self.chunk.len() - len];
4893
4894 if !self.range.is_empty() && self.chunk.is_empty() {
4895 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4896 self.chunk = chunk;
4897 } else {
4898 self.excerpts.prev(&());
4899 if let Some(excerpt) = self.excerpts.item() {
4900 let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
4901 self.range.start.saturating_sub(*self.excerpts.start())..usize::MAX,
4902 );
4903 self.chunk = excerpt_bytes.next().unwrap();
4904 self.excerpt_bytes = Some(excerpt_bytes);
4905 }
4906 }
4907 }
4908 }
4909}
4910
4911impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
4912 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4913 let len = cmp::min(buf.len(), self.chunk.len());
4914 buf[..len].copy_from_slice(&self.chunk[..len]);
4915 buf[..len].reverse();
4916 if len > 0 {
4917 self.consume(len);
4918 }
4919 Ok(len)
4920 }
4921}
4922impl<'a> Iterator for ExcerptBytes<'a> {
4923 type Item = &'a [u8];
4924
4925 fn next(&mut self) -> Option<Self::Item> {
4926 if self.reversed && self.padding_height > 0 {
4927 let result = &NEWLINES[..self.padding_height];
4928 self.padding_height = 0;
4929 return Some(result);
4930 }
4931
4932 if let Some(chunk) = self.content_bytes.next() {
4933 if !chunk.is_empty() {
4934 return Some(chunk);
4935 }
4936 }
4937
4938 if self.padding_height > 0 {
4939 let result = &NEWLINES[..self.padding_height];
4940 self.padding_height = 0;
4941 return Some(result);
4942 }
4943
4944 None
4945 }
4946}
4947
4948impl<'a> Iterator for ExcerptChunks<'a> {
4949 type Item = Chunk<'a>;
4950
4951 fn next(&mut self) -> Option<Self::Item> {
4952 if let Some(chunk) = self.content_chunks.next() {
4953 return Some(chunk);
4954 }
4955
4956 if self.footer_height > 0 {
4957 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
4958 self.footer_height = 0;
4959 return Some(Chunk {
4960 text,
4961 ..Default::default()
4962 });
4963 }
4964
4965 None
4966 }
4967}
4968
4969impl ToOffset for Point {
4970 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4971 snapshot.point_to_offset(*self)
4972 }
4973}
4974
4975impl ToOffset for usize {
4976 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4977 assert!(*self <= snapshot.len(), "offset is out of range");
4978 *self
4979 }
4980}
4981
4982impl ToOffset for OffsetUtf16 {
4983 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4984 snapshot.offset_utf16_to_offset(*self)
4985 }
4986}
4987
4988impl ToOffset for PointUtf16 {
4989 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4990 snapshot.point_utf16_to_offset(*self)
4991 }
4992}
4993
4994impl ToOffsetUtf16 for OffsetUtf16 {
4995 fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4996 *self
4997 }
4998}
4999
5000impl ToOffsetUtf16 for usize {
5001 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
5002 snapshot.offset_to_offset_utf16(*self)
5003 }
5004}
5005
5006impl ToPoint for usize {
5007 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
5008 snapshot.offset_to_point(*self)
5009 }
5010}
5011
5012impl ToPoint for Point {
5013 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
5014 *self
5015 }
5016}
5017
5018impl ToPointUtf16 for usize {
5019 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
5020 snapshot.offset_to_point_utf16(*self)
5021 }
5022}
5023
5024impl ToPointUtf16 for Point {
5025 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
5026 snapshot.point_to_point_utf16(*self)
5027 }
5028}
5029
5030impl ToPointUtf16 for PointUtf16 {
5031 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
5032 *self
5033 }
5034}
5035
5036pub fn build_excerpt_ranges<T>(
5037 buffer: &BufferSnapshot,
5038 ranges: &[Range<T>],
5039 context_line_count: u32,
5040) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
5041where
5042 T: text::ToPoint,
5043{
5044 let max_point = buffer.max_point();
5045 let mut range_counts = Vec::new();
5046 let mut excerpt_ranges = Vec::new();
5047 let mut range_iter = ranges
5048 .iter()
5049 .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
5050 .peekable();
5051 while let Some(range) = range_iter.next() {
5052 let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
5053 let row = (range.end.row + context_line_count).min(max_point.row);
5054 let mut excerpt_end = Point::new(row, buffer.line_len(row));
5055
5056 let mut ranges_in_excerpt = 1;
5057
5058 while let Some(next_range) = range_iter.peek() {
5059 if next_range.start.row <= excerpt_end.row + context_line_count {
5060 let row = (next_range.end.row + context_line_count).min(max_point.row);
5061 excerpt_end = Point::new(row, buffer.line_len(row));
5062
5063 ranges_in_excerpt += 1;
5064 range_iter.next();
5065 } else {
5066 break;
5067 }
5068 }
5069
5070 excerpt_ranges.push(ExcerptRange {
5071 context: excerpt_start..excerpt_end,
5072 primary: Some(range),
5073 });
5074 range_counts.push(ranges_in_excerpt);
5075 }
5076
5077 (excerpt_ranges, range_counts)
5078}
5079
5080#[cfg(test)]
5081mod tests {
5082 use super::*;
5083 use gpui::{AppContext, Context, TestAppContext};
5084 use language::{Buffer, Rope};
5085 use parking_lot::RwLock;
5086 use rand::prelude::*;
5087 use settings::SettingsStore;
5088 use std::env;
5089 use util::test::sample_text;
5090
5091 #[ctor::ctor]
5092 fn init_logger() {
5093 if std::env::var("RUST_LOG").is_ok() {
5094 env_logger::init();
5095 }
5096 }
5097
5098 #[gpui::test]
5099 fn test_singleton(cx: &mut AppContext) {
5100 let buffer = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
5101 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
5102
5103 let snapshot = multibuffer.read(cx).snapshot(cx);
5104 assert_eq!(snapshot.text(), buffer.read(cx).text());
5105
5106 assert_eq!(
5107 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5108 (0..buffer.read(cx).row_count())
5109 .map(Some)
5110 .collect::<Vec<_>>()
5111 );
5112
5113 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
5114 let snapshot = multibuffer.read(cx).snapshot(cx);
5115
5116 assert_eq!(snapshot.text(), buffer.read(cx).text());
5117 assert_eq!(
5118 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5119 (0..buffer.read(cx).row_count())
5120 .map(Some)
5121 .collect::<Vec<_>>()
5122 );
5123 }
5124
5125 #[gpui::test]
5126 fn test_remote(cx: &mut AppContext) {
5127 let host_buffer = cx.new_model(|cx| Buffer::local("a", cx));
5128 let guest_buffer = cx.new_model(|cx| {
5129 let state = host_buffer.read(cx).to_proto(cx);
5130 let ops = cx
5131 .background_executor()
5132 .block(host_buffer.read(cx).serialize_ops(None, cx));
5133 let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
5134 buffer.apply_ops(
5135 ops.into_iter()
5136 .map(|op| language::proto::deserialize_operation(op).unwrap()),
5137 cx,
5138 );
5139 buffer
5140 });
5141 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
5142 let snapshot = multibuffer.read(cx).snapshot(cx);
5143 assert_eq!(snapshot.text(), "a");
5144
5145 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
5146 let snapshot = multibuffer.read(cx).snapshot(cx);
5147 assert_eq!(snapshot.text(), "ab");
5148
5149 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
5150 let snapshot = multibuffer.read(cx).snapshot(cx);
5151 assert_eq!(snapshot.text(), "abc");
5152 }
5153
5154 #[gpui::test]
5155 fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
5156 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
5157 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
5158 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5159
5160 let events = Arc::new(RwLock::new(Vec::<Event>::new()));
5161 multibuffer.update(cx, |_, cx| {
5162 let events = events.clone();
5163 cx.subscribe(&multibuffer, move |_, _, event, _| {
5164 if let Event::Edited { .. } = event {
5165 events.write().push(event.clone())
5166 }
5167 })
5168 .detach();
5169 });
5170
5171 let subscription = multibuffer.update(cx, |multibuffer, cx| {
5172 let subscription = multibuffer.subscribe();
5173 multibuffer.push_excerpts(
5174 buffer_1.clone(),
5175 [ExcerptRange {
5176 context: Point::new(1, 2)..Point::new(2, 5),
5177 primary: None,
5178 }],
5179 cx,
5180 );
5181 assert_eq!(
5182 subscription.consume().into_inner(),
5183 [Edit {
5184 old: 0..0,
5185 new: 0..10
5186 }]
5187 );
5188
5189 multibuffer.push_excerpts(
5190 buffer_1.clone(),
5191 [ExcerptRange {
5192 context: Point::new(3, 3)..Point::new(4, 4),
5193 primary: None,
5194 }],
5195 cx,
5196 );
5197 multibuffer.push_excerpts(
5198 buffer_2.clone(),
5199 [ExcerptRange {
5200 context: Point::new(3, 1)..Point::new(3, 3),
5201 primary: None,
5202 }],
5203 cx,
5204 );
5205 assert_eq!(
5206 subscription.consume().into_inner(),
5207 [Edit {
5208 old: 10..10,
5209 new: 10..22
5210 }]
5211 );
5212
5213 subscription
5214 });
5215
5216 // Adding excerpts emits an edited event.
5217 assert_eq!(
5218 events.read().as_slice(),
5219 &[
5220 Event::Edited {
5221 singleton_buffer_edited: false
5222 },
5223 Event::Edited {
5224 singleton_buffer_edited: false
5225 },
5226 Event::Edited {
5227 singleton_buffer_edited: false
5228 }
5229 ]
5230 );
5231
5232 let snapshot = multibuffer.read(cx).snapshot(cx);
5233 assert_eq!(
5234 snapshot.text(),
5235 concat!(
5236 "bbbb\n", // Preserve newlines
5237 "ccccc\n", //
5238 "ddd\n", //
5239 "eeee\n", //
5240 "jj" //
5241 )
5242 );
5243 assert_eq!(
5244 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5245 [Some(1), Some(2), Some(3), Some(4), Some(3)]
5246 );
5247 assert_eq!(
5248 snapshot.buffer_rows(MultiBufferRow(2)).collect::<Vec<_>>(),
5249 [Some(3), Some(4), Some(3)]
5250 );
5251 assert_eq!(
5252 snapshot.buffer_rows(MultiBufferRow(4)).collect::<Vec<_>>(),
5253 [Some(3)]
5254 );
5255 assert_eq!(
5256 snapshot.buffer_rows(MultiBufferRow(5)).collect::<Vec<_>>(),
5257 []
5258 );
5259
5260 assert_eq!(
5261 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
5262 &[
5263 (MultiBufferRow(0), "bbbb\nccccc".to_string(), true),
5264 (MultiBufferRow(2), "ddd\neeee".to_string(), false),
5265 (MultiBufferRow(4), "jj".to_string(), true),
5266 ]
5267 );
5268 assert_eq!(
5269 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
5270 &[(MultiBufferRow(0), "bbbb\nccccc".to_string(), true)]
5271 );
5272 assert_eq!(
5273 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
5274 &[]
5275 );
5276 assert_eq!(
5277 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
5278 &[]
5279 );
5280 assert_eq!(
5281 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
5282 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
5283 );
5284 assert_eq!(
5285 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
5286 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
5287 );
5288 assert_eq!(
5289 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
5290 &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
5291 );
5292 assert_eq!(
5293 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
5294 &[(MultiBufferRow(4), "jj".to_string(), true)]
5295 );
5296 assert_eq!(
5297 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
5298 &[]
5299 );
5300
5301 buffer_1.update(cx, |buffer, cx| {
5302 let text = "\n";
5303 buffer.edit(
5304 [
5305 (Point::new(0, 0)..Point::new(0, 0), text),
5306 (Point::new(2, 1)..Point::new(2, 3), text),
5307 ],
5308 None,
5309 cx,
5310 );
5311 });
5312
5313 let snapshot = multibuffer.read(cx).snapshot(cx);
5314 assert_eq!(
5315 snapshot.text(),
5316 concat!(
5317 "bbbb\n", // Preserve newlines
5318 "c\n", //
5319 "cc\n", //
5320 "ddd\n", //
5321 "eeee\n", //
5322 "jj" //
5323 )
5324 );
5325
5326 assert_eq!(
5327 subscription.consume().into_inner(),
5328 [Edit {
5329 old: 6..8,
5330 new: 6..7
5331 }]
5332 );
5333
5334 let snapshot = multibuffer.read(cx).snapshot(cx);
5335 assert_eq!(
5336 snapshot.clip_point(Point::new(0, 5), Bias::Left),
5337 Point::new(0, 4)
5338 );
5339 assert_eq!(
5340 snapshot.clip_point(Point::new(0, 5), Bias::Right),
5341 Point::new(0, 4)
5342 );
5343 assert_eq!(
5344 snapshot.clip_point(Point::new(5, 1), Bias::Right),
5345 Point::new(5, 1)
5346 );
5347 assert_eq!(
5348 snapshot.clip_point(Point::new(5, 2), Bias::Right),
5349 Point::new(5, 2)
5350 );
5351 assert_eq!(
5352 snapshot.clip_point(Point::new(5, 3), Bias::Right),
5353 Point::new(5, 2)
5354 );
5355
5356 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
5357 let (buffer_2_excerpt_id, _) =
5358 multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
5359 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
5360 multibuffer.snapshot(cx)
5361 });
5362
5363 assert_eq!(
5364 snapshot.text(),
5365 concat!(
5366 "bbbb\n", // Preserve newlines
5367 "c\n", //
5368 "cc\n", //
5369 "ddd\n", //
5370 "eeee", //
5371 )
5372 );
5373
5374 fn boundaries_in_range(
5375 range: Range<Point>,
5376 snapshot: &MultiBufferSnapshot,
5377 ) -> Vec<(MultiBufferRow, String, bool)> {
5378 snapshot
5379 .excerpt_boundaries_in_range(range)
5380 .filter_map(|boundary| {
5381 let starts_new_buffer = boundary.starts_new_buffer();
5382 boundary.next.map(|next| {
5383 (
5384 boundary.row,
5385 next.buffer
5386 .text_for_range(next.range.context)
5387 .collect::<String>(),
5388 starts_new_buffer,
5389 )
5390 })
5391 })
5392 .collect::<Vec<_>>()
5393 }
5394 }
5395
5396 #[gpui::test]
5397 fn test_excerpt_events(cx: &mut AppContext) {
5398 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
5399 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
5400
5401 let leader_multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5402 let follower_multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5403 let follower_edit_event_count = Arc::new(RwLock::new(0));
5404
5405 follower_multibuffer.update(cx, |_, cx| {
5406 let follower_edit_event_count = follower_edit_event_count.clone();
5407 cx.subscribe(
5408 &leader_multibuffer,
5409 move |follower, _, event, cx| match event.clone() {
5410 Event::ExcerptsAdded {
5411 buffer,
5412 predecessor,
5413 excerpts,
5414 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
5415 Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
5416 Event::Edited { .. } => {
5417 *follower_edit_event_count.write() += 1;
5418 }
5419 _ => {}
5420 },
5421 )
5422 .detach();
5423 });
5424
5425 leader_multibuffer.update(cx, |leader, cx| {
5426 leader.push_excerpts(
5427 buffer_1.clone(),
5428 [
5429 ExcerptRange {
5430 context: 0..8,
5431 primary: None,
5432 },
5433 ExcerptRange {
5434 context: 12..16,
5435 primary: None,
5436 },
5437 ],
5438 cx,
5439 );
5440 leader.insert_excerpts_after(
5441 leader.excerpt_ids()[0],
5442 buffer_2.clone(),
5443 [
5444 ExcerptRange {
5445 context: 0..5,
5446 primary: None,
5447 },
5448 ExcerptRange {
5449 context: 10..15,
5450 primary: None,
5451 },
5452 ],
5453 cx,
5454 )
5455 });
5456 assert_eq!(
5457 leader_multibuffer.read(cx).snapshot(cx).text(),
5458 follower_multibuffer.read(cx).snapshot(cx).text(),
5459 );
5460 assert_eq!(*follower_edit_event_count.read(), 2);
5461
5462 leader_multibuffer.update(cx, |leader, cx| {
5463 let excerpt_ids = leader.excerpt_ids();
5464 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
5465 });
5466 assert_eq!(
5467 leader_multibuffer.read(cx).snapshot(cx).text(),
5468 follower_multibuffer.read(cx).snapshot(cx).text(),
5469 );
5470 assert_eq!(*follower_edit_event_count.read(), 3);
5471
5472 // Removing an empty set of excerpts is a noop.
5473 leader_multibuffer.update(cx, |leader, cx| {
5474 leader.remove_excerpts([], cx);
5475 });
5476 assert_eq!(
5477 leader_multibuffer.read(cx).snapshot(cx).text(),
5478 follower_multibuffer.read(cx).snapshot(cx).text(),
5479 );
5480 assert_eq!(*follower_edit_event_count.read(), 3);
5481
5482 // Adding an empty set of excerpts is a noop.
5483 leader_multibuffer.update(cx, |leader, cx| {
5484 leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
5485 });
5486 assert_eq!(
5487 leader_multibuffer.read(cx).snapshot(cx).text(),
5488 follower_multibuffer.read(cx).snapshot(cx).text(),
5489 );
5490 assert_eq!(*follower_edit_event_count.read(), 3);
5491
5492 leader_multibuffer.update(cx, |leader, cx| {
5493 leader.clear(cx);
5494 });
5495 assert_eq!(
5496 leader_multibuffer.read(cx).snapshot(cx).text(),
5497 follower_multibuffer.read(cx).snapshot(cx).text(),
5498 );
5499 assert_eq!(*follower_edit_event_count.read(), 4);
5500 }
5501
5502 #[gpui::test]
5503 fn test_expand_excerpts(cx: &mut AppContext) {
5504 let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5505 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5506
5507 multibuffer.update(cx, |multibuffer, cx| {
5508 multibuffer.push_excerpts_with_context_lines(
5509 buffer.clone(),
5510 vec![
5511 // Note that in this test, this first excerpt
5512 // does not contain a new line
5513 Point::new(3, 2)..Point::new(3, 3),
5514 Point::new(7, 1)..Point::new(7, 3),
5515 Point::new(15, 0)..Point::new(15, 0),
5516 ],
5517 1,
5518 cx,
5519 )
5520 });
5521
5522 let snapshot = multibuffer.read(cx).snapshot(cx);
5523
5524 assert_eq!(
5525 snapshot.text(),
5526 concat!(
5527 "ccc\n", //
5528 "ddd\n", //
5529 "eee", //
5530 "\n", // End of excerpt
5531 "ggg\n", //
5532 "hhh\n", //
5533 "iii", //
5534 "\n", // End of excerpt
5535 "ooo\n", //
5536 "ppp\n", //
5537 "qqq", // End of excerpt
5538 )
5539 );
5540 drop(snapshot);
5541
5542 multibuffer.update(cx, |multibuffer, cx| {
5543 multibuffer.expand_excerpts(
5544 multibuffer.excerpt_ids(),
5545 1,
5546 ExpandExcerptDirection::UpAndDown,
5547 cx,
5548 )
5549 });
5550
5551 let snapshot = multibuffer.read(cx).snapshot(cx);
5552
5553 // Expanding context lines causes the line containing 'fff' to appear in two different excerpts.
5554 // We don't attempt to merge them, because removing the excerpt could create inconsistency with other layers
5555 // that are tracking excerpt ids.
5556 assert_eq!(
5557 snapshot.text(),
5558 concat!(
5559 "bbb\n", //
5560 "ccc\n", //
5561 "ddd\n", //
5562 "eee\n", //
5563 "fff\n", // End of excerpt
5564 "fff\n", //
5565 "ggg\n", //
5566 "hhh\n", //
5567 "iii\n", //
5568 "jjj\n", // End of excerpt
5569 "nnn\n", //
5570 "ooo\n", //
5571 "ppp\n", //
5572 "qqq\n", //
5573 "rrr", // End of excerpt
5574 )
5575 );
5576 }
5577
5578 #[gpui::test]
5579 fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
5580 let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5581 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5582 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5583 multibuffer.push_excerpts_with_context_lines(
5584 buffer.clone(),
5585 vec![
5586 // Note that in this test, this first excerpt
5587 // does contain a new line
5588 Point::new(3, 2)..Point::new(4, 2),
5589 Point::new(7, 1)..Point::new(7, 3),
5590 Point::new(15, 0)..Point::new(15, 0),
5591 ],
5592 2,
5593 cx,
5594 )
5595 });
5596
5597 let snapshot = multibuffer.read(cx).snapshot(cx);
5598 assert_eq!(
5599 snapshot.text(),
5600 concat!(
5601 "bbb\n", // Preserve newlines
5602 "ccc\n", //
5603 "ddd\n", //
5604 "eee\n", //
5605 "fff\n", //
5606 "ggg\n", //
5607 "hhh\n", //
5608 "iii\n", //
5609 "jjj\n", //
5610 "nnn\n", //
5611 "ooo\n", //
5612 "ppp\n", //
5613 "qqq\n", //
5614 "rrr", //
5615 )
5616 );
5617
5618 assert_eq!(
5619 anchor_ranges
5620 .iter()
5621 .map(|range| range.to_point(&snapshot))
5622 .collect::<Vec<_>>(),
5623 vec![
5624 Point::new(2, 2)..Point::new(3, 2),
5625 Point::new(6, 1)..Point::new(6, 3),
5626 Point::new(11, 0)..Point::new(11, 0)
5627 ]
5628 );
5629 }
5630
5631 #[gpui::test(iterations = 100)]
5632 async fn test_push_multiple_excerpts_with_context_lines(cx: &mut TestAppContext) {
5633 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5634 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(15, 4, 'a'), cx));
5635 let snapshot_1 = buffer_1.update(cx, |buffer, _| buffer.snapshot());
5636 let snapshot_2 = buffer_2.update(cx, |buffer, _| buffer.snapshot());
5637 let ranges_1 = vec![
5638 snapshot_1.anchor_before(Point::new(3, 2))..snapshot_1.anchor_before(Point::new(4, 2)),
5639 snapshot_1.anchor_before(Point::new(7, 1))..snapshot_1.anchor_before(Point::new(7, 3)),
5640 snapshot_1.anchor_before(Point::new(15, 0))
5641 ..snapshot_1.anchor_before(Point::new(15, 0)),
5642 ];
5643 let ranges_2 = vec![
5644 snapshot_2.anchor_before(Point::new(2, 1))..snapshot_2.anchor_before(Point::new(3, 1)),
5645 snapshot_2.anchor_before(Point::new(10, 0))
5646 ..snapshot_2.anchor_before(Point::new(10, 2)),
5647 ];
5648
5649 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5650 let anchor_ranges = multibuffer
5651 .update(cx, |multibuffer, cx| {
5652 multibuffer.push_multiple_excerpts_with_context_lines(
5653 vec![(buffer_1.clone(), ranges_1), (buffer_2.clone(), ranges_2)],
5654 2,
5655 cx,
5656 )
5657 })
5658 .await;
5659
5660 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
5661 assert_eq!(
5662 snapshot.text(),
5663 concat!(
5664 "bbb\n", // buffer_1
5665 "ccc\n", //
5666 "ddd\n", // <-- excerpt 1
5667 "eee\n", // <-- excerpt 1
5668 "fff\n", //
5669 "ggg\n", //
5670 "hhh\n", // <-- excerpt 2
5671 "iii\n", //
5672 "jjj\n", //
5673 //
5674 "nnn\n", //
5675 "ooo\n", //
5676 "ppp\n", // <-- excerpt 3
5677 "qqq\n", //
5678 "rrr\n", //
5679 //
5680 "aaaa\n", // buffer 2
5681 "bbbb\n", //
5682 "cccc\n", // <-- excerpt 4
5683 "dddd\n", // <-- excerpt 4
5684 "eeee\n", //
5685 "ffff\n", //
5686 //
5687 "iiii\n", //
5688 "jjjj\n", //
5689 "kkkk\n", // <-- excerpt 5
5690 "llll\n", //
5691 "mmmm", //
5692 )
5693 );
5694
5695 assert_eq!(
5696 anchor_ranges
5697 .iter()
5698 .map(|range| range.to_point(&snapshot))
5699 .collect::<Vec<_>>(),
5700 vec![
5701 Point::new(2, 2)..Point::new(3, 2),
5702 Point::new(6, 1)..Point::new(6, 3),
5703 Point::new(11, 0)..Point::new(11, 0),
5704 Point::new(16, 1)..Point::new(17, 1),
5705 Point::new(22, 0)..Point::new(22, 2)
5706 ]
5707 );
5708 }
5709
5710 #[gpui::test]
5711 fn test_empty_multibuffer(cx: &mut AppContext) {
5712 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5713
5714 let snapshot = multibuffer.read(cx).snapshot(cx);
5715 assert_eq!(snapshot.text(), "");
5716 assert_eq!(
5717 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5718 &[Some(0)]
5719 );
5720 assert_eq!(
5721 snapshot.buffer_rows(MultiBufferRow(1)).collect::<Vec<_>>(),
5722 &[]
5723 );
5724 }
5725
5726 #[gpui::test]
5727 fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
5728 let buffer = cx.new_model(|cx| Buffer::local("abcd", cx));
5729 let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
5730 let old_snapshot = multibuffer.read(cx).snapshot(cx);
5731 buffer.update(cx, |buffer, cx| {
5732 buffer.edit([(0..0, "X")], None, cx);
5733 buffer.edit([(5..5, "Y")], None, cx);
5734 });
5735 let new_snapshot = multibuffer.read(cx).snapshot(cx);
5736
5737 assert_eq!(old_snapshot.text(), "abcd");
5738 assert_eq!(new_snapshot.text(), "XabcdY");
5739
5740 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5741 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5742 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
5743 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
5744 }
5745
5746 #[gpui::test]
5747 fn test_multibuffer_anchors(cx: &mut AppContext) {
5748 let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5749 let buffer_2 = cx.new_model(|cx| Buffer::local("efghi", cx));
5750 let multibuffer = cx.new_model(|cx| {
5751 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
5752 multibuffer.push_excerpts(
5753 buffer_1.clone(),
5754 [ExcerptRange {
5755 context: 0..4,
5756 primary: None,
5757 }],
5758 cx,
5759 );
5760 multibuffer.push_excerpts(
5761 buffer_2.clone(),
5762 [ExcerptRange {
5763 context: 0..5,
5764 primary: None,
5765 }],
5766 cx,
5767 );
5768 multibuffer
5769 });
5770 let old_snapshot = multibuffer.read(cx).snapshot(cx);
5771
5772 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
5773 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
5774 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5775 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5776 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5777 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5778
5779 buffer_1.update(cx, |buffer, cx| {
5780 buffer.edit([(0..0, "W")], None, cx);
5781 buffer.edit([(5..5, "X")], None, cx);
5782 });
5783 buffer_2.update(cx, |buffer, cx| {
5784 buffer.edit([(0..0, "Y")], None, cx);
5785 buffer.edit([(6..6, "Z")], None, cx);
5786 });
5787 let new_snapshot = multibuffer.read(cx).snapshot(cx);
5788
5789 assert_eq!(old_snapshot.text(), "abcd\nefghi");
5790 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
5791
5792 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5793 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5794 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
5795 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
5796 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
5797 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
5798 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
5799 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
5800 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
5801 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
5802 }
5803
5804 #[gpui::test]
5805 fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
5806 let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5807 let buffer_2 = cx.new_model(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
5808 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5809
5810 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
5811 // Add an excerpt from buffer 1 that spans this new insertion.
5812 buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
5813 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
5814 multibuffer
5815 .push_excerpts(
5816 buffer_1.clone(),
5817 [ExcerptRange {
5818 context: 0..7,
5819 primary: None,
5820 }],
5821 cx,
5822 )
5823 .pop()
5824 .unwrap()
5825 });
5826
5827 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
5828 assert_eq!(snapshot_1.text(), "abcd123");
5829
5830 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
5831 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
5832 multibuffer.remove_excerpts([excerpt_id_1], cx);
5833 let mut ids = multibuffer
5834 .push_excerpts(
5835 buffer_2.clone(),
5836 [
5837 ExcerptRange {
5838 context: 0..4,
5839 primary: None,
5840 },
5841 ExcerptRange {
5842 context: 6..10,
5843 primary: None,
5844 },
5845 ExcerptRange {
5846 context: 12..16,
5847 primary: None,
5848 },
5849 ],
5850 cx,
5851 )
5852 .into_iter();
5853 (ids.next().unwrap(), ids.next().unwrap())
5854 });
5855 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
5856 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
5857
5858 // The old excerpt id doesn't get reused.
5859 assert_ne!(excerpt_id_2, excerpt_id_1);
5860
5861 // Resolve some anchors from the previous snapshot in the new snapshot.
5862 // The current excerpts are from a different buffer, so we don't attempt to
5863 // resolve the old text anchor in the new buffer.
5864 assert_eq!(
5865 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
5866 0
5867 );
5868 assert_eq!(
5869 snapshot_2.summaries_for_anchors::<usize, _>(&[
5870 snapshot_1.anchor_before(2),
5871 snapshot_1.anchor_after(3)
5872 ]),
5873 vec![0, 0]
5874 );
5875
5876 // Refresh anchors from the old snapshot. The return value indicates that both
5877 // anchors lost their original excerpt.
5878 let refresh =
5879 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
5880 assert_eq!(
5881 refresh,
5882 &[
5883 (0, snapshot_2.anchor_before(0), false),
5884 (1, snapshot_2.anchor_after(0), false),
5885 ]
5886 );
5887
5888 // Replace the middle excerpt with a smaller excerpt in buffer 2,
5889 // that intersects the old excerpt.
5890 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
5891 multibuffer.remove_excerpts([excerpt_id_3], cx);
5892 multibuffer
5893 .insert_excerpts_after(
5894 excerpt_id_2,
5895 buffer_2.clone(),
5896 [ExcerptRange {
5897 context: 5..8,
5898 primary: None,
5899 }],
5900 cx,
5901 )
5902 .pop()
5903 .unwrap()
5904 });
5905
5906 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
5907 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
5908 assert_ne!(excerpt_id_5, excerpt_id_3);
5909
5910 // Resolve some anchors from the previous snapshot in the new snapshot.
5911 // The third anchor can't be resolved, since its excerpt has been removed,
5912 // so it resolves to the same position as its predecessor.
5913 let anchors = [
5914 snapshot_2.anchor_before(0),
5915 snapshot_2.anchor_after(2),
5916 snapshot_2.anchor_after(6),
5917 snapshot_2.anchor_after(14),
5918 ];
5919 assert_eq!(
5920 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
5921 &[0, 2, 9, 13]
5922 );
5923
5924 let new_anchors = snapshot_3.refresh_anchors(&anchors);
5925 assert_eq!(
5926 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
5927 &[(0, true), (1, true), (2, true), (3, true)]
5928 );
5929 assert_eq!(
5930 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
5931 &[0, 2, 7, 13]
5932 );
5933 }
5934
5935 #[gpui::test(iterations = 100)]
5936 fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
5937 let operations = env::var("OPERATIONS")
5938 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
5939 .unwrap_or(10);
5940
5941 let mut buffers: Vec<Model<Buffer>> = Vec::new();
5942 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
5943 let mut excerpt_ids = Vec::<ExcerptId>::new();
5944 let mut expected_excerpts = Vec::<(Model<Buffer>, Range<text::Anchor>)>::new();
5945 let mut anchors = Vec::new();
5946 let mut old_versions = Vec::new();
5947
5948 for _ in 0..operations {
5949 match rng.gen_range(0..100) {
5950 0..=14 if !buffers.is_empty() => {
5951 let buffer = buffers.choose(&mut rng).unwrap();
5952 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
5953 }
5954 15..=19 if !expected_excerpts.is_empty() => {
5955 multibuffer.update(cx, |multibuffer, cx| {
5956 let ids = multibuffer.excerpt_ids();
5957 let mut excerpts = HashSet::default();
5958 for _ in 0..rng.gen_range(0..ids.len()) {
5959 excerpts.extend(ids.choose(&mut rng).copied());
5960 }
5961
5962 let line_count = rng.gen_range(0..5);
5963
5964 let excerpt_ixs = excerpts
5965 .iter()
5966 .map(|id| excerpt_ids.iter().position(|i| i == id).unwrap())
5967 .collect::<Vec<_>>();
5968 log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
5969 multibuffer.expand_excerpts(
5970 excerpts.iter().cloned(),
5971 line_count,
5972 ExpandExcerptDirection::UpAndDown,
5973 cx,
5974 );
5975
5976 if line_count > 0 {
5977 for id in excerpts {
5978 let excerpt_ix = excerpt_ids.iter().position(|&i| i == id).unwrap();
5979 let (buffer, range) = &mut expected_excerpts[excerpt_ix];
5980 let snapshot = buffer.read(cx).snapshot();
5981 let mut point_range = range.to_point(&snapshot);
5982 point_range.start =
5983 Point::new(point_range.start.row.saturating_sub(line_count), 0);
5984 point_range.end = snapshot.clip_point(
5985 Point::new(point_range.end.row + line_count, 0),
5986 Bias::Left,
5987 );
5988 point_range.end.column = snapshot.line_len(point_range.end.row);
5989 *range = snapshot.anchor_before(point_range.start)
5990 ..snapshot.anchor_after(point_range.end);
5991 }
5992 }
5993 });
5994 }
5995 20..=29 if !expected_excerpts.is_empty() => {
5996 let mut ids_to_remove = vec![];
5997 for _ in 0..rng.gen_range(1..=3) {
5998 if expected_excerpts.is_empty() {
5999 break;
6000 }
6001
6002 let ix = rng.gen_range(0..expected_excerpts.len());
6003 ids_to_remove.push(excerpt_ids.remove(ix));
6004 let (buffer, range) = expected_excerpts.remove(ix);
6005 let buffer = buffer.read(cx);
6006 log::info!(
6007 "Removing excerpt {}: {:?}",
6008 ix,
6009 buffer
6010 .text_for_range(range.to_offset(buffer))
6011 .collect::<String>(),
6012 );
6013 }
6014 let snapshot = multibuffer.read(cx).read(cx);
6015 ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
6016 drop(snapshot);
6017 multibuffer.update(cx, |multibuffer, cx| {
6018 multibuffer.remove_excerpts(ids_to_remove, cx)
6019 });
6020 }
6021 30..=39 if !expected_excerpts.is_empty() => {
6022 let multibuffer = multibuffer.read(cx).read(cx);
6023 let offset =
6024 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
6025 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
6026 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
6027 anchors.push(multibuffer.anchor_at(offset, bias));
6028 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
6029 }
6030 40..=44 if !anchors.is_empty() => {
6031 let multibuffer = multibuffer.read(cx).read(cx);
6032 let prev_len = anchors.len();
6033 anchors = multibuffer
6034 .refresh_anchors(&anchors)
6035 .into_iter()
6036 .map(|a| a.1)
6037 .collect();
6038
6039 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
6040 // overshoot its boundaries.
6041 assert_eq!(anchors.len(), prev_len);
6042 for anchor in &anchors {
6043 if anchor.excerpt_id == ExcerptId::min()
6044 || anchor.excerpt_id == ExcerptId::max()
6045 {
6046 continue;
6047 }
6048
6049 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
6050 assert_eq!(excerpt.id, anchor.excerpt_id);
6051 assert!(excerpt.contains(anchor));
6052 }
6053 }
6054 _ => {
6055 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
6056 let base_text = util::RandomCharIter::new(&mut rng)
6057 .take(25)
6058 .collect::<String>();
6059
6060 buffers.push(cx.new_model(|cx| Buffer::local(base_text, cx)));
6061 buffers.last().unwrap()
6062 } else {
6063 buffers.choose(&mut rng).unwrap()
6064 };
6065
6066 let buffer = buffer_handle.read(cx);
6067 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
6068 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
6069 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
6070 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
6071 let prev_excerpt_id = excerpt_ids
6072 .get(prev_excerpt_ix)
6073 .cloned()
6074 .unwrap_or_else(ExcerptId::max);
6075 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
6076
6077 log::info!(
6078 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
6079 excerpt_ix,
6080 expected_excerpts.len(),
6081 buffer_handle.read(cx).remote_id(),
6082 buffer.text(),
6083 start_ix..end_ix,
6084 &buffer.text()[start_ix..end_ix]
6085 );
6086
6087 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
6088 multibuffer
6089 .insert_excerpts_after(
6090 prev_excerpt_id,
6091 buffer_handle.clone(),
6092 [ExcerptRange {
6093 context: start_ix..end_ix,
6094 primary: None,
6095 }],
6096 cx,
6097 )
6098 .pop()
6099 .unwrap()
6100 });
6101
6102 excerpt_ids.insert(excerpt_ix, excerpt_id);
6103 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
6104 }
6105 }
6106
6107 if rng.gen_bool(0.3) {
6108 multibuffer.update(cx, |multibuffer, cx| {
6109 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
6110 })
6111 }
6112
6113 let snapshot = multibuffer.read(cx).snapshot(cx);
6114
6115 let mut excerpt_starts = Vec::new();
6116 let mut expected_text = String::new();
6117 let mut expected_buffer_rows = Vec::new();
6118 for (buffer, range) in &expected_excerpts {
6119 let buffer = buffer.read(cx);
6120 let buffer_range = range.to_offset(buffer);
6121
6122 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
6123 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
6124 expected_text.push('\n');
6125
6126 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
6127 ..=buffer.offset_to_point(buffer_range.end).row;
6128 for row in buffer_row_range {
6129 expected_buffer_rows.push(Some(row));
6130 }
6131 }
6132 // Remove final trailing newline.
6133 if !expected_excerpts.is_empty() {
6134 expected_text.pop();
6135 }
6136
6137 // Always report one buffer row
6138 if expected_buffer_rows.is_empty() {
6139 expected_buffer_rows.push(Some(0));
6140 }
6141
6142 assert_eq!(snapshot.text(), expected_text);
6143 log::info!("MultiBuffer text: {:?}", expected_text);
6144
6145 assert_eq!(
6146 snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
6147 expected_buffer_rows,
6148 );
6149
6150 for _ in 0..5 {
6151 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
6152 assert_eq!(
6153 snapshot
6154 .buffer_rows(MultiBufferRow(start_row as u32))
6155 .collect::<Vec<_>>(),
6156 &expected_buffer_rows[start_row..],
6157 "buffer_rows({})",
6158 start_row
6159 );
6160 }
6161
6162 assert_eq!(
6163 snapshot.max_buffer_row().0,
6164 expected_buffer_rows.into_iter().flatten().max().unwrap()
6165 );
6166
6167 let mut excerpt_starts = excerpt_starts.into_iter();
6168 for (buffer, range) in &expected_excerpts {
6169 let buffer = buffer.read(cx);
6170 let buffer_id = buffer.remote_id();
6171 let buffer_range = range.to_offset(buffer);
6172 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
6173 let buffer_start_point_utf16 =
6174 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
6175
6176 let excerpt_start = excerpt_starts.next().unwrap();
6177 let mut offset = excerpt_start.len;
6178 let mut buffer_offset = buffer_range.start;
6179 let mut point = excerpt_start.lines;
6180 let mut buffer_point = buffer_start_point;
6181 let mut point_utf16 = excerpt_start.lines_utf16();
6182 let mut buffer_point_utf16 = buffer_start_point_utf16;
6183 for ch in buffer
6184 .snapshot()
6185 .chunks(buffer_range.clone(), false)
6186 .flat_map(|c| c.text.chars())
6187 {
6188 for _ in 0..ch.len_utf8() {
6189 let left_offset = snapshot.clip_offset(offset, Bias::Left);
6190 let right_offset = snapshot.clip_offset(offset, Bias::Right);
6191 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
6192 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
6193 assert_eq!(
6194 left_offset,
6195 excerpt_start.len + (buffer_left_offset - buffer_range.start),
6196 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
6197 offset,
6198 buffer_id,
6199 buffer_offset,
6200 );
6201 assert_eq!(
6202 right_offset,
6203 excerpt_start.len + (buffer_right_offset - buffer_range.start),
6204 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
6205 offset,
6206 buffer_id,
6207 buffer_offset,
6208 );
6209
6210 let left_point = snapshot.clip_point(point, Bias::Left);
6211 let right_point = snapshot.clip_point(point, Bias::Right);
6212 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
6213 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
6214 assert_eq!(
6215 left_point,
6216 excerpt_start.lines + (buffer_left_point - buffer_start_point),
6217 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
6218 point,
6219 buffer_id,
6220 buffer_point,
6221 );
6222 assert_eq!(
6223 right_point,
6224 excerpt_start.lines + (buffer_right_point - buffer_start_point),
6225 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
6226 point,
6227 buffer_id,
6228 buffer_point,
6229 );
6230
6231 assert_eq!(
6232 snapshot.point_to_offset(left_point),
6233 left_offset,
6234 "point_to_offset({:?})",
6235 left_point,
6236 );
6237 assert_eq!(
6238 snapshot.offset_to_point(left_offset),
6239 left_point,
6240 "offset_to_point({:?})",
6241 left_offset,
6242 );
6243
6244 offset += 1;
6245 buffer_offset += 1;
6246 if ch == '\n' {
6247 point += Point::new(1, 0);
6248 buffer_point += Point::new(1, 0);
6249 } else {
6250 point += Point::new(0, 1);
6251 buffer_point += Point::new(0, 1);
6252 }
6253 }
6254
6255 for _ in 0..ch.len_utf16() {
6256 let left_point_utf16 =
6257 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
6258 let right_point_utf16 =
6259 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
6260 let buffer_left_point_utf16 =
6261 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
6262 let buffer_right_point_utf16 =
6263 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
6264 assert_eq!(
6265 left_point_utf16,
6266 excerpt_start.lines_utf16()
6267 + (buffer_left_point_utf16 - buffer_start_point_utf16),
6268 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
6269 point_utf16,
6270 buffer_id,
6271 buffer_point_utf16,
6272 );
6273 assert_eq!(
6274 right_point_utf16,
6275 excerpt_start.lines_utf16()
6276 + (buffer_right_point_utf16 - buffer_start_point_utf16),
6277 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
6278 point_utf16,
6279 buffer_id,
6280 buffer_point_utf16,
6281 );
6282
6283 if ch == '\n' {
6284 point_utf16 += PointUtf16::new(1, 0);
6285 buffer_point_utf16 += PointUtf16::new(1, 0);
6286 } else {
6287 point_utf16 += PointUtf16::new(0, 1);
6288 buffer_point_utf16 += PointUtf16::new(0, 1);
6289 }
6290 }
6291 }
6292 }
6293
6294 for (row, line) in expected_text.split('\n').enumerate() {
6295 assert_eq!(
6296 snapshot.line_len(MultiBufferRow(row as u32)),
6297 line.len() as u32,
6298 "line_len({}).",
6299 row
6300 );
6301 }
6302
6303 let text_rope = Rope::from(expected_text.as_str());
6304 for _ in 0..10 {
6305 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
6306 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
6307
6308 let text_for_range = snapshot
6309 .text_for_range(start_ix..end_ix)
6310 .collect::<String>();
6311 assert_eq!(
6312 text_for_range,
6313 &expected_text[start_ix..end_ix],
6314 "incorrect text for range {:?}",
6315 start_ix..end_ix
6316 );
6317
6318 let excerpted_buffer_ranges = multibuffer
6319 .read(cx)
6320 .range_to_buffer_ranges(start_ix..end_ix, cx);
6321 let excerpted_buffers_text = excerpted_buffer_ranges
6322 .iter()
6323 .map(|(buffer, buffer_range, _)| {
6324 buffer
6325 .read(cx)
6326 .text_for_range(buffer_range.clone())
6327 .collect::<String>()
6328 })
6329 .collect::<Vec<_>>()
6330 .join("\n");
6331 assert_eq!(excerpted_buffers_text, text_for_range);
6332 if !expected_excerpts.is_empty() {
6333 assert!(!excerpted_buffer_ranges.is_empty());
6334 }
6335
6336 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
6337 assert_eq!(
6338 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
6339 expected_summary,
6340 "incorrect summary for range {:?}",
6341 start_ix..end_ix
6342 );
6343 }
6344
6345 // Anchor resolution
6346 let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
6347 assert_eq!(anchors.len(), summaries.len());
6348 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
6349 assert!(resolved_offset <= snapshot.len());
6350 assert_eq!(
6351 snapshot.summary_for_anchor::<usize>(anchor),
6352 resolved_offset
6353 );
6354 }
6355
6356 for _ in 0..10 {
6357 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
6358 assert_eq!(
6359 snapshot.reversed_chars_at(end_ix).collect::<String>(),
6360 expected_text[..end_ix].chars().rev().collect::<String>(),
6361 );
6362 }
6363
6364 for _ in 0..10 {
6365 let end_ix = rng.gen_range(0..=text_rope.len());
6366 let start_ix = rng.gen_range(0..=end_ix);
6367 assert_eq!(
6368 snapshot
6369 .bytes_in_range(start_ix..end_ix)
6370 .flatten()
6371 .copied()
6372 .collect::<Vec<_>>(),
6373 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
6374 "bytes_in_range({:?})",
6375 start_ix..end_ix,
6376 );
6377 }
6378 }
6379
6380 let snapshot = multibuffer.read(cx).snapshot(cx);
6381 for (old_snapshot, subscription) in old_versions {
6382 let edits = subscription.consume().into_inner();
6383
6384 log::info!(
6385 "applying subscription edits to old text: {:?}: {:?}",
6386 old_snapshot.text(),
6387 edits,
6388 );
6389
6390 let mut text = old_snapshot.text();
6391 for edit in edits {
6392 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
6393 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
6394 }
6395 assert_eq!(text.to_string(), snapshot.text());
6396 }
6397 }
6398
6399 #[gpui::test]
6400 fn test_history(cx: &mut AppContext) {
6401 let test_settings = SettingsStore::test(cx);
6402 cx.set_global(test_settings);
6403
6404 let buffer_1 = cx.new_model(|cx| Buffer::local("1234", cx));
6405 let buffer_2 = cx.new_model(|cx| Buffer::local("5678", cx));
6406 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
6407 let group_interval = multibuffer.read(cx).history.group_interval;
6408 multibuffer.update(cx, |multibuffer, cx| {
6409 multibuffer.push_excerpts(
6410 buffer_1.clone(),
6411 [ExcerptRange {
6412 context: 0..buffer_1.read(cx).len(),
6413 primary: None,
6414 }],
6415 cx,
6416 );
6417 multibuffer.push_excerpts(
6418 buffer_2.clone(),
6419 [ExcerptRange {
6420 context: 0..buffer_2.read(cx).len(),
6421 primary: None,
6422 }],
6423 cx,
6424 );
6425 });
6426
6427 let mut now = Instant::now();
6428
6429 multibuffer.update(cx, |multibuffer, cx| {
6430 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
6431 multibuffer.edit(
6432 [
6433 (Point::new(0, 0)..Point::new(0, 0), "A"),
6434 (Point::new(1, 0)..Point::new(1, 0), "A"),
6435 ],
6436 None,
6437 cx,
6438 );
6439 multibuffer.edit(
6440 [
6441 (Point::new(0, 1)..Point::new(0, 1), "B"),
6442 (Point::new(1, 1)..Point::new(1, 1), "B"),
6443 ],
6444 None,
6445 cx,
6446 );
6447 multibuffer.end_transaction_at(now, cx);
6448 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6449
6450 // Verify edited ranges for transaction 1
6451 assert_eq!(
6452 multibuffer.edited_ranges_for_transaction(transaction_1, cx),
6453 &[
6454 Point::new(0, 0)..Point::new(0, 2),
6455 Point::new(1, 0)..Point::new(1, 2)
6456 ]
6457 );
6458
6459 // Edit buffer 1 through the multibuffer
6460 now += 2 * group_interval;
6461 multibuffer.start_transaction_at(now, cx);
6462 multibuffer.edit([(2..2, "C")], None, cx);
6463 multibuffer.end_transaction_at(now, cx);
6464 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
6465
6466 // Edit buffer 1 independently
6467 buffer_1.update(cx, |buffer_1, cx| {
6468 buffer_1.start_transaction_at(now);
6469 buffer_1.edit([(3..3, "D")], None, cx);
6470 buffer_1.end_transaction_at(now, cx);
6471
6472 now += 2 * group_interval;
6473 buffer_1.start_transaction_at(now);
6474 buffer_1.edit([(4..4, "E")], None, cx);
6475 buffer_1.end_transaction_at(now, cx);
6476 });
6477 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
6478
6479 // An undo in the multibuffer undoes the multibuffer transaction
6480 // and also any individual buffer edits that have occurred since
6481 // that transaction.
6482 multibuffer.undo(cx);
6483 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6484
6485 multibuffer.undo(cx);
6486 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6487
6488 multibuffer.redo(cx);
6489 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6490
6491 multibuffer.redo(cx);
6492 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
6493
6494 // Undo buffer 2 independently.
6495 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
6496 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
6497
6498 // An undo in the multibuffer undoes the components of the
6499 // the last multibuffer transaction that are not already undone.
6500 multibuffer.undo(cx);
6501 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
6502
6503 multibuffer.undo(cx);
6504 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6505
6506 multibuffer.redo(cx);
6507 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6508
6509 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
6510 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
6511
6512 // Redo stack gets cleared after an edit.
6513 now += 2 * group_interval;
6514 multibuffer.start_transaction_at(now, cx);
6515 multibuffer.edit([(0..0, "X")], None, cx);
6516 multibuffer.end_transaction_at(now, cx);
6517 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6518 multibuffer.redo(cx);
6519 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6520 multibuffer.undo(cx);
6521 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
6522 multibuffer.undo(cx);
6523 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6524
6525 // Transactions can be grouped manually.
6526 multibuffer.redo(cx);
6527 multibuffer.redo(cx);
6528 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6529 multibuffer.group_until_transaction(transaction_1, cx);
6530 multibuffer.undo(cx);
6531 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6532 multibuffer.redo(cx);
6533 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6534 });
6535 }
6536
6537 #[gpui::test]
6538 fn test_excerpts_in_ranges_no_ranges(cx: &mut AppContext) {
6539 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6540 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6541 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
6542 multibuffer.update(cx, |multibuffer, cx| {
6543 multibuffer.push_excerpts(
6544 buffer_1.clone(),
6545 [ExcerptRange {
6546 context: 0..buffer_1.read(cx).len(),
6547 primary: None,
6548 }],
6549 cx,
6550 );
6551 multibuffer.push_excerpts(
6552 buffer_2.clone(),
6553 [ExcerptRange {
6554 context: 0..buffer_2.read(cx).len(),
6555 primary: None,
6556 }],
6557 cx,
6558 );
6559 });
6560
6561 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
6562
6563 let mut excerpts = snapshot.excerpts_in_ranges(iter::from_fn(|| None));
6564
6565 assert!(excerpts.next().is_none());
6566 }
6567
6568 fn validate_excerpts(
6569 actual: &[(ExcerptId, BufferId, Range<Anchor>)],
6570 expected: &Vec<(ExcerptId, BufferId, Range<Anchor>)>,
6571 ) {
6572 assert_eq!(actual.len(), expected.len());
6573
6574 actual
6575 .iter()
6576 .zip(expected)
6577 .map(|(actual, expected)| {
6578 assert_eq!(actual.0, expected.0);
6579 assert_eq!(actual.1, expected.1);
6580 assert_eq!(actual.2.start, expected.2.start);
6581 assert_eq!(actual.2.end, expected.2.end);
6582 })
6583 .collect_vec();
6584 }
6585
6586 fn map_range_from_excerpt(
6587 snapshot: &MultiBufferSnapshot,
6588 excerpt_id: ExcerptId,
6589 excerpt_buffer: &BufferSnapshot,
6590 range: Range<usize>,
6591 ) -> Range<Anchor> {
6592 snapshot
6593 .anchor_in_excerpt(excerpt_id, excerpt_buffer.anchor_before(range.start))
6594 .unwrap()
6595 ..snapshot
6596 .anchor_in_excerpt(excerpt_id, excerpt_buffer.anchor_after(range.end))
6597 .unwrap()
6598 }
6599
6600 fn make_expected_excerpt_info(
6601 snapshot: &MultiBufferSnapshot,
6602 cx: &mut AppContext,
6603 excerpt_id: ExcerptId,
6604 buffer: &Model<Buffer>,
6605 range: Range<usize>,
6606 ) -> (ExcerptId, BufferId, Range<Anchor>) {
6607 (
6608 excerpt_id,
6609 buffer.read(cx).remote_id(),
6610 map_range_from_excerpt(snapshot, excerpt_id, &buffer.read(cx).snapshot(), range),
6611 )
6612 }
6613
6614 #[gpui::test]
6615 fn test_excerpts_in_ranges_range_inside_the_excerpt(cx: &mut AppContext) {
6616 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6617 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6618 let buffer_len = buffer_1.read(cx).len();
6619 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
6620 let mut expected_excerpt_id = ExcerptId(0);
6621
6622 multibuffer.update(cx, |multibuffer, cx| {
6623 expected_excerpt_id = multibuffer.push_excerpts(
6624 buffer_1.clone(),
6625 [ExcerptRange {
6626 context: 0..buffer_1.read(cx).len(),
6627 primary: None,
6628 }],
6629 cx,
6630 )[0];
6631 multibuffer.push_excerpts(
6632 buffer_2.clone(),
6633 [ExcerptRange {
6634 context: 0..buffer_2.read(cx).len(),
6635 primary: None,
6636 }],
6637 cx,
6638 );
6639 });
6640
6641 let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
6642
6643 let range = snapshot
6644 .anchor_in_excerpt(expected_excerpt_id, buffer_1.read(cx).anchor_before(1))
6645 .unwrap()
6646 ..snapshot
6647 .anchor_in_excerpt(
6648 expected_excerpt_id,
6649 buffer_1.read(cx).anchor_after(buffer_len / 2),
6650 )
6651 .unwrap();
6652
6653 let expected_excerpts = vec![make_expected_excerpt_info(
6654 &snapshot,
6655 cx,
6656 expected_excerpt_id,
6657 &buffer_1,
6658 1..(buffer_len / 2),
6659 )];
6660
6661 let excerpts = snapshot
6662 .excerpts_in_ranges(vec![range.clone()].into_iter())
6663 .map(|(excerpt_id, buffer, actual_range)| {
6664 (
6665 excerpt_id,
6666 buffer.remote_id(),
6667 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6668 )
6669 })
6670 .collect_vec();
6671
6672 validate_excerpts(&excerpts, &expected_excerpts);
6673 }
6674
6675 #[gpui::test]
6676 fn test_excerpts_in_ranges_range_crosses_excerpts_boundary(cx: &mut AppContext) {
6677 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6678 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6679 let buffer_len = buffer_1.read(cx).len();
6680 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
6681 let mut excerpt_1_id = ExcerptId(0);
6682 let mut excerpt_2_id = ExcerptId(0);
6683
6684 multibuffer.update(cx, |multibuffer, cx| {
6685 excerpt_1_id = multibuffer.push_excerpts(
6686 buffer_1.clone(),
6687 [ExcerptRange {
6688 context: 0..buffer_1.read(cx).len(),
6689 primary: None,
6690 }],
6691 cx,
6692 )[0];
6693 excerpt_2_id = multibuffer.push_excerpts(
6694 buffer_2.clone(),
6695 [ExcerptRange {
6696 context: 0..buffer_2.read(cx).len(),
6697 primary: None,
6698 }],
6699 cx,
6700 )[0];
6701 });
6702
6703 let snapshot = multibuffer.read(cx).snapshot(cx);
6704
6705 let expected_range = snapshot
6706 .anchor_in_excerpt(
6707 excerpt_1_id,
6708 buffer_1.read(cx).anchor_before(buffer_len / 2),
6709 )
6710 .unwrap()
6711 ..snapshot
6712 .anchor_in_excerpt(excerpt_2_id, buffer_2.read(cx).anchor_after(buffer_len / 2))
6713 .unwrap();
6714
6715 let expected_excerpts = vec![
6716 make_expected_excerpt_info(
6717 &snapshot,
6718 cx,
6719 excerpt_1_id,
6720 &buffer_1,
6721 (buffer_len / 2)..buffer_len,
6722 ),
6723 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, 0..buffer_len / 2),
6724 ];
6725
6726 let excerpts = snapshot
6727 .excerpts_in_ranges(vec![expected_range.clone()].into_iter())
6728 .map(|(excerpt_id, buffer, actual_range)| {
6729 (
6730 excerpt_id,
6731 buffer.remote_id(),
6732 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6733 )
6734 })
6735 .collect_vec();
6736
6737 validate_excerpts(&excerpts, &expected_excerpts);
6738 }
6739
6740 #[gpui::test]
6741 fn test_excerpts_in_ranges_range_encloses_excerpt(cx: &mut AppContext) {
6742 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6743 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6744 let buffer_3 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'r'), cx));
6745 let buffer_len = buffer_1.read(cx).len();
6746 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
6747 let mut excerpt_1_id = ExcerptId(0);
6748 let mut excerpt_2_id = ExcerptId(0);
6749 let mut excerpt_3_id = ExcerptId(0);
6750
6751 multibuffer.update(cx, |multibuffer, cx| {
6752 excerpt_1_id = multibuffer.push_excerpts(
6753 buffer_1.clone(),
6754 [ExcerptRange {
6755 context: 0..buffer_1.read(cx).len(),
6756 primary: None,
6757 }],
6758 cx,
6759 )[0];
6760 excerpt_2_id = multibuffer.push_excerpts(
6761 buffer_2.clone(),
6762 [ExcerptRange {
6763 context: 0..buffer_2.read(cx).len(),
6764 primary: None,
6765 }],
6766 cx,
6767 )[0];
6768 excerpt_3_id = multibuffer.push_excerpts(
6769 buffer_3.clone(),
6770 [ExcerptRange {
6771 context: 0..buffer_3.read(cx).len(),
6772 primary: None,
6773 }],
6774 cx,
6775 )[0];
6776 });
6777
6778 let snapshot = multibuffer.read(cx).snapshot(cx);
6779
6780 let expected_range = snapshot
6781 .anchor_in_excerpt(
6782 excerpt_1_id,
6783 buffer_1.read(cx).anchor_before(buffer_len / 2),
6784 )
6785 .unwrap()
6786 ..snapshot
6787 .anchor_in_excerpt(excerpt_3_id, buffer_3.read(cx).anchor_after(buffer_len / 2))
6788 .unwrap();
6789
6790 let expected_excerpts = vec![
6791 make_expected_excerpt_info(
6792 &snapshot,
6793 cx,
6794 excerpt_1_id,
6795 &buffer_1,
6796 (buffer_len / 2)..buffer_len,
6797 ),
6798 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, 0..buffer_len),
6799 make_expected_excerpt_info(&snapshot, cx, excerpt_3_id, &buffer_3, 0..buffer_len / 2),
6800 ];
6801
6802 let excerpts = snapshot
6803 .excerpts_in_ranges(vec![expected_range.clone()].into_iter())
6804 .map(|(excerpt_id, buffer, actual_range)| {
6805 (
6806 excerpt_id,
6807 buffer.remote_id(),
6808 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6809 )
6810 })
6811 .collect_vec();
6812
6813 validate_excerpts(&excerpts, &expected_excerpts);
6814 }
6815
6816 #[gpui::test]
6817 fn test_excerpts_in_ranges_multiple_ranges(cx: &mut AppContext) {
6818 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6819 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6820 let buffer_len = buffer_1.read(cx).len();
6821 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
6822 let mut excerpt_1_id = ExcerptId(0);
6823 let mut excerpt_2_id = ExcerptId(0);
6824
6825 multibuffer.update(cx, |multibuffer, cx| {
6826 excerpt_1_id = multibuffer.push_excerpts(
6827 buffer_1.clone(),
6828 [ExcerptRange {
6829 context: 0..buffer_1.read(cx).len(),
6830 primary: None,
6831 }],
6832 cx,
6833 )[0];
6834 excerpt_2_id = multibuffer.push_excerpts(
6835 buffer_2.clone(),
6836 [ExcerptRange {
6837 context: 0..buffer_2.read(cx).len(),
6838 primary: None,
6839 }],
6840 cx,
6841 )[0];
6842 });
6843
6844 let snapshot = multibuffer.read(cx).snapshot(cx);
6845
6846 let ranges = vec![
6847 1..(buffer_len / 4),
6848 (buffer_len / 3)..(buffer_len / 2),
6849 (buffer_len / 4 * 3)..(buffer_len),
6850 ];
6851
6852 let expected_excerpts = ranges
6853 .iter()
6854 .map(|range| {
6855 make_expected_excerpt_info(&snapshot, cx, excerpt_1_id, &buffer_1, range.clone())
6856 })
6857 .collect_vec();
6858
6859 let ranges = ranges.into_iter().map(|range| {
6860 map_range_from_excerpt(
6861 &snapshot,
6862 excerpt_1_id,
6863 &buffer_1.read(cx).snapshot(),
6864 range,
6865 )
6866 });
6867
6868 let excerpts = snapshot
6869 .excerpts_in_ranges(ranges)
6870 .map(|(excerpt_id, buffer, actual_range)| {
6871 (
6872 excerpt_id,
6873 buffer.remote_id(),
6874 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6875 )
6876 })
6877 .collect_vec();
6878
6879 validate_excerpts(&excerpts, &expected_excerpts);
6880 }
6881
6882 #[gpui::test]
6883 fn test_excerpts_in_ranges_range_ends_at_excerpt_end(cx: &mut AppContext) {
6884 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6885 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6886 let buffer_len = buffer_1.read(cx).len();
6887 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
6888 let mut excerpt_1_id = ExcerptId(0);
6889 let mut excerpt_2_id = ExcerptId(0);
6890
6891 multibuffer.update(cx, |multibuffer, cx| {
6892 excerpt_1_id = multibuffer.push_excerpts(
6893 buffer_1.clone(),
6894 [ExcerptRange {
6895 context: 0..buffer_1.read(cx).len(),
6896 primary: None,
6897 }],
6898 cx,
6899 )[0];
6900 excerpt_2_id = multibuffer.push_excerpts(
6901 buffer_2.clone(),
6902 [ExcerptRange {
6903 context: 0..buffer_2.read(cx).len(),
6904 primary: None,
6905 }],
6906 cx,
6907 )[0];
6908 });
6909
6910 let snapshot = multibuffer.read(cx).snapshot(cx);
6911
6912 let ranges = [0..buffer_len, (buffer_len / 3)..(buffer_len / 2)];
6913
6914 let expected_excerpts = vec![
6915 make_expected_excerpt_info(&snapshot, cx, excerpt_1_id, &buffer_1, ranges[0].clone()),
6916 make_expected_excerpt_info(&snapshot, cx, excerpt_2_id, &buffer_2, ranges[1].clone()),
6917 ];
6918
6919 let ranges = [
6920 map_range_from_excerpt(
6921 &snapshot,
6922 excerpt_1_id,
6923 &buffer_1.read(cx).snapshot(),
6924 ranges[0].clone(),
6925 ),
6926 map_range_from_excerpt(
6927 &snapshot,
6928 excerpt_2_id,
6929 &buffer_2.read(cx).snapshot(),
6930 ranges[1].clone(),
6931 ),
6932 ];
6933
6934 let excerpts = snapshot
6935 .excerpts_in_ranges(ranges.into_iter())
6936 .map(|(excerpt_id, buffer, actual_range)| {
6937 (
6938 excerpt_id,
6939 buffer.remote_id(),
6940 map_range_from_excerpt(&snapshot, excerpt_id, buffer, actual_range),
6941 )
6942 })
6943 .collect_vec();
6944
6945 validate_excerpts(&excerpts, &expected_excerpts);
6946 }
6947
6948 #[gpui::test]
6949 fn test_split_ranges(cx: &mut AppContext) {
6950 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
6951 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
6952 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
6953 multibuffer.update(cx, |multibuffer, cx| {
6954 multibuffer.push_excerpts(
6955 buffer_1.clone(),
6956 [ExcerptRange {
6957 context: 0..buffer_1.read(cx).len(),
6958 primary: None,
6959 }],
6960 cx,
6961 );
6962 multibuffer.push_excerpts(
6963 buffer_2.clone(),
6964 [ExcerptRange {
6965 context: 0..buffer_2.read(cx).len(),
6966 primary: None,
6967 }],
6968 cx,
6969 );
6970 });
6971
6972 let snapshot = multibuffer.read(cx).snapshot(cx);
6973
6974 let buffer_1_len = buffer_1.read(cx).len();
6975 let buffer_2_len = buffer_2.read(cx).len();
6976 let buffer_1_midpoint = buffer_1_len / 2;
6977 let buffer_2_start = buffer_1_len + '\n'.len_utf8();
6978 let buffer_2_midpoint = buffer_2_start + buffer_2_len / 2;
6979 let total_len = buffer_2_start + buffer_2_len;
6980
6981 let input_ranges = [
6982 0..buffer_1_midpoint,
6983 buffer_1_midpoint..buffer_2_midpoint,
6984 buffer_2_midpoint..total_len,
6985 ]
6986 .map(|range| snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end));
6987
6988 let actual_ranges = snapshot
6989 .split_ranges(input_ranges.into_iter())
6990 .map(|range| range.to_offset(&snapshot))
6991 .collect::<Vec<_>>();
6992
6993 let expected_ranges = vec![
6994 0..buffer_1_midpoint,
6995 buffer_1_midpoint..buffer_1_len,
6996 buffer_2_start..buffer_2_midpoint,
6997 buffer_2_midpoint..total_len,
6998 ];
6999
7000 assert_eq!(actual_ranges, expected_ranges);
7001 }
7002
7003 #[gpui::test]
7004 fn test_split_ranges_single_range_spanning_three_excerpts(cx: &mut AppContext) {
7005 let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
7006 let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
7007 let buffer_3 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'm'), cx));
7008 let multibuffer = cx.new_model(|_| MultiBuffer::new(Capability::ReadWrite));
7009 multibuffer.update(cx, |multibuffer, cx| {
7010 multibuffer.push_excerpts(
7011 buffer_1.clone(),
7012 [ExcerptRange {
7013 context: 0..buffer_1.read(cx).len(),
7014 primary: None,
7015 }],
7016 cx,
7017 );
7018 multibuffer.push_excerpts(
7019 buffer_2.clone(),
7020 [ExcerptRange {
7021 context: 0..buffer_2.read(cx).len(),
7022 primary: None,
7023 }],
7024 cx,
7025 );
7026 multibuffer.push_excerpts(
7027 buffer_3.clone(),
7028 [ExcerptRange {
7029 context: 0..buffer_3.read(cx).len(),
7030 primary: None,
7031 }],
7032 cx,
7033 );
7034 });
7035
7036 let snapshot = multibuffer.read(cx).snapshot(cx);
7037
7038 let buffer_1_len = buffer_1.read(cx).len();
7039 let buffer_2_len = buffer_2.read(cx).len();
7040 let buffer_3_len = buffer_3.read(cx).len();
7041 let buffer_2_start = buffer_1_len + '\n'.len_utf8();
7042 let buffer_3_start = buffer_2_start + buffer_2_len + '\n'.len_utf8();
7043 let buffer_1_midpoint = buffer_1_len / 2;
7044 let buffer_3_midpoint = buffer_3_start + buffer_3_len / 2;
7045
7046 let input_range =
7047 snapshot.anchor_before(buffer_1_midpoint)..snapshot.anchor_after(buffer_3_midpoint);
7048
7049 let actual_ranges = snapshot
7050 .split_ranges(std::iter::once(input_range))
7051 .map(|range| range.to_offset(&snapshot))
7052 .collect::<Vec<_>>();
7053
7054 let expected_ranges = vec![
7055 buffer_1_midpoint..buffer_1_len,
7056 buffer_2_start..buffer_2_start + buffer_2_len,
7057 buffer_3_start..buffer_3_midpoint,
7058 ];
7059
7060 assert_eq!(actual_ranges, expected_ranges);
7061 }
7062}