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};
8pub use language::Completion;
9use language::{
10 Buffer, BufferChunks, BufferSnapshot, Chunk, DiagnosticEntry, Event, File, Language, Outline,
11 OutlineItem, Selection, ToOffset as _, ToPoint as _, TransactionId,
12};
13use std::{
14 cell::{Ref, RefCell},
15 cmp, fmt, io,
16 iter::{self, FromIterator},
17 ops::{Range, Sub},
18 str,
19 sync::Arc,
20 time::{Duration, Instant},
21};
22use sum_tree::{Bias, Cursor, SumTree};
23use text::{
24 locator::Locator,
25 rope::TextDimension,
26 subscription::{Subscription, Topic},
27 AnchorRangeExt as _, Edit, Point, PointUtf16, TextSummary,
28};
29use theme::SyntaxTheme;
30use util::post_inc;
31
32const NEWLINES: &'static [u8] = &[b'\n'; u8::MAX as usize];
33
34pub type ExcerptId = Locator;
35
36pub struct MultiBuffer {
37 snapshot: RefCell<MultiBufferSnapshot>,
38 buffers: RefCell<HashMap<usize, BufferState>>,
39 subscriptions: Topic,
40 singleton: bool,
41 replica_id: ReplicaId,
42 history: History,
43}
44
45struct History {
46 next_transaction_id: usize,
47 undo_stack: Vec<Transaction>,
48 redo_stack: Vec<Transaction>,
49 transaction_depth: usize,
50 group_interval: Duration,
51}
52
53#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
54pub enum CharKind {
55 Newline,
56 Punctuation,
57 Whitespace,
58 Word,
59}
60
61struct Transaction {
62 id: usize,
63 buffer_transactions: HashSet<(usize, text::TransactionId)>,
64 first_edit_at: Instant,
65 last_edit_at: Instant,
66}
67
68pub trait ToOffset: 'static + fmt::Debug {
69 fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
70}
71
72pub trait ToPoint: 'static + fmt::Debug {
73 fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
74}
75
76struct BufferState {
77 buffer: ModelHandle<Buffer>,
78 last_version: clock::Global,
79 last_parse_count: usize,
80 last_selections_update_count: usize,
81 last_diagnostics_update_count: usize,
82 excerpts: Vec<ExcerptId>,
83 _subscriptions: [gpui::Subscription; 2],
84}
85
86#[derive(Clone, Default)]
87pub struct MultiBufferSnapshot {
88 singleton: bool,
89 excerpts: SumTree<Excerpt>,
90 parse_count: usize,
91 diagnostics_update_count: usize,
92 is_dirty: bool,
93 has_conflict: bool,
94}
95
96pub struct ExcerptProperties<'a, T> {
97 pub buffer: &'a ModelHandle<Buffer>,
98 pub range: Range<T>,
99}
100
101#[derive(Clone)]
102struct Excerpt {
103 id: ExcerptId,
104 buffer_id: usize,
105 buffer: BufferSnapshot,
106 range: Range<text::Anchor>,
107 max_buffer_row: u32,
108 text_summary: TextSummary,
109 has_trailing_newline: bool,
110}
111
112#[derive(Clone, Debug, Default)]
113struct ExcerptSummary {
114 excerpt_id: ExcerptId,
115 max_buffer_row: u32,
116 text: TextSummary,
117}
118
119pub struct MultiBufferRows<'a> {
120 buffer_row_range: Range<u32>,
121 excerpts: Cursor<'a, Excerpt, Point>,
122}
123
124pub struct MultiBufferChunks<'a> {
125 range: Range<usize>,
126 excerpts: Cursor<'a, Excerpt, usize>,
127 excerpt_chunks: Option<ExcerptChunks<'a>>,
128 theme: Option<&'a SyntaxTheme>,
129}
130
131pub struct MultiBufferBytes<'a> {
132 range: Range<usize>,
133 excerpts: Cursor<'a, Excerpt, usize>,
134 excerpt_bytes: Option<ExcerptBytes<'a>>,
135 chunk: &'a [u8],
136}
137
138struct ExcerptChunks<'a> {
139 content_chunks: BufferChunks<'a>,
140 footer_height: usize,
141}
142
143struct ExcerptBytes<'a> {
144 content_bytes: language::rope::Bytes<'a>,
145 footer_height: usize,
146}
147
148impl MultiBuffer {
149 pub fn new(replica_id: ReplicaId) -> Self {
150 Self {
151 snapshot: Default::default(),
152 buffers: Default::default(),
153 subscriptions: Default::default(),
154 singleton: false,
155 replica_id,
156 history: History {
157 next_transaction_id: Default::default(),
158 undo_stack: Default::default(),
159 redo_stack: Default::default(),
160 transaction_depth: 0,
161 group_interval: Duration::from_millis(300),
162 },
163 }
164 }
165
166 pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
167 let mut this = Self::new(buffer.read(cx).replica_id());
168 this.singleton = true;
169 this.push_excerpt(
170 ExcerptProperties {
171 buffer: &buffer,
172 range: text::Anchor::min()..text::Anchor::max(),
173 },
174 cx,
175 );
176 this.snapshot.borrow_mut().singleton = true;
177 this
178 }
179
180 #[cfg(any(test, feature = "test-support"))]
181 pub fn build_simple(text: &str, cx: &mut gpui::MutableAppContext) -> ModelHandle<Self> {
182 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
183 cx.add_model(|cx| Self::singleton(buffer, cx))
184 }
185
186 #[cfg(any(test, feature = "test-support"))]
187 pub fn build_random(
188 mut rng: &mut impl rand::Rng,
189 cx: &mut gpui::MutableAppContext,
190 ) -> ModelHandle<Self> {
191 use rand::prelude::*;
192 use std::env;
193 use text::RandomCharIter;
194
195 let max_excerpts = env::var("MAX_EXCERPTS")
196 .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
197 .unwrap_or(5);
198 let excerpts = rng.gen_range(1..=max_excerpts);
199
200 cx.add_model(|cx| {
201 let mut multibuffer = MultiBuffer::new(0);
202 let mut buffers = Vec::new();
203 for _ in 0..excerpts {
204 let buffer_handle = if rng.gen() || buffers.is_empty() {
205 let text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
206 buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
207 let buffer = buffers.last().unwrap();
208 log::info!(
209 "Creating new buffer {} with text: {:?}",
210 buffer.id(),
211 buffer.read(cx).text()
212 );
213 buffers.last().unwrap()
214 } else {
215 buffers.choose(rng).unwrap()
216 };
217
218 let buffer = buffer_handle.read(cx);
219 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
220 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
221 let header_height = rng.gen_range(0..=5);
222 log::info!(
223 "Inserting excerpt from buffer {} with header height {} and range {:?}: {:?}",
224 buffer_handle.id(),
225 header_height,
226 start_ix..end_ix,
227 &buffer.text()[start_ix..end_ix]
228 );
229
230 multibuffer.push_excerpt(
231 ExcerptProperties {
232 buffer: buffer_handle,
233 range: start_ix..end_ix,
234 },
235 cx,
236 );
237 }
238 multibuffer
239 })
240 }
241
242 pub fn replica_id(&self) -> ReplicaId {
243 self.replica_id
244 }
245
246 pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
247 self.sync(cx);
248 self.snapshot.borrow().clone()
249 }
250
251 pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
252 self.sync(cx);
253 self.snapshot.borrow()
254 }
255
256 pub fn as_singleton(&self) -> Option<ModelHandle<Buffer>> {
257 if self.singleton {
258 return Some(
259 self.buffers
260 .borrow()
261 .values()
262 .next()
263 .unwrap()
264 .buffer
265 .clone(),
266 );
267 } else {
268 None
269 }
270 }
271
272 pub fn subscribe(&mut self) -> Subscription {
273 self.subscriptions.subscribe()
274 }
275
276 pub fn edit<I, S, T>(&mut self, ranges: I, new_text: T, cx: &mut ModelContext<Self>)
277 where
278 I: IntoIterator<Item = Range<S>>,
279 S: ToOffset,
280 T: Into<String>,
281 {
282 self.edit_internal(ranges, new_text, false, cx)
283 }
284
285 pub fn edit_with_autoindent<I, S, T>(
286 &mut self,
287 ranges: I,
288 new_text: T,
289 cx: &mut ModelContext<Self>,
290 ) where
291 I: IntoIterator<Item = Range<S>>,
292 S: ToOffset,
293 T: Into<String>,
294 {
295 self.edit_internal(ranges, new_text, true, cx)
296 }
297
298 pub fn edit_internal<I, S, T>(
299 &mut self,
300 ranges_iter: I,
301 new_text: T,
302 autoindent: bool,
303 cx: &mut ModelContext<Self>,
304 ) where
305 I: IntoIterator<Item = Range<S>>,
306 S: ToOffset,
307 T: Into<String>,
308 {
309 if let Some(buffer) = self.as_singleton() {
310 let snapshot = self.read(cx);
311 let ranges = ranges_iter
312 .into_iter()
313 .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot));
314 return buffer.update(cx, |buffer, cx| {
315 if autoindent {
316 buffer.edit_with_autoindent(ranges, new_text, cx);
317 } else {
318 buffer.edit(ranges, new_text, cx);
319 }
320 });
321 }
322
323 let snapshot = self.read(cx);
324 let mut buffer_edits: HashMap<usize, Vec<(Range<usize>, bool)>> = Default::default();
325 let mut cursor = snapshot.excerpts.cursor::<usize>();
326 for range in ranges_iter {
327 let start = range.start.to_offset(&snapshot);
328 let end = range.end.to_offset(&snapshot);
329 cursor.seek(&start, Bias::Right, &());
330 if cursor.item().is_none() && start == *cursor.start() {
331 cursor.prev(&());
332 }
333 let start_excerpt = cursor.item().expect("start offset out of bounds");
334 let start_overshoot = start - cursor.start();
335 let buffer_start =
336 start_excerpt.range.start.to_offset(&start_excerpt.buffer) + start_overshoot;
337
338 cursor.seek(&end, Bias::Right, &());
339 if cursor.item().is_none() && end == *cursor.start() {
340 cursor.prev(&());
341 }
342 let end_excerpt = cursor.item().expect("end offset out of bounds");
343 let end_overshoot = end - cursor.start();
344 let buffer_end = end_excerpt.range.start.to_offset(&end_excerpt.buffer) + end_overshoot;
345
346 if start_excerpt.id == end_excerpt.id {
347 buffer_edits
348 .entry(start_excerpt.buffer_id)
349 .or_insert(Vec::new())
350 .push((buffer_start..buffer_end, true));
351 } else {
352 let start_excerpt_range =
353 buffer_start..start_excerpt.range.end.to_offset(&start_excerpt.buffer);
354 let end_excerpt_range =
355 end_excerpt.range.start.to_offset(&end_excerpt.buffer)..buffer_end;
356 buffer_edits
357 .entry(start_excerpt.buffer_id)
358 .or_insert(Vec::new())
359 .push((start_excerpt_range, true));
360 buffer_edits
361 .entry(end_excerpt.buffer_id)
362 .or_insert(Vec::new())
363 .push((end_excerpt_range, false));
364
365 cursor.seek(&start, Bias::Right, &());
366 cursor.next(&());
367 while let Some(excerpt) = cursor.item() {
368 if excerpt.id == end_excerpt.id {
369 break;
370 }
371 buffer_edits
372 .entry(excerpt.buffer_id)
373 .or_insert(Vec::new())
374 .push((excerpt.range.to_offset(&excerpt.buffer), false));
375 cursor.next(&());
376 }
377 }
378 }
379
380 let new_text = new_text.into();
381 for (buffer_id, mut edits) in buffer_edits {
382 edits.sort_unstable_by_key(|(range, _)| range.start);
383 self.buffers.borrow()[&buffer_id]
384 .buffer
385 .update(cx, |buffer, cx| {
386 let mut edits = edits.into_iter().peekable();
387 let mut insertions = Vec::new();
388 let mut deletions = Vec::new();
389 while let Some((mut range, mut is_insertion)) = edits.next() {
390 while let Some((next_range, next_is_insertion)) = edits.peek() {
391 if range.end >= next_range.start {
392 range.end = cmp::max(next_range.end, range.end);
393 is_insertion |= *next_is_insertion;
394 edits.next();
395 } else {
396 break;
397 }
398 }
399
400 if is_insertion {
401 insertions.push(
402 buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
403 );
404 } else if !range.is_empty() {
405 deletions.push(
406 buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
407 );
408 }
409 }
410
411 if autoindent {
412 buffer.edit_with_autoindent(deletions, "", cx);
413 buffer.edit_with_autoindent(insertions, new_text.clone(), cx);
414 } else {
415 buffer.edit(deletions, "", cx);
416 buffer.edit(insertions, new_text.clone(), cx);
417 }
418 })
419 }
420 }
421
422 pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
423 self.start_transaction_at(Instant::now(), cx)
424 }
425
426 pub(crate) fn start_transaction_at(
427 &mut self,
428 now: Instant,
429 cx: &mut ModelContext<Self>,
430 ) -> Option<TransactionId> {
431 if let Some(buffer) = self.as_singleton() {
432 return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
433 }
434
435 for BufferState { buffer, .. } in self.buffers.borrow().values() {
436 buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
437 }
438 self.history.start_transaction(now)
439 }
440
441 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
442 self.end_transaction_at(Instant::now(), cx)
443 }
444
445 pub(crate) fn end_transaction_at(
446 &mut self,
447 now: Instant,
448 cx: &mut ModelContext<Self>,
449 ) -> Option<TransactionId> {
450 if let Some(buffer) = self.as_singleton() {
451 return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
452 }
453
454 let mut buffer_transactions = HashSet::default();
455 for BufferState { buffer, .. } in self.buffers.borrow().values() {
456 if let Some(transaction_id) =
457 buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
458 {
459 buffer_transactions.insert((buffer.id(), transaction_id));
460 }
461 }
462
463 if self.history.end_transaction(now, buffer_transactions) {
464 let transaction_id = self.history.group().unwrap();
465 Some(transaction_id)
466 } else {
467 None
468 }
469 }
470
471 pub fn avoid_grouping_next_transaction(&mut self, cx: &mut ModelContext<Self>) {
472 for BufferState { buffer, .. } in self.buffers.borrow().values() {
473 buffer.update(cx, |buffer, _| buffer.avoid_grouping_next_transaction());
474 }
475 }
476
477 pub fn set_active_selections(
478 &mut self,
479 selections: &[Selection<Anchor>],
480 cx: &mut ModelContext<Self>,
481 ) {
482 let mut selections_by_buffer: HashMap<usize, Vec<Selection<text::Anchor>>> =
483 Default::default();
484 let snapshot = self.read(cx);
485 let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
486 for selection in selections {
487 cursor.seek(&Some(&selection.start.excerpt_id), Bias::Left, &());
488 while let Some(excerpt) = cursor.item() {
489 if excerpt.id > selection.end.excerpt_id {
490 break;
491 }
492
493 let mut start = excerpt.range.start.clone();
494 let mut end = excerpt.range.end.clone();
495 if excerpt.id == selection.start.excerpt_id {
496 start = selection.start.text_anchor.clone();
497 }
498 if excerpt.id == selection.end.excerpt_id {
499 end = selection.end.text_anchor.clone();
500 }
501 selections_by_buffer
502 .entry(excerpt.buffer_id)
503 .or_default()
504 .push(Selection {
505 id: selection.id,
506 start,
507 end,
508 reversed: selection.reversed,
509 goal: selection.goal,
510 });
511
512 cursor.next(&());
513 }
514 }
515
516 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
517 if !selections_by_buffer.contains_key(buffer_id) {
518 buffer_state
519 .buffer
520 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
521 }
522 }
523
524 for (buffer_id, mut selections) in selections_by_buffer {
525 self.buffers.borrow()[&buffer_id]
526 .buffer
527 .update(cx, |buffer, cx| {
528 selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer).unwrap());
529 let mut selections = selections.into_iter().peekable();
530 let merged_selections = Arc::from_iter(iter::from_fn(|| {
531 let mut selection = selections.next()?;
532 while let Some(next_selection) = selections.peek() {
533 if selection
534 .end
535 .cmp(&next_selection.start, buffer)
536 .unwrap()
537 .is_ge()
538 {
539 let next_selection = selections.next().unwrap();
540 if next_selection
541 .end
542 .cmp(&selection.end, buffer)
543 .unwrap()
544 .is_ge()
545 {
546 selection.end = next_selection.end;
547 }
548 } else {
549 break;
550 }
551 }
552 Some(selection)
553 }));
554 buffer.set_active_selections(merged_selections, cx);
555 });
556 }
557 }
558
559 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
560 for buffer in self.buffers.borrow().values() {
561 buffer
562 .buffer
563 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
564 }
565 }
566
567 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
568 if let Some(buffer) = self.as_singleton() {
569 return buffer.update(cx, |buffer, cx| buffer.undo(cx));
570 }
571
572 while let Some(transaction) = self.history.pop_undo() {
573 let mut undone = false;
574 for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
575 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(&buffer_id) {
576 undone |= buffer.update(cx, |buf, cx| {
577 buf.undo_transaction(*buffer_transaction_id, cx)
578 });
579 }
580 }
581
582 if undone {
583 return Some(transaction.id);
584 }
585 }
586
587 None
588 }
589
590 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
591 if let Some(buffer) = self.as_singleton() {
592 return buffer.update(cx, |buffer, cx| buffer.redo(cx));
593 }
594
595 while let Some(transaction) = self.history.pop_redo() {
596 let mut redone = false;
597 for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
598 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(&buffer_id) {
599 redone |= buffer.update(cx, |buf, cx| {
600 buf.redo_transaction(*buffer_transaction_id, cx)
601 });
602 }
603 }
604
605 if redone {
606 return Some(transaction.id);
607 }
608 }
609
610 None
611 }
612
613 pub fn push_excerpt<O>(
614 &mut self,
615 props: ExcerptProperties<O>,
616 cx: &mut ModelContext<Self>,
617 ) -> ExcerptId
618 where
619 O: text::ToOffset,
620 {
621 self.insert_excerpt_after(&ExcerptId::max(), props, cx)
622 }
623
624 pub fn insert_excerpt_after<O>(
625 &mut self,
626 prev_excerpt_id: &ExcerptId,
627 props: ExcerptProperties<O>,
628 cx: &mut ModelContext<Self>,
629 ) -> ExcerptId
630 where
631 O: text::ToOffset,
632 {
633 assert_eq!(self.history.transaction_depth, 0);
634 self.sync(cx);
635
636 let buffer_snapshot = props.buffer.read(cx).snapshot();
637 let range = buffer_snapshot.anchor_before(&props.range.start)
638 ..buffer_snapshot.anchor_after(&props.range.end);
639 let mut snapshot = self.snapshot.borrow_mut();
640 let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
641 let mut new_excerpts = cursor.slice(&Some(prev_excerpt_id), Bias::Right, &());
642
643 let mut prev_id = ExcerptId::min();
644 let edit_start = new_excerpts.summary().text.bytes;
645 new_excerpts.update_last(
646 |excerpt| {
647 excerpt.has_trailing_newline = true;
648 prev_id = excerpt.id.clone();
649 },
650 &(),
651 );
652
653 let mut next_id = ExcerptId::max();
654 if let Some(next_excerpt) = cursor.item() {
655 next_id = next_excerpt.id.clone();
656 }
657
658 let id = ExcerptId::between(&prev_id, &next_id);
659
660 let mut buffers = self.buffers.borrow_mut();
661 let buffer_state = buffers
662 .entry(props.buffer.id())
663 .or_insert_with(|| BufferState {
664 last_version: buffer_snapshot.version().clone(),
665 last_parse_count: buffer_snapshot.parse_count(),
666 last_selections_update_count: buffer_snapshot.selections_update_count(),
667 last_diagnostics_update_count: buffer_snapshot.diagnostics_update_count(),
668 excerpts: Default::default(),
669 _subscriptions: [
670 cx.observe(&props.buffer, |_, _, cx| cx.notify()),
671 cx.subscribe(&props.buffer, Self::on_buffer_event),
672 ],
673 buffer: props.buffer.clone(),
674 });
675 if let Err(ix) = buffer_state.excerpts.binary_search(&id) {
676 buffer_state.excerpts.insert(ix, id.clone());
677 }
678
679 let excerpt = Excerpt::new(
680 id.clone(),
681 props.buffer.id(),
682 buffer_snapshot,
683 range,
684 cursor.item().is_some(),
685 );
686 new_excerpts.push(excerpt, &());
687 let edit_end = new_excerpts.summary().text.bytes;
688
689 new_excerpts.push_tree(cursor.suffix(&()), &());
690 drop(cursor);
691 snapshot.excerpts = new_excerpts;
692
693 self.subscriptions.publish_mut([Edit {
694 old: edit_start..edit_start,
695 new: edit_start..edit_end,
696 }]);
697
698 cx.notify();
699 id
700 }
701
702 pub fn excerpt_ids_for_buffer(&self, buffer: &ModelHandle<Buffer>) -> Vec<ExcerptId> {
703 self.buffers
704 .borrow()
705 .get(&buffer.id())
706 .map_or(Vec::new(), |state| state.excerpts.clone())
707 }
708
709 pub fn excerpted_buffers<'a, T: ToOffset>(
710 &'a self,
711 range: Range<T>,
712 cx: &AppContext,
713 ) -> Vec<(ModelHandle<Buffer>, Range<usize>)> {
714 let snapshot = self.snapshot(cx);
715 let start = range.start.to_offset(&snapshot);
716 let end = range.end.to_offset(&snapshot);
717
718 let mut result = Vec::new();
719 let mut cursor = snapshot.excerpts.cursor::<usize>();
720 cursor.seek(&start, Bias::Right, &());
721 while let Some(excerpt) = cursor.item() {
722 if *cursor.start() > end {
723 break;
724 }
725
726 let mut end_before_newline = cursor.end(&());
727 if excerpt.has_trailing_newline {
728 end_before_newline -= 1;
729 }
730 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
731 let start = excerpt_start + (cmp::max(start, *cursor.start()) - *cursor.start());
732 let end = excerpt_start + (cmp::min(end, end_before_newline) - *cursor.start());
733 let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
734 result.push((buffer, start..end));
735 cursor.next(&());
736 }
737
738 result
739 }
740
741 pub fn remove_excerpts<'a>(
742 &mut self,
743 excerpt_ids: impl IntoIterator<Item = &'a ExcerptId>,
744 cx: &mut ModelContext<Self>,
745 ) {
746 let mut buffers = self.buffers.borrow_mut();
747 let mut snapshot = self.snapshot.borrow_mut();
748 let mut new_excerpts = SumTree::new();
749 let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
750 let mut edits = Vec::new();
751 let mut excerpt_ids = excerpt_ids.into_iter().peekable();
752
753 while let Some(mut excerpt_id) = excerpt_ids.next() {
754 // Seek to the next excerpt to remove, preserving any preceding excerpts.
755 new_excerpts.push_tree(cursor.slice(&Some(excerpt_id), Bias::Left, &()), &());
756 if let Some(mut excerpt) = cursor.item() {
757 if excerpt.id != *excerpt_id {
758 continue;
759 }
760 let mut old_start = cursor.start().1;
761
762 // Skip over the removed excerpt.
763 loop {
764 if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
765 buffer_state.excerpts.retain(|id| id != excerpt_id);
766 if buffer_state.excerpts.is_empty() {
767 buffers.remove(&excerpt.buffer_id);
768 }
769 }
770 cursor.next(&());
771
772 // Skip over any subsequent excerpts that are also removed.
773 if let Some(&next_excerpt_id) = excerpt_ids.peek() {
774 if let Some(next_excerpt) = cursor.item() {
775 if next_excerpt.id == *next_excerpt_id {
776 excerpt = next_excerpt;
777 excerpt_id = excerpt_ids.next().unwrap();
778 continue;
779 }
780 }
781 }
782
783 break;
784 }
785
786 // When removing the last excerpt, remove the trailing newline from
787 // the previous excerpt.
788 if cursor.item().is_none() && old_start > 0 {
789 old_start -= 1;
790 new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
791 }
792
793 // Push an edit for the removal of this run of excerpts.
794 let old_end = cursor.start().1;
795 let new_start = new_excerpts.summary().text.bytes;
796 edits.push(Edit {
797 old: old_start..old_end,
798 new: new_start..new_start,
799 });
800 }
801 }
802 new_excerpts.push_tree(cursor.suffix(&()), &());
803 drop(cursor);
804 snapshot.excerpts = new_excerpts;
805 self.subscriptions.publish_mut(edits);
806 cx.notify();
807 }
808
809 pub fn text_anchor_for_position<'a, T: ToOffset>(
810 &'a self,
811 position: T,
812 cx: &AppContext,
813 ) -> (ModelHandle<Buffer>, language::Anchor) {
814 let snapshot = self.read(cx);
815 let anchor = snapshot.anchor_before(position);
816 (
817 self.buffers.borrow()[&anchor.buffer_id].buffer.clone(),
818 anchor.text_anchor,
819 )
820 }
821
822 fn on_buffer_event(
823 &mut self,
824 _: ModelHandle<Buffer>,
825 event: &Event,
826 cx: &mut ModelContext<Self>,
827 ) {
828 cx.emit(event.clone());
829 }
830
831 pub fn format(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
832 let mut format_tasks = Vec::new();
833 for BufferState { buffer, .. } in self.buffers.borrow().values() {
834 format_tasks.push(buffer.update(cx, |buffer, cx| buffer.format(cx)));
835 }
836
837 cx.spawn(|_, _| async move {
838 for format in format_tasks {
839 format.await?;
840 }
841 Ok(())
842 })
843 }
844
845 pub fn save(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
846 let mut save_tasks = Vec::new();
847 for BufferState { buffer, .. } in self.buffers.borrow().values() {
848 save_tasks.push(buffer.update(cx, |buffer, cx| buffer.save(cx)));
849 }
850
851 cx.spawn(|_, _| async move {
852 for save in save_tasks {
853 save.await?;
854 }
855 Ok(())
856 })
857 }
858
859 pub fn completions<T>(
860 &self,
861 position: T,
862 cx: &mut ModelContext<Self>,
863 ) -> Task<Result<Vec<Completion<Anchor>>>>
864 where
865 T: ToOffset,
866 {
867 let anchor = self.read(cx).anchor_before(position);
868 let buffer = self.buffers.borrow()[&anchor.buffer_id].buffer.clone();
869 let completions =
870 buffer.update(cx, |buffer, cx| buffer.completions(anchor.text_anchor, cx));
871 cx.spawn(|this, cx| async move {
872 completions.await.map(|completions| {
873 let snapshot = this.read_with(&cx, |buffer, cx| buffer.snapshot(cx));
874 completions
875 .into_iter()
876 .map(|completion| Completion {
877 old_range: snapshot.anchor_in_excerpt(
878 anchor.excerpt_id.clone(),
879 completion.old_range.start,
880 )
881 ..snapshot.anchor_in_excerpt(
882 anchor.excerpt_id.clone(),
883 completion.old_range.end,
884 ),
885 new_text: completion.new_text,
886 lsp_completion: completion.lsp_completion,
887 })
888 .collect()
889 })
890 })
891 }
892
893 pub fn is_completion_trigger<T>(&self, position: T, text: &str, cx: &AppContext) -> bool
894 where
895 T: ToOffset,
896 {
897 let mut chars = text.chars();
898 let char = if let Some(char) = chars.next() {
899 char
900 } else {
901 return false;
902 };
903 if chars.next().is_some() {
904 return false;
905 }
906
907 if char.is_alphanumeric() || char == '_' {
908 return true;
909 }
910
911 let snapshot = self.snapshot(cx);
912 let anchor = snapshot.anchor_before(position);
913 let buffer = self.buffers.borrow()[&anchor.buffer_id].buffer.clone();
914 buffer
915 .read(cx)
916 .completion_triggers()
917 .iter()
918 .any(|string| string == text)
919 }
920
921 pub fn apply_additional_edits_for_completion(
922 &self,
923 completion: Completion<Anchor>,
924 cx: &mut ModelContext<Self>,
925 ) -> Task<Result<()>> {
926 let buffer = if let Some(buffer_state) = self
927 .buffers
928 .borrow()
929 .get(&completion.old_range.start.buffer_id)
930 {
931 buffer_state.buffer.clone()
932 } else {
933 return Task::ready(Ok(()));
934 };
935
936 let apply_edits = buffer.update(cx, |buffer, cx| {
937 buffer.apply_additional_edits_for_completion(
938 Completion {
939 old_range: completion.old_range.start.text_anchor
940 ..completion.old_range.end.text_anchor,
941 new_text: completion.new_text,
942 lsp_completion: completion.lsp_completion,
943 },
944 true,
945 cx,
946 )
947 });
948 cx.foreground().spawn(async move {
949 apply_edits.await?;
950 Ok(())
951 })
952 }
953
954 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
955 self.buffers
956 .borrow()
957 .values()
958 .next()
959 .and_then(|state| state.buffer.read(cx).language())
960 }
961
962 pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
963 self.as_singleton()?.read(cx).file()
964 }
965
966 #[cfg(test)]
967 pub fn is_parsing(&self, cx: &AppContext) -> bool {
968 self.as_singleton().unwrap().read(cx).is_parsing()
969 }
970
971 fn sync(&self, cx: &AppContext) {
972 let mut snapshot = self.snapshot.borrow_mut();
973 let mut excerpts_to_edit = Vec::new();
974 let mut reparsed = false;
975 let mut diagnostics_updated = false;
976 let mut is_dirty = false;
977 let mut has_conflict = false;
978 let mut buffers = self.buffers.borrow_mut();
979 for buffer_state in buffers.values_mut() {
980 let buffer = buffer_state.buffer.read(cx);
981 let version = buffer.version();
982 let parse_count = buffer.parse_count();
983 let selections_update_count = buffer.selections_update_count();
984 let diagnostics_update_count = buffer.diagnostics_update_count();
985
986 let buffer_edited = version.changed_since(&buffer_state.last_version);
987 let buffer_reparsed = parse_count > buffer_state.last_parse_count;
988 let buffer_selections_updated =
989 selections_update_count > buffer_state.last_selections_update_count;
990 let buffer_diagnostics_updated =
991 diagnostics_update_count > buffer_state.last_diagnostics_update_count;
992 if buffer_edited
993 || buffer_reparsed
994 || buffer_selections_updated
995 || buffer_diagnostics_updated
996 {
997 buffer_state.last_version = version;
998 buffer_state.last_parse_count = parse_count;
999 buffer_state.last_selections_update_count = selections_update_count;
1000 buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1001 excerpts_to_edit.extend(
1002 buffer_state
1003 .excerpts
1004 .iter()
1005 .map(|excerpt_id| (excerpt_id, buffer_state.buffer.clone(), buffer_edited)),
1006 );
1007 }
1008
1009 reparsed |= buffer_reparsed;
1010 diagnostics_updated |= buffer_diagnostics_updated;
1011 is_dirty |= buffer.is_dirty();
1012 has_conflict |= buffer.has_conflict();
1013 }
1014 if reparsed {
1015 snapshot.parse_count += 1;
1016 }
1017 if diagnostics_updated {
1018 snapshot.diagnostics_update_count += 1;
1019 }
1020 snapshot.is_dirty = is_dirty;
1021 snapshot.has_conflict = has_conflict;
1022
1023 excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
1024
1025 let mut edits = Vec::new();
1026 let mut new_excerpts = SumTree::new();
1027 let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
1028
1029 for (id, buffer, buffer_edited) in excerpts_to_edit {
1030 new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
1031 let old_excerpt = cursor.item().unwrap();
1032 let buffer_id = buffer.id();
1033 let buffer = buffer.read(cx);
1034
1035 let mut new_excerpt;
1036 if buffer_edited {
1037 edits.extend(
1038 buffer
1039 .edits_since_in_range::<usize>(
1040 old_excerpt.buffer.version(),
1041 old_excerpt.range.clone(),
1042 )
1043 .map(|mut edit| {
1044 let excerpt_old_start = cursor.start().1;
1045 let excerpt_new_start = new_excerpts.summary().text.bytes;
1046 edit.old.start += excerpt_old_start;
1047 edit.old.end += excerpt_old_start;
1048 edit.new.start += excerpt_new_start;
1049 edit.new.end += excerpt_new_start;
1050 edit
1051 }),
1052 );
1053
1054 new_excerpt = Excerpt::new(
1055 id.clone(),
1056 buffer_id,
1057 buffer.snapshot(),
1058 old_excerpt.range.clone(),
1059 old_excerpt.has_trailing_newline,
1060 );
1061 } else {
1062 new_excerpt = old_excerpt.clone();
1063 new_excerpt.buffer = buffer.snapshot();
1064 }
1065
1066 new_excerpts.push(new_excerpt, &());
1067 cursor.next(&());
1068 }
1069 new_excerpts.push_tree(cursor.suffix(&()), &());
1070
1071 drop(cursor);
1072 snapshot.excerpts = new_excerpts;
1073
1074 self.subscriptions.publish(edits);
1075 }
1076}
1077
1078#[cfg(any(test, feature = "test-support"))]
1079impl MultiBuffer {
1080 pub fn randomly_edit(
1081 &mut self,
1082 rng: &mut impl rand::Rng,
1083 count: usize,
1084 cx: &mut ModelContext<Self>,
1085 ) {
1086 use text::RandomCharIter;
1087
1088 let snapshot = self.read(cx);
1089 let mut old_ranges: Vec<Range<usize>> = Vec::new();
1090 for _ in 0..count {
1091 let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1092 if last_end > snapshot.len() {
1093 break;
1094 }
1095 let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
1096 let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1097 old_ranges.push(start_ix..end_ix);
1098 }
1099 let new_text_len = rng.gen_range(0..10);
1100 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1101 log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
1102 drop(snapshot);
1103
1104 self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1105 }
1106}
1107
1108impl Entity for MultiBuffer {
1109 type Event = language::Event;
1110}
1111
1112impl MultiBufferSnapshot {
1113 pub fn text(&self) -> String {
1114 self.chunks(0..self.len(), None)
1115 .map(|chunk| chunk.text)
1116 .collect()
1117 }
1118
1119 pub fn reversed_chars_at<'a, T: ToOffset>(
1120 &'a self,
1121 position: T,
1122 ) -> impl Iterator<Item = char> + 'a {
1123 let mut offset = position.to_offset(self);
1124 let mut cursor = self.excerpts.cursor::<usize>();
1125 cursor.seek(&offset, Bias::Left, &());
1126 let mut excerpt_chunks = cursor.item().map(|excerpt| {
1127 let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
1128 let start = excerpt.range.start.to_offset(&excerpt.buffer);
1129 let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1130 excerpt.buffer.reversed_chunks_in_range(start..end)
1131 });
1132 iter::from_fn(move || {
1133 if offset == *cursor.start() {
1134 cursor.prev(&());
1135 let excerpt = cursor.item()?;
1136 excerpt_chunks = Some(
1137 excerpt
1138 .buffer
1139 .reversed_chunks_in_range(excerpt.range.clone()),
1140 );
1141 }
1142
1143 let excerpt = cursor.item().unwrap();
1144 if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1145 offset -= 1;
1146 Some("\n")
1147 } else {
1148 let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1149 offset -= chunk.len();
1150 Some(chunk)
1151 }
1152 })
1153 .flat_map(|c| c.chars().rev())
1154 }
1155
1156 pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1157 let offset = position.to_offset(self);
1158 self.text_for_range(offset..self.len())
1159 .flat_map(|chunk| chunk.chars())
1160 }
1161
1162 pub fn text_for_range<'a, T: ToOffset>(
1163 &'a self,
1164 range: Range<T>,
1165 ) -> impl Iterator<Item = &'a str> {
1166 self.chunks(range, None).map(|chunk| chunk.text)
1167 }
1168
1169 pub fn is_line_blank(&self, row: u32) -> bool {
1170 self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1171 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1172 }
1173
1174 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1175 where
1176 T: ToOffset,
1177 {
1178 let position = position.to_offset(self);
1179 position == self.clip_offset(position, Bias::Left)
1180 && self
1181 .bytes_in_range(position..self.len())
1182 .flatten()
1183 .copied()
1184 .take(needle.len())
1185 .eq(needle.bytes())
1186 }
1187
1188 pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1189 let mut start = start.to_offset(self);
1190 let mut end = start;
1191 let mut next_chars = self.chars_at(start).peekable();
1192 let mut prev_chars = self.reversed_chars_at(start).peekable();
1193 let word_kind = cmp::max(
1194 prev_chars.peek().copied().map(char_kind),
1195 next_chars.peek().copied().map(char_kind),
1196 );
1197
1198 for ch in prev_chars {
1199 if Some(char_kind(ch)) == word_kind {
1200 start -= ch.len_utf8();
1201 } else {
1202 break;
1203 }
1204 }
1205
1206 for ch in next_chars {
1207 if Some(char_kind(ch)) == word_kind {
1208 end += ch.len_utf8();
1209 } else {
1210 break;
1211 }
1212 }
1213
1214 (start..end, word_kind)
1215 }
1216
1217 fn as_singleton(&self) -> Option<&Excerpt> {
1218 if self.singleton {
1219 self.excerpts.iter().next()
1220 } else {
1221 None
1222 }
1223 }
1224
1225 pub fn len(&self) -> usize {
1226 self.excerpts.summary().text.bytes
1227 }
1228
1229 pub fn max_buffer_row(&self) -> u32 {
1230 self.excerpts.summary().max_buffer_row
1231 }
1232
1233 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1234 if let Some(excerpt) = self.as_singleton() {
1235 return excerpt.buffer.clip_offset(offset, bias);
1236 }
1237
1238 let mut cursor = self.excerpts.cursor::<usize>();
1239 cursor.seek(&offset, Bias::Right, &());
1240 let overshoot = if let Some(excerpt) = cursor.item() {
1241 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1242 let buffer_offset = excerpt
1243 .buffer
1244 .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1245 buffer_offset.saturating_sub(excerpt_start)
1246 } else {
1247 0
1248 };
1249 cursor.start() + overshoot
1250 }
1251
1252 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1253 if let Some(excerpt) = self.as_singleton() {
1254 return excerpt.buffer.clip_point(point, bias);
1255 }
1256
1257 let mut cursor = self.excerpts.cursor::<Point>();
1258 cursor.seek(&point, Bias::Right, &());
1259 let overshoot = if let Some(excerpt) = cursor.item() {
1260 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1261 let buffer_point = excerpt
1262 .buffer
1263 .clip_point(excerpt_start + (point - cursor.start()), bias);
1264 buffer_point.saturating_sub(excerpt_start)
1265 } else {
1266 Point::zero()
1267 };
1268 *cursor.start() + overshoot
1269 }
1270
1271 pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1272 if let Some(excerpt) = self.as_singleton() {
1273 return excerpt.buffer.clip_point_utf16(point, bias);
1274 }
1275
1276 let mut cursor = self.excerpts.cursor::<PointUtf16>();
1277 cursor.seek(&point, Bias::Right, &());
1278 let overshoot = if let Some(excerpt) = cursor.item() {
1279 let excerpt_start = excerpt
1280 .buffer
1281 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1282 let buffer_point = excerpt
1283 .buffer
1284 .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1285 buffer_point.saturating_sub(excerpt_start)
1286 } else {
1287 PointUtf16::zero()
1288 };
1289 *cursor.start() + overshoot
1290 }
1291
1292 pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1293 let range = range.start.to_offset(self)..range.end.to_offset(self);
1294 let mut excerpts = self.excerpts.cursor::<usize>();
1295 excerpts.seek(&range.start, Bias::Right, &());
1296
1297 let mut chunk = &[][..];
1298 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1299 let mut excerpt_bytes = excerpt
1300 .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1301 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1302 Some(excerpt_bytes)
1303 } else {
1304 None
1305 };
1306
1307 MultiBufferBytes {
1308 range,
1309 excerpts,
1310 excerpt_bytes,
1311 chunk,
1312 }
1313 }
1314
1315 pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1316 let mut result = MultiBufferRows {
1317 buffer_row_range: 0..0,
1318 excerpts: self.excerpts.cursor(),
1319 };
1320 result.seek(start_row);
1321 result
1322 }
1323
1324 pub fn chunks<'a, T: ToOffset>(
1325 &'a self,
1326 range: Range<T>,
1327 theme: Option<&'a SyntaxTheme>,
1328 ) -> MultiBufferChunks<'a> {
1329 let range = range.start.to_offset(self)..range.end.to_offset(self);
1330 let mut chunks = MultiBufferChunks {
1331 range: range.clone(),
1332 excerpts: self.excerpts.cursor(),
1333 excerpt_chunks: None,
1334 theme,
1335 };
1336 chunks.seek(range.start);
1337 chunks
1338 }
1339
1340 pub fn offset_to_point(&self, offset: usize) -> Point {
1341 if let Some(excerpt) = self.as_singleton() {
1342 return excerpt.buffer.offset_to_point(offset);
1343 }
1344
1345 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1346 cursor.seek(&offset, Bias::Right, &());
1347 if let Some(excerpt) = cursor.item() {
1348 let (start_offset, start_point) = cursor.start();
1349 let overshoot = offset - start_offset;
1350 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1351 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1352 let buffer_point = excerpt
1353 .buffer
1354 .offset_to_point(excerpt_start_offset + overshoot);
1355 *start_point + (buffer_point - excerpt_start_point)
1356 } else {
1357 self.excerpts.summary().text.lines
1358 }
1359 }
1360
1361 pub fn point_to_offset(&self, point: Point) -> usize {
1362 if let Some(excerpt) = self.as_singleton() {
1363 return excerpt.buffer.point_to_offset(point);
1364 }
1365
1366 let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1367 cursor.seek(&point, Bias::Right, &());
1368 if let Some(excerpt) = cursor.item() {
1369 let (start_point, start_offset) = cursor.start();
1370 let overshoot = point - start_point;
1371 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1372 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1373 let buffer_offset = excerpt
1374 .buffer
1375 .point_to_offset(excerpt_start_point + overshoot);
1376 *start_offset + buffer_offset - excerpt_start_offset
1377 } else {
1378 self.excerpts.summary().text.bytes
1379 }
1380 }
1381
1382 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1383 if let Some(excerpt) = self.as_singleton() {
1384 return excerpt.buffer.point_utf16_to_offset(point);
1385 }
1386
1387 let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1388 cursor.seek(&point, Bias::Right, &());
1389 if let Some(excerpt) = cursor.item() {
1390 let (start_point, start_offset) = cursor.start();
1391 let overshoot = point - start_point;
1392 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1393 let excerpt_start_point = excerpt
1394 .buffer
1395 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1396 let buffer_offset = excerpt
1397 .buffer
1398 .point_utf16_to_offset(excerpt_start_point + overshoot);
1399 *start_offset + (buffer_offset - excerpt_start_offset)
1400 } else {
1401 self.excerpts.summary().text.bytes
1402 }
1403 }
1404
1405 pub fn indent_column_for_line(&self, row: u32) -> u32 {
1406 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1407 buffer
1408 .indent_column_for_line(range.start.row)
1409 .min(range.end.column)
1410 .saturating_sub(range.start.column)
1411 } else {
1412 0
1413 }
1414 }
1415
1416 pub fn line_len(&self, row: u32) -> u32 {
1417 if let Some((_, range)) = self.buffer_line_for_row(row) {
1418 range.end.column - range.start.column
1419 } else {
1420 0
1421 }
1422 }
1423
1424 fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1425 let mut cursor = self.excerpts.cursor::<Point>();
1426 cursor.seek(&Point::new(row, 0), Bias::Right, &());
1427 if let Some(excerpt) = cursor.item() {
1428 let overshoot = row - cursor.start().row;
1429 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1430 let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1431 let buffer_row = excerpt_start.row + overshoot;
1432 let line_start = Point::new(buffer_row, 0);
1433 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1434 return Some((
1435 &excerpt.buffer,
1436 line_start.max(excerpt_start)..line_end.min(excerpt_end),
1437 ));
1438 }
1439 None
1440 }
1441
1442 pub fn max_point(&self) -> Point {
1443 self.text_summary().lines
1444 }
1445
1446 pub fn text_summary(&self) -> TextSummary {
1447 self.excerpts.summary().text
1448 }
1449
1450 pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1451 where
1452 D: TextDimension,
1453 O: ToOffset,
1454 {
1455 let mut summary = D::default();
1456 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1457 let mut cursor = self.excerpts.cursor::<usize>();
1458 cursor.seek(&range.start, Bias::Right, &());
1459 if let Some(excerpt) = cursor.item() {
1460 let mut end_before_newline = cursor.end(&());
1461 if excerpt.has_trailing_newline {
1462 end_before_newline -= 1;
1463 }
1464
1465 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1466 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
1467 let end_in_excerpt =
1468 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
1469 summary.add_assign(
1470 &excerpt
1471 .buffer
1472 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1473 );
1474
1475 if range.end > end_before_newline {
1476 summary.add_assign(&D::from_text_summary(&TextSummary {
1477 bytes: 1,
1478 lines: Point::new(1 as u32, 0),
1479 lines_utf16: PointUtf16::new(1 as u32, 0),
1480 first_line_chars: 0,
1481 last_line_chars: 0,
1482 longest_row: 0,
1483 longest_row_chars: 0,
1484 }));
1485 }
1486
1487 cursor.next(&());
1488 }
1489
1490 if range.end > *cursor.start() {
1491 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1492 &range.end,
1493 Bias::Right,
1494 &(),
1495 )));
1496 if let Some(excerpt) = cursor.item() {
1497 range.end = cmp::max(*cursor.start(), range.end);
1498
1499 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1500 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
1501 summary.add_assign(
1502 &excerpt
1503 .buffer
1504 .text_summary_for_range(excerpt_start..end_in_excerpt),
1505 );
1506 }
1507 }
1508
1509 summary
1510 }
1511
1512 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1513 where
1514 D: TextDimension + Ord + Sub<D, Output = D>,
1515 {
1516 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1517 cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1518 if cursor.item().is_none() {
1519 cursor.next(&());
1520 }
1521
1522 let mut position = D::from_text_summary(&cursor.start().text);
1523 if let Some(excerpt) = cursor.item() {
1524 if excerpt.id == anchor.excerpt_id && excerpt.buffer_id == anchor.buffer_id {
1525 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1526 let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1527 let buffer_position = cmp::min(
1528 excerpt_buffer_end,
1529 anchor.text_anchor.summary::<D>(&excerpt.buffer),
1530 );
1531 if buffer_position > excerpt_buffer_start {
1532 position.add_assign(&(buffer_position - excerpt_buffer_start));
1533 }
1534 }
1535 }
1536 position
1537 }
1538
1539 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1540 where
1541 D: TextDimension + Ord + Sub<D, Output = D>,
1542 I: 'a + IntoIterator<Item = &'a Anchor>,
1543 {
1544 let mut anchors = anchors.into_iter().peekable();
1545 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1546 let mut summaries = Vec::new();
1547 while let Some(anchor) = anchors.peek() {
1548 let excerpt_id = &anchor.excerpt_id;
1549 let buffer_id = anchor.buffer_id;
1550 let excerpt_anchors = iter::from_fn(|| {
1551 let anchor = anchors.peek()?;
1552 if anchor.excerpt_id == *excerpt_id && anchor.buffer_id == buffer_id {
1553 Some(&anchors.next().unwrap().text_anchor)
1554 } else {
1555 None
1556 }
1557 });
1558
1559 cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1560 if cursor.item().is_none() {
1561 cursor.next(&());
1562 }
1563
1564 let position = D::from_text_summary(&cursor.start().text);
1565 if let Some(excerpt) = cursor.item() {
1566 if excerpt.id == *excerpt_id && excerpt.buffer_id == buffer_id {
1567 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1568 let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1569 summaries.extend(
1570 excerpt
1571 .buffer
1572 .summaries_for_anchors::<D, _>(excerpt_anchors)
1573 .map(move |summary| {
1574 let summary = cmp::min(excerpt_buffer_end.clone(), summary);
1575 let mut position = position.clone();
1576 let excerpt_buffer_start = excerpt_buffer_start.clone();
1577 if summary > excerpt_buffer_start {
1578 position.add_assign(&(summary - excerpt_buffer_start));
1579 }
1580 position
1581 }),
1582 );
1583 continue;
1584 }
1585 }
1586
1587 summaries.extend(excerpt_anchors.map(|_| position.clone()));
1588 }
1589
1590 summaries
1591 }
1592
1593 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
1594 where
1595 I: 'a + IntoIterator<Item = &'a Anchor>,
1596 {
1597 let mut anchors = anchors.into_iter().enumerate().peekable();
1598 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1599 let mut result = Vec::new();
1600 while let Some((_, anchor)) = anchors.peek() {
1601 let old_excerpt_id = &anchor.excerpt_id;
1602
1603 // Find the location where this anchor's excerpt should be.
1604 cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
1605 if cursor.item().is_none() {
1606 cursor.next(&());
1607 }
1608
1609 let next_excerpt = cursor.item();
1610 let prev_excerpt = cursor.prev_item();
1611
1612 // Process all of the anchors for this excerpt.
1613 while let Some((_, anchor)) = anchors.peek() {
1614 if anchor.excerpt_id != *old_excerpt_id {
1615 break;
1616 }
1617 let mut kept_position = false;
1618 let (anchor_ix, anchor) = anchors.next().unwrap();
1619 let mut anchor = anchor.clone();
1620
1621 // Leave min and max anchors unchanged.
1622 if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
1623 kept_position = true;
1624 }
1625 // If the old excerpt still exists at this location, then leave
1626 // the anchor unchanged.
1627 else if next_excerpt.map_or(false, |excerpt| {
1628 excerpt.id == *old_excerpt_id && excerpt.contains(&anchor)
1629 }) {
1630 kept_position = true;
1631 }
1632 // If the old excerpt no longer exists at this location, then attempt to
1633 // find an equivalent position for this anchor in an adjacent excerpt.
1634 else {
1635 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
1636 if excerpt.contains(&anchor) {
1637 anchor.excerpt_id = excerpt.id.clone();
1638 kept_position = true;
1639 break;
1640 }
1641 }
1642 }
1643 // If there's no adjacent excerpt that contains the anchor's position,
1644 // then report that the anchor has lost its position.
1645 if !kept_position {
1646 anchor = if let Some(excerpt) = next_excerpt {
1647 let mut text_anchor = excerpt
1648 .range
1649 .start
1650 .bias(anchor.text_anchor.bias, &excerpt.buffer);
1651 if text_anchor
1652 .cmp(&excerpt.range.end, &excerpt.buffer)
1653 .unwrap()
1654 .is_gt()
1655 {
1656 text_anchor = excerpt.range.end.clone();
1657 }
1658 Anchor {
1659 buffer_id: excerpt.buffer_id,
1660 excerpt_id: excerpt.id.clone(),
1661 text_anchor,
1662 }
1663 } else if let Some(excerpt) = prev_excerpt {
1664 let mut text_anchor = excerpt
1665 .range
1666 .end
1667 .bias(anchor.text_anchor.bias, &excerpt.buffer);
1668 if text_anchor
1669 .cmp(&excerpt.range.start, &excerpt.buffer)
1670 .unwrap()
1671 .is_lt()
1672 {
1673 text_anchor = excerpt.range.start.clone();
1674 }
1675 Anchor {
1676 buffer_id: excerpt.buffer_id,
1677 excerpt_id: excerpt.id.clone(),
1678 text_anchor,
1679 }
1680 } else if anchor.text_anchor.bias == Bias::Left {
1681 Anchor::min()
1682 } else {
1683 Anchor::max()
1684 };
1685 }
1686
1687 result.push((anchor_ix, anchor, kept_position));
1688 }
1689 }
1690 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self).unwrap());
1691 result
1692 }
1693
1694 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1695 self.anchor_at(position, Bias::Left)
1696 }
1697
1698 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1699 self.anchor_at(position, Bias::Right)
1700 }
1701
1702 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1703 let offset = position.to_offset(self);
1704 if let Some(excerpt) = self.as_singleton() {
1705 return Anchor {
1706 buffer_id: excerpt.buffer_id,
1707 excerpt_id: excerpt.id.clone(),
1708 text_anchor: excerpt.buffer.anchor_at(offset, bias),
1709 };
1710 }
1711
1712 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1713 cursor.seek(&offset, Bias::Right, &());
1714 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1715 cursor.prev(&());
1716 }
1717 if let Some(excerpt) = cursor.item() {
1718 let mut overshoot = offset.saturating_sub(cursor.start().0);
1719 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1720 overshoot -= 1;
1721 bias = Bias::Right;
1722 }
1723
1724 let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1725 let text_anchor =
1726 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1727 Anchor {
1728 buffer_id: excerpt.buffer_id,
1729 excerpt_id: excerpt.id.clone(),
1730 text_anchor,
1731 }
1732 } else if offset == 0 && bias == Bias::Left {
1733 Anchor::min()
1734 } else {
1735 Anchor::max()
1736 }
1737 }
1738
1739 pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1740 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1741 cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1742 if let Some(excerpt) = cursor.item() {
1743 if excerpt.id == excerpt_id {
1744 let text_anchor = excerpt.clip_anchor(text_anchor);
1745 drop(cursor);
1746 return Anchor {
1747 buffer_id: excerpt.buffer_id,
1748 excerpt_id,
1749 text_anchor,
1750 };
1751 }
1752 }
1753 panic!("excerpt not found");
1754 }
1755
1756 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1757 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
1758 true
1759 } else if let Some((buffer_id, buffer_snapshot)) =
1760 self.buffer_snapshot_for_excerpt(&anchor.excerpt_id)
1761 {
1762 anchor.buffer_id == buffer_id && buffer_snapshot.can_resolve(&anchor.text_anchor)
1763 } else {
1764 false
1765 }
1766 }
1767
1768 pub fn range_contains_excerpt_boundary<T: ToOffset>(&self, range: Range<T>) -> bool {
1769 let start = range.start.to_offset(self);
1770 let end = range.end.to_offset(self);
1771 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1772 cursor.seek(&start, Bias::Right, &());
1773 let start_id = cursor
1774 .item()
1775 .or_else(|| cursor.prev_item())
1776 .map(|excerpt| &excerpt.id);
1777 cursor.seek_forward(&end, Bias::Right, &());
1778 let end_id = cursor
1779 .item()
1780 .or_else(|| cursor.prev_item())
1781 .map(|excerpt| &excerpt.id);
1782 start_id != end_id
1783 }
1784
1785 pub fn parse_count(&self) -> usize {
1786 self.parse_count
1787 }
1788
1789 pub fn enclosing_bracket_ranges<T: ToOffset>(
1790 &self,
1791 range: Range<T>,
1792 ) -> Option<(Range<usize>, Range<usize>)> {
1793 let range = range.start.to_offset(self)..range.end.to_offset(self);
1794
1795 let mut cursor = self.excerpts.cursor::<usize>();
1796 cursor.seek(&range.start, Bias::Right, &());
1797 let start_excerpt = cursor.item();
1798
1799 cursor.seek(&range.end, Bias::Right, &());
1800 let end_excerpt = cursor.item();
1801
1802 start_excerpt
1803 .zip(end_excerpt)
1804 .and_then(|(start_excerpt, end_excerpt)| {
1805 if start_excerpt.id != end_excerpt.id {
1806 return None;
1807 }
1808
1809 let excerpt_buffer_start =
1810 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1811 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1812
1813 let start_in_buffer =
1814 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1815 let end_in_buffer =
1816 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1817 let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1818 .buffer
1819 .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1820
1821 if start_bracket_range.start >= excerpt_buffer_start
1822 && end_bracket_range.end < excerpt_buffer_end
1823 {
1824 start_bracket_range.start =
1825 cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
1826 start_bracket_range.end =
1827 cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
1828 end_bracket_range.start =
1829 cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
1830 end_bracket_range.end =
1831 cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
1832 Some((start_bracket_range, end_bracket_range))
1833 } else {
1834 None
1835 }
1836 })
1837 }
1838
1839 pub fn diagnostics_update_count(&self) -> usize {
1840 self.diagnostics_update_count
1841 }
1842
1843 pub fn language(&self) -> Option<&Arc<Language>> {
1844 self.excerpts
1845 .iter()
1846 .next()
1847 .and_then(|excerpt| excerpt.buffer.language())
1848 }
1849
1850 pub fn is_dirty(&self) -> bool {
1851 self.is_dirty
1852 }
1853
1854 pub fn has_conflict(&self) -> bool {
1855 self.has_conflict
1856 }
1857
1858 pub fn diagnostic_group<'a, O>(
1859 &'a self,
1860 group_id: usize,
1861 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1862 where
1863 O: text::FromAnchor + 'a,
1864 {
1865 self.as_singleton()
1866 .into_iter()
1867 .flat_map(move |excerpt| excerpt.buffer.diagnostic_group(group_id))
1868 }
1869
1870 pub fn diagnostics_in_range<'a, T, O>(
1871 &'a self,
1872 range: Range<T>,
1873 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1874 where
1875 T: 'a + ToOffset,
1876 O: 'a + text::FromAnchor,
1877 {
1878 self.as_singleton().into_iter().flat_map(move |excerpt| {
1879 excerpt
1880 .buffer
1881 .diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
1882 })
1883 }
1884
1885 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1886 let range = range.start.to_offset(self)..range.end.to_offset(self);
1887
1888 let mut cursor = self.excerpts.cursor::<usize>();
1889 cursor.seek(&range.start, Bias::Right, &());
1890 let start_excerpt = cursor.item();
1891
1892 cursor.seek(&range.end, Bias::Right, &());
1893 let end_excerpt = cursor.item();
1894
1895 start_excerpt
1896 .zip(end_excerpt)
1897 .and_then(|(start_excerpt, end_excerpt)| {
1898 if start_excerpt.id != end_excerpt.id {
1899 return None;
1900 }
1901
1902 let excerpt_buffer_start =
1903 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1904 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1905
1906 let start_in_buffer =
1907 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1908 let end_in_buffer =
1909 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1910 let mut ancestor_buffer_range = start_excerpt
1911 .buffer
1912 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
1913 ancestor_buffer_range.start =
1914 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
1915 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
1916
1917 let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
1918 let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
1919 Some(start..end)
1920 })
1921 }
1922
1923 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1924 let excerpt = self.as_singleton()?;
1925 let outline = excerpt.buffer.outline(theme)?;
1926 Some(Outline::new(
1927 outline
1928 .items
1929 .into_iter()
1930 .map(|item| OutlineItem {
1931 depth: item.depth,
1932 range: self.anchor_in_excerpt(excerpt.id.clone(), item.range.start)
1933 ..self.anchor_in_excerpt(excerpt.id.clone(), item.range.end),
1934 text: item.text,
1935 highlight_ranges: item.highlight_ranges,
1936 name_ranges: item.name_ranges,
1937 })
1938 .collect(),
1939 ))
1940 }
1941
1942 fn buffer_snapshot_for_excerpt<'a>(
1943 &'a self,
1944 excerpt_id: &'a ExcerptId,
1945 ) -> Option<(usize, &'a BufferSnapshot)> {
1946 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1947 cursor.seek(&Some(excerpt_id), Bias::Left, &());
1948 if let Some(excerpt) = cursor.item() {
1949 if excerpt.id == *excerpt_id {
1950 return Some((excerpt.buffer_id, &excerpt.buffer));
1951 }
1952 }
1953 None
1954 }
1955
1956 pub fn remote_selections_in_range<'a>(
1957 &'a self,
1958 range: &'a Range<Anchor>,
1959 ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
1960 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1961 cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
1962 cursor
1963 .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
1964 .flat_map(move |excerpt| {
1965 let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
1966 if excerpt.id == range.start.excerpt_id {
1967 query_range.start = range.start.text_anchor.clone();
1968 }
1969 if excerpt.id == range.end.excerpt_id {
1970 query_range.end = range.end.text_anchor.clone();
1971 }
1972
1973 excerpt
1974 .buffer
1975 .remote_selections_in_range(query_range)
1976 .flat_map(move |(replica_id, selections)| {
1977 selections.map(move |selection| {
1978 let mut start = Anchor {
1979 buffer_id: excerpt.buffer_id,
1980 excerpt_id: excerpt.id.clone(),
1981 text_anchor: selection.start.clone(),
1982 };
1983 let mut end = Anchor {
1984 buffer_id: excerpt.buffer_id,
1985 excerpt_id: excerpt.id.clone(),
1986 text_anchor: selection.end.clone(),
1987 };
1988 if range.start.cmp(&start, self).unwrap().is_gt() {
1989 start = range.start.clone();
1990 }
1991 if range.end.cmp(&end, self).unwrap().is_lt() {
1992 end = range.end.clone();
1993 }
1994
1995 (
1996 replica_id,
1997 Selection {
1998 id: selection.id,
1999 start,
2000 end,
2001 reversed: selection.reversed,
2002 goal: selection.goal,
2003 },
2004 )
2005 })
2006 })
2007 })
2008 }
2009}
2010
2011impl History {
2012 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2013 self.transaction_depth += 1;
2014 if self.transaction_depth == 1 {
2015 let id = post_inc(&mut self.next_transaction_id);
2016 self.undo_stack.push(Transaction {
2017 id,
2018 buffer_transactions: Default::default(),
2019 first_edit_at: now,
2020 last_edit_at: now,
2021 });
2022 Some(id)
2023 } else {
2024 None
2025 }
2026 }
2027
2028 fn end_transaction(
2029 &mut self,
2030 now: Instant,
2031 buffer_transactions: HashSet<(usize, TransactionId)>,
2032 ) -> bool {
2033 assert_ne!(self.transaction_depth, 0);
2034 self.transaction_depth -= 1;
2035 if self.transaction_depth == 0 {
2036 if buffer_transactions.is_empty() {
2037 self.undo_stack.pop();
2038 false
2039 } else {
2040 let transaction = self.undo_stack.last_mut().unwrap();
2041 transaction.last_edit_at = now;
2042 transaction.buffer_transactions.extend(buffer_transactions);
2043 true
2044 }
2045 } else {
2046 false
2047 }
2048 }
2049
2050 fn pop_undo(&mut self) -> Option<&Transaction> {
2051 assert_eq!(self.transaction_depth, 0);
2052 if let Some(transaction) = self.undo_stack.pop() {
2053 self.redo_stack.push(transaction);
2054 self.redo_stack.last()
2055 } else {
2056 None
2057 }
2058 }
2059
2060 fn pop_redo(&mut self) -> Option<&Transaction> {
2061 assert_eq!(self.transaction_depth, 0);
2062 if let Some(transaction) = self.redo_stack.pop() {
2063 self.undo_stack.push(transaction);
2064 self.undo_stack.last()
2065 } else {
2066 None
2067 }
2068 }
2069
2070 fn group(&mut self) -> Option<TransactionId> {
2071 let mut new_len = self.undo_stack.len();
2072 let mut transactions = self.undo_stack.iter_mut();
2073
2074 if let Some(mut transaction) = transactions.next_back() {
2075 while let Some(prev_transaction) = transactions.next_back() {
2076 if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
2077 {
2078 transaction = prev_transaction;
2079 new_len -= 1;
2080 } else {
2081 break;
2082 }
2083 }
2084 }
2085
2086 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2087 if let Some(last_transaction) = transactions_to_keep.last_mut() {
2088 if let Some(transaction) = transactions_to_merge.last() {
2089 last_transaction.last_edit_at = transaction.last_edit_at;
2090 }
2091 }
2092
2093 self.undo_stack.truncate(new_len);
2094 self.undo_stack.last().map(|t| t.id)
2095 }
2096}
2097
2098impl Excerpt {
2099 fn new(
2100 id: ExcerptId,
2101 buffer_id: usize,
2102 buffer: BufferSnapshot,
2103 range: Range<text::Anchor>,
2104 has_trailing_newline: bool,
2105 ) -> Self {
2106 Excerpt {
2107 id,
2108 max_buffer_row: range.end.to_point(&buffer).row,
2109 text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
2110 buffer_id,
2111 buffer,
2112 range,
2113 has_trailing_newline,
2114 }
2115 }
2116
2117 fn chunks_in_range<'a>(
2118 &'a self,
2119 range: Range<usize>,
2120 theme: Option<&'a SyntaxTheme>,
2121 ) -> ExcerptChunks<'a> {
2122 let content_start = self.range.start.to_offset(&self.buffer);
2123 let chunks_start = content_start + range.start;
2124 let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2125
2126 let footer_height = if self.has_trailing_newline
2127 && range.start <= self.text_summary.bytes
2128 && range.end > self.text_summary.bytes
2129 {
2130 1
2131 } else {
2132 0
2133 };
2134
2135 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, theme);
2136
2137 ExcerptChunks {
2138 content_chunks,
2139 footer_height,
2140 }
2141 }
2142
2143 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2144 let content_start = self.range.start.to_offset(&self.buffer);
2145 let bytes_start = content_start + range.start;
2146 let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2147 let footer_height = if self.has_trailing_newline
2148 && range.start <= self.text_summary.bytes
2149 && range.end > self.text_summary.bytes
2150 {
2151 1
2152 } else {
2153 0
2154 };
2155 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2156
2157 ExcerptBytes {
2158 content_bytes,
2159 footer_height,
2160 }
2161 }
2162
2163 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2164 if text_anchor
2165 .cmp(&self.range.start, &self.buffer)
2166 .unwrap()
2167 .is_lt()
2168 {
2169 self.range.start.clone()
2170 } else if text_anchor
2171 .cmp(&self.range.end, &self.buffer)
2172 .unwrap()
2173 .is_gt()
2174 {
2175 self.range.end.clone()
2176 } else {
2177 text_anchor
2178 }
2179 }
2180
2181 fn contains(&self, anchor: &Anchor) -> bool {
2182 self.buffer_id == anchor.buffer_id
2183 && self
2184 .range
2185 .start
2186 .cmp(&anchor.text_anchor, &self.buffer)
2187 .unwrap()
2188 .is_le()
2189 && self
2190 .range
2191 .end
2192 .cmp(&anchor.text_anchor, &self.buffer)
2193 .unwrap()
2194 .is_ge()
2195 }
2196}
2197
2198impl fmt::Debug for Excerpt {
2199 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2200 f.debug_struct("Excerpt")
2201 .field("id", &self.id)
2202 .field("buffer_id", &self.buffer_id)
2203 .field("range", &self.range)
2204 .field("text_summary", &self.text_summary)
2205 .field("has_trailing_newline", &self.has_trailing_newline)
2206 .finish()
2207 }
2208}
2209
2210impl sum_tree::Item for Excerpt {
2211 type Summary = ExcerptSummary;
2212
2213 fn summary(&self) -> Self::Summary {
2214 let mut text = self.text_summary.clone();
2215 if self.has_trailing_newline {
2216 text += TextSummary::from("\n");
2217 }
2218 ExcerptSummary {
2219 excerpt_id: self.id.clone(),
2220 max_buffer_row: self.max_buffer_row,
2221 text,
2222 }
2223 }
2224}
2225
2226impl sum_tree::Summary for ExcerptSummary {
2227 type Context = ();
2228
2229 fn add_summary(&mut self, summary: &Self, _: &()) {
2230 debug_assert!(summary.excerpt_id > self.excerpt_id);
2231 self.excerpt_id = summary.excerpt_id.clone();
2232 self.text.add_summary(&summary.text, &());
2233 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2234 }
2235}
2236
2237impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2238 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2239 *self += &summary.text;
2240 }
2241}
2242
2243impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2244 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2245 *self += summary.text.bytes;
2246 }
2247}
2248
2249impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2250 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2251 Ord::cmp(self, &cursor_location.text.bytes)
2252 }
2253}
2254
2255impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2256 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2257 Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2258 }
2259}
2260
2261impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2262 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2263 *self += summary.text.lines;
2264 }
2265}
2266
2267impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2268 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2269 *self += summary.text.lines_utf16
2270 }
2271}
2272
2273impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2274 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2275 *self = Some(&summary.excerpt_id);
2276 }
2277}
2278
2279impl<'a> MultiBufferRows<'a> {
2280 pub fn seek(&mut self, row: u32) {
2281 self.buffer_row_range = 0..0;
2282
2283 self.excerpts
2284 .seek_forward(&Point::new(row, 0), Bias::Right, &());
2285 if self.excerpts.item().is_none() {
2286 self.excerpts.prev(&());
2287
2288 if self.excerpts.item().is_none() && row == 0 {
2289 self.buffer_row_range = 0..1;
2290 return;
2291 }
2292 }
2293
2294 if let Some(excerpt) = self.excerpts.item() {
2295 let overshoot = row - self.excerpts.start().row;
2296 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
2297 self.buffer_row_range.start = excerpt_start + overshoot;
2298 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
2299 }
2300 }
2301}
2302
2303impl<'a> Iterator for MultiBufferRows<'a> {
2304 type Item = Option<u32>;
2305
2306 fn next(&mut self) -> Option<Self::Item> {
2307 loop {
2308 if !self.buffer_row_range.is_empty() {
2309 let row = Some(self.buffer_row_range.start);
2310 self.buffer_row_range.start += 1;
2311 return Some(row);
2312 }
2313 self.excerpts.item()?;
2314 self.excerpts.next(&());
2315 let excerpt = self.excerpts.item()?;
2316 self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
2317 self.buffer_row_range.end =
2318 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
2319 }
2320 }
2321}
2322
2323impl<'a> MultiBufferChunks<'a> {
2324 pub fn offset(&self) -> usize {
2325 self.range.start
2326 }
2327
2328 pub fn seek(&mut self, offset: usize) {
2329 self.range.start = offset;
2330 self.excerpts.seek(&offset, Bias::Right, &());
2331 if let Some(excerpt) = self.excerpts.item() {
2332 self.excerpt_chunks = Some(excerpt.chunks_in_range(
2333 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
2334 self.theme,
2335 ));
2336 } else {
2337 self.excerpt_chunks = None;
2338 }
2339 }
2340}
2341
2342impl<'a> Iterator for MultiBufferChunks<'a> {
2343 type Item = Chunk<'a>;
2344
2345 fn next(&mut self) -> Option<Self::Item> {
2346 if self.range.is_empty() {
2347 None
2348 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
2349 self.range.start += chunk.text.len();
2350 Some(chunk)
2351 } else {
2352 self.excerpts.next(&());
2353 let excerpt = self.excerpts.item()?;
2354 self.excerpt_chunks = Some(
2355 excerpt.chunks_in_range(0..self.range.end - self.excerpts.start(), self.theme),
2356 );
2357 self.next()
2358 }
2359 }
2360}
2361
2362impl<'a> MultiBufferBytes<'a> {
2363 fn consume(&mut self, len: usize) {
2364 self.range.start += len;
2365 self.chunk = &self.chunk[len..];
2366
2367 if !self.range.is_empty() && self.chunk.is_empty() {
2368 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
2369 self.chunk = chunk;
2370 } else {
2371 self.excerpts.next(&());
2372 if let Some(excerpt) = self.excerpts.item() {
2373 let mut excerpt_bytes =
2374 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
2375 self.chunk = excerpt_bytes.next().unwrap();
2376 self.excerpt_bytes = Some(excerpt_bytes);
2377 }
2378 }
2379 }
2380 }
2381}
2382
2383impl<'a> Iterator for MultiBufferBytes<'a> {
2384 type Item = &'a [u8];
2385
2386 fn next(&mut self) -> Option<Self::Item> {
2387 let chunk = self.chunk;
2388 if chunk.is_empty() {
2389 None
2390 } else {
2391 self.consume(chunk.len());
2392 Some(chunk)
2393 }
2394 }
2395}
2396
2397impl<'a> io::Read for MultiBufferBytes<'a> {
2398 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2399 let len = cmp::min(buf.len(), self.chunk.len());
2400 buf[..len].copy_from_slice(&self.chunk[..len]);
2401 if len > 0 {
2402 self.consume(len);
2403 }
2404 Ok(len)
2405 }
2406}
2407
2408impl<'a> Iterator for ExcerptBytes<'a> {
2409 type Item = &'a [u8];
2410
2411 fn next(&mut self) -> Option<Self::Item> {
2412 if let Some(chunk) = self.content_bytes.next() {
2413 if !chunk.is_empty() {
2414 return Some(chunk);
2415 }
2416 }
2417
2418 if self.footer_height > 0 {
2419 let result = &NEWLINES[..self.footer_height];
2420 self.footer_height = 0;
2421 return Some(result);
2422 }
2423
2424 None
2425 }
2426}
2427
2428impl<'a> Iterator for ExcerptChunks<'a> {
2429 type Item = Chunk<'a>;
2430
2431 fn next(&mut self) -> Option<Self::Item> {
2432 if let Some(chunk) = self.content_chunks.next() {
2433 return Some(chunk);
2434 }
2435
2436 if self.footer_height > 0 {
2437 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2438 self.footer_height = 0;
2439 return Some(Chunk {
2440 text,
2441 ..Default::default()
2442 });
2443 }
2444
2445 None
2446 }
2447}
2448
2449impl ToOffset for Point {
2450 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2451 snapshot.point_to_offset(*self)
2452 }
2453}
2454
2455impl ToOffset for PointUtf16 {
2456 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2457 snapshot.point_utf16_to_offset(*self)
2458 }
2459}
2460
2461impl ToOffset for usize {
2462 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2463 assert!(*self <= snapshot.len(), "offset is out of range");
2464 *self
2465 }
2466}
2467
2468impl ToPoint for usize {
2469 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2470 snapshot.offset_to_point(*self)
2471 }
2472}
2473
2474impl ToPoint for Point {
2475 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2476 *self
2477 }
2478}
2479
2480pub fn char_kind(c: char) -> CharKind {
2481 if c == '\n' {
2482 CharKind::Newline
2483 } else if c.is_whitespace() {
2484 CharKind::Whitespace
2485 } else if c.is_alphanumeric() || c == '_' {
2486 CharKind::Word
2487 } else {
2488 CharKind::Punctuation
2489 }
2490}
2491
2492#[cfg(test)]
2493mod tests {
2494 use super::*;
2495 use gpui::MutableAppContext;
2496 use language::{Buffer, Rope};
2497 use rand::prelude::*;
2498 use std::env;
2499 use text::{Point, RandomCharIter};
2500 use util::test::sample_text;
2501
2502 #[gpui::test]
2503 fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2504 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2505 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2506
2507 let snapshot = multibuffer.read(cx).snapshot(cx);
2508 assert_eq!(snapshot.text(), buffer.read(cx).text());
2509
2510 assert_eq!(
2511 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2512 (0..buffer.read(cx).row_count())
2513 .map(Some)
2514 .collect::<Vec<_>>()
2515 );
2516
2517 buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2518 let snapshot = multibuffer.read(cx).snapshot(cx);
2519
2520 assert_eq!(snapshot.text(), buffer.read(cx).text());
2521 assert_eq!(
2522 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2523 (0..buffer.read(cx).row_count())
2524 .map(Some)
2525 .collect::<Vec<_>>()
2526 );
2527 }
2528
2529 #[gpui::test]
2530 fn test_remote_multibuffer(cx: &mut MutableAppContext) {
2531 let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
2532 let guest_buffer = cx.add_model(|cx| {
2533 let message = host_buffer.read(cx).to_proto();
2534 Buffer::from_proto(1, message, None, cx).unwrap()
2535 });
2536 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
2537 let snapshot = multibuffer.read(cx).snapshot(cx);
2538 assert_eq!(snapshot.text(), "a");
2539
2540 guest_buffer.update(cx, |buffer, cx| buffer.edit([1..1], "b", cx));
2541 let snapshot = multibuffer.read(cx).snapshot(cx);
2542 assert_eq!(snapshot.text(), "ab");
2543
2544 guest_buffer.update(cx, |buffer, cx| buffer.edit([2..2], "c", cx));
2545 let snapshot = multibuffer.read(cx).snapshot(cx);
2546 assert_eq!(snapshot.text(), "abc");
2547 }
2548
2549 #[gpui::test]
2550 fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2551 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2552 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2553 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2554
2555 let subscription = multibuffer.update(cx, |multibuffer, cx| {
2556 let subscription = multibuffer.subscribe();
2557 multibuffer.push_excerpt(
2558 ExcerptProperties {
2559 buffer: &buffer_1,
2560 range: Point::new(1, 2)..Point::new(2, 5),
2561 },
2562 cx,
2563 );
2564 assert_eq!(
2565 subscription.consume().into_inner(),
2566 [Edit {
2567 old: 0..0,
2568 new: 0..10
2569 }]
2570 );
2571
2572 multibuffer.push_excerpt(
2573 ExcerptProperties {
2574 buffer: &buffer_1,
2575 range: Point::new(3, 3)..Point::new(4, 4),
2576 },
2577 cx,
2578 );
2579 multibuffer.push_excerpt(
2580 ExcerptProperties {
2581 buffer: &buffer_2,
2582 range: Point::new(3, 1)..Point::new(3, 3),
2583 },
2584 cx,
2585 );
2586 assert_eq!(
2587 subscription.consume().into_inner(),
2588 [Edit {
2589 old: 10..10,
2590 new: 10..22
2591 }]
2592 );
2593
2594 subscription
2595 });
2596
2597 let snapshot = multibuffer.read(cx).snapshot(cx);
2598 assert_eq!(
2599 snapshot.text(),
2600 concat!(
2601 "bbbb\n", // Preserve newlines
2602 "ccccc\n", //
2603 "ddd\n", //
2604 "eeee\n", //
2605 "jj" //
2606 )
2607 );
2608 assert_eq!(
2609 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2610 [Some(1), Some(2), Some(3), Some(4), Some(3)]
2611 );
2612 assert_eq!(
2613 snapshot.buffer_rows(2).collect::<Vec<_>>(),
2614 [Some(3), Some(4), Some(3)]
2615 );
2616 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2617 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2618 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(1, 5)));
2619 assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(2, 0)));
2620 assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(4, 0)));
2621 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(2, 0)..Point::new(3, 0)));
2622 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 0)..Point::new(4, 2)));
2623 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 2)..Point::new(4, 2)));
2624
2625 buffer_1.update(cx, |buffer, cx| {
2626 buffer.edit(
2627 [
2628 Point::new(0, 0)..Point::new(0, 0),
2629 Point::new(2, 1)..Point::new(2, 3),
2630 ],
2631 "\n",
2632 cx,
2633 );
2634 });
2635
2636 let snapshot = multibuffer.read(cx).snapshot(cx);
2637 assert_eq!(
2638 snapshot.text(),
2639 concat!(
2640 "bbbb\n", // Preserve newlines
2641 "c\n", //
2642 "cc\n", //
2643 "ddd\n", //
2644 "eeee\n", //
2645 "jj" //
2646 )
2647 );
2648
2649 assert_eq!(
2650 subscription.consume().into_inner(),
2651 [Edit {
2652 old: 6..8,
2653 new: 6..7
2654 }]
2655 );
2656
2657 let snapshot = multibuffer.read(cx).snapshot(cx);
2658 assert_eq!(
2659 snapshot.clip_point(Point::new(0, 5), Bias::Left),
2660 Point::new(0, 4)
2661 );
2662 assert_eq!(
2663 snapshot.clip_point(Point::new(0, 5), Bias::Right),
2664 Point::new(0, 4)
2665 );
2666 assert_eq!(
2667 snapshot.clip_point(Point::new(5, 1), Bias::Right),
2668 Point::new(5, 1)
2669 );
2670 assert_eq!(
2671 snapshot.clip_point(Point::new(5, 2), Bias::Right),
2672 Point::new(5, 2)
2673 );
2674 assert_eq!(
2675 snapshot.clip_point(Point::new(5, 3), Bias::Right),
2676 Point::new(5, 2)
2677 );
2678
2679 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2680 let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2681 multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2682 multibuffer.snapshot(cx)
2683 });
2684
2685 assert_eq!(
2686 snapshot.text(),
2687 concat!(
2688 "bbbb\n", // Preserve newlines
2689 "c\n", //
2690 "cc\n", //
2691 "ddd\n", //
2692 "eeee", //
2693 )
2694 );
2695 }
2696
2697 #[gpui::test]
2698 fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2699 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2700
2701 let snapshot = multibuffer.read(cx).snapshot(cx);
2702 assert_eq!(snapshot.text(), "");
2703 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2704 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2705 }
2706
2707 #[gpui::test]
2708 fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2709 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2710 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2711 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2712 buffer.update(cx, |buffer, cx| {
2713 buffer.edit([0..0], "X", cx);
2714 buffer.edit([5..5], "Y", cx);
2715 });
2716 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2717
2718 assert_eq!(old_snapshot.text(), "abcd");
2719 assert_eq!(new_snapshot.text(), "XabcdY");
2720
2721 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2722 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2723 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2724 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2725 }
2726
2727 #[gpui::test]
2728 fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2729 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2730 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2731 let multibuffer = cx.add_model(|cx| {
2732 let mut multibuffer = MultiBuffer::new(0);
2733 multibuffer.push_excerpt(
2734 ExcerptProperties {
2735 buffer: &buffer_1,
2736 range: 0..4,
2737 },
2738 cx,
2739 );
2740 multibuffer.push_excerpt(
2741 ExcerptProperties {
2742 buffer: &buffer_2,
2743 range: 0..5,
2744 },
2745 cx,
2746 );
2747 multibuffer
2748 });
2749 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2750
2751 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
2752 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
2753 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2754 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2755 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2756 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2757
2758 buffer_1.update(cx, |buffer, cx| {
2759 buffer.edit([0..0], "W", cx);
2760 buffer.edit([5..5], "X", cx);
2761 });
2762 buffer_2.update(cx, |buffer, cx| {
2763 buffer.edit([0..0], "Y", cx);
2764 buffer.edit([6..0], "Z", cx);
2765 });
2766 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2767
2768 assert_eq!(old_snapshot.text(), "abcd\nefghi");
2769 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
2770
2771 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2772 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2773 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
2774 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2775 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2776 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2777 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
2778 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
2779 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
2780 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
2781 }
2782
2783 #[gpui::test]
2784 fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
2785 cx: &mut MutableAppContext,
2786 ) {
2787 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2788 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
2789 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2790
2791 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
2792 // Add an excerpt from buffer 1 that spans this new insertion.
2793 buffer_1.update(cx, |buffer, cx| buffer.edit([4..4], "123", cx));
2794 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
2795 multibuffer.push_excerpt(
2796 ExcerptProperties {
2797 buffer: &buffer_1,
2798 range: 0..7,
2799 },
2800 cx,
2801 )
2802 });
2803
2804 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
2805 assert_eq!(snapshot_1.text(), "abcd123");
2806
2807 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
2808 let (excerpt_id_2, excerpt_id_3, _) = multibuffer.update(cx, |multibuffer, cx| {
2809 multibuffer.remove_excerpts([&excerpt_id_1], cx);
2810 (
2811 multibuffer.push_excerpt(
2812 ExcerptProperties {
2813 buffer: &buffer_2,
2814 range: 0..4,
2815 },
2816 cx,
2817 ),
2818 multibuffer.push_excerpt(
2819 ExcerptProperties {
2820 buffer: &buffer_2,
2821 range: 6..10,
2822 },
2823 cx,
2824 ),
2825 multibuffer.push_excerpt(
2826 ExcerptProperties {
2827 buffer: &buffer_2,
2828 range: 12..16,
2829 },
2830 cx,
2831 ),
2832 )
2833 });
2834 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
2835 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
2836
2837 // The old excerpt id has been reused.
2838 assert_eq!(excerpt_id_2, excerpt_id_1);
2839
2840 // Resolve some anchors from the previous snapshot in the new snapshot.
2841 // Although there is still an excerpt with the same id, it is for
2842 // a different buffer, so we don't attempt to resolve the old text
2843 // anchor in the new buffer.
2844 assert_eq!(
2845 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
2846 0
2847 );
2848 assert_eq!(
2849 snapshot_2.summaries_for_anchors::<usize, _>(&[
2850 snapshot_1.anchor_before(2),
2851 snapshot_1.anchor_after(3)
2852 ]),
2853 vec![0, 0]
2854 );
2855 let refresh =
2856 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
2857 assert_eq!(
2858 refresh,
2859 &[
2860 (0, snapshot_2.anchor_before(0), false),
2861 (1, snapshot_2.anchor_after(0), false),
2862 ]
2863 );
2864
2865 // Replace the middle excerpt with a smaller excerpt in buffer 2,
2866 // that intersects the old excerpt.
2867 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
2868 multibuffer.remove_excerpts([&excerpt_id_3], cx);
2869 multibuffer.insert_excerpt_after(
2870 &excerpt_id_3,
2871 ExcerptProperties {
2872 buffer: &buffer_2,
2873 range: 5..8,
2874 },
2875 cx,
2876 )
2877 });
2878
2879 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
2880 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
2881 assert_ne!(excerpt_id_5, excerpt_id_3);
2882
2883 // Resolve some anchors from the previous snapshot in the new snapshot.
2884 // The anchor in the middle excerpt snaps to the beginning of the
2885 // excerpt, since it is not
2886 let anchors = [
2887 snapshot_2.anchor_before(0),
2888 snapshot_2.anchor_after(2),
2889 snapshot_2.anchor_after(6),
2890 snapshot_2.anchor_after(14),
2891 ];
2892 assert_eq!(
2893 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
2894 &[0, 2, 9, 13]
2895 );
2896
2897 let new_anchors = snapshot_3.refresh_anchors(&anchors);
2898 assert_eq!(
2899 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
2900 &[(0, true), (1, true), (2, true), (3, true)]
2901 );
2902 assert_eq!(
2903 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
2904 &[0, 2, 7, 13]
2905 );
2906 }
2907
2908 #[gpui::test(iterations = 100)]
2909 fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
2910 let operations = env::var("OPERATIONS")
2911 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2912 .unwrap_or(10);
2913
2914 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
2915 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2916 let mut excerpt_ids = Vec::new();
2917 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
2918 let mut anchors = Vec::new();
2919 let mut old_versions = Vec::new();
2920
2921 for _ in 0..operations {
2922 match rng.gen_range(0..100) {
2923 0..=19 if !buffers.is_empty() => {
2924 let buffer = buffers.choose(&mut rng).unwrap();
2925 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
2926 }
2927 20..=29 if !expected_excerpts.is_empty() => {
2928 let mut ids_to_remove = vec![];
2929 for _ in 0..rng.gen_range(1..=3) {
2930 if expected_excerpts.is_empty() {
2931 break;
2932 }
2933
2934 let ix = rng.gen_range(0..expected_excerpts.len());
2935 ids_to_remove.push(excerpt_ids.remove(ix));
2936 let (buffer, range) = expected_excerpts.remove(ix);
2937 let buffer = buffer.read(cx);
2938 log::info!(
2939 "Removing excerpt {}: {:?}",
2940 ix,
2941 buffer
2942 .text_for_range(range.to_offset(&buffer))
2943 .collect::<String>(),
2944 );
2945 }
2946 ids_to_remove.sort_unstable();
2947 multibuffer.update(cx, |multibuffer, cx| {
2948 multibuffer.remove_excerpts(&ids_to_remove, cx)
2949 });
2950 }
2951 30..=39 if !expected_excerpts.is_empty() => {
2952 let multibuffer = multibuffer.read(cx).read(cx);
2953 let offset =
2954 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
2955 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
2956 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2957 anchors.push(multibuffer.anchor_at(offset, bias));
2958 anchors.sort_by(|a, b| a.cmp(&b, &multibuffer).unwrap());
2959 }
2960 40..=44 if !anchors.is_empty() => {
2961 let multibuffer = multibuffer.read(cx).read(cx);
2962
2963 anchors = multibuffer
2964 .refresh_anchors(&anchors)
2965 .into_iter()
2966 .map(|a| a.1)
2967 .collect();
2968
2969 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2970 // overshoot its boundaries.
2971 let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
2972 for anchor in &anchors {
2973 if anchor.excerpt_id == ExcerptId::min()
2974 || anchor.excerpt_id == ExcerptId::max()
2975 {
2976 continue;
2977 }
2978
2979 cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
2980 let excerpt = cursor.item().unwrap();
2981 assert_eq!(excerpt.id, anchor.excerpt_id);
2982 assert!(excerpt.contains(anchor));
2983 }
2984 }
2985 _ => {
2986 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2987 let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
2988 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
2989 buffers.last().unwrap()
2990 } else {
2991 buffers.choose(&mut rng).unwrap()
2992 };
2993
2994 let buffer = buffer_handle.read(cx);
2995 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
2996 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2997 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2998 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
2999 let prev_excerpt_id = excerpt_ids
3000 .get(prev_excerpt_ix)
3001 .cloned()
3002 .unwrap_or(ExcerptId::max());
3003 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3004
3005 log::info!(
3006 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3007 excerpt_ix,
3008 expected_excerpts.len(),
3009 buffer_handle.id(),
3010 buffer.text(),
3011 start_ix..end_ix,
3012 &buffer.text()[start_ix..end_ix]
3013 );
3014
3015 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3016 multibuffer.insert_excerpt_after(
3017 &prev_excerpt_id,
3018 ExcerptProperties {
3019 buffer: &buffer_handle,
3020 range: start_ix..end_ix,
3021 },
3022 cx,
3023 )
3024 });
3025
3026 excerpt_ids.insert(excerpt_ix, excerpt_id);
3027 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
3028 }
3029 }
3030
3031 if rng.gen_bool(0.3) {
3032 multibuffer.update(cx, |multibuffer, cx| {
3033 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3034 })
3035 }
3036
3037 let snapshot = multibuffer.read(cx).snapshot(cx);
3038
3039 let mut excerpt_starts = Vec::new();
3040 let mut expected_text = String::new();
3041 let mut expected_buffer_rows = Vec::new();
3042 for (buffer, range) in &expected_excerpts {
3043 let buffer = buffer.read(cx);
3044 let buffer_range = range.to_offset(buffer);
3045
3046 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
3047 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
3048 expected_text.push('\n');
3049
3050 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
3051 ..=buffer.offset_to_point(buffer_range.end).row;
3052 for row in buffer_row_range {
3053 expected_buffer_rows.push(Some(row));
3054 }
3055 }
3056 // Remove final trailing newline.
3057 if !expected_excerpts.is_empty() {
3058 expected_text.pop();
3059 }
3060
3061 // Always report one buffer row
3062 if expected_buffer_rows.is_empty() {
3063 expected_buffer_rows.push(Some(0));
3064 }
3065
3066 assert_eq!(snapshot.text(), expected_text);
3067 log::info!("MultiBuffer text: {:?}", expected_text);
3068
3069 assert_eq!(
3070 snapshot.buffer_rows(0).collect::<Vec<_>>(),
3071 expected_buffer_rows,
3072 );
3073
3074 for _ in 0..5 {
3075 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
3076 assert_eq!(
3077 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
3078 &expected_buffer_rows[start_row..],
3079 "buffer_rows({})",
3080 start_row
3081 );
3082 }
3083
3084 assert_eq!(
3085 snapshot.max_buffer_row(),
3086 expected_buffer_rows
3087 .into_iter()
3088 .filter_map(|r| r)
3089 .max()
3090 .unwrap()
3091 );
3092
3093 let mut excerpt_starts = excerpt_starts.into_iter();
3094 for (buffer, range) in &expected_excerpts {
3095 let buffer_id = buffer.id();
3096 let buffer = buffer.read(cx);
3097 let buffer_range = range.to_offset(buffer);
3098 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
3099 let buffer_start_point_utf16 =
3100 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
3101
3102 let excerpt_start = excerpt_starts.next().unwrap();
3103 let mut offset = excerpt_start.bytes;
3104 let mut buffer_offset = buffer_range.start;
3105 let mut point = excerpt_start.lines;
3106 let mut buffer_point = buffer_start_point;
3107 let mut point_utf16 = excerpt_start.lines_utf16;
3108 let mut buffer_point_utf16 = buffer_start_point_utf16;
3109 for ch in buffer
3110 .snapshot()
3111 .chunks(buffer_range.clone(), None)
3112 .flat_map(|c| c.text.chars())
3113 {
3114 for _ in 0..ch.len_utf8() {
3115 let left_offset = snapshot.clip_offset(offset, Bias::Left);
3116 let right_offset = snapshot.clip_offset(offset, Bias::Right);
3117 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
3118 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
3119 assert_eq!(
3120 left_offset,
3121 excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
3122 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
3123 offset,
3124 buffer_id,
3125 buffer_offset,
3126 );
3127 assert_eq!(
3128 right_offset,
3129 excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
3130 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
3131 offset,
3132 buffer_id,
3133 buffer_offset,
3134 );
3135
3136 let left_point = snapshot.clip_point(point, Bias::Left);
3137 let right_point = snapshot.clip_point(point, Bias::Right);
3138 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
3139 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
3140 assert_eq!(
3141 left_point,
3142 excerpt_start.lines + (buffer_left_point - buffer_start_point),
3143 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
3144 point,
3145 buffer_id,
3146 buffer_point,
3147 );
3148 assert_eq!(
3149 right_point,
3150 excerpt_start.lines + (buffer_right_point - buffer_start_point),
3151 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
3152 point,
3153 buffer_id,
3154 buffer_point,
3155 );
3156
3157 assert_eq!(
3158 snapshot.point_to_offset(left_point),
3159 left_offset,
3160 "point_to_offset({:?})",
3161 left_point,
3162 );
3163 assert_eq!(
3164 snapshot.offset_to_point(left_offset),
3165 left_point,
3166 "offset_to_point({:?})",
3167 left_offset,
3168 );
3169
3170 offset += 1;
3171 buffer_offset += 1;
3172 if ch == '\n' {
3173 point += Point::new(1, 0);
3174 buffer_point += Point::new(1, 0);
3175 } else {
3176 point += Point::new(0, 1);
3177 buffer_point += Point::new(0, 1);
3178 }
3179 }
3180
3181 for _ in 0..ch.len_utf16() {
3182 let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
3183 let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
3184 let buffer_left_point_utf16 =
3185 buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
3186 let buffer_right_point_utf16 =
3187 buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
3188 assert_eq!(
3189 left_point_utf16,
3190 excerpt_start.lines_utf16
3191 + (buffer_left_point_utf16 - buffer_start_point_utf16),
3192 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
3193 point_utf16,
3194 buffer_id,
3195 buffer_point_utf16,
3196 );
3197 assert_eq!(
3198 right_point_utf16,
3199 excerpt_start.lines_utf16
3200 + (buffer_right_point_utf16 - buffer_start_point_utf16),
3201 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
3202 point_utf16,
3203 buffer_id,
3204 buffer_point_utf16,
3205 );
3206
3207 if ch == '\n' {
3208 point_utf16 += PointUtf16::new(1, 0);
3209 buffer_point_utf16 += PointUtf16::new(1, 0);
3210 } else {
3211 point_utf16 += PointUtf16::new(0, 1);
3212 buffer_point_utf16 += PointUtf16::new(0, 1);
3213 }
3214 }
3215 }
3216 }
3217
3218 for (row, line) in expected_text.split('\n').enumerate() {
3219 assert_eq!(
3220 snapshot.line_len(row as u32),
3221 line.len() as u32,
3222 "line_len({}).",
3223 row
3224 );
3225 }
3226
3227 let text_rope = Rope::from(expected_text.as_str());
3228 for _ in 0..10 {
3229 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3230 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3231
3232 let text_for_range = snapshot
3233 .text_for_range(start_ix..end_ix)
3234 .collect::<String>();
3235 assert_eq!(
3236 text_for_range,
3237 &expected_text[start_ix..end_ix],
3238 "incorrect text for range {:?}",
3239 start_ix..end_ix
3240 );
3241
3242 let excerpted_buffer_ranges =
3243 multibuffer.read(cx).excerpted_buffers(start_ix..end_ix, cx);
3244 let excerpted_buffers_text = excerpted_buffer_ranges
3245 .into_iter()
3246 .map(|(buffer, buffer_range)| {
3247 buffer
3248 .read(cx)
3249 .text_for_range(buffer_range)
3250 .collect::<String>()
3251 })
3252 .collect::<Vec<_>>()
3253 .join("\n");
3254 assert_eq!(excerpted_buffers_text, text_for_range);
3255
3256 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
3257 assert_eq!(
3258 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
3259 expected_summary,
3260 "incorrect summary for range {:?}",
3261 start_ix..end_ix
3262 );
3263 }
3264
3265 // Anchor resolution
3266 for (anchor, resolved_offset) in anchors
3267 .iter()
3268 .zip(snapshot.summaries_for_anchors::<usize, _>(&anchors))
3269 {
3270 assert!(resolved_offset <= snapshot.len());
3271 assert_eq!(
3272 snapshot.summary_for_anchor::<usize>(anchor),
3273 resolved_offset
3274 );
3275 }
3276
3277 for _ in 0..10 {
3278 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3279 assert_eq!(
3280 snapshot.reversed_chars_at(end_ix).collect::<String>(),
3281 expected_text[..end_ix].chars().rev().collect::<String>(),
3282 );
3283 }
3284
3285 for _ in 0..10 {
3286 let end_ix = rng.gen_range(0..=text_rope.len());
3287 let start_ix = rng.gen_range(0..=end_ix);
3288 assert_eq!(
3289 snapshot
3290 .bytes_in_range(start_ix..end_ix)
3291 .flatten()
3292 .copied()
3293 .collect::<Vec<_>>(),
3294 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3295 "bytes_in_range({:?})",
3296 start_ix..end_ix,
3297 );
3298 }
3299 }
3300
3301 let snapshot = multibuffer.read(cx).snapshot(cx);
3302 for (old_snapshot, subscription) in old_versions {
3303 let edits = subscription.consume().into_inner();
3304
3305 log::info!(
3306 "applying subscription edits to old text: {:?}: {:?}",
3307 old_snapshot.text(),
3308 edits,
3309 );
3310
3311 let mut text = old_snapshot.text();
3312 for edit in edits {
3313 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
3314 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
3315 }
3316 assert_eq!(text.to_string(), snapshot.text());
3317 }
3318 }
3319
3320 #[gpui::test]
3321 fn test_history(cx: &mut MutableAppContext) {
3322 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
3323 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
3324 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3325 let group_interval = multibuffer.read(cx).history.group_interval;
3326 multibuffer.update(cx, |multibuffer, cx| {
3327 multibuffer.push_excerpt(
3328 ExcerptProperties {
3329 buffer: &buffer_1,
3330 range: 0..buffer_1.read(cx).len(),
3331 },
3332 cx,
3333 );
3334 multibuffer.push_excerpt(
3335 ExcerptProperties {
3336 buffer: &buffer_2,
3337 range: 0..buffer_2.read(cx).len(),
3338 },
3339 cx,
3340 );
3341 });
3342
3343 let mut now = Instant::now();
3344
3345 multibuffer.update(cx, |multibuffer, cx| {
3346 multibuffer.start_transaction_at(now, cx);
3347 multibuffer.edit(
3348 [
3349 Point::new(0, 0)..Point::new(0, 0),
3350 Point::new(1, 0)..Point::new(1, 0),
3351 ],
3352 "A",
3353 cx,
3354 );
3355 multibuffer.edit(
3356 [
3357 Point::new(0, 1)..Point::new(0, 1),
3358 Point::new(1, 1)..Point::new(1, 1),
3359 ],
3360 "B",
3361 cx,
3362 );
3363 multibuffer.end_transaction_at(now, cx);
3364 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3365
3366 now += 2 * group_interval;
3367 multibuffer.start_transaction_at(now, cx);
3368 multibuffer.edit([2..2], "C", cx);
3369 multibuffer.end_transaction_at(now, cx);
3370 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3371
3372 multibuffer.undo(cx);
3373 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3374
3375 multibuffer.undo(cx);
3376 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3377
3378 multibuffer.redo(cx);
3379 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3380
3381 multibuffer.redo(cx);
3382 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3383
3384 buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
3385 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3386
3387 multibuffer.undo(cx);
3388 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3389
3390 multibuffer.redo(cx);
3391 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3392
3393 multibuffer.redo(cx);
3394 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3395
3396 multibuffer.undo(cx);
3397 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3398
3399 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3400 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3401
3402 multibuffer.undo(cx);
3403 assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
3404 });
3405 }
3406}