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 let mut excerpt_ids = excerpt_ids.into_iter().peekable();
693
694 while let Some(mut excerpt_id) = excerpt_ids.next() {
695 // Seek to the next excerpt to remove, preserving any preceding excerpts.
696 new_excerpts.push_tree(cursor.slice(&Some(excerpt_id), Bias::Left, &()), &());
697 if let Some(mut excerpt) = cursor.item() {
698 if excerpt.id != *excerpt_id {
699 continue;
700 }
701 let mut old_start = cursor.start().1;
702
703 // Skip over the removed excerpt.
704 loop {
705 if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
706 buffer_state.excerpts.retain(|id| id != excerpt_id);
707 }
708 cursor.next(&());
709
710 // Skip over any subsequent excerpts that are also removed.
711 if let Some(&next_excerpt_id) = excerpt_ids.peek() {
712 if let Some(next_excerpt) = cursor.item() {
713 if next_excerpt.id == *next_excerpt_id {
714 excerpt = next_excerpt;
715 excerpt_id = excerpt_ids.next().unwrap();
716 continue;
717 }
718 }
719 }
720
721 break;
722 }
723
724 // When removing the last excerpt, remove the trailing newline from
725 // the previous excerpt.
726 if cursor.item().is_none() && old_start > 0 {
727 old_start -= 1;
728 new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
729 }
730
731 // Push an edit for the removal of this run of excerpts.
732 let old_end = cursor.start().1;
733 let new_start = new_excerpts.summary().text.bytes;
734 edits.push(Edit {
735 old: old_start..old_end,
736 new: new_start..new_start,
737 });
738 }
739 }
740 new_excerpts.push_tree(cursor.suffix(&()), &());
741 drop(cursor);
742 snapshot.excerpts = new_excerpts;
743 self.subscriptions.publish_mut(edits);
744 cx.notify();
745 }
746
747 fn on_buffer_event(
748 &mut self,
749 _: ModelHandle<Buffer>,
750 event: &Event,
751 cx: &mut ModelContext<Self>,
752 ) {
753 cx.emit(event.clone());
754 }
755
756 pub fn save(&mut self, cx: &mut ModelContext<Self>) -> Result<Task<Result<()>>> {
757 let mut save_tasks = Vec::new();
758 for BufferState { buffer, .. } in self.buffers.borrow().values() {
759 save_tasks.push(buffer.update(cx, |buffer, cx| buffer.save(cx))?);
760 }
761
762 Ok(cx.spawn(|_, _| async move {
763 for save in save_tasks {
764 save.await?;
765 }
766 Ok(())
767 }))
768 }
769
770 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
771 self.buffers
772 .borrow()
773 .values()
774 .next()
775 .and_then(|state| state.buffer.read(cx).language())
776 }
777
778 pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
779 self.as_singleton()?.read(cx).file()
780 }
781
782 #[cfg(test)]
783 pub fn is_parsing(&self, cx: &AppContext) -> bool {
784 self.as_singleton().unwrap().read(cx).is_parsing()
785 }
786
787 fn sync(&self, cx: &AppContext) {
788 let mut snapshot = self.snapshot.borrow_mut();
789 let mut excerpts_to_edit = Vec::new();
790 let mut reparsed = false;
791 let mut diagnostics_updated = false;
792 let mut is_dirty = false;
793 let mut has_conflict = false;
794 let mut buffers = self.buffers.borrow_mut();
795 for buffer_state in buffers.values_mut() {
796 let buffer = buffer_state.buffer.read(cx);
797 let version = buffer.version();
798 let parse_count = buffer.parse_count();
799 let diagnostics_update_count = buffer.diagnostics_update_count();
800
801 let buffer_edited = version.gt(&buffer_state.last_version);
802 let buffer_reparsed = parse_count > buffer_state.last_parse_count;
803 let buffer_diagnostics_updated =
804 diagnostics_update_count > buffer_state.last_diagnostics_update_count;
805 if buffer_edited || buffer_reparsed || buffer_diagnostics_updated {
806 buffer_state.last_version = version;
807 buffer_state.last_parse_count = parse_count;
808 buffer_state.last_diagnostics_update_count = diagnostics_update_count;
809 excerpts_to_edit.extend(
810 buffer_state
811 .excerpts
812 .iter()
813 .map(|excerpt_id| (excerpt_id, buffer_state.buffer.clone(), buffer_edited)),
814 );
815 }
816
817 reparsed |= buffer_reparsed;
818 diagnostics_updated |= buffer_diagnostics_updated;
819 is_dirty |= buffer.is_dirty();
820 has_conflict |= buffer.has_conflict();
821 }
822 if reparsed {
823 snapshot.parse_count += 1;
824 }
825 if diagnostics_updated {
826 snapshot.diagnostics_update_count += 1;
827 }
828 snapshot.is_dirty = is_dirty;
829 snapshot.has_conflict = has_conflict;
830
831 excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
832
833 let mut edits = Vec::new();
834 let mut new_excerpts = SumTree::new();
835 let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
836
837 for (id, buffer, buffer_edited) in excerpts_to_edit {
838 new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
839 let old_excerpt = cursor.item().unwrap();
840 let buffer_id = buffer.id();
841 let buffer = buffer.read(cx);
842
843 let mut new_excerpt;
844 if buffer_edited {
845 edits.extend(
846 buffer
847 .edits_since_in_range::<usize>(
848 old_excerpt.buffer.version(),
849 old_excerpt.range.clone(),
850 )
851 .map(|mut edit| {
852 let excerpt_old_start = cursor.start().1;
853 let excerpt_new_start = new_excerpts.summary().text.bytes;
854 edit.old.start += excerpt_old_start;
855 edit.old.end += excerpt_old_start;
856 edit.new.start += excerpt_new_start;
857 edit.new.end += excerpt_new_start;
858 edit
859 }),
860 );
861
862 new_excerpt = Excerpt::new(
863 id.clone(),
864 buffer_id,
865 buffer.snapshot(),
866 old_excerpt.range.clone(),
867 old_excerpt.has_trailing_newline,
868 );
869 } else {
870 new_excerpt = old_excerpt.clone();
871 new_excerpt.buffer = buffer.snapshot();
872 }
873
874 new_excerpts.push(new_excerpt, &());
875 cursor.next(&());
876 }
877 new_excerpts.push_tree(cursor.suffix(&()), &());
878
879 drop(cursor);
880 snapshot.excerpts = new_excerpts;
881
882 self.subscriptions.publish(edits);
883 }
884}
885
886#[cfg(any(test, feature = "test-support"))]
887impl MultiBuffer {
888 pub fn randomly_edit(
889 &mut self,
890 rng: &mut impl rand::Rng,
891 count: usize,
892 cx: &mut ModelContext<Self>,
893 ) {
894 use text::RandomCharIter;
895
896 let snapshot = self.read(cx);
897 let mut old_ranges: Vec<Range<usize>> = Vec::new();
898 for _ in 0..count {
899 let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
900 if last_end > snapshot.len() {
901 break;
902 }
903 let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
904 let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
905 old_ranges.push(start_ix..end_ix);
906 }
907 let new_text_len = rng.gen_range(0..10);
908 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
909 log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
910 drop(snapshot);
911
912 self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
913 }
914}
915
916impl Entity for MultiBuffer {
917 type Event = language::Event;
918}
919
920impl MultiBufferSnapshot {
921 pub fn text(&self) -> String {
922 self.chunks(0..self.len(), None)
923 .map(|chunk| chunk.text)
924 .collect()
925 }
926
927 pub fn reversed_chars_at<'a, T: ToOffset>(
928 &'a self,
929 position: T,
930 ) -> impl Iterator<Item = char> + 'a {
931 let mut offset = position.to_offset(self);
932 let mut cursor = self.excerpts.cursor::<usize>();
933 cursor.seek(&offset, Bias::Left, &());
934 let mut excerpt_chunks = cursor.item().map(|excerpt| {
935 let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
936 let start = excerpt.range.start.to_offset(&excerpt.buffer);
937 let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
938 excerpt.buffer.reversed_chunks_in_range(start..end)
939 });
940 iter::from_fn(move || {
941 if offset == *cursor.start() {
942 cursor.prev(&());
943 let excerpt = cursor.item()?;
944 excerpt_chunks = Some(
945 excerpt
946 .buffer
947 .reversed_chunks_in_range(excerpt.range.clone()),
948 );
949 }
950
951 let excerpt = cursor.item().unwrap();
952 if offset == cursor.end(&()) && excerpt.has_trailing_newline {
953 offset -= 1;
954 Some("\n")
955 } else {
956 let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
957 offset -= chunk.len();
958 Some(chunk)
959 }
960 })
961 .flat_map(|c| c.chars().rev())
962 }
963
964 pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
965 let offset = position.to_offset(self);
966 self.text_for_range(offset..self.len())
967 .flat_map(|chunk| chunk.chars())
968 }
969
970 pub fn text_for_range<'a, T: ToOffset>(
971 &'a self,
972 range: Range<T>,
973 ) -> impl Iterator<Item = &'a str> {
974 self.chunks(range, None).map(|chunk| chunk.text)
975 }
976
977 pub fn is_line_blank(&self, row: u32) -> bool {
978 self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
979 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
980 }
981
982 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
983 where
984 T: ToOffset,
985 {
986 let position = position.to_offset(self);
987 position == self.clip_offset(position, Bias::Left)
988 && self
989 .bytes_in_range(position..self.len())
990 .flatten()
991 .copied()
992 .take(needle.len())
993 .eq(needle.bytes())
994 }
995
996 fn as_singleton(&self) -> Option<&BufferSnapshot> {
997 let mut excerpts = self.excerpts.iter();
998 let buffer = excerpts.next().map(|excerpt| &excerpt.buffer);
999 if excerpts.next().is_none() {
1000 buffer
1001 } else {
1002 None
1003 }
1004 }
1005
1006 pub fn len(&self) -> usize {
1007 self.excerpts.summary().text.bytes
1008 }
1009
1010 pub fn max_buffer_row(&self) -> u32 {
1011 self.excerpts.summary().max_buffer_row
1012 }
1013
1014 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1015 let mut cursor = self.excerpts.cursor::<usize>();
1016 cursor.seek(&offset, Bias::Right, &());
1017 let overshoot = if let Some(excerpt) = cursor.item() {
1018 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1019 let buffer_offset = excerpt
1020 .buffer
1021 .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1022 buffer_offset.saturating_sub(excerpt_start)
1023 } else {
1024 0
1025 };
1026 cursor.start() + overshoot
1027 }
1028
1029 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1030 let mut cursor = self.excerpts.cursor::<Point>();
1031 cursor.seek(&point, Bias::Right, &());
1032 let overshoot = if let Some(excerpt) = cursor.item() {
1033 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1034 let buffer_point = excerpt
1035 .buffer
1036 .clip_point(excerpt_start + (point - cursor.start()), bias);
1037 buffer_point.saturating_sub(excerpt_start)
1038 } else {
1039 Point::zero()
1040 };
1041 *cursor.start() + overshoot
1042 }
1043
1044 pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1045 let mut cursor = self.excerpts.cursor::<PointUtf16>();
1046 cursor.seek(&point, Bias::Right, &());
1047 let overshoot = if let Some(excerpt) = cursor.item() {
1048 let excerpt_start = excerpt
1049 .buffer
1050 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1051 let buffer_point = excerpt
1052 .buffer
1053 .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1054 buffer_point.saturating_sub(excerpt_start)
1055 } else {
1056 PointUtf16::zero()
1057 };
1058 *cursor.start() + overshoot
1059 }
1060
1061 pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1062 let range = range.start.to_offset(self)..range.end.to_offset(self);
1063 let mut excerpts = self.excerpts.cursor::<usize>();
1064 excerpts.seek(&range.start, Bias::Right, &());
1065
1066 let mut chunk = &[][..];
1067 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1068 let mut excerpt_bytes = excerpt
1069 .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1070 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1071 Some(excerpt_bytes)
1072 } else {
1073 None
1074 };
1075
1076 MultiBufferBytes {
1077 range,
1078 excerpts,
1079 excerpt_bytes,
1080 chunk,
1081 }
1082 }
1083
1084 pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1085 let mut result = MultiBufferRows {
1086 buffer_row_range: 0..0,
1087 excerpts: self.excerpts.cursor(),
1088 };
1089 result.seek(start_row);
1090 result
1091 }
1092
1093 pub fn chunks<'a, T: ToOffset>(
1094 &'a self,
1095 range: Range<T>,
1096 theme: Option<&'a SyntaxTheme>,
1097 ) -> MultiBufferChunks<'a> {
1098 let range = range.start.to_offset(self)..range.end.to_offset(self);
1099 let mut chunks = MultiBufferChunks {
1100 range: range.clone(),
1101 excerpts: self.excerpts.cursor(),
1102 excerpt_chunks: None,
1103 theme,
1104 };
1105 chunks.seek(range.start);
1106 chunks
1107 }
1108
1109 pub fn offset_to_point(&self, offset: usize) -> Point {
1110 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1111 cursor.seek(&offset, Bias::Right, &());
1112 if let Some(excerpt) = cursor.item() {
1113 let (start_offset, start_point) = cursor.start();
1114 let overshoot = offset - start_offset;
1115 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1116 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1117 let buffer_point = excerpt
1118 .buffer
1119 .offset_to_point(excerpt_start_offset + overshoot);
1120 *start_point + (buffer_point - excerpt_start_point)
1121 } else {
1122 self.excerpts.summary().text.lines
1123 }
1124 }
1125
1126 pub fn point_to_offset(&self, point: Point) -> usize {
1127 let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1128 cursor.seek(&point, Bias::Right, &());
1129 if let Some(excerpt) = cursor.item() {
1130 let (start_point, start_offset) = cursor.start();
1131 let overshoot = point - start_point;
1132 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1133 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1134 let buffer_offset = excerpt
1135 .buffer
1136 .point_to_offset(excerpt_start_point + overshoot);
1137 *start_offset + buffer_offset - excerpt_start_offset
1138 } else {
1139 self.excerpts.summary().text.bytes
1140 }
1141 }
1142
1143 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1144 let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1145 cursor.seek(&point, Bias::Right, &());
1146 if let Some(excerpt) = cursor.item() {
1147 let (start_point, start_offset) = cursor.start();
1148 let overshoot = point - start_point;
1149 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1150 let excerpt_start_point = excerpt
1151 .buffer
1152 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1153 let buffer_offset = excerpt
1154 .buffer
1155 .point_utf16_to_offset(excerpt_start_point + overshoot);
1156 *start_offset + (buffer_offset - excerpt_start_offset)
1157 } else {
1158 self.excerpts.summary().text.bytes
1159 }
1160 }
1161
1162 pub fn indent_column_for_line(&self, row: u32) -> u32 {
1163 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1164 buffer
1165 .indent_column_for_line(range.start.row)
1166 .min(range.end.column)
1167 .saturating_sub(range.start.column)
1168 } else {
1169 0
1170 }
1171 }
1172
1173 pub fn line_len(&self, row: u32) -> u32 {
1174 if let Some((_, range)) = self.buffer_line_for_row(row) {
1175 range.end.column - range.start.column
1176 } else {
1177 0
1178 }
1179 }
1180
1181 fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1182 let mut cursor = self.excerpts.cursor::<Point>();
1183 cursor.seek(&Point::new(row, 0), Bias::Right, &());
1184 if let Some(excerpt) = cursor.item() {
1185 let overshoot = row - cursor.start().row;
1186 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1187 let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1188 let buffer_row = excerpt_start.row + overshoot;
1189 let line_start = Point::new(buffer_row, 0);
1190 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1191 return Some((
1192 &excerpt.buffer,
1193 line_start.max(excerpt_start)..line_end.min(excerpt_end),
1194 ));
1195 }
1196 None
1197 }
1198
1199 pub fn max_point(&self) -> Point {
1200 self.text_summary().lines
1201 }
1202
1203 pub fn text_summary(&self) -> TextSummary {
1204 self.excerpts.summary().text
1205 }
1206
1207 pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1208 where
1209 D: TextDimension,
1210 O: ToOffset,
1211 {
1212 let mut summary = D::default();
1213 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1214 let mut cursor = self.excerpts.cursor::<usize>();
1215 cursor.seek(&range.start, Bias::Right, &());
1216 if let Some(excerpt) = cursor.item() {
1217 let mut end_before_newline = cursor.end(&());
1218 if excerpt.has_trailing_newline {
1219 end_before_newline -= 1;
1220 }
1221
1222 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1223 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
1224 let end_in_excerpt =
1225 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
1226 summary.add_assign(
1227 &excerpt
1228 .buffer
1229 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1230 );
1231
1232 if range.end > end_before_newline {
1233 summary.add_assign(&D::from_text_summary(&TextSummary {
1234 bytes: 1,
1235 lines: Point::new(1 as u32, 0),
1236 lines_utf16: PointUtf16::new(1 as u32, 0),
1237 first_line_chars: 0,
1238 last_line_chars: 0,
1239 longest_row: 0,
1240 longest_row_chars: 0,
1241 }));
1242 }
1243
1244 cursor.next(&());
1245 }
1246
1247 if range.end > *cursor.start() {
1248 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1249 &range.end,
1250 Bias::Right,
1251 &(),
1252 )));
1253 if let Some(excerpt) = cursor.item() {
1254 range.end = cmp::max(*cursor.start(), range.end);
1255
1256 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1257 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
1258 summary.add_assign(
1259 &excerpt
1260 .buffer
1261 .text_summary_for_range(excerpt_start..end_in_excerpt),
1262 );
1263 }
1264 }
1265
1266 summary
1267 }
1268
1269 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1270 where
1271 D: TextDimension + Ord + Sub<D, Output = D>,
1272 {
1273 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1274 cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1275 if cursor.item().is_none() {
1276 cursor.next(&());
1277 }
1278
1279 let mut position = D::from_text_summary(&cursor.start().text);
1280 if let Some(excerpt) = cursor.item() {
1281 if excerpt.id == anchor.excerpt_id {
1282 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1283 let buffer_position = anchor.text_anchor.summary::<D>(&excerpt.buffer);
1284 if buffer_position > excerpt_buffer_start {
1285 position.add_assign(&(buffer_position - excerpt_buffer_start));
1286 }
1287 }
1288 }
1289 position
1290 }
1291
1292 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1293 where
1294 D: TextDimension + Ord + Sub<D, Output = D>,
1295 I: 'a + IntoIterator<Item = &'a Anchor>,
1296 {
1297 let mut anchors = anchors.into_iter().peekable();
1298 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1299 let mut summaries = Vec::new();
1300 while let Some(anchor) = anchors.peek() {
1301 let excerpt_id = &anchor.excerpt_id;
1302 let excerpt_anchors = iter::from_fn(|| {
1303 let anchor = anchors.peek()?;
1304 if anchor.excerpt_id == *excerpt_id {
1305 Some(&anchors.next().unwrap().text_anchor)
1306 } else {
1307 None
1308 }
1309 });
1310
1311 cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1312 if cursor.item().is_none() {
1313 cursor.next(&());
1314 }
1315
1316 let position = D::from_text_summary(&cursor.start().text);
1317 if let Some(excerpt) = cursor.item() {
1318 if excerpt.id == *excerpt_id {
1319 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1320 summaries.extend(
1321 excerpt
1322 .buffer
1323 .summaries_for_anchors::<D, _>(excerpt_anchors)
1324 .map(move |summary| {
1325 let mut position = position.clone();
1326 let excerpt_buffer_start = excerpt_buffer_start.clone();
1327 if summary > excerpt_buffer_start {
1328 position.add_assign(&(summary - excerpt_buffer_start));
1329 }
1330 position
1331 }),
1332 );
1333 continue;
1334 }
1335 }
1336
1337 summaries.extend(excerpt_anchors.map(|_| position.clone()));
1338 }
1339
1340 summaries
1341 }
1342
1343 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1344 self.anchor_at(position, Bias::Left)
1345 }
1346
1347 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1348 self.anchor_at(position, Bias::Right)
1349 }
1350
1351 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1352 let offset = position.to_offset(self);
1353 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1354 cursor.seek(&offset, Bias::Right, &());
1355 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1356 cursor.prev(&());
1357 }
1358 if let Some(excerpt) = cursor.item() {
1359 let mut overshoot = offset.saturating_sub(cursor.start().0);
1360 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1361 overshoot -= 1;
1362 bias = Bias::Right;
1363 }
1364
1365 let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1366 let text_anchor =
1367 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1368 Anchor {
1369 excerpt_id: excerpt.id.clone(),
1370 text_anchor,
1371 }
1372 } else if offset == 0 && bias == Bias::Left {
1373 Anchor::min()
1374 } else {
1375 Anchor::max()
1376 }
1377 }
1378
1379 pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1380 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1381 cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1382 if let Some(excerpt) = cursor.item() {
1383 if excerpt.id == excerpt_id {
1384 let text_anchor = excerpt.clip_anchor(text_anchor);
1385 drop(cursor);
1386 return Anchor {
1387 excerpt_id,
1388 text_anchor,
1389 };
1390 }
1391 }
1392 panic!("excerpt not found");
1393 }
1394
1395 pub fn parse_count(&self) -> usize {
1396 self.parse_count
1397 }
1398
1399 pub fn enclosing_bracket_ranges<T: ToOffset>(
1400 &self,
1401 range: Range<T>,
1402 ) -> Option<(Range<usize>, Range<usize>)> {
1403 let range = range.start.to_offset(self)..range.end.to_offset(self);
1404
1405 let mut cursor = self.excerpts.cursor::<usize>();
1406 cursor.seek(&range.start, Bias::Right, &());
1407 let start_excerpt = cursor.item();
1408
1409 cursor.seek(&range.end, Bias::Right, &());
1410 let end_excerpt = cursor.item();
1411
1412 start_excerpt
1413 .zip(end_excerpt)
1414 .and_then(|(start_excerpt, end_excerpt)| {
1415 if start_excerpt.id != end_excerpt.id {
1416 return None;
1417 }
1418
1419 let excerpt_buffer_start =
1420 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1421 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1422
1423 let start_in_buffer =
1424 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1425 let end_in_buffer =
1426 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1427 let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1428 .buffer
1429 .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1430
1431 if start_bracket_range.start >= excerpt_buffer_start
1432 && end_bracket_range.end < excerpt_buffer_end
1433 {
1434 start_bracket_range.start =
1435 cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
1436 start_bracket_range.end =
1437 cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
1438 end_bracket_range.start =
1439 cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
1440 end_bracket_range.end =
1441 cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
1442 Some((start_bracket_range, end_bracket_range))
1443 } else {
1444 None
1445 }
1446 })
1447 }
1448
1449 pub fn diagnostics_update_count(&self) -> usize {
1450 self.diagnostics_update_count
1451 }
1452
1453 pub fn language(&self) -> Option<&Arc<Language>> {
1454 self.excerpts
1455 .iter()
1456 .next()
1457 .and_then(|excerpt| excerpt.buffer.language())
1458 }
1459
1460 pub fn is_dirty(&self) -> bool {
1461 self.is_dirty
1462 }
1463
1464 pub fn has_conflict(&self) -> bool {
1465 self.has_conflict
1466 }
1467
1468 pub fn diagnostic_group<'a, O>(
1469 &'a self,
1470 group_id: usize,
1471 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1472 where
1473 O: text::FromAnchor + 'a,
1474 {
1475 self.as_singleton()
1476 .into_iter()
1477 .flat_map(move |buffer| buffer.diagnostic_group(group_id))
1478 }
1479
1480 pub fn diagnostics_in_range<'a, T, O>(
1481 &'a self,
1482 range: Range<T>,
1483 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1484 where
1485 T: 'a + ToOffset,
1486 O: 'a + text::FromAnchor,
1487 {
1488 self.as_singleton().into_iter().flat_map(move |buffer| {
1489 buffer.diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
1490 })
1491 }
1492
1493 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1494 let range = range.start.to_offset(self)..range.end.to_offset(self);
1495
1496 let mut cursor = self.excerpts.cursor::<usize>();
1497 cursor.seek(&range.start, Bias::Right, &());
1498 let start_excerpt = cursor.item();
1499
1500 cursor.seek(&range.end, Bias::Right, &());
1501 let end_excerpt = cursor.item();
1502
1503 start_excerpt
1504 .zip(end_excerpt)
1505 .and_then(|(start_excerpt, end_excerpt)| {
1506 if start_excerpt.id != end_excerpt.id {
1507 return None;
1508 }
1509
1510 let excerpt_buffer_start =
1511 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1512 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1513
1514 let start_in_buffer =
1515 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1516 let end_in_buffer =
1517 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1518 let mut ancestor_buffer_range = start_excerpt
1519 .buffer
1520 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
1521 ancestor_buffer_range.start =
1522 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
1523 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
1524
1525 let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
1526 let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
1527 Some(start..end)
1528 })
1529 }
1530
1531 fn buffer_snapshot_for_excerpt<'a>(
1532 &'a self,
1533 excerpt_id: &'a ExcerptId,
1534 ) -> Option<&'a BufferSnapshot> {
1535 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1536 cursor.seek(&Some(excerpt_id), Bias::Left, &());
1537 if let Some(excerpt) = cursor.item() {
1538 if excerpt.id == *excerpt_id {
1539 return Some(&excerpt.buffer);
1540 }
1541 }
1542 None
1543 }
1544
1545 pub fn remote_selections_in_range<'a>(
1546 &'a self,
1547 range: &'a Range<Anchor>,
1548 ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
1549 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1550 cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
1551 cursor
1552 .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
1553 .flat_map(move |excerpt| {
1554 let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
1555 if excerpt.id == range.start.excerpt_id {
1556 query_range.start = range.start.text_anchor.clone();
1557 }
1558 if excerpt.id == range.end.excerpt_id {
1559 query_range.end = range.end.text_anchor.clone();
1560 }
1561
1562 excerpt
1563 .buffer
1564 .remote_selections_in_range(query_range)
1565 .flat_map(move |(replica_id, selections)| {
1566 selections.map(move |selection| {
1567 let mut start = Anchor {
1568 excerpt_id: excerpt.id.clone(),
1569 text_anchor: selection.start.clone(),
1570 };
1571 let mut end = Anchor {
1572 excerpt_id: excerpt.id.clone(),
1573 text_anchor: selection.end.clone(),
1574 };
1575 if range.start.cmp(&start, self).unwrap().is_gt() {
1576 start = range.start.clone();
1577 }
1578 if range.end.cmp(&end, self).unwrap().is_lt() {
1579 end = range.end.clone();
1580 }
1581
1582 (
1583 replica_id,
1584 Selection {
1585 id: selection.id,
1586 start,
1587 end,
1588 reversed: selection.reversed,
1589 goal: selection.goal,
1590 },
1591 )
1592 })
1593 })
1594 })
1595 }
1596}
1597
1598impl History {
1599 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
1600 self.transaction_depth += 1;
1601 if self.transaction_depth == 1 {
1602 let id = post_inc(&mut self.next_transaction_id);
1603 self.undo_stack.push(Transaction {
1604 id,
1605 buffer_transactions: Default::default(),
1606 first_edit_at: now,
1607 last_edit_at: now,
1608 });
1609 Some(id)
1610 } else {
1611 None
1612 }
1613 }
1614
1615 fn end_transaction(
1616 &mut self,
1617 now: Instant,
1618 buffer_transactions: HashSet<(usize, TransactionId)>,
1619 ) -> bool {
1620 assert_ne!(self.transaction_depth, 0);
1621 self.transaction_depth -= 1;
1622 if self.transaction_depth == 0 {
1623 if buffer_transactions.is_empty() {
1624 self.undo_stack.pop();
1625 false
1626 } else {
1627 let transaction = self.undo_stack.last_mut().unwrap();
1628 transaction.last_edit_at = now;
1629 transaction.buffer_transactions.extend(buffer_transactions);
1630 true
1631 }
1632 } else {
1633 false
1634 }
1635 }
1636
1637 fn pop_undo(&mut self) -> Option<&Transaction> {
1638 assert_eq!(self.transaction_depth, 0);
1639 if let Some(transaction) = self.undo_stack.pop() {
1640 self.redo_stack.push(transaction);
1641 self.redo_stack.last()
1642 } else {
1643 None
1644 }
1645 }
1646
1647 fn pop_redo(&mut self) -> Option<&Transaction> {
1648 assert_eq!(self.transaction_depth, 0);
1649 if let Some(transaction) = self.redo_stack.pop() {
1650 self.undo_stack.push(transaction);
1651 self.undo_stack.last()
1652 } else {
1653 None
1654 }
1655 }
1656
1657 fn group(&mut self) -> Option<TransactionId> {
1658 let mut new_len = self.undo_stack.len();
1659 let mut transactions = self.undo_stack.iter_mut();
1660
1661 if let Some(mut transaction) = transactions.next_back() {
1662 while let Some(prev_transaction) = transactions.next_back() {
1663 if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
1664 {
1665 transaction = prev_transaction;
1666 new_len -= 1;
1667 } else {
1668 break;
1669 }
1670 }
1671 }
1672
1673 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
1674 if let Some(last_transaction) = transactions_to_keep.last_mut() {
1675 if let Some(transaction) = transactions_to_merge.last() {
1676 last_transaction.last_edit_at = transaction.last_edit_at;
1677 }
1678 }
1679
1680 self.undo_stack.truncate(new_len);
1681 self.undo_stack.last().map(|t| t.id)
1682 }
1683}
1684
1685impl Excerpt {
1686 fn new(
1687 id: ExcerptId,
1688 buffer_id: usize,
1689 buffer: BufferSnapshot,
1690 range: Range<text::Anchor>,
1691 has_trailing_newline: bool,
1692 ) -> Self {
1693 Excerpt {
1694 id,
1695 max_buffer_row: range.end.to_point(&buffer).row,
1696 text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
1697 buffer_id,
1698 buffer,
1699 range,
1700 has_trailing_newline,
1701 }
1702 }
1703
1704 fn chunks_in_range<'a>(
1705 &'a self,
1706 range: Range<usize>,
1707 theme: Option<&'a SyntaxTheme>,
1708 ) -> ExcerptChunks<'a> {
1709 let content_start = self.range.start.to_offset(&self.buffer);
1710 let chunks_start = content_start + range.start;
1711 let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
1712
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
1722 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, theme);
1723
1724 ExcerptChunks {
1725 content_chunks,
1726 footer_height,
1727 }
1728 }
1729
1730 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
1731 let content_start = self.range.start.to_offset(&self.buffer);
1732 let bytes_start = content_start + range.start;
1733 let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
1734 let footer_height = if self.has_trailing_newline
1735 && range.start <= self.text_summary.bytes
1736 && range.end > self.text_summary.bytes
1737 {
1738 1
1739 } else {
1740 0
1741 };
1742 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
1743
1744 ExcerptBytes {
1745 content_bytes,
1746 footer_height,
1747 }
1748 }
1749
1750 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
1751 if text_anchor
1752 .cmp(&self.range.start, &self.buffer)
1753 .unwrap()
1754 .is_lt()
1755 {
1756 self.range.start.clone()
1757 } else if text_anchor
1758 .cmp(&self.range.end, &self.buffer)
1759 .unwrap()
1760 .is_gt()
1761 {
1762 self.range.end.clone()
1763 } else {
1764 text_anchor
1765 }
1766 }
1767}
1768
1769impl fmt::Debug for Excerpt {
1770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1771 f.debug_struct("Excerpt")
1772 .field("id", &self.id)
1773 .field("buffer_id", &self.buffer_id)
1774 .field("range", &self.range)
1775 .field("text_summary", &self.text_summary)
1776 .field("has_trailing_newline", &self.has_trailing_newline)
1777 .finish()
1778 }
1779}
1780
1781impl sum_tree::Item for Excerpt {
1782 type Summary = ExcerptSummary;
1783
1784 fn summary(&self) -> Self::Summary {
1785 let mut text = self.text_summary.clone();
1786 if self.has_trailing_newline {
1787 text += TextSummary::from("\n");
1788 }
1789 ExcerptSummary {
1790 excerpt_id: self.id.clone(),
1791 max_buffer_row: self.max_buffer_row,
1792 text,
1793 }
1794 }
1795}
1796
1797impl sum_tree::Summary for ExcerptSummary {
1798 type Context = ();
1799
1800 fn add_summary(&mut self, summary: &Self, _: &()) {
1801 debug_assert!(summary.excerpt_id > self.excerpt_id);
1802 self.excerpt_id = summary.excerpt_id.clone();
1803 self.text.add_summary(&summary.text, &());
1804 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
1805 }
1806}
1807
1808impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
1809 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1810 *self += &summary.text;
1811 }
1812}
1813
1814impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
1815 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1816 *self += summary.text.bytes;
1817 }
1818}
1819
1820impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
1821 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1822 Ord::cmp(self, &cursor_location.text.bytes)
1823 }
1824}
1825
1826impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
1827 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1828 Ord::cmp(self, &Some(&cursor_location.excerpt_id))
1829 }
1830}
1831
1832impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
1833 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1834 *self += summary.text.lines;
1835 }
1836}
1837
1838impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
1839 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1840 *self += summary.text.lines_utf16
1841 }
1842}
1843
1844impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
1845 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1846 *self = Some(&summary.excerpt_id);
1847 }
1848}
1849
1850impl<'a> MultiBufferRows<'a> {
1851 pub fn seek(&mut self, row: u32) {
1852 self.buffer_row_range = 0..0;
1853
1854 self.excerpts
1855 .seek_forward(&Point::new(row, 0), Bias::Right, &());
1856 if self.excerpts.item().is_none() {
1857 self.excerpts.prev(&());
1858
1859 if self.excerpts.item().is_none() && row == 0 {
1860 self.buffer_row_range = 0..1;
1861 return;
1862 }
1863 }
1864
1865 if let Some(excerpt) = self.excerpts.item() {
1866 let overshoot = row - self.excerpts.start().row;
1867 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
1868 self.buffer_row_range.start = excerpt_start + overshoot;
1869 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
1870 }
1871 }
1872}
1873
1874impl<'a> Iterator for MultiBufferRows<'a> {
1875 type Item = Option<u32>;
1876
1877 fn next(&mut self) -> Option<Self::Item> {
1878 loop {
1879 if !self.buffer_row_range.is_empty() {
1880 let row = Some(self.buffer_row_range.start);
1881 self.buffer_row_range.start += 1;
1882 return Some(row);
1883 }
1884 self.excerpts.item()?;
1885 self.excerpts.next(&());
1886 let excerpt = self.excerpts.item()?;
1887 self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
1888 self.buffer_row_range.end =
1889 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
1890 }
1891 }
1892}
1893
1894impl<'a> MultiBufferChunks<'a> {
1895 pub fn offset(&self) -> usize {
1896 self.range.start
1897 }
1898
1899 pub fn seek(&mut self, offset: usize) {
1900 self.range.start = offset;
1901 self.excerpts.seek(&offset, Bias::Right, &());
1902 if let Some(excerpt) = self.excerpts.item() {
1903 self.excerpt_chunks = Some(excerpt.chunks_in_range(
1904 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
1905 self.theme,
1906 ));
1907 } else {
1908 self.excerpt_chunks = None;
1909 }
1910 }
1911}
1912
1913impl<'a> Iterator for MultiBufferChunks<'a> {
1914 type Item = Chunk<'a>;
1915
1916 fn next(&mut self) -> Option<Self::Item> {
1917 if self.range.is_empty() {
1918 None
1919 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
1920 self.range.start += chunk.text.len();
1921 Some(chunk)
1922 } else {
1923 self.excerpts.next(&());
1924 let excerpt = self.excerpts.item()?;
1925 self.excerpt_chunks = Some(
1926 excerpt.chunks_in_range(0..self.range.end - self.excerpts.start(), self.theme),
1927 );
1928 self.next()
1929 }
1930 }
1931}
1932
1933impl<'a> MultiBufferBytes<'a> {
1934 fn consume(&mut self, len: usize) {
1935 self.range.start += len;
1936 self.chunk = &self.chunk[len..];
1937
1938 if !self.range.is_empty() && self.chunk.is_empty() {
1939 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
1940 self.chunk = chunk;
1941 } else {
1942 self.excerpts.next(&());
1943 if let Some(excerpt) = self.excerpts.item() {
1944 let mut excerpt_bytes =
1945 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
1946 self.chunk = excerpt_bytes.next().unwrap();
1947 self.excerpt_bytes = Some(excerpt_bytes);
1948 }
1949 }
1950 }
1951 }
1952}
1953
1954impl<'a> Iterator for MultiBufferBytes<'a> {
1955 type Item = &'a [u8];
1956
1957 fn next(&mut self) -> Option<Self::Item> {
1958 let chunk = self.chunk;
1959 if chunk.is_empty() {
1960 None
1961 } else {
1962 self.consume(chunk.len());
1963 Some(chunk)
1964 }
1965 }
1966}
1967
1968impl<'a> io::Read for MultiBufferBytes<'a> {
1969 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1970 let len = cmp::min(buf.len(), self.chunk.len());
1971 buf[..len].copy_from_slice(&self.chunk[..len]);
1972 if len > 0 {
1973 self.consume(len);
1974 }
1975 Ok(len)
1976 }
1977}
1978
1979impl<'a> Iterator for ExcerptBytes<'a> {
1980 type Item = &'a [u8];
1981
1982 fn next(&mut self) -> Option<Self::Item> {
1983 if let Some(chunk) = self.content_bytes.next() {
1984 if !chunk.is_empty() {
1985 return Some(chunk);
1986 }
1987 }
1988
1989 if self.footer_height > 0 {
1990 let result = &NEWLINES[..self.footer_height];
1991 self.footer_height = 0;
1992 return Some(result);
1993 }
1994
1995 None
1996 }
1997}
1998
1999impl<'a> Iterator for ExcerptChunks<'a> {
2000 type Item = Chunk<'a>;
2001
2002 fn next(&mut self) -> Option<Self::Item> {
2003 if let Some(chunk) = self.content_chunks.next() {
2004 return Some(chunk);
2005 }
2006
2007 if self.footer_height > 0 {
2008 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2009 self.footer_height = 0;
2010 return Some(Chunk {
2011 text,
2012 ..Default::default()
2013 });
2014 }
2015
2016 None
2017 }
2018}
2019
2020impl ToOffset for Point {
2021 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2022 snapshot.point_to_offset(*self)
2023 }
2024}
2025
2026impl ToOffset for PointUtf16 {
2027 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2028 snapshot.point_utf16_to_offset(*self)
2029 }
2030}
2031
2032impl ToOffset for usize {
2033 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2034 assert!(*self <= snapshot.len(), "offset is out of range");
2035 *self
2036 }
2037}
2038
2039impl ToPoint for usize {
2040 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2041 snapshot.offset_to_point(*self)
2042 }
2043}
2044
2045impl ToPoint for Point {
2046 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2047 *self
2048 }
2049}
2050
2051#[cfg(test)]
2052mod tests {
2053 use super::*;
2054 use gpui::MutableAppContext;
2055 use language::{Buffer, Rope};
2056 use rand::prelude::*;
2057 use std::env;
2058 use text::{Point, RandomCharIter};
2059 use util::test::sample_text;
2060
2061 #[gpui::test]
2062 fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2063 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2064 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2065
2066 let snapshot = multibuffer.read(cx).snapshot(cx);
2067 assert_eq!(snapshot.text(), buffer.read(cx).text());
2068
2069 assert_eq!(
2070 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2071 (0..buffer.read(cx).row_count())
2072 .map(Some)
2073 .collect::<Vec<_>>()
2074 );
2075
2076 buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2077 let snapshot = multibuffer.read(cx).snapshot(cx);
2078
2079 assert_eq!(snapshot.text(), buffer.read(cx).text());
2080 assert_eq!(
2081 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2082 (0..buffer.read(cx).row_count())
2083 .map(Some)
2084 .collect::<Vec<_>>()
2085 );
2086 }
2087
2088 #[gpui::test]
2089 fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2090 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2091 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2092 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2093
2094 let subscription = multibuffer.update(cx, |multibuffer, cx| {
2095 let subscription = multibuffer.subscribe();
2096 multibuffer.push_excerpt(
2097 ExcerptProperties {
2098 buffer: &buffer_1,
2099 range: Point::new(1, 2)..Point::new(2, 5),
2100 },
2101 cx,
2102 );
2103 assert_eq!(
2104 subscription.consume().into_inner(),
2105 [Edit {
2106 old: 0..0,
2107 new: 0..10
2108 }]
2109 );
2110
2111 multibuffer.push_excerpt(
2112 ExcerptProperties {
2113 buffer: &buffer_1,
2114 range: Point::new(3, 3)..Point::new(4, 4),
2115 },
2116 cx,
2117 );
2118 multibuffer.push_excerpt(
2119 ExcerptProperties {
2120 buffer: &buffer_2,
2121 range: Point::new(3, 1)..Point::new(3, 3),
2122 },
2123 cx,
2124 );
2125 assert_eq!(
2126 subscription.consume().into_inner(),
2127 [Edit {
2128 old: 10..10,
2129 new: 10..22
2130 }]
2131 );
2132
2133 subscription
2134 });
2135
2136 let snapshot = multibuffer.read(cx).snapshot(cx);
2137 assert_eq!(
2138 snapshot.text(),
2139 concat!(
2140 "bbbb\n", // Preserve newlines
2141 "ccccc\n", //
2142 "ddd\n", //
2143 "eeee\n", //
2144 "jj" //
2145 )
2146 );
2147 assert_eq!(
2148 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2149 [Some(1), Some(2), Some(3), Some(4), Some(3)]
2150 );
2151 assert_eq!(
2152 snapshot.buffer_rows(2).collect::<Vec<_>>(),
2153 [Some(3), Some(4), Some(3)]
2154 );
2155 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2156 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2157
2158 buffer_1.update(cx, |buffer, cx| {
2159 buffer.edit(
2160 [
2161 Point::new(0, 0)..Point::new(0, 0),
2162 Point::new(2, 1)..Point::new(2, 3),
2163 ],
2164 "\n",
2165 cx,
2166 );
2167 });
2168
2169 let snapshot = multibuffer.read(cx).snapshot(cx);
2170 assert_eq!(
2171 snapshot.text(),
2172 concat!(
2173 "bbbb\n", // Preserve newlines
2174 "c\n", //
2175 "cc\n", //
2176 "ddd\n", //
2177 "eeee\n", //
2178 "jj" //
2179 )
2180 );
2181
2182 assert_eq!(
2183 subscription.consume().into_inner(),
2184 [Edit {
2185 old: 6..8,
2186 new: 6..7
2187 }]
2188 );
2189
2190 let snapshot = multibuffer.read(cx).snapshot(cx);
2191 assert_eq!(
2192 snapshot.clip_point(Point::new(0, 5), Bias::Left),
2193 Point::new(0, 4)
2194 );
2195 assert_eq!(
2196 snapshot.clip_point(Point::new(0, 5), Bias::Right),
2197 Point::new(0, 4)
2198 );
2199 assert_eq!(
2200 snapshot.clip_point(Point::new(5, 1), Bias::Right),
2201 Point::new(5, 1)
2202 );
2203 assert_eq!(
2204 snapshot.clip_point(Point::new(5, 2), Bias::Right),
2205 Point::new(5, 2)
2206 );
2207 assert_eq!(
2208 snapshot.clip_point(Point::new(5, 3), Bias::Right),
2209 Point::new(5, 2)
2210 );
2211
2212 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2213 let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2214 multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2215 multibuffer.snapshot(cx)
2216 });
2217
2218 assert_eq!(
2219 snapshot.text(),
2220 concat!(
2221 "bbbb\n", // Preserve newlines
2222 "c\n", //
2223 "cc\n", //
2224 "ddd\n", //
2225 "eeee", //
2226 )
2227 );
2228 }
2229
2230 #[gpui::test]
2231 fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2232 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2233
2234 let snapshot = multibuffer.read(cx).snapshot(cx);
2235 assert_eq!(snapshot.text(), "");
2236 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2237 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2238 }
2239
2240 #[gpui::test]
2241 fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2242 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2243 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2244 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2245 buffer.update(cx, |buffer, cx| {
2246 buffer.edit([0..0], "X", cx);
2247 buffer.edit([5..5], "Y", cx);
2248 });
2249 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2250
2251 assert_eq!(old_snapshot.text(), "abcd");
2252 assert_eq!(new_snapshot.text(), "XabcdY");
2253
2254 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2255 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2256 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2257 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2258 }
2259
2260 #[gpui::test]
2261 fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2262 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2263 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2264 let multibuffer = cx.add_model(|cx| {
2265 let mut multibuffer = MultiBuffer::new(0);
2266 multibuffer.push_excerpt(
2267 ExcerptProperties {
2268 buffer: &buffer_1,
2269 range: 0..4,
2270 },
2271 cx,
2272 );
2273 multibuffer.push_excerpt(
2274 ExcerptProperties {
2275 buffer: &buffer_2,
2276 range: 0..5,
2277 },
2278 cx,
2279 );
2280 multibuffer
2281 });
2282 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2283
2284 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
2285 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
2286 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2287 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2288 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2289 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2290
2291 buffer_1.update(cx, |buffer, cx| {
2292 buffer.edit([0..0], "W", cx);
2293 buffer.edit([5..5], "X", cx);
2294 });
2295 buffer_2.update(cx, |buffer, cx| {
2296 buffer.edit([0..0], "Y", cx);
2297 buffer.edit([6..0], "Z", cx);
2298 });
2299 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2300
2301 assert_eq!(old_snapshot.text(), "abcd\nefghi");
2302 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
2303
2304 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2305 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2306 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
2307 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2308 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2309 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2310 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
2311 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
2312 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
2313 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
2314 }
2315
2316 #[gpui::test(iterations = 100)]
2317 fn test_random_excerpts(cx: &mut MutableAppContext, mut rng: StdRng) {
2318 let operations = env::var("OPERATIONS")
2319 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2320 .unwrap_or(10);
2321
2322 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
2323 let list = cx.add_model(|_| MultiBuffer::new(0));
2324 let mut excerpt_ids = Vec::new();
2325 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
2326 let mut old_versions = Vec::new();
2327
2328 for _ in 0..operations {
2329 match rng.gen_range(0..100) {
2330 0..=19 if !buffers.is_empty() => {
2331 let buffer = buffers.choose(&mut rng).unwrap();
2332 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
2333 }
2334 20..=29 if !expected_excerpts.is_empty() => {
2335 let mut ids_to_remove = vec![];
2336 for _ in 0..rng.gen_range(1..=3) {
2337 if expected_excerpts.is_empty() {
2338 break;
2339 }
2340
2341 let ix = rng.gen_range(0..expected_excerpts.len());
2342 ids_to_remove.push(excerpt_ids.remove(ix));
2343 let (buffer, range) = expected_excerpts.remove(ix);
2344 let buffer = buffer.read(cx);
2345 log::info!(
2346 "Removing excerpt {}: {:?}",
2347 ix,
2348 buffer
2349 .text_for_range(range.to_offset(&buffer))
2350 .collect::<String>(),
2351 );
2352 }
2353 ids_to_remove.sort_unstable();
2354 list.update(cx, |list, cx| list.remove_excerpts(&ids_to_remove, cx));
2355 }
2356 _ => {
2357 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2358 let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
2359 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
2360 buffers.last().unwrap()
2361 } else {
2362 buffers.choose(&mut rng).unwrap()
2363 };
2364
2365 let buffer = buffer_handle.read(cx);
2366 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
2367 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2368 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2369 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
2370 let prev_excerpt_id = excerpt_ids
2371 .get(prev_excerpt_ix)
2372 .cloned()
2373 .unwrap_or(ExcerptId::max());
2374 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
2375
2376 log::info!(
2377 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2378 excerpt_ix,
2379 expected_excerpts.len(),
2380 buffer_handle.id(),
2381 buffer.text(),
2382 start_ix..end_ix,
2383 &buffer.text()[start_ix..end_ix]
2384 );
2385
2386 let excerpt_id = list.update(cx, |list, cx| {
2387 list.insert_excerpt_after(
2388 &prev_excerpt_id,
2389 ExcerptProperties {
2390 buffer: &buffer_handle,
2391 range: start_ix..end_ix,
2392 },
2393 cx,
2394 )
2395 });
2396
2397 excerpt_ids.insert(excerpt_ix, excerpt_id);
2398 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
2399 }
2400 }
2401
2402 if rng.gen_bool(0.3) {
2403 list.update(cx, |list, cx| {
2404 old_versions.push((list.snapshot(cx), list.subscribe()));
2405 })
2406 }
2407
2408 let snapshot = list.read(cx).snapshot(cx);
2409
2410 let mut excerpt_starts = Vec::new();
2411 let mut expected_text = String::new();
2412 let mut expected_buffer_rows = Vec::new();
2413 for (buffer, range) in &expected_excerpts {
2414 let buffer = buffer.read(cx);
2415 let buffer_range = range.to_offset(buffer);
2416
2417 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
2418 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
2419 expected_text.push('\n');
2420
2421 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
2422 ..=buffer.offset_to_point(buffer_range.end).row;
2423 for row in buffer_row_range {
2424 expected_buffer_rows.push(Some(row));
2425 }
2426 }
2427 // Remove final trailing newline.
2428 if !expected_excerpts.is_empty() {
2429 expected_text.pop();
2430 }
2431
2432 // Always report one buffer row
2433 if expected_buffer_rows.is_empty() {
2434 expected_buffer_rows.push(Some(0));
2435 }
2436
2437 assert_eq!(snapshot.text(), expected_text);
2438 log::info!("MultiBuffer text: {:?}", expected_text);
2439
2440 assert_eq!(
2441 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2442 expected_buffer_rows,
2443 );
2444
2445 for _ in 0..5 {
2446 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
2447 assert_eq!(
2448 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
2449 &expected_buffer_rows[start_row..],
2450 "buffer_rows({})",
2451 start_row
2452 );
2453 }
2454
2455 assert_eq!(
2456 snapshot.max_buffer_row(),
2457 expected_buffer_rows
2458 .into_iter()
2459 .filter_map(|r| r)
2460 .max()
2461 .unwrap()
2462 );
2463
2464 let mut excerpt_starts = excerpt_starts.into_iter();
2465 for (buffer, range) in &expected_excerpts {
2466 let buffer_id = buffer.id();
2467 let buffer = buffer.read(cx);
2468 let buffer_range = range.to_offset(buffer);
2469 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
2470 let buffer_start_point_utf16 =
2471 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
2472
2473 let excerpt_start = excerpt_starts.next().unwrap();
2474 let mut offset = excerpt_start.bytes;
2475 let mut buffer_offset = buffer_range.start;
2476 let mut point = excerpt_start.lines;
2477 let mut buffer_point = buffer_start_point;
2478 let mut point_utf16 = excerpt_start.lines_utf16;
2479 let mut buffer_point_utf16 = buffer_start_point_utf16;
2480 for ch in buffer
2481 .snapshot()
2482 .chunks(buffer_range.clone(), None)
2483 .flat_map(|c| c.text.chars())
2484 {
2485 for _ in 0..ch.len_utf8() {
2486 let left_offset = snapshot.clip_offset(offset, Bias::Left);
2487 let right_offset = snapshot.clip_offset(offset, Bias::Right);
2488 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
2489 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
2490 assert_eq!(
2491 left_offset,
2492 excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
2493 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
2494 offset,
2495 buffer_id,
2496 buffer_offset,
2497 );
2498 assert_eq!(
2499 right_offset,
2500 excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
2501 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
2502 offset,
2503 buffer_id,
2504 buffer_offset,
2505 );
2506
2507 let left_point = snapshot.clip_point(point, Bias::Left);
2508 let right_point = snapshot.clip_point(point, Bias::Right);
2509 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
2510 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
2511 assert_eq!(
2512 left_point,
2513 excerpt_start.lines + (buffer_left_point - buffer_start_point),
2514 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
2515 point,
2516 buffer_id,
2517 buffer_point,
2518 );
2519 assert_eq!(
2520 right_point,
2521 excerpt_start.lines + (buffer_right_point - buffer_start_point),
2522 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
2523 point,
2524 buffer_id,
2525 buffer_point,
2526 );
2527
2528 assert_eq!(
2529 snapshot.point_to_offset(left_point),
2530 left_offset,
2531 "point_to_offset({:?})",
2532 left_point,
2533 );
2534 assert_eq!(
2535 snapshot.offset_to_point(left_offset),
2536 left_point,
2537 "offset_to_point({:?})",
2538 left_offset,
2539 );
2540
2541 offset += 1;
2542 buffer_offset += 1;
2543 if ch == '\n' {
2544 point += Point::new(1, 0);
2545 buffer_point += Point::new(1, 0);
2546 } else {
2547 point += Point::new(0, 1);
2548 buffer_point += Point::new(0, 1);
2549 }
2550 }
2551
2552 for _ in 0..ch.len_utf16() {
2553 let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
2554 let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
2555 let buffer_left_point_utf16 =
2556 buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
2557 let buffer_right_point_utf16 =
2558 buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
2559 assert_eq!(
2560 left_point_utf16,
2561 excerpt_start.lines_utf16
2562 + (buffer_left_point_utf16 - buffer_start_point_utf16),
2563 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
2564 point_utf16,
2565 buffer_id,
2566 buffer_point_utf16,
2567 );
2568 assert_eq!(
2569 right_point_utf16,
2570 excerpt_start.lines_utf16
2571 + (buffer_right_point_utf16 - buffer_start_point_utf16),
2572 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
2573 point_utf16,
2574 buffer_id,
2575 buffer_point_utf16,
2576 );
2577
2578 if ch == '\n' {
2579 point_utf16 += PointUtf16::new(1, 0);
2580 buffer_point_utf16 += PointUtf16::new(1, 0);
2581 } else {
2582 point_utf16 += PointUtf16::new(0, 1);
2583 buffer_point_utf16 += PointUtf16::new(0, 1);
2584 }
2585 }
2586 }
2587 }
2588
2589 for (row, line) in expected_text.split('\n').enumerate() {
2590 assert_eq!(
2591 snapshot.line_len(row as u32),
2592 line.len() as u32,
2593 "line_len({}).",
2594 row
2595 );
2596 }
2597
2598 let text_rope = Rope::from(expected_text.as_str());
2599 for _ in 0..10 {
2600 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2601 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2602
2603 assert_eq!(
2604 snapshot
2605 .text_for_range(start_ix..end_ix)
2606 .collect::<String>(),
2607 &expected_text[start_ix..end_ix],
2608 "incorrect text for range {:?}",
2609 start_ix..end_ix
2610 );
2611
2612 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
2613 assert_eq!(
2614 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
2615 expected_summary,
2616 "incorrect summary for range {:?}",
2617 start_ix..end_ix
2618 );
2619 }
2620
2621 for _ in 0..10 {
2622 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2623 assert_eq!(
2624 snapshot.reversed_chars_at(end_ix).collect::<String>(),
2625 expected_text[..end_ix].chars().rev().collect::<String>(),
2626 );
2627 }
2628
2629 for _ in 0..10 {
2630 let end_ix = rng.gen_range(0..=text_rope.len());
2631 let start_ix = rng.gen_range(0..=end_ix);
2632 assert_eq!(
2633 snapshot
2634 .bytes_in_range(start_ix..end_ix)
2635 .flatten()
2636 .copied()
2637 .collect::<Vec<_>>(),
2638 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
2639 "bytes_in_range({:?})",
2640 start_ix..end_ix,
2641 );
2642 }
2643 }
2644
2645 let snapshot = list.read(cx).snapshot(cx);
2646 for (old_snapshot, subscription) in old_versions {
2647 let edits = subscription.consume().into_inner();
2648
2649 log::info!(
2650 "applying subscription edits to old text: {:?}: {:?}",
2651 old_snapshot.text(),
2652 edits,
2653 );
2654
2655 let mut text = old_snapshot.text();
2656 for edit in edits {
2657 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
2658 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
2659 }
2660 assert_eq!(text.to_string(), snapshot.text());
2661 }
2662 }
2663
2664 #[gpui::test]
2665 fn test_history(cx: &mut MutableAppContext) {
2666 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
2667 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
2668 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2669 let group_interval = multibuffer.read(cx).history.group_interval;
2670 multibuffer.update(cx, |multibuffer, cx| {
2671 multibuffer.push_excerpt(
2672 ExcerptProperties {
2673 buffer: &buffer_1,
2674 range: 0..buffer_1.read(cx).len(),
2675 },
2676 cx,
2677 );
2678 multibuffer.push_excerpt(
2679 ExcerptProperties {
2680 buffer: &buffer_2,
2681 range: 0..buffer_2.read(cx).len(),
2682 },
2683 cx,
2684 );
2685 });
2686
2687 let mut now = Instant::now();
2688
2689 multibuffer.update(cx, |multibuffer, cx| {
2690 multibuffer.start_transaction_at(now, cx);
2691 multibuffer.edit(
2692 [
2693 Point::new(0, 0)..Point::new(0, 0),
2694 Point::new(1, 0)..Point::new(1, 0),
2695 ],
2696 "A",
2697 cx,
2698 );
2699 multibuffer.edit(
2700 [
2701 Point::new(0, 1)..Point::new(0, 1),
2702 Point::new(1, 1)..Point::new(1, 1),
2703 ],
2704 "B",
2705 cx,
2706 );
2707 multibuffer.end_transaction_at(now, cx);
2708 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2709
2710 now += 2 * group_interval;
2711 multibuffer.start_transaction_at(now, cx);
2712 multibuffer.edit([2..2], "C", cx);
2713 multibuffer.end_transaction_at(now, cx);
2714 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2715
2716 multibuffer.undo(cx);
2717 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2718
2719 multibuffer.undo(cx);
2720 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2721
2722 multibuffer.redo(cx);
2723 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2724
2725 multibuffer.redo(cx);
2726 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2727
2728 buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
2729 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2730
2731 multibuffer.undo(cx);
2732 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2733
2734 multibuffer.redo(cx);
2735 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2736
2737 multibuffer.redo(cx);
2738 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2739
2740 multibuffer.undo(cx);
2741 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2742
2743 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
2744 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2745
2746 multibuffer.undo(cx);
2747 assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
2748 });
2749 }
2750}