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