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