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