1mod anchor;
2
3pub use anchor::{Anchor, AnchorRangeExt};
4use anyhow::Result;
5use clock::ReplicaId;
6use collections::{HashMap, HashSet};
7use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task};
8use language::{
9 Buffer, BufferChunks, BufferSnapshot, Chunk, DiagnosticEntry, Event, File, Language, Selection,
10 ToOffset as _, ToPoint as _, TransactionId,
11};
12use std::{
13 cell::{Ref, RefCell},
14 cmp, fmt, io,
15 iter::{self, FromIterator},
16 ops::{Range, Sub},
17 str,
18 sync::Arc,
19 time::{Duration, Instant},
20};
21use sum_tree::{Bias, Cursor, SumTree};
22use text::{
23 locator::Locator,
24 rope::TextDimension,
25 subscription::{Subscription, Topic},
26 AnchorRangeExt as _, Edit, Point, PointUtf16, TextSummary,
27};
28use theme::SyntaxTheme;
29use util::post_inc;
30
31const NEWLINES: &'static [u8] = &[b'\n'; u8::MAX as usize];
32
33pub type ExcerptId = Locator;
34
35pub struct MultiBuffer {
36 snapshot: RefCell<MultiBufferSnapshot>,
37 buffers: RefCell<HashMap<usize, BufferState>>,
38 subscriptions: Topic,
39 singleton: bool,
40 replica_id: ReplicaId,
41 history: History,
42}
43
44struct History {
45 next_transaction_id: usize,
46 undo_stack: Vec<Transaction>,
47 redo_stack: Vec<Transaction>,
48 transaction_depth: usize,
49 group_interval: Duration,
50}
51
52struct Transaction {
53 id: usize,
54 buffer_transactions: HashSet<(usize, text::TransactionId)>,
55 first_edit_at: Instant,
56 last_edit_at: Instant,
57}
58
59pub trait ToOffset: 'static + fmt::Debug {
60 fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
61}
62
63pub trait ToPoint: 'static + fmt::Debug {
64 fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
65}
66
67struct BufferState {
68 buffer: ModelHandle<Buffer>,
69 last_version: clock::Global,
70 last_parse_count: usize,
71 last_diagnostics_update_count: usize,
72 excerpts: Vec<ExcerptId>,
73 _subscriptions: [gpui::Subscription; 2],
74}
75
76#[derive(Clone, Default)]
77pub struct MultiBufferSnapshot {
78 excerpts: SumTree<Excerpt>,
79 parse_count: usize,
80 diagnostics_update_count: usize,
81 is_dirty: bool,
82 has_conflict: bool,
83}
84
85pub struct ExcerptProperties<'a, T> {
86 pub buffer: &'a ModelHandle<Buffer>,
87 pub range: Range<T>,
88}
89
90#[derive(Clone)]
91struct Excerpt {
92 id: ExcerptId,
93 buffer_id: usize,
94 buffer: BufferSnapshot,
95 range: Range<text::Anchor>,
96 max_buffer_row: u32,
97 text_summary: TextSummary,
98 has_trailing_newline: bool,
99}
100
101#[derive(Clone, Debug, Default)]
102struct ExcerptSummary {
103 excerpt_id: ExcerptId,
104 max_buffer_row: u32,
105 text: TextSummary,
106}
107
108pub struct MultiBufferRows<'a> {
109 buffer_row_range: Range<u32>,
110 excerpts: Cursor<'a, Excerpt, Point>,
111}
112
113pub struct MultiBufferChunks<'a> {
114 range: Range<usize>,
115 excerpts: Cursor<'a, Excerpt, usize>,
116 excerpt_chunks: Option<ExcerptChunks<'a>>,
117 theme: Option<&'a SyntaxTheme>,
118}
119
120pub struct MultiBufferBytes<'a> {
121 range: Range<usize>,
122 excerpts: Cursor<'a, Excerpt, usize>,
123 excerpt_bytes: Option<ExcerptBytes<'a>>,
124 chunk: &'a [u8],
125}
126
127struct ExcerptChunks<'a> {
128 content_chunks: BufferChunks<'a>,
129 footer_height: usize,
130}
131
132struct ExcerptBytes<'a> {
133 content_bytes: language::rope::Bytes<'a>,
134 footer_height: usize,
135}
136
137impl MultiBuffer {
138 pub fn new(replica_id: ReplicaId) -> Self {
139 Self {
140 snapshot: Default::default(),
141 buffers: Default::default(),
142 subscriptions: Default::default(),
143 singleton: false,
144 replica_id,
145 history: History {
146 next_transaction_id: Default::default(),
147 undo_stack: Default::default(),
148 redo_stack: Default::default(),
149 transaction_depth: 0,
150 group_interval: Duration::from_millis(300),
151 },
152 }
153 }
154
155 pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
156 let mut this = Self::new(buffer.read(cx).replica_id());
157 this.singleton = true;
158 this.push_excerpt(
159 ExcerptProperties {
160 buffer: &buffer,
161 range: text::Anchor::min()..text::Anchor::max(),
162 },
163 cx,
164 );
165 this
166 }
167
168 #[cfg(any(test, feature = "test-support"))]
169 pub fn build_simple(text: &str, cx: &mut gpui::MutableAppContext) -> ModelHandle<Self> {
170 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
171 cx.add_model(|cx| Self::singleton(buffer, cx))
172 }
173
174 #[cfg(any(test, feature = "test-support"))]
175 pub fn build_random(
176 mut rng: &mut impl rand::Rng,
177 cx: &mut gpui::MutableAppContext,
178 ) -> ModelHandle<Self> {
179 use rand::prelude::*;
180 use std::env;
181 use text::RandomCharIter;
182
183 let max_excerpts = env::var("MAX_EXCERPTS")
184 .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
185 .unwrap_or(5);
186 let excerpts = rng.gen_range(1..=max_excerpts);
187
188 cx.add_model(|cx| {
189 let mut multibuffer = MultiBuffer::new(0);
190 let mut buffers = Vec::new();
191 for _ in 0..excerpts {
192 let buffer_handle = if rng.gen() || buffers.is_empty() {
193 let text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
194 buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
195 let buffer = buffers.last().unwrap();
196 log::info!(
197 "Creating new buffer {} with text: {:?}",
198 buffer.id(),
199 buffer.read(cx).text()
200 );
201 buffers.last().unwrap()
202 } else {
203 buffers.choose(rng).unwrap()
204 };
205
206 let buffer = buffer_handle.read(cx);
207 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
208 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
209 let header_height = rng.gen_range(0..=5);
210 log::info!(
211 "Inserting excerpt from buffer {} with header height {} and range {:?}: {:?}",
212 buffer_handle.id(),
213 header_height,
214 start_ix..end_ix,
215 &buffer.text()[start_ix..end_ix]
216 );
217
218 multibuffer.push_excerpt(
219 ExcerptProperties {
220 buffer: buffer_handle,
221 range: start_ix..end_ix,
222 },
223 cx,
224 );
225 }
226 multibuffer
227 })
228 }
229
230 pub fn replica_id(&self) -> ReplicaId {
231 self.replica_id
232 }
233
234 pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
235 self.sync(cx);
236 self.snapshot.borrow().clone()
237 }
238
239 pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
240 self.sync(cx);
241 self.snapshot.borrow()
242 }
243
244 pub fn as_singleton(&self) -> Option<ModelHandle<Buffer>> {
245 if self.singleton {
246 return Some(
247 self.buffers
248 .borrow()
249 .values()
250 .next()
251 .unwrap()
252 .buffer
253 .clone(),
254 );
255 } else {
256 None
257 }
258 }
259
260 pub fn subscribe(&mut self) -> Subscription {
261 self.subscriptions.subscribe()
262 }
263
264 pub fn edit<I, S, T>(&mut self, ranges: I, new_text: T, cx: &mut ModelContext<Self>)
265 where
266 I: IntoIterator<Item = Range<S>>,
267 S: ToOffset,
268 T: Into<String>,
269 {
270 self.edit_internal(ranges, new_text, false, cx)
271 }
272
273 pub fn edit_with_autoindent<I, S, T>(
274 &mut self,
275 ranges: I,
276 new_text: T,
277 cx: &mut ModelContext<Self>,
278 ) where
279 I: IntoIterator<Item = Range<S>>,
280 S: ToOffset,
281 T: Into<String>,
282 {
283 self.edit_internal(ranges, new_text, true, cx)
284 }
285
286 pub fn edit_internal<I, S, T>(
287 &mut self,
288 ranges_iter: I,
289 new_text: T,
290 autoindent: bool,
291 cx: &mut ModelContext<Self>,
292 ) where
293 I: IntoIterator<Item = Range<S>>,
294 S: ToOffset,
295 T: Into<String>,
296 {
297 if let Some(buffer) = self.as_singleton() {
298 let snapshot = self.read(cx);
299 let ranges = ranges_iter
300 .into_iter()
301 .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot));
302 return buffer.update(cx, |buffer, cx| {
303 if autoindent {
304 buffer.edit_with_autoindent(ranges, new_text, cx)
305 } else {
306 buffer.edit(ranges, new_text, cx)
307 }
308 });
309 }
310
311 let snapshot = self.read(cx);
312 let mut buffer_edits: HashMap<usize, Vec<(Range<usize>, bool)>> = Default::default();
313 let mut cursor = snapshot.excerpts.cursor::<usize>();
314 for range in ranges_iter {
315 let start = range.start.to_offset(&snapshot);
316 let end = range.end.to_offset(&snapshot);
317 cursor.seek(&start, Bias::Right, &());
318 if cursor.item().is_none() && start == *cursor.start() {
319 cursor.prev(&());
320 }
321 let start_excerpt = cursor.item().expect("start offset out of bounds");
322 let start_overshoot = start - cursor.start();
323 let buffer_start =
324 start_excerpt.range.start.to_offset(&start_excerpt.buffer) + start_overshoot;
325
326 cursor.seek(&end, Bias::Right, &());
327 if cursor.item().is_none() && end == *cursor.start() {
328 cursor.prev(&());
329 }
330 let end_excerpt = cursor.item().expect("end offset out of bounds");
331 let end_overshoot = end - cursor.start();
332 let buffer_end = end_excerpt.range.start.to_offset(&end_excerpt.buffer) + end_overshoot;
333
334 if start_excerpt.id == end_excerpt.id {
335 buffer_edits
336 .entry(start_excerpt.buffer_id)
337 .or_insert(Vec::new())
338 .push((buffer_start..buffer_end, true));
339 } else {
340 let start_excerpt_range =
341 buffer_start..start_excerpt.range.end.to_offset(&start_excerpt.buffer);
342 let end_excerpt_range =
343 end_excerpt.range.start.to_offset(&end_excerpt.buffer)..buffer_end;
344 buffer_edits
345 .entry(start_excerpt.buffer_id)
346 .or_insert(Vec::new())
347 .push((start_excerpt_range, true));
348 buffer_edits
349 .entry(end_excerpt.buffer_id)
350 .or_insert(Vec::new())
351 .push((end_excerpt_range, false));
352
353 cursor.seek(&start, Bias::Right, &());
354 cursor.next(&());
355 while let Some(excerpt) = cursor.item() {
356 if excerpt.id == end_excerpt.id {
357 break;
358 }
359 buffer_edits
360 .entry(excerpt.buffer_id)
361 .or_insert(Vec::new())
362 .push((excerpt.range.to_offset(&excerpt.buffer), false));
363 cursor.next(&());
364 }
365 }
366 }
367
368 let new_text = new_text.into();
369 for (buffer_id, mut edits) in buffer_edits {
370 edits.sort_unstable_by_key(|(range, _)| range.start);
371 self.buffers.borrow()[&buffer_id]
372 .buffer
373 .update(cx, |buffer, cx| {
374 let mut edits = edits.into_iter().peekable();
375 let mut insertions = Vec::new();
376 let mut deletions = Vec::new();
377 while let Some((mut range, mut is_insertion)) = edits.next() {
378 while let Some((next_range, next_is_insertion)) = edits.peek() {
379 if range.end >= next_range.start {
380 range.end = cmp::max(next_range.end, range.end);
381 is_insertion |= *next_is_insertion;
382 edits.next();
383 } else {
384 break;
385 }
386 }
387
388 if is_insertion {
389 insertions.push(
390 buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
391 );
392 } else if !range.is_empty() {
393 deletions.push(
394 buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
395 );
396 }
397 }
398
399 if autoindent {
400 buffer.edit_with_autoindent(deletions, "", cx);
401 buffer.edit_with_autoindent(insertions, new_text.clone(), cx);
402 } else {
403 buffer.edit(deletions, "", cx);
404 buffer.edit(insertions, new_text.clone(), cx);
405 }
406 })
407 }
408 }
409
410 pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
411 self.start_transaction_at(Instant::now(), cx)
412 }
413
414 pub(crate) fn start_transaction_at(
415 &mut self,
416 now: Instant,
417 cx: &mut ModelContext<Self>,
418 ) -> Option<TransactionId> {
419 if let Some(buffer) = self.as_singleton() {
420 return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
421 }
422
423 for BufferState { buffer, .. } in self.buffers.borrow().values() {
424 buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
425 }
426 self.history.start_transaction(now)
427 }
428
429 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
430 self.end_transaction_at(Instant::now(), cx)
431 }
432
433 pub(crate) fn end_transaction_at(
434 &mut self,
435 now: Instant,
436 cx: &mut ModelContext<Self>,
437 ) -> Option<TransactionId> {
438 if let Some(buffer) = self.as_singleton() {
439 return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
440 }
441
442 let mut buffer_transactions = HashSet::default();
443 for BufferState { buffer, .. } in self.buffers.borrow().values() {
444 if let Some(transaction_id) =
445 buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
446 {
447 buffer_transactions.insert((buffer.id(), transaction_id));
448 }
449 }
450
451 if self.history.end_transaction(now, buffer_transactions) {
452 let transaction_id = self.history.group().unwrap();
453 Some(transaction_id)
454 } else {
455 None
456 }
457 }
458
459 pub fn set_active_selections(
460 &mut self,
461 selections: &[Selection<Anchor>],
462 cx: &mut ModelContext<Self>,
463 ) {
464 let mut selections_by_buffer: HashMap<usize, Vec<Selection<text::Anchor>>> =
465 Default::default();
466 let snapshot = self.read(cx);
467 let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
468 for selection in selections {
469 cursor.seek(&Some(&selection.start.excerpt_id), Bias::Left, &());
470 while let Some(excerpt) = cursor.item() {
471 if excerpt.id > selection.end.excerpt_id {
472 break;
473 }
474
475 let mut start = excerpt.range.start.clone();
476 let mut end = excerpt.range.end.clone();
477 if excerpt.id == selection.start.excerpt_id {
478 start = selection.start.text_anchor.clone();
479 }
480 if excerpt.id == selection.end.excerpt_id {
481 end = selection.end.text_anchor.clone();
482 }
483 selections_by_buffer
484 .entry(excerpt.buffer_id)
485 .or_default()
486 .push(Selection {
487 id: selection.id,
488 start,
489 end,
490 reversed: selection.reversed,
491 goal: selection.goal,
492 });
493
494 cursor.next(&());
495 }
496 }
497
498 for (buffer_id, mut selections) in selections_by_buffer {
499 self.buffers.borrow()[&buffer_id]
500 .buffer
501 .update(cx, |buffer, cx| {
502 selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer).unwrap());
503 let mut selections = selections.into_iter().peekable();
504 let merged_selections = Arc::from_iter(iter::from_fn(|| {
505 let mut selection = selections.next()?;
506 while let Some(next_selection) = selections.peek() {
507 if selection
508 .end
509 .cmp(&next_selection.start, buffer)
510 .unwrap()
511 .is_ge()
512 {
513 let next_selection = selections.next().unwrap();
514 if next_selection
515 .end
516 .cmp(&selection.end, buffer)
517 .unwrap()
518 .is_ge()
519 {
520 selection.end = next_selection.end;
521 }
522 } else {
523 break;
524 }
525 }
526 Some(selection)
527 }));
528 buffer.set_active_selections(merged_selections, cx);
529 });
530 }
531 }
532
533 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
534 for buffer in self.buffers.borrow().values() {
535 buffer
536 .buffer
537 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
538 }
539 }
540
541 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
542 if let Some(buffer) = self.as_singleton() {
543 return buffer.update(cx, |buffer, cx| buffer.undo(cx));
544 }
545
546 while let Some(transaction) = self.history.pop_undo() {
547 let mut undone = false;
548 for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
549 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(&buffer_id) {
550 undone |= buffer.update(cx, |buf, cx| {
551 buf.undo_transaction(*buffer_transaction_id, cx)
552 });
553 }
554 }
555
556 if undone {
557 return Some(transaction.id);
558 }
559 }
560
561 None
562 }
563
564 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
565 if let Some(buffer) = self.as_singleton() {
566 return buffer.update(cx, |buffer, cx| buffer.redo(cx));
567 }
568
569 while let Some(transaction) = self.history.pop_redo() {
570 let mut redone = false;
571 for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
572 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(&buffer_id) {
573 redone |= buffer.update(cx, |buf, cx| {
574 buf.redo_transaction(*buffer_transaction_id, cx)
575 });
576 }
577 }
578
579 if redone {
580 return Some(transaction.id);
581 }
582 }
583
584 None
585 }
586
587 pub fn push_excerpt<O>(
588 &mut self,
589 props: ExcerptProperties<O>,
590 cx: &mut ModelContext<Self>,
591 ) -> ExcerptId
592 where
593 O: text::ToOffset,
594 {
595 self.insert_excerpt_after(&ExcerptId::max(), props, cx)
596 }
597
598 pub fn insert_excerpt_after<O>(
599 &mut self,
600 prev_excerpt_id: &ExcerptId,
601 props: ExcerptProperties<O>,
602 cx: &mut ModelContext<Self>,
603 ) -> ExcerptId
604 where
605 O: text::ToOffset,
606 {
607 assert_eq!(self.history.transaction_depth, 0);
608 self.sync(cx);
609
610 let buffer_snapshot = props.buffer.read(cx).snapshot();
611 let range = buffer_snapshot.anchor_before(&props.range.start)
612 ..buffer_snapshot.anchor_after(&props.range.end);
613 let mut snapshot = self.snapshot.borrow_mut();
614 let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
615 let mut new_excerpts = cursor.slice(&Some(prev_excerpt_id), Bias::Right, &());
616
617 let mut prev_id = ExcerptId::min();
618 let edit_start = new_excerpts.summary().text.bytes;
619 new_excerpts.update_last(
620 |excerpt| {
621 excerpt.has_trailing_newline = true;
622 prev_id = excerpt.id.clone();
623 },
624 &(),
625 );
626
627 let mut next_id = ExcerptId::max();
628 if let Some(next_excerpt) = cursor.item() {
629 next_id = next_excerpt.id.clone();
630 }
631
632 let id = ExcerptId::between(&prev_id, &next_id);
633
634 let mut buffers = self.buffers.borrow_mut();
635 let buffer_state = buffers
636 .entry(props.buffer.id())
637 .or_insert_with(|| BufferState {
638 last_version: buffer_snapshot.version().clone(),
639 last_parse_count: buffer_snapshot.parse_count(),
640 last_diagnostics_update_count: buffer_snapshot.diagnostics_update_count(),
641 excerpts: Default::default(),
642 _subscriptions: [
643 cx.observe(&props.buffer, |_, _, cx| cx.notify()),
644 cx.subscribe(&props.buffer, Self::on_buffer_event),
645 ],
646 buffer: props.buffer.clone(),
647 });
648 if let Err(ix) = buffer_state.excerpts.binary_search(&id) {
649 buffer_state.excerpts.insert(ix, id.clone());
650 }
651
652 let excerpt = Excerpt::new(
653 id.clone(),
654 props.buffer.id(),
655 buffer_snapshot,
656 range,
657 cursor.item().is_some(),
658 );
659 new_excerpts.push(excerpt, &());
660 let edit_end = new_excerpts.summary().text.bytes;
661
662 new_excerpts.push_tree(cursor.suffix(&()), &());
663 drop(cursor);
664 snapshot.excerpts = new_excerpts;
665
666 self.subscriptions.publish_mut([Edit {
667 old: edit_start..edit_start,
668 new: edit_start..edit_end,
669 }]);
670
671 cx.notify();
672 id
673 }
674
675 pub fn excerpt_ids_for_buffer(&self, buffer: &ModelHandle<Buffer>) -> Vec<ExcerptId> {
676 self.buffers
677 .borrow()
678 .get(&buffer.id())
679 .map_or(Vec::new(), |state| state.excerpts.clone())
680 }
681
682 pub fn remove_excerpts<'a>(
683 &mut self,
684 excerpt_ids: impl IntoIterator<Item = &'a ExcerptId>,
685 cx: &mut ModelContext<Self>,
686 ) {
687 let mut buffers = self.buffers.borrow_mut();
688 let mut snapshot = self.snapshot.borrow_mut();
689 let mut new_excerpts = SumTree::new();
690 let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
691 let mut edits = Vec::new();
692 for excerpt_id in excerpt_ids {
693 new_excerpts.push_tree(cursor.slice(&Some(excerpt_id), Bias::Left, &()), &());
694 if let Some(excerpt) = cursor.item() {
695 if excerpt.id == *excerpt_id {
696 let mut old_start = cursor.start().1;
697 let old_end = cursor.end(&()).1;
698 cursor.next(&());
699
700 if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
701 buffer_state.excerpts.retain(|id| id != excerpt_id);
702 }
703
704 // When removing the last excerpt, remove the trailing newline from
705 // the previous excerpt.
706 if cursor.item().is_none() && old_start > 0 {
707 old_start -= 1;
708 new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
709 }
710
711 let new_start = new_excerpts.summary().text.bytes;
712 edits.push(Edit {
713 old: old_start..old_end,
714 new: new_start..new_start,
715 });
716 }
717 }
718 }
719 new_excerpts.push_tree(cursor.suffix(&()), &());
720 drop(cursor);
721 snapshot.excerpts = new_excerpts;
722 self.subscriptions.publish_mut(edits);
723 cx.notify();
724 }
725
726 fn on_buffer_event(
727 &mut self,
728 _: ModelHandle<Buffer>,
729 event: &Event,
730 cx: &mut ModelContext<Self>,
731 ) {
732 cx.emit(event.clone());
733 }
734
735 pub fn save(&mut self, cx: &mut ModelContext<Self>) -> Result<Task<Result<()>>> {
736 let mut save_tasks = Vec::new();
737 for BufferState { buffer, .. } in self.buffers.borrow().values() {
738 save_tasks.push(buffer.update(cx, |buffer, cx| buffer.save(cx))?);
739 }
740
741 Ok(cx.spawn(|_, _| async move {
742 for save in save_tasks {
743 save.await?;
744 }
745 Ok(())
746 }))
747 }
748
749 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
750 self.buffers
751 .borrow()
752 .values()
753 .next()
754 .and_then(|state| state.buffer.read(cx).language())
755 }
756
757 pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
758 self.as_singleton()?.read(cx).file()
759 }
760
761 #[cfg(test)]
762 pub fn is_parsing(&self, cx: &AppContext) -> bool {
763 self.as_singleton().unwrap().read(cx).is_parsing()
764 }
765
766 fn sync(&self, cx: &AppContext) {
767 let mut snapshot = self.snapshot.borrow_mut();
768 let mut excerpts_to_edit = Vec::new();
769 let mut reparsed = false;
770 let mut diagnostics_updated = false;
771 let mut is_dirty = false;
772 let mut has_conflict = false;
773 let mut buffers = self.buffers.borrow_mut();
774 for buffer_state in buffers.values_mut() {
775 let buffer = buffer_state.buffer.read(cx);
776 let version = buffer.version();
777 let parse_count = buffer.parse_count();
778 let diagnostics_update_count = buffer.diagnostics_update_count();
779
780 let buffer_edited = version.gt(&buffer_state.last_version);
781 let buffer_reparsed = parse_count > buffer_state.last_parse_count;
782 let buffer_diagnostics_updated =
783 diagnostics_update_count > buffer_state.last_diagnostics_update_count;
784 if buffer_edited || buffer_reparsed || buffer_diagnostics_updated {
785 buffer_state.last_version = version;
786 buffer_state.last_parse_count = parse_count;
787 buffer_state.last_diagnostics_update_count = diagnostics_update_count;
788 excerpts_to_edit.extend(
789 buffer_state
790 .excerpts
791 .iter()
792 .map(|excerpt_id| (excerpt_id, buffer_state.buffer.clone(), buffer_edited)),
793 );
794 }
795
796 reparsed |= buffer_reparsed;
797 diagnostics_updated |= buffer_diagnostics_updated;
798 is_dirty |= buffer.is_dirty();
799 has_conflict |= buffer.has_conflict();
800 }
801 if reparsed {
802 snapshot.parse_count += 1;
803 }
804 if diagnostics_updated {
805 snapshot.diagnostics_update_count += 1;
806 }
807 snapshot.is_dirty = is_dirty;
808 snapshot.has_conflict = has_conflict;
809
810 excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
811
812 let mut edits = Vec::new();
813 let mut new_excerpts = SumTree::new();
814 let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
815
816 for (id, buffer, buffer_edited) in excerpts_to_edit {
817 new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
818 let old_excerpt = cursor.item().unwrap();
819 let buffer_id = buffer.id();
820 let buffer = buffer.read(cx);
821
822 let mut new_excerpt;
823 if buffer_edited {
824 edits.extend(
825 buffer
826 .edits_since_in_range::<usize>(
827 old_excerpt.buffer.version(),
828 old_excerpt.range.clone(),
829 )
830 .map(|mut edit| {
831 let excerpt_old_start = cursor.start().1;
832 let excerpt_new_start = new_excerpts.summary().text.bytes;
833 edit.old.start += excerpt_old_start;
834 edit.old.end += excerpt_old_start;
835 edit.new.start += excerpt_new_start;
836 edit.new.end += excerpt_new_start;
837 edit
838 }),
839 );
840
841 new_excerpt = Excerpt::new(
842 id.clone(),
843 buffer_id,
844 buffer.snapshot(),
845 old_excerpt.range.clone(),
846 old_excerpt.has_trailing_newline,
847 );
848 } else {
849 new_excerpt = old_excerpt.clone();
850 new_excerpt.buffer = buffer.snapshot();
851 }
852
853 new_excerpts.push(new_excerpt, &());
854 cursor.next(&());
855 }
856 new_excerpts.push_tree(cursor.suffix(&()), &());
857
858 drop(cursor);
859 snapshot.excerpts = new_excerpts;
860
861 self.subscriptions.publish(edits);
862 }
863}
864
865#[cfg(any(test, feature = "test-support"))]
866impl MultiBuffer {
867 pub fn randomly_edit(
868 &mut self,
869 rng: &mut impl rand::Rng,
870 count: usize,
871 cx: &mut ModelContext<Self>,
872 ) {
873 use text::RandomCharIter;
874
875 let snapshot = self.read(cx);
876 let mut old_ranges: Vec<Range<usize>> = Vec::new();
877 for _ in 0..count {
878 let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
879 if last_end > snapshot.len() {
880 break;
881 }
882 let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
883 let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
884 old_ranges.push(start_ix..end_ix);
885 }
886 let new_text_len = rng.gen_range(0..10);
887 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
888 log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
889 drop(snapshot);
890
891 self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
892 }
893}
894
895impl Entity for MultiBuffer {
896 type Event = language::Event;
897}
898
899impl MultiBufferSnapshot {
900 pub fn text(&self) -> String {
901 self.chunks(0..self.len(), None)
902 .map(|chunk| chunk.text)
903 .collect()
904 }
905
906 pub fn reversed_chars_at<'a, T: ToOffset>(
907 &'a self,
908 position: T,
909 ) -> impl Iterator<Item = char> + 'a {
910 let mut offset = position.to_offset(self);
911 let mut cursor = self.excerpts.cursor::<usize>();
912 cursor.seek(&offset, Bias::Left, &());
913 let mut excerpt_chunks = cursor.item().map(|excerpt| {
914 let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
915 let start = excerpt.range.start.to_offset(&excerpt.buffer);
916 let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
917 excerpt.buffer.reversed_chunks_in_range(start..end)
918 });
919 iter::from_fn(move || {
920 if offset == *cursor.start() {
921 cursor.prev(&());
922 let excerpt = cursor.item()?;
923 excerpt_chunks = Some(
924 excerpt
925 .buffer
926 .reversed_chunks_in_range(excerpt.range.clone()),
927 );
928 }
929
930 let excerpt = cursor.item().unwrap();
931 if offset == cursor.end(&()) && excerpt.has_trailing_newline {
932 offset -= 1;
933 Some("\n")
934 } else {
935 let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
936 offset -= chunk.len();
937 Some(chunk)
938 }
939 })
940 .flat_map(|c| c.chars().rev())
941 }
942
943 pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
944 let offset = position.to_offset(self);
945 self.text_for_range(offset..self.len())
946 .flat_map(|chunk| chunk.chars())
947 }
948
949 pub fn text_for_range<'a, T: ToOffset>(
950 &'a self,
951 range: Range<T>,
952 ) -> impl Iterator<Item = &'a str> {
953 self.chunks(range, None).map(|chunk| chunk.text)
954 }
955
956 pub fn is_line_blank(&self, row: u32) -> bool {
957 self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
958 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
959 }
960
961 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
962 where
963 T: ToOffset,
964 {
965 let position = position.to_offset(self);
966 position == self.clip_offset(position, Bias::Left)
967 && self
968 .bytes_in_range(position..self.len())
969 .flatten()
970 .copied()
971 .take(needle.len())
972 .eq(needle.bytes())
973 }
974
975 fn as_singleton(&self) -> Option<&BufferSnapshot> {
976 let mut excerpts = self.excerpts.iter();
977 let buffer = excerpts.next().map(|excerpt| &excerpt.buffer);
978 if excerpts.next().is_none() {
979 buffer
980 } else {
981 None
982 }
983 }
984
985 pub fn len(&self) -> usize {
986 self.excerpts.summary().text.bytes
987 }
988
989 pub fn max_buffer_row(&self) -> u32 {
990 self.excerpts.summary().max_buffer_row
991 }
992
993 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
994 let mut cursor = self.excerpts.cursor::<usize>();
995 cursor.seek(&offset, Bias::Right, &());
996 let overshoot = if let Some(excerpt) = cursor.item() {
997 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
998 let buffer_offset = excerpt
999 .buffer
1000 .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1001 buffer_offset.saturating_sub(excerpt_start)
1002 } else {
1003 0
1004 };
1005 cursor.start() + overshoot
1006 }
1007
1008 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1009 let mut cursor = self.excerpts.cursor::<Point>();
1010 cursor.seek(&point, Bias::Right, &());
1011 let overshoot = if let Some(excerpt) = cursor.item() {
1012 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1013 let buffer_point = excerpt
1014 .buffer
1015 .clip_point(excerpt_start + (point - cursor.start()), bias);
1016 buffer_point.saturating_sub(excerpt_start)
1017 } else {
1018 Point::zero()
1019 };
1020 *cursor.start() + overshoot
1021 }
1022
1023 pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1024 let mut cursor = self.excerpts.cursor::<PointUtf16>();
1025 cursor.seek(&point, Bias::Right, &());
1026 let overshoot = if let Some(excerpt) = cursor.item() {
1027 let excerpt_start = excerpt
1028 .buffer
1029 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1030 let buffer_point = excerpt
1031 .buffer
1032 .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1033 buffer_point.saturating_sub(excerpt_start)
1034 } else {
1035 PointUtf16::zero()
1036 };
1037 *cursor.start() + overshoot
1038 }
1039
1040 pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1041 let range = range.start.to_offset(self)..range.end.to_offset(self);
1042 let mut excerpts = self.excerpts.cursor::<usize>();
1043 excerpts.seek(&range.start, Bias::Right, &());
1044
1045 let mut chunk = &[][..];
1046 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1047 let mut excerpt_bytes = excerpt
1048 .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1049 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1050 Some(excerpt_bytes)
1051 } else {
1052 None
1053 };
1054
1055 MultiBufferBytes {
1056 range,
1057 excerpts,
1058 excerpt_bytes,
1059 chunk,
1060 }
1061 }
1062
1063 pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1064 let mut result = MultiBufferRows {
1065 buffer_row_range: 0..0,
1066 excerpts: self.excerpts.cursor(),
1067 };
1068 result.seek(start_row);
1069 result
1070 }
1071
1072 pub fn chunks<'a, T: ToOffset>(
1073 &'a self,
1074 range: Range<T>,
1075 theme: Option<&'a SyntaxTheme>,
1076 ) -> MultiBufferChunks<'a> {
1077 let range = range.start.to_offset(self)..range.end.to_offset(self);
1078 let mut chunks = MultiBufferChunks {
1079 range: range.clone(),
1080 excerpts: self.excerpts.cursor(),
1081 excerpt_chunks: None,
1082 theme,
1083 };
1084 chunks.seek(range.start);
1085 chunks
1086 }
1087
1088 pub fn offset_to_point(&self, offset: usize) -> Point {
1089 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1090 cursor.seek(&offset, Bias::Right, &());
1091 if let Some(excerpt) = cursor.item() {
1092 let (start_offset, start_point) = cursor.start();
1093 let overshoot = offset - start_offset;
1094 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1095 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1096 let buffer_point = excerpt
1097 .buffer
1098 .offset_to_point(excerpt_start_offset + overshoot);
1099 *start_point + (buffer_point - excerpt_start_point)
1100 } else {
1101 self.excerpts.summary().text.lines
1102 }
1103 }
1104
1105 pub fn point_to_offset(&self, point: Point) -> usize {
1106 let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1107 cursor.seek(&point, Bias::Right, &());
1108 if let Some(excerpt) = cursor.item() {
1109 let (start_point, start_offset) = cursor.start();
1110 let overshoot = point - start_point;
1111 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1112 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1113 let buffer_offset = excerpt
1114 .buffer
1115 .point_to_offset(excerpt_start_point + overshoot);
1116 *start_offset + buffer_offset - excerpt_start_offset
1117 } else {
1118 self.excerpts.summary().text.bytes
1119 }
1120 }
1121
1122 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1123 let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1124 cursor.seek(&point, Bias::Right, &());
1125 if let Some(excerpt) = cursor.item() {
1126 let (start_point, start_offset) = cursor.start();
1127 let overshoot = point - start_point;
1128 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1129 let excerpt_start_point = excerpt
1130 .buffer
1131 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1132 let buffer_offset = excerpt
1133 .buffer
1134 .point_utf16_to_offset(excerpt_start_point + overshoot);
1135 *start_offset + (buffer_offset - excerpt_start_offset)
1136 } else {
1137 self.excerpts.summary().text.bytes
1138 }
1139 }
1140
1141 pub fn indent_column_for_line(&self, row: u32) -> u32 {
1142 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1143 buffer
1144 .indent_column_for_line(range.start.row)
1145 .min(range.end.column)
1146 .saturating_sub(range.start.column)
1147 } else {
1148 0
1149 }
1150 }
1151
1152 pub fn line_len(&self, row: u32) -> u32 {
1153 if let Some((_, range)) = self.buffer_line_for_row(row) {
1154 range.end.column - range.start.column
1155 } else {
1156 0
1157 }
1158 }
1159
1160 fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1161 let mut cursor = self.excerpts.cursor::<Point>();
1162 cursor.seek(&Point::new(row, 0), Bias::Right, &());
1163 if let Some(excerpt) = cursor.item() {
1164 let overshoot = row - cursor.start().row;
1165 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1166 let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1167 let buffer_row = excerpt_start.row + overshoot;
1168 let line_start = Point::new(buffer_row, 0);
1169 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1170 return Some((
1171 &excerpt.buffer,
1172 line_start.max(excerpt_start)..line_end.min(excerpt_end),
1173 ));
1174 }
1175 None
1176 }
1177
1178 pub fn max_point(&self) -> Point {
1179 self.text_summary().lines
1180 }
1181
1182 pub fn text_summary(&self) -> TextSummary {
1183 self.excerpts.summary().text
1184 }
1185
1186 pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1187 where
1188 D: TextDimension,
1189 O: ToOffset,
1190 {
1191 let mut summary = D::default();
1192 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1193 let mut cursor = self.excerpts.cursor::<usize>();
1194 cursor.seek(&range.start, Bias::Right, &());
1195 if let Some(excerpt) = cursor.item() {
1196 let mut end_before_newline = cursor.end(&());
1197 if excerpt.has_trailing_newline {
1198 end_before_newline -= 1;
1199 }
1200
1201 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1202 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
1203 let end_in_excerpt =
1204 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
1205 summary.add_assign(
1206 &excerpt
1207 .buffer
1208 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1209 );
1210
1211 if range.end > end_before_newline {
1212 summary.add_assign(&D::from_text_summary(&TextSummary {
1213 bytes: 1,
1214 lines: Point::new(1 as u32, 0),
1215 lines_utf16: PointUtf16::new(1 as u32, 0),
1216 first_line_chars: 0,
1217 last_line_chars: 0,
1218 longest_row: 0,
1219 longest_row_chars: 0,
1220 }));
1221 }
1222
1223 cursor.next(&());
1224 }
1225
1226 if range.end > *cursor.start() {
1227 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1228 &range.end,
1229 Bias::Right,
1230 &(),
1231 )));
1232 if let Some(excerpt) = cursor.item() {
1233 range.end = cmp::max(*cursor.start(), range.end);
1234
1235 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1236 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
1237 summary.add_assign(
1238 &excerpt
1239 .buffer
1240 .text_summary_for_range(excerpt_start..end_in_excerpt),
1241 );
1242 }
1243 }
1244
1245 summary
1246 }
1247
1248 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1249 where
1250 D: TextDimension + Ord + Sub<D, Output = D>,
1251 {
1252 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1253 cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1254 if cursor.item().is_none() {
1255 cursor.next(&());
1256 }
1257
1258 let mut position = D::from_text_summary(&cursor.start().text);
1259 if let Some(excerpt) = cursor.item() {
1260 if excerpt.id == anchor.excerpt_id {
1261 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1262 let buffer_position = anchor.text_anchor.summary::<D>(&excerpt.buffer);
1263 if buffer_position > excerpt_buffer_start {
1264 position.add_assign(&(buffer_position - excerpt_buffer_start));
1265 }
1266 }
1267 }
1268 position
1269 }
1270
1271 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1272 where
1273 D: TextDimension + Ord + Sub<D, Output = D>,
1274 I: 'a + IntoIterator<Item = &'a Anchor>,
1275 {
1276 let mut anchors = anchors.into_iter().peekable();
1277 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1278 let mut summaries = Vec::new();
1279 while let Some(anchor) = anchors.peek() {
1280 let excerpt_id = &anchor.excerpt_id;
1281 let excerpt_anchors = iter::from_fn(|| {
1282 let anchor = anchors.peek()?;
1283 if anchor.excerpt_id == *excerpt_id {
1284 Some(&anchors.next().unwrap().text_anchor)
1285 } else {
1286 None
1287 }
1288 });
1289
1290 cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1291 if cursor.item().is_none() {
1292 cursor.next(&());
1293 }
1294
1295 let position = D::from_text_summary(&cursor.start().text);
1296 if let Some(excerpt) = cursor.item() {
1297 if excerpt.id == *excerpt_id {
1298 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1299 summaries.extend(
1300 excerpt
1301 .buffer
1302 .summaries_for_anchors::<D, _>(excerpt_anchors)
1303 .map(move |summary| {
1304 let mut position = position.clone();
1305 let excerpt_buffer_start = excerpt_buffer_start.clone();
1306 if summary > excerpt_buffer_start {
1307 position.add_assign(&(summary - excerpt_buffer_start));
1308 }
1309 position
1310 }),
1311 );
1312 continue;
1313 }
1314 }
1315
1316 summaries.extend(excerpt_anchors.map(|_| position.clone()));
1317 }
1318
1319 summaries
1320 }
1321
1322 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1323 self.anchor_at(position, Bias::Left)
1324 }
1325
1326 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1327 self.anchor_at(position, Bias::Right)
1328 }
1329
1330 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1331 let offset = position.to_offset(self);
1332 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1333 cursor.seek(&offset, Bias::Right, &());
1334 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1335 cursor.prev(&());
1336 }
1337 if let Some(excerpt) = cursor.item() {
1338 let mut overshoot = offset.saturating_sub(cursor.start().0);
1339 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1340 overshoot -= 1;
1341 bias = Bias::Right;
1342 }
1343
1344 let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1345 let text_anchor =
1346 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1347 Anchor {
1348 excerpt_id: excerpt.id.clone(),
1349 text_anchor,
1350 }
1351 } else if offset == 0 && bias == Bias::Left {
1352 Anchor::min()
1353 } else {
1354 Anchor::max()
1355 }
1356 }
1357
1358 pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1359 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1360 cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1361 if let Some(excerpt) = cursor.item() {
1362 if excerpt.id == excerpt_id {
1363 let text_anchor = excerpt.clip_anchor(text_anchor);
1364 drop(cursor);
1365 return Anchor {
1366 excerpt_id,
1367 text_anchor,
1368 };
1369 }
1370 }
1371 panic!("excerpt not found");
1372 }
1373
1374 pub fn parse_count(&self) -> usize {
1375 self.parse_count
1376 }
1377
1378 pub fn enclosing_bracket_ranges<T: ToOffset>(
1379 &self,
1380 range: Range<T>,
1381 ) -> Option<(Range<usize>, Range<usize>)> {
1382 let range = range.start.to_offset(self)..range.end.to_offset(self);
1383
1384 let mut cursor = self.excerpts.cursor::<usize>();
1385 cursor.seek(&range.start, Bias::Right, &());
1386 let start_excerpt = cursor.item();
1387
1388 cursor.seek(&range.end, Bias::Right, &());
1389 let end_excerpt = cursor.item();
1390
1391 start_excerpt
1392 .zip(end_excerpt)
1393 .and_then(|(start_excerpt, end_excerpt)| {
1394 if start_excerpt.id != end_excerpt.id {
1395 return None;
1396 }
1397
1398 let excerpt_buffer_start =
1399 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1400 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1401
1402 let start_in_buffer =
1403 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1404 let end_in_buffer =
1405 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1406 let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1407 .buffer
1408 .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1409
1410 if start_bracket_range.start >= excerpt_buffer_start
1411 && end_bracket_range.end < excerpt_buffer_end
1412 {
1413 start_bracket_range.start =
1414 cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
1415 start_bracket_range.end =
1416 cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
1417 end_bracket_range.start =
1418 cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
1419 end_bracket_range.end =
1420 cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
1421 Some((start_bracket_range, end_bracket_range))
1422 } else {
1423 None
1424 }
1425 })
1426 }
1427
1428 pub fn diagnostics_update_count(&self) -> usize {
1429 self.diagnostics_update_count
1430 }
1431
1432 pub fn language(&self) -> Option<&Arc<Language>> {
1433 self.excerpts
1434 .iter()
1435 .next()
1436 .and_then(|excerpt| excerpt.buffer.language())
1437 }
1438
1439 pub fn is_dirty(&self) -> bool {
1440 self.is_dirty
1441 }
1442
1443 pub fn has_conflict(&self) -> bool {
1444 self.has_conflict
1445 }
1446
1447 pub fn diagnostic_group<'a, O>(
1448 &'a self,
1449 group_id: usize,
1450 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1451 where
1452 O: text::FromAnchor + 'a,
1453 {
1454 self.as_singleton()
1455 .into_iter()
1456 .flat_map(move |buffer| buffer.diagnostic_group(group_id))
1457 }
1458
1459 pub fn diagnostics_in_range<'a, T, O>(
1460 &'a self,
1461 range: Range<T>,
1462 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1463 where
1464 T: 'a + ToOffset,
1465 O: 'a + text::FromAnchor,
1466 {
1467 self.as_singleton().into_iter().flat_map(move |buffer| {
1468 buffer.diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
1469 })
1470 }
1471
1472 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1473 let range = range.start.to_offset(self)..range.end.to_offset(self);
1474
1475 let mut cursor = self.excerpts.cursor::<usize>();
1476 cursor.seek(&range.start, Bias::Right, &());
1477 let start_excerpt = cursor.item();
1478
1479 cursor.seek(&range.end, Bias::Right, &());
1480 let end_excerpt = cursor.item();
1481
1482 start_excerpt
1483 .zip(end_excerpt)
1484 .and_then(|(start_excerpt, end_excerpt)| {
1485 if start_excerpt.id != end_excerpt.id {
1486 return None;
1487 }
1488
1489 let excerpt_buffer_start =
1490 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1491 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1492
1493 let start_in_buffer =
1494 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1495 let end_in_buffer =
1496 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1497 let mut ancestor_buffer_range = start_excerpt
1498 .buffer
1499 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
1500 ancestor_buffer_range.start =
1501 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
1502 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
1503
1504 let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
1505 let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
1506 Some(start..end)
1507 })
1508 }
1509
1510 fn buffer_snapshot_for_excerpt<'a>(
1511 &'a self,
1512 excerpt_id: &'a ExcerptId,
1513 ) -> Option<&'a BufferSnapshot> {
1514 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1515 cursor.seek(&Some(excerpt_id), Bias::Left, &());
1516 if let Some(excerpt) = cursor.item() {
1517 if excerpt.id == *excerpt_id {
1518 return Some(&excerpt.buffer);
1519 }
1520 }
1521 None
1522 }
1523
1524 pub fn remote_selections_in_range<'a>(
1525 &'a self,
1526 range: &'a Range<Anchor>,
1527 ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
1528 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1529 cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
1530 cursor
1531 .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
1532 .flat_map(move |excerpt| {
1533 let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
1534 if excerpt.id == range.start.excerpt_id {
1535 query_range.start = range.start.text_anchor.clone();
1536 }
1537 if excerpt.id == range.end.excerpt_id {
1538 query_range.end = range.end.text_anchor.clone();
1539 }
1540
1541 excerpt
1542 .buffer
1543 .remote_selections_in_range(query_range)
1544 .flat_map(move |(replica_id, selections)| {
1545 selections.map(move |selection| {
1546 let mut start = Anchor {
1547 excerpt_id: excerpt.id.clone(),
1548 text_anchor: selection.start.clone(),
1549 };
1550 let mut end = Anchor {
1551 excerpt_id: excerpt.id.clone(),
1552 text_anchor: selection.end.clone(),
1553 };
1554 if range.start.cmp(&start, self).unwrap().is_gt() {
1555 start = range.start.clone();
1556 }
1557 if range.end.cmp(&end, self).unwrap().is_lt() {
1558 end = range.end.clone();
1559 }
1560
1561 (
1562 replica_id,
1563 Selection {
1564 id: selection.id,
1565 start,
1566 end,
1567 reversed: selection.reversed,
1568 goal: selection.goal,
1569 },
1570 )
1571 })
1572 })
1573 })
1574 }
1575}
1576
1577impl History {
1578 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
1579 self.transaction_depth += 1;
1580 if self.transaction_depth == 1 {
1581 let id = post_inc(&mut self.next_transaction_id);
1582 self.undo_stack.push(Transaction {
1583 id,
1584 buffer_transactions: Default::default(),
1585 first_edit_at: now,
1586 last_edit_at: now,
1587 });
1588 Some(id)
1589 } else {
1590 None
1591 }
1592 }
1593
1594 fn end_transaction(
1595 &mut self,
1596 now: Instant,
1597 buffer_transactions: HashSet<(usize, TransactionId)>,
1598 ) -> bool {
1599 assert_ne!(self.transaction_depth, 0);
1600 self.transaction_depth -= 1;
1601 if self.transaction_depth == 0 {
1602 if buffer_transactions.is_empty() {
1603 self.undo_stack.pop();
1604 false
1605 } else {
1606 let transaction = self.undo_stack.last_mut().unwrap();
1607 transaction.last_edit_at = now;
1608 transaction.buffer_transactions.extend(buffer_transactions);
1609 true
1610 }
1611 } else {
1612 false
1613 }
1614 }
1615
1616 fn pop_undo(&mut self) -> Option<&Transaction> {
1617 assert_eq!(self.transaction_depth, 0);
1618 if let Some(transaction) = self.undo_stack.pop() {
1619 self.redo_stack.push(transaction);
1620 self.redo_stack.last()
1621 } else {
1622 None
1623 }
1624 }
1625
1626 fn pop_redo(&mut self) -> Option<&Transaction> {
1627 assert_eq!(self.transaction_depth, 0);
1628 if let Some(transaction) = self.redo_stack.pop() {
1629 self.undo_stack.push(transaction);
1630 self.undo_stack.last()
1631 } else {
1632 None
1633 }
1634 }
1635
1636 fn group(&mut self) -> Option<TransactionId> {
1637 let mut new_len = self.undo_stack.len();
1638 let mut transactions = self.undo_stack.iter_mut();
1639
1640 if let Some(mut transaction) = transactions.next_back() {
1641 while let Some(prev_transaction) = transactions.next_back() {
1642 if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
1643 {
1644 transaction = prev_transaction;
1645 new_len -= 1;
1646 } else {
1647 break;
1648 }
1649 }
1650 }
1651
1652 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
1653 if let Some(last_transaction) = transactions_to_keep.last_mut() {
1654 if let Some(transaction) = transactions_to_merge.last() {
1655 last_transaction.last_edit_at = transaction.last_edit_at;
1656 }
1657 }
1658
1659 self.undo_stack.truncate(new_len);
1660 self.undo_stack.last().map(|t| t.id)
1661 }
1662}
1663
1664impl Excerpt {
1665 fn new(
1666 id: ExcerptId,
1667 buffer_id: usize,
1668 buffer: BufferSnapshot,
1669 range: Range<text::Anchor>,
1670 has_trailing_newline: bool,
1671 ) -> Self {
1672 Excerpt {
1673 id,
1674 max_buffer_row: range.end.to_point(&buffer).row,
1675 text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
1676 buffer_id,
1677 buffer,
1678 range,
1679 has_trailing_newline,
1680 }
1681 }
1682
1683 fn chunks_in_range<'a>(
1684 &'a self,
1685 range: Range<usize>,
1686 theme: Option<&'a SyntaxTheme>,
1687 ) -> ExcerptChunks<'a> {
1688 let content_start = self.range.start.to_offset(&self.buffer);
1689 let chunks_start = content_start + range.start;
1690 let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
1691
1692 let footer_height = if self.has_trailing_newline
1693 && range.start <= self.text_summary.bytes
1694 && range.end > self.text_summary.bytes
1695 {
1696 1
1697 } else {
1698 0
1699 };
1700
1701 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, theme);
1702
1703 ExcerptChunks {
1704 content_chunks,
1705 footer_height,
1706 }
1707 }
1708
1709 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
1710 let content_start = self.range.start.to_offset(&self.buffer);
1711 let bytes_start = content_start + range.start;
1712 let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
1713 let footer_height = if self.has_trailing_newline
1714 && range.start <= self.text_summary.bytes
1715 && range.end > self.text_summary.bytes
1716 {
1717 1
1718 } else {
1719 0
1720 };
1721 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
1722
1723 ExcerptBytes {
1724 content_bytes,
1725 footer_height,
1726 }
1727 }
1728
1729 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
1730 if text_anchor
1731 .cmp(&self.range.start, &self.buffer)
1732 .unwrap()
1733 .is_lt()
1734 {
1735 self.range.start.clone()
1736 } else if text_anchor
1737 .cmp(&self.range.end, &self.buffer)
1738 .unwrap()
1739 .is_gt()
1740 {
1741 self.range.end.clone()
1742 } else {
1743 text_anchor
1744 }
1745 }
1746}
1747
1748impl fmt::Debug for Excerpt {
1749 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1750 f.debug_struct("Excerpt")
1751 .field("id", &self.id)
1752 .field("buffer_id", &self.buffer_id)
1753 .field("range", &self.range)
1754 .field("text_summary", &self.text_summary)
1755 .field("has_trailing_newline", &self.has_trailing_newline)
1756 .finish()
1757 }
1758}
1759
1760impl sum_tree::Item for Excerpt {
1761 type Summary = ExcerptSummary;
1762
1763 fn summary(&self) -> Self::Summary {
1764 let mut text = self.text_summary.clone();
1765 if self.has_trailing_newline {
1766 text += TextSummary::from("\n");
1767 }
1768 ExcerptSummary {
1769 excerpt_id: self.id.clone(),
1770 max_buffer_row: self.max_buffer_row,
1771 text,
1772 }
1773 }
1774}
1775
1776impl sum_tree::Summary for ExcerptSummary {
1777 type Context = ();
1778
1779 fn add_summary(&mut self, summary: &Self, _: &()) {
1780 debug_assert!(summary.excerpt_id > self.excerpt_id);
1781 self.excerpt_id = summary.excerpt_id.clone();
1782 self.text.add_summary(&summary.text, &());
1783 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
1784 }
1785}
1786
1787impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
1788 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1789 *self += &summary.text;
1790 }
1791}
1792
1793impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
1794 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1795 *self += summary.text.bytes;
1796 }
1797}
1798
1799impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
1800 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1801 Ord::cmp(self, &cursor_location.text.bytes)
1802 }
1803}
1804
1805impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
1806 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1807 Ord::cmp(self, &Some(&cursor_location.excerpt_id))
1808 }
1809}
1810
1811impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
1812 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1813 *self += summary.text.lines;
1814 }
1815}
1816
1817impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
1818 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1819 *self += summary.text.lines_utf16
1820 }
1821}
1822
1823impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
1824 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1825 *self = Some(&summary.excerpt_id);
1826 }
1827}
1828
1829impl<'a> MultiBufferRows<'a> {
1830 pub fn seek(&mut self, row: u32) {
1831 self.buffer_row_range = 0..0;
1832
1833 self.excerpts
1834 .seek_forward(&Point::new(row, 0), Bias::Right, &());
1835 if self.excerpts.item().is_none() {
1836 self.excerpts.prev(&());
1837
1838 if self.excerpts.item().is_none() && row == 0 {
1839 self.buffer_row_range = 0..1;
1840 return;
1841 }
1842 }
1843
1844 if let Some(excerpt) = self.excerpts.item() {
1845 let overshoot = row - self.excerpts.start().row;
1846 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
1847 self.buffer_row_range.start = excerpt_start + overshoot;
1848 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
1849 }
1850 }
1851}
1852
1853impl<'a> Iterator for MultiBufferRows<'a> {
1854 type Item = Option<u32>;
1855
1856 fn next(&mut self) -> Option<Self::Item> {
1857 loop {
1858 if !self.buffer_row_range.is_empty() {
1859 let row = Some(self.buffer_row_range.start);
1860 self.buffer_row_range.start += 1;
1861 return Some(row);
1862 }
1863 self.excerpts.item()?;
1864 self.excerpts.next(&());
1865 let excerpt = self.excerpts.item()?;
1866 self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
1867 self.buffer_row_range.end =
1868 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
1869 }
1870 }
1871}
1872
1873impl<'a> MultiBufferChunks<'a> {
1874 pub fn offset(&self) -> usize {
1875 self.range.start
1876 }
1877
1878 pub fn seek(&mut self, offset: usize) {
1879 self.range.start = offset;
1880 self.excerpts.seek(&offset, Bias::Right, &());
1881 if let Some(excerpt) = self.excerpts.item() {
1882 self.excerpt_chunks = Some(excerpt.chunks_in_range(
1883 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
1884 self.theme,
1885 ));
1886 } else {
1887 self.excerpt_chunks = None;
1888 }
1889 }
1890}
1891
1892impl<'a> Iterator for MultiBufferChunks<'a> {
1893 type Item = Chunk<'a>;
1894
1895 fn next(&mut self) -> Option<Self::Item> {
1896 if self.range.is_empty() {
1897 None
1898 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
1899 self.range.start += chunk.text.len();
1900 Some(chunk)
1901 } else {
1902 self.excerpts.next(&());
1903 let excerpt = self.excerpts.item()?;
1904 self.excerpt_chunks = Some(
1905 excerpt.chunks_in_range(0..self.range.end - self.excerpts.start(), self.theme),
1906 );
1907 self.next()
1908 }
1909 }
1910}
1911
1912impl<'a> MultiBufferBytes<'a> {
1913 fn consume(&mut self, len: usize) {
1914 self.range.start += len;
1915 self.chunk = &self.chunk[len..];
1916
1917 if !self.range.is_empty() && self.chunk.is_empty() {
1918 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
1919 self.chunk = chunk;
1920 } else {
1921 self.excerpts.next(&());
1922 if let Some(excerpt) = self.excerpts.item() {
1923 let mut excerpt_bytes =
1924 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
1925 self.chunk = excerpt_bytes.next().unwrap();
1926 self.excerpt_bytes = Some(excerpt_bytes);
1927 }
1928 }
1929 }
1930 }
1931}
1932
1933impl<'a> Iterator for MultiBufferBytes<'a> {
1934 type Item = &'a [u8];
1935
1936 fn next(&mut self) -> Option<Self::Item> {
1937 let chunk = self.chunk;
1938 if chunk.is_empty() {
1939 None
1940 } else {
1941 self.consume(chunk.len());
1942 Some(chunk)
1943 }
1944 }
1945}
1946
1947impl<'a> io::Read for MultiBufferBytes<'a> {
1948 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1949 let len = cmp::min(buf.len(), self.chunk.len());
1950 buf[..len].copy_from_slice(&self.chunk[..len]);
1951 if len > 0 {
1952 self.consume(len);
1953 }
1954 Ok(len)
1955 }
1956}
1957
1958impl<'a> Iterator for ExcerptBytes<'a> {
1959 type Item = &'a [u8];
1960
1961 fn next(&mut self) -> Option<Self::Item> {
1962 if let Some(chunk) = self.content_bytes.next() {
1963 if !chunk.is_empty() {
1964 return Some(chunk);
1965 }
1966 }
1967
1968 if self.footer_height > 0 {
1969 let result = &NEWLINES[..self.footer_height];
1970 self.footer_height = 0;
1971 return Some(result);
1972 }
1973
1974 None
1975 }
1976}
1977
1978impl<'a> Iterator for ExcerptChunks<'a> {
1979 type Item = Chunk<'a>;
1980
1981 fn next(&mut self) -> Option<Self::Item> {
1982 if let Some(chunk) = self.content_chunks.next() {
1983 return Some(chunk);
1984 }
1985
1986 if self.footer_height > 0 {
1987 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
1988 self.footer_height = 0;
1989 return Some(Chunk {
1990 text,
1991 ..Default::default()
1992 });
1993 }
1994
1995 None
1996 }
1997}
1998
1999impl ToOffset for Point {
2000 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2001 snapshot.point_to_offset(*self)
2002 }
2003}
2004
2005impl ToOffset for PointUtf16 {
2006 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2007 snapshot.point_utf16_to_offset(*self)
2008 }
2009}
2010
2011impl ToOffset for usize {
2012 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2013 assert!(*self <= snapshot.len(), "offset is out of range");
2014 *self
2015 }
2016}
2017
2018impl ToPoint for usize {
2019 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2020 snapshot.offset_to_point(*self)
2021 }
2022}
2023
2024impl ToPoint for Point {
2025 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2026 *self
2027 }
2028}
2029
2030#[cfg(test)]
2031mod tests {
2032 use super::*;
2033 use gpui::MutableAppContext;
2034 use language::{Buffer, Rope};
2035 use rand::prelude::*;
2036 use std::env;
2037 use text::{Point, RandomCharIter};
2038 use util::test::sample_text;
2039
2040 #[gpui::test]
2041 fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2042 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2043 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2044
2045 let snapshot = multibuffer.read(cx).snapshot(cx);
2046 assert_eq!(snapshot.text(), buffer.read(cx).text());
2047
2048 assert_eq!(
2049 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2050 (0..buffer.read(cx).row_count())
2051 .map(Some)
2052 .collect::<Vec<_>>()
2053 );
2054
2055 buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2056 let snapshot = multibuffer.read(cx).snapshot(cx);
2057
2058 assert_eq!(snapshot.text(), buffer.read(cx).text());
2059 assert_eq!(
2060 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2061 (0..buffer.read(cx).row_count())
2062 .map(Some)
2063 .collect::<Vec<_>>()
2064 );
2065 }
2066
2067 #[gpui::test]
2068 fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2069 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2070 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2071 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2072
2073 let subscription = multibuffer.update(cx, |multibuffer, cx| {
2074 let subscription = multibuffer.subscribe();
2075 multibuffer.push_excerpt(
2076 ExcerptProperties {
2077 buffer: &buffer_1,
2078 range: Point::new(1, 2)..Point::new(2, 5),
2079 },
2080 cx,
2081 );
2082 assert_eq!(
2083 subscription.consume().into_inner(),
2084 [Edit {
2085 old: 0..0,
2086 new: 0..10
2087 }]
2088 );
2089
2090 multibuffer.push_excerpt(
2091 ExcerptProperties {
2092 buffer: &buffer_1,
2093 range: Point::new(3, 3)..Point::new(4, 4),
2094 },
2095 cx,
2096 );
2097 multibuffer.push_excerpt(
2098 ExcerptProperties {
2099 buffer: &buffer_2,
2100 range: Point::new(3, 1)..Point::new(3, 3),
2101 },
2102 cx,
2103 );
2104 assert_eq!(
2105 subscription.consume().into_inner(),
2106 [Edit {
2107 old: 10..10,
2108 new: 10..22
2109 }]
2110 );
2111
2112 subscription
2113 });
2114
2115 let snapshot = multibuffer.read(cx).snapshot(cx);
2116 assert_eq!(
2117 snapshot.text(),
2118 concat!(
2119 "bbbb\n", // Preserve newlines
2120 "ccccc\n", //
2121 "ddd\n", //
2122 "eeee\n", //
2123 "jj" //
2124 )
2125 );
2126 assert_eq!(
2127 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2128 [Some(1), Some(2), Some(3), Some(4), Some(3)]
2129 );
2130 assert_eq!(
2131 snapshot.buffer_rows(2).collect::<Vec<_>>(),
2132 [Some(3), Some(4), Some(3)]
2133 );
2134 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2135 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2136
2137 buffer_1.update(cx, |buffer, cx| {
2138 buffer.edit(
2139 [
2140 Point::new(0, 0)..Point::new(0, 0),
2141 Point::new(2, 1)..Point::new(2, 3),
2142 ],
2143 "\n",
2144 cx,
2145 );
2146 });
2147
2148 let snapshot = multibuffer.read(cx).snapshot(cx);
2149 assert_eq!(
2150 snapshot.text(),
2151 concat!(
2152 "bbbb\n", // Preserve newlines
2153 "c\n", //
2154 "cc\n", //
2155 "ddd\n", //
2156 "eeee\n", //
2157 "jj" //
2158 )
2159 );
2160
2161 assert_eq!(
2162 subscription.consume().into_inner(),
2163 [Edit {
2164 old: 6..8,
2165 new: 6..7
2166 }]
2167 );
2168
2169 let snapshot = multibuffer.read(cx).snapshot(cx);
2170 assert_eq!(
2171 snapshot.clip_point(Point::new(0, 5), Bias::Left),
2172 Point::new(0, 4)
2173 );
2174 assert_eq!(
2175 snapshot.clip_point(Point::new(0, 5), Bias::Right),
2176 Point::new(0, 4)
2177 );
2178 assert_eq!(
2179 snapshot.clip_point(Point::new(5, 1), Bias::Right),
2180 Point::new(5, 1)
2181 );
2182 assert_eq!(
2183 snapshot.clip_point(Point::new(5, 2), Bias::Right),
2184 Point::new(5, 2)
2185 );
2186 assert_eq!(
2187 snapshot.clip_point(Point::new(5, 3), Bias::Right),
2188 Point::new(5, 2)
2189 );
2190
2191 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2192 let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2193 multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2194 multibuffer.snapshot(cx)
2195 });
2196
2197 assert_eq!(
2198 snapshot.text(),
2199 concat!(
2200 "bbbb\n", // Preserve newlines
2201 "c\n", //
2202 "cc\n", //
2203 "ddd\n", //
2204 "eeee", //
2205 )
2206 );
2207 }
2208
2209 #[gpui::test]
2210 fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2211 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2212
2213 let snapshot = multibuffer.read(cx).snapshot(cx);
2214 assert_eq!(snapshot.text(), "");
2215 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2216 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2217 }
2218
2219 #[gpui::test]
2220 fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2221 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2222 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2223 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2224 buffer.update(cx, |buffer, cx| {
2225 buffer.edit([0..0], "X", cx);
2226 buffer.edit([5..5], "Y", cx);
2227 });
2228 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2229
2230 assert_eq!(old_snapshot.text(), "abcd");
2231 assert_eq!(new_snapshot.text(), "XabcdY");
2232
2233 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2234 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2235 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2236 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2237 }
2238
2239 #[gpui::test]
2240 fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2241 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2242 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2243 let multibuffer = cx.add_model(|cx| {
2244 let mut multibuffer = MultiBuffer::new(0);
2245 multibuffer.push_excerpt(
2246 ExcerptProperties {
2247 buffer: &buffer_1,
2248 range: 0..4,
2249 },
2250 cx,
2251 );
2252 multibuffer.push_excerpt(
2253 ExcerptProperties {
2254 buffer: &buffer_2,
2255 range: 0..5,
2256 },
2257 cx,
2258 );
2259 multibuffer
2260 });
2261 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2262
2263 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
2264 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
2265 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2266 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2267 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2268 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2269
2270 buffer_1.update(cx, |buffer, cx| {
2271 buffer.edit([0..0], "W", cx);
2272 buffer.edit([5..5], "X", cx);
2273 });
2274 buffer_2.update(cx, |buffer, cx| {
2275 buffer.edit([0..0], "Y", cx);
2276 buffer.edit([6..0], "Z", cx);
2277 });
2278 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2279
2280 assert_eq!(old_snapshot.text(), "abcd\nefghi");
2281 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
2282
2283 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2284 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2285 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
2286 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2287 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2288 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2289 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
2290 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
2291 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
2292 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
2293 }
2294
2295 #[gpui::test(iterations = 100)]
2296 fn test_random_excerpts(cx: &mut MutableAppContext, mut rng: StdRng) {
2297 let operations = env::var("OPERATIONS")
2298 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2299 .unwrap_or(10);
2300
2301 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
2302 let list = cx.add_model(|_| MultiBuffer::new(0));
2303 let mut excerpt_ids = Vec::new();
2304 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
2305 let mut old_versions = Vec::new();
2306
2307 for _ in 0..operations {
2308 match rng.gen_range(0..100) {
2309 0..=19 if !buffers.is_empty() => {
2310 let buffer = buffers.choose(&mut rng).unwrap();
2311 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
2312 }
2313 20..=29 if !expected_excerpts.is_empty() => {
2314 let ix = rng.gen_range(0..expected_excerpts.len());
2315 let id = excerpt_ids.remove(ix);
2316 let (buffer, range) = expected_excerpts.remove(ix);
2317 let buffer = buffer.read(cx);
2318 log::info!(
2319 "Removing excerpt {}: {:?}",
2320 ix,
2321 buffer
2322 .text_for_range(range.to_offset(&buffer))
2323 .collect::<String>(),
2324 );
2325 list.update(cx, |list, cx| list.remove_excerpts(&[id], cx));
2326 }
2327 _ => {
2328 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2329 let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
2330 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
2331 buffers.last().unwrap()
2332 } else {
2333 buffers.choose(&mut rng).unwrap()
2334 };
2335
2336 let buffer = buffer_handle.read(cx);
2337 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
2338 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2339 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2340 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
2341 let prev_excerpt_id = excerpt_ids
2342 .get(prev_excerpt_ix)
2343 .cloned()
2344 .unwrap_or(ExcerptId::max());
2345 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
2346
2347 log::info!(
2348 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2349 excerpt_ix,
2350 expected_excerpts.len(),
2351 buffer_handle.id(),
2352 buffer.text(),
2353 start_ix..end_ix,
2354 &buffer.text()[start_ix..end_ix]
2355 );
2356
2357 let excerpt_id = list.update(cx, |list, cx| {
2358 list.insert_excerpt_after(
2359 &prev_excerpt_id,
2360 ExcerptProperties {
2361 buffer: &buffer_handle,
2362 range: start_ix..end_ix,
2363 },
2364 cx,
2365 )
2366 });
2367
2368 excerpt_ids.insert(excerpt_ix, excerpt_id);
2369 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
2370 }
2371 }
2372
2373 if rng.gen_bool(0.3) {
2374 list.update(cx, |list, cx| {
2375 old_versions.push((list.snapshot(cx), list.subscribe()));
2376 })
2377 }
2378
2379 let snapshot = list.read(cx).snapshot(cx);
2380
2381 let mut excerpt_starts = Vec::new();
2382 let mut expected_text = String::new();
2383 let mut expected_buffer_rows = Vec::new();
2384 for (buffer, range) in &expected_excerpts {
2385 let buffer = buffer.read(cx);
2386 let buffer_range = range.to_offset(buffer);
2387
2388 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
2389 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
2390 expected_text.push('\n');
2391
2392 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
2393 ..=buffer.offset_to_point(buffer_range.end).row;
2394 for row in buffer_row_range {
2395 expected_buffer_rows.push(Some(row));
2396 }
2397 }
2398 // Remove final trailing newline.
2399 if !expected_excerpts.is_empty() {
2400 expected_text.pop();
2401 }
2402
2403 // Always report one buffer row
2404 if expected_buffer_rows.is_empty() {
2405 expected_buffer_rows.push(Some(0));
2406 }
2407
2408 assert_eq!(snapshot.text(), expected_text);
2409 log::info!("MultiBuffer text: {:?}", expected_text);
2410
2411 assert_eq!(
2412 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2413 expected_buffer_rows,
2414 );
2415
2416 for _ in 0..5 {
2417 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
2418 assert_eq!(
2419 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
2420 &expected_buffer_rows[start_row..],
2421 "buffer_rows({})",
2422 start_row
2423 );
2424 }
2425
2426 assert_eq!(
2427 snapshot.max_buffer_row(),
2428 expected_buffer_rows
2429 .into_iter()
2430 .filter_map(|r| r)
2431 .max()
2432 .unwrap()
2433 );
2434
2435 let mut excerpt_starts = excerpt_starts.into_iter();
2436 for (buffer, range) in &expected_excerpts {
2437 let buffer_id = buffer.id();
2438 let buffer = buffer.read(cx);
2439 let buffer_range = range.to_offset(buffer);
2440 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
2441 let buffer_start_point_utf16 =
2442 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
2443
2444 let excerpt_start = excerpt_starts.next().unwrap();
2445 let mut offset = excerpt_start.bytes;
2446 let mut buffer_offset = buffer_range.start;
2447 let mut point = excerpt_start.lines;
2448 let mut buffer_point = buffer_start_point;
2449 let mut point_utf16 = excerpt_start.lines_utf16;
2450 let mut buffer_point_utf16 = buffer_start_point_utf16;
2451 for ch in buffer
2452 .snapshot()
2453 .chunks(buffer_range.clone(), None)
2454 .flat_map(|c| c.text.chars())
2455 {
2456 for _ in 0..ch.len_utf8() {
2457 let left_offset = snapshot.clip_offset(offset, Bias::Left);
2458 let right_offset = snapshot.clip_offset(offset, Bias::Right);
2459 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
2460 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
2461 assert_eq!(
2462 left_offset,
2463 excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
2464 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
2465 offset,
2466 buffer_id,
2467 buffer_offset,
2468 );
2469 assert_eq!(
2470 right_offset,
2471 excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
2472 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
2473 offset,
2474 buffer_id,
2475 buffer_offset,
2476 );
2477
2478 let left_point = snapshot.clip_point(point, Bias::Left);
2479 let right_point = snapshot.clip_point(point, Bias::Right);
2480 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
2481 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
2482 assert_eq!(
2483 left_point,
2484 excerpt_start.lines + (buffer_left_point - buffer_start_point),
2485 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
2486 point,
2487 buffer_id,
2488 buffer_point,
2489 );
2490 assert_eq!(
2491 right_point,
2492 excerpt_start.lines + (buffer_right_point - buffer_start_point),
2493 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
2494 point,
2495 buffer_id,
2496 buffer_point,
2497 );
2498
2499 assert_eq!(
2500 snapshot.point_to_offset(left_point),
2501 left_offset,
2502 "point_to_offset({:?})",
2503 left_point,
2504 );
2505 assert_eq!(
2506 snapshot.offset_to_point(left_offset),
2507 left_point,
2508 "offset_to_point({:?})",
2509 left_offset,
2510 );
2511
2512 offset += 1;
2513 buffer_offset += 1;
2514 if ch == '\n' {
2515 point += Point::new(1, 0);
2516 buffer_point += Point::new(1, 0);
2517 } else {
2518 point += Point::new(0, 1);
2519 buffer_point += Point::new(0, 1);
2520 }
2521 }
2522
2523 for _ in 0..ch.len_utf16() {
2524 let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
2525 let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
2526 let buffer_left_point_utf16 =
2527 buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
2528 let buffer_right_point_utf16 =
2529 buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
2530 assert_eq!(
2531 left_point_utf16,
2532 excerpt_start.lines_utf16
2533 + (buffer_left_point_utf16 - buffer_start_point_utf16),
2534 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
2535 point_utf16,
2536 buffer_id,
2537 buffer_point_utf16,
2538 );
2539 assert_eq!(
2540 right_point_utf16,
2541 excerpt_start.lines_utf16
2542 + (buffer_right_point_utf16 - buffer_start_point_utf16),
2543 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
2544 point_utf16,
2545 buffer_id,
2546 buffer_point_utf16,
2547 );
2548
2549 if ch == '\n' {
2550 point_utf16 += PointUtf16::new(1, 0);
2551 buffer_point_utf16 += PointUtf16::new(1, 0);
2552 } else {
2553 point_utf16 += PointUtf16::new(0, 1);
2554 buffer_point_utf16 += PointUtf16::new(0, 1);
2555 }
2556 }
2557 }
2558 }
2559
2560 for (row, line) in expected_text.split('\n').enumerate() {
2561 assert_eq!(
2562 snapshot.line_len(row as u32),
2563 line.len() as u32,
2564 "line_len({}).",
2565 row
2566 );
2567 }
2568
2569 let text_rope = Rope::from(expected_text.as_str());
2570 for _ in 0..10 {
2571 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2572 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2573
2574 assert_eq!(
2575 snapshot
2576 .text_for_range(start_ix..end_ix)
2577 .collect::<String>(),
2578 &expected_text[start_ix..end_ix],
2579 "incorrect text for range {:?}",
2580 start_ix..end_ix
2581 );
2582
2583 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
2584 assert_eq!(
2585 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
2586 expected_summary,
2587 "incorrect summary for range {:?}",
2588 start_ix..end_ix
2589 );
2590 }
2591
2592 for _ in 0..10 {
2593 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2594 assert_eq!(
2595 snapshot.reversed_chars_at(end_ix).collect::<String>(),
2596 expected_text[..end_ix].chars().rev().collect::<String>(),
2597 );
2598 }
2599
2600 for _ in 0..10 {
2601 let end_ix = rng.gen_range(0..=text_rope.len());
2602 let start_ix = rng.gen_range(0..=end_ix);
2603 assert_eq!(
2604 snapshot
2605 .bytes_in_range(start_ix..end_ix)
2606 .flatten()
2607 .copied()
2608 .collect::<Vec<_>>(),
2609 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
2610 "bytes_in_range({:?})",
2611 start_ix..end_ix,
2612 );
2613 }
2614 }
2615
2616 let snapshot = list.read(cx).snapshot(cx);
2617 for (old_snapshot, subscription) in old_versions {
2618 let edits = subscription.consume().into_inner();
2619
2620 log::info!(
2621 "applying subscription edits to old text: {:?}: {:?}",
2622 old_snapshot.text(),
2623 edits,
2624 );
2625
2626 let mut text = old_snapshot.text();
2627 for edit in edits {
2628 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
2629 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
2630 }
2631 assert_eq!(text.to_string(), snapshot.text());
2632 }
2633 }
2634
2635 #[gpui::test]
2636 fn test_history(cx: &mut MutableAppContext) {
2637 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
2638 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
2639 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2640 let group_interval = multibuffer.read(cx).history.group_interval;
2641 multibuffer.update(cx, |multibuffer, cx| {
2642 multibuffer.push_excerpt(
2643 ExcerptProperties {
2644 buffer: &buffer_1,
2645 range: 0..buffer_1.read(cx).len(),
2646 },
2647 cx,
2648 );
2649 multibuffer.push_excerpt(
2650 ExcerptProperties {
2651 buffer: &buffer_2,
2652 range: 0..buffer_2.read(cx).len(),
2653 },
2654 cx,
2655 );
2656 });
2657
2658 let mut now = Instant::now();
2659
2660 multibuffer.update(cx, |multibuffer, cx| {
2661 multibuffer.start_transaction_at(now, cx);
2662 multibuffer.edit(
2663 [
2664 Point::new(0, 0)..Point::new(0, 0),
2665 Point::new(1, 0)..Point::new(1, 0),
2666 ],
2667 "A",
2668 cx,
2669 );
2670 multibuffer.edit(
2671 [
2672 Point::new(0, 1)..Point::new(0, 1),
2673 Point::new(1, 1)..Point::new(1, 1),
2674 ],
2675 "B",
2676 cx,
2677 );
2678 multibuffer.end_transaction_at(now, cx);
2679 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2680
2681 now += 2 * group_interval;
2682 multibuffer.start_transaction_at(now, cx);
2683 multibuffer.edit([2..2], "C", cx);
2684 multibuffer.end_transaction_at(now, cx);
2685 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2686
2687 multibuffer.undo(cx);
2688 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2689
2690 multibuffer.undo(cx);
2691 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2692
2693 multibuffer.redo(cx);
2694 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2695
2696 multibuffer.redo(cx);
2697 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2698
2699 buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
2700 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2701
2702 multibuffer.undo(cx);
2703 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2704
2705 multibuffer.redo(cx);
2706 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2707
2708 multibuffer.redo(cx);
2709 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2710
2711 multibuffer.undo(cx);
2712 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2713
2714 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
2715 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2716
2717 multibuffer.undo(cx);
2718 assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
2719 });
2720 }
2721}