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 language_aware: bool,
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 label: completion.label,
887 lsp_completion: completion.lsp_completion,
888 })
889 .collect()
890 })
891 })
892 }
893
894 pub fn is_completion_trigger<T>(&self, position: T, text: &str, cx: &AppContext) -> bool
895 where
896 T: ToOffset,
897 {
898 let mut chars = text.chars();
899 let char = if let Some(char) = chars.next() {
900 char
901 } else {
902 return false;
903 };
904 if chars.next().is_some() {
905 return false;
906 }
907
908 if char.is_alphanumeric() || char == '_' {
909 return true;
910 }
911
912 let snapshot = self.snapshot(cx);
913 let anchor = snapshot.anchor_before(position);
914 let buffer = self.buffers.borrow()[&anchor.buffer_id].buffer.clone();
915 buffer
916 .read(cx)
917 .completion_triggers()
918 .iter()
919 .any(|string| string == text)
920 }
921
922 pub fn apply_additional_edits_for_completion(
923 &self,
924 completion: Completion<Anchor>,
925 cx: &mut ModelContext<Self>,
926 ) -> Task<Result<()>> {
927 let buffer = if let Some(buffer_state) = self
928 .buffers
929 .borrow()
930 .get(&completion.old_range.start.buffer_id)
931 {
932 buffer_state.buffer.clone()
933 } else {
934 return Task::ready(Ok(()));
935 };
936
937 let apply_edits = buffer.update(cx, |buffer, cx| {
938 buffer.apply_additional_edits_for_completion(
939 Completion {
940 old_range: completion.old_range.start.text_anchor
941 ..completion.old_range.end.text_anchor,
942 new_text: completion.new_text,
943 label: completion.label,
944 lsp_completion: completion.lsp_completion,
945 },
946 true,
947 cx,
948 )
949 });
950 cx.foreground().spawn(async move {
951 apply_edits.await?;
952 Ok(())
953 })
954 }
955
956 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
957 self.buffers
958 .borrow()
959 .values()
960 .next()
961 .and_then(|state| state.buffer.read(cx).language())
962 }
963
964 pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
965 self.as_singleton()?.read(cx).file()
966 }
967
968 #[cfg(test)]
969 pub fn is_parsing(&self, cx: &AppContext) -> bool {
970 self.as_singleton().unwrap().read(cx).is_parsing()
971 }
972
973 fn sync(&self, cx: &AppContext) {
974 let mut snapshot = self.snapshot.borrow_mut();
975 let mut excerpts_to_edit = Vec::new();
976 let mut reparsed = false;
977 let mut diagnostics_updated = false;
978 let mut is_dirty = false;
979 let mut has_conflict = false;
980 let mut buffers = self.buffers.borrow_mut();
981 for buffer_state in buffers.values_mut() {
982 let buffer = buffer_state.buffer.read(cx);
983 let version = buffer.version();
984 let parse_count = buffer.parse_count();
985 let selections_update_count = buffer.selections_update_count();
986 let diagnostics_update_count = buffer.diagnostics_update_count();
987
988 let buffer_edited = version.changed_since(&buffer_state.last_version);
989 let buffer_reparsed = parse_count > buffer_state.last_parse_count;
990 let buffer_selections_updated =
991 selections_update_count > buffer_state.last_selections_update_count;
992 let buffer_diagnostics_updated =
993 diagnostics_update_count > buffer_state.last_diagnostics_update_count;
994 if buffer_edited
995 || buffer_reparsed
996 || buffer_selections_updated
997 || buffer_diagnostics_updated
998 {
999 buffer_state.last_version = version;
1000 buffer_state.last_parse_count = parse_count;
1001 buffer_state.last_selections_update_count = selections_update_count;
1002 buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1003 excerpts_to_edit.extend(
1004 buffer_state
1005 .excerpts
1006 .iter()
1007 .map(|excerpt_id| (excerpt_id, buffer_state.buffer.clone(), buffer_edited)),
1008 );
1009 }
1010
1011 reparsed |= buffer_reparsed;
1012 diagnostics_updated |= buffer_diagnostics_updated;
1013 is_dirty |= buffer.is_dirty();
1014 has_conflict |= buffer.has_conflict();
1015 }
1016 if reparsed {
1017 snapshot.parse_count += 1;
1018 }
1019 if diagnostics_updated {
1020 snapshot.diagnostics_update_count += 1;
1021 }
1022 snapshot.is_dirty = is_dirty;
1023 snapshot.has_conflict = has_conflict;
1024
1025 excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
1026
1027 let mut edits = Vec::new();
1028 let mut new_excerpts = SumTree::new();
1029 let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
1030
1031 for (id, buffer, buffer_edited) in excerpts_to_edit {
1032 new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
1033 let old_excerpt = cursor.item().unwrap();
1034 let buffer_id = buffer.id();
1035 let buffer = buffer.read(cx);
1036
1037 let mut new_excerpt;
1038 if buffer_edited {
1039 edits.extend(
1040 buffer
1041 .edits_since_in_range::<usize>(
1042 old_excerpt.buffer.version(),
1043 old_excerpt.range.clone(),
1044 )
1045 .map(|mut edit| {
1046 let excerpt_old_start = cursor.start().1;
1047 let excerpt_new_start = new_excerpts.summary().text.bytes;
1048 edit.old.start += excerpt_old_start;
1049 edit.old.end += excerpt_old_start;
1050 edit.new.start += excerpt_new_start;
1051 edit.new.end += excerpt_new_start;
1052 edit
1053 }),
1054 );
1055
1056 new_excerpt = Excerpt::new(
1057 id.clone(),
1058 buffer_id,
1059 buffer.snapshot(),
1060 old_excerpt.range.clone(),
1061 old_excerpt.has_trailing_newline,
1062 );
1063 } else {
1064 new_excerpt = old_excerpt.clone();
1065 new_excerpt.buffer = buffer.snapshot();
1066 }
1067
1068 new_excerpts.push(new_excerpt, &());
1069 cursor.next(&());
1070 }
1071 new_excerpts.push_tree(cursor.suffix(&()), &());
1072
1073 drop(cursor);
1074 snapshot.excerpts = new_excerpts;
1075
1076 self.subscriptions.publish(edits);
1077 }
1078}
1079
1080#[cfg(any(test, feature = "test-support"))]
1081impl MultiBuffer {
1082 pub fn randomly_edit(
1083 &mut self,
1084 rng: &mut impl rand::Rng,
1085 count: usize,
1086 cx: &mut ModelContext<Self>,
1087 ) {
1088 use text::RandomCharIter;
1089
1090 let snapshot = self.read(cx);
1091 let mut old_ranges: Vec<Range<usize>> = Vec::new();
1092 for _ in 0..count {
1093 let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1094 if last_end > snapshot.len() {
1095 break;
1096 }
1097 let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
1098 let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1099 old_ranges.push(start_ix..end_ix);
1100 }
1101 let new_text_len = rng.gen_range(0..10);
1102 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1103 log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
1104 drop(snapshot);
1105
1106 self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1107 }
1108}
1109
1110impl Entity for MultiBuffer {
1111 type Event = language::Event;
1112}
1113
1114impl MultiBufferSnapshot {
1115 pub fn text(&self) -> String {
1116 self.chunks(0..self.len(), false)
1117 .map(|chunk| chunk.text)
1118 .collect()
1119 }
1120
1121 pub fn reversed_chars_at<'a, T: ToOffset>(
1122 &'a self,
1123 position: T,
1124 ) -> impl Iterator<Item = char> + 'a {
1125 let mut offset = position.to_offset(self);
1126 let mut cursor = self.excerpts.cursor::<usize>();
1127 cursor.seek(&offset, Bias::Left, &());
1128 let mut excerpt_chunks = cursor.item().map(|excerpt| {
1129 let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
1130 let start = excerpt.range.start.to_offset(&excerpt.buffer);
1131 let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1132 excerpt.buffer.reversed_chunks_in_range(start..end)
1133 });
1134 iter::from_fn(move || {
1135 if offset == *cursor.start() {
1136 cursor.prev(&());
1137 let excerpt = cursor.item()?;
1138 excerpt_chunks = Some(
1139 excerpt
1140 .buffer
1141 .reversed_chunks_in_range(excerpt.range.clone()),
1142 );
1143 }
1144
1145 let excerpt = cursor.item().unwrap();
1146 if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1147 offset -= 1;
1148 Some("\n")
1149 } else {
1150 let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1151 offset -= chunk.len();
1152 Some(chunk)
1153 }
1154 })
1155 .flat_map(|c| c.chars().rev())
1156 }
1157
1158 pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1159 let offset = position.to_offset(self);
1160 self.text_for_range(offset..self.len())
1161 .flat_map(|chunk| chunk.chars())
1162 }
1163
1164 pub fn text_for_range<'a, T: ToOffset>(
1165 &'a self,
1166 range: Range<T>,
1167 ) -> impl Iterator<Item = &'a str> {
1168 self.chunks(range, false).map(|chunk| chunk.text)
1169 }
1170
1171 pub fn is_line_blank(&self, row: u32) -> bool {
1172 self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1173 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1174 }
1175
1176 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1177 where
1178 T: ToOffset,
1179 {
1180 let position = position.to_offset(self);
1181 position == self.clip_offset(position, Bias::Left)
1182 && self
1183 .bytes_in_range(position..self.len())
1184 .flatten()
1185 .copied()
1186 .take(needle.len())
1187 .eq(needle.bytes())
1188 }
1189
1190 pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1191 let mut start = start.to_offset(self);
1192 let mut end = start;
1193 let mut next_chars = self.chars_at(start).peekable();
1194 let mut prev_chars = self.reversed_chars_at(start).peekable();
1195 let word_kind = cmp::max(
1196 prev_chars.peek().copied().map(char_kind),
1197 next_chars.peek().copied().map(char_kind),
1198 );
1199
1200 for ch in prev_chars {
1201 if Some(char_kind(ch)) == word_kind {
1202 start -= ch.len_utf8();
1203 } else {
1204 break;
1205 }
1206 }
1207
1208 for ch in next_chars {
1209 if Some(char_kind(ch)) == word_kind {
1210 end += ch.len_utf8();
1211 } else {
1212 break;
1213 }
1214 }
1215
1216 (start..end, word_kind)
1217 }
1218
1219 fn as_singleton(&self) -> Option<&Excerpt> {
1220 if self.singleton {
1221 self.excerpts.iter().next()
1222 } else {
1223 None
1224 }
1225 }
1226
1227 pub fn len(&self) -> usize {
1228 self.excerpts.summary().text.bytes
1229 }
1230
1231 pub fn max_buffer_row(&self) -> u32 {
1232 self.excerpts.summary().max_buffer_row
1233 }
1234
1235 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1236 if let Some(excerpt) = self.as_singleton() {
1237 return excerpt.buffer.clip_offset(offset, bias);
1238 }
1239
1240 let mut cursor = self.excerpts.cursor::<usize>();
1241 cursor.seek(&offset, Bias::Right, &());
1242 let overshoot = if let Some(excerpt) = cursor.item() {
1243 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1244 let buffer_offset = excerpt
1245 .buffer
1246 .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1247 buffer_offset.saturating_sub(excerpt_start)
1248 } else {
1249 0
1250 };
1251 cursor.start() + overshoot
1252 }
1253
1254 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1255 if let Some(excerpt) = self.as_singleton() {
1256 return excerpt.buffer.clip_point(point, bias);
1257 }
1258
1259 let mut cursor = self.excerpts.cursor::<Point>();
1260 cursor.seek(&point, Bias::Right, &());
1261 let overshoot = if let Some(excerpt) = cursor.item() {
1262 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1263 let buffer_point = excerpt
1264 .buffer
1265 .clip_point(excerpt_start + (point - cursor.start()), bias);
1266 buffer_point.saturating_sub(excerpt_start)
1267 } else {
1268 Point::zero()
1269 };
1270 *cursor.start() + overshoot
1271 }
1272
1273 pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1274 if let Some(excerpt) = self.as_singleton() {
1275 return excerpt.buffer.clip_point_utf16(point, bias);
1276 }
1277
1278 let mut cursor = self.excerpts.cursor::<PointUtf16>();
1279 cursor.seek(&point, Bias::Right, &());
1280 let overshoot = if let Some(excerpt) = cursor.item() {
1281 let excerpt_start = excerpt
1282 .buffer
1283 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1284 let buffer_point = excerpt
1285 .buffer
1286 .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1287 buffer_point.saturating_sub(excerpt_start)
1288 } else {
1289 PointUtf16::zero()
1290 };
1291 *cursor.start() + overshoot
1292 }
1293
1294 pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1295 let range = range.start.to_offset(self)..range.end.to_offset(self);
1296 let mut excerpts = self.excerpts.cursor::<usize>();
1297 excerpts.seek(&range.start, Bias::Right, &());
1298
1299 let mut chunk = &[][..];
1300 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1301 let mut excerpt_bytes = excerpt
1302 .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1303 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1304 Some(excerpt_bytes)
1305 } else {
1306 None
1307 };
1308
1309 MultiBufferBytes {
1310 range,
1311 excerpts,
1312 excerpt_bytes,
1313 chunk,
1314 }
1315 }
1316
1317 pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1318 let mut result = MultiBufferRows {
1319 buffer_row_range: 0..0,
1320 excerpts: self.excerpts.cursor(),
1321 };
1322 result.seek(start_row);
1323 result
1324 }
1325
1326 pub fn chunks<'a, T: ToOffset>(
1327 &'a self,
1328 range: Range<T>,
1329 language_aware: bool,
1330 ) -> MultiBufferChunks<'a> {
1331 let range = range.start.to_offset(self)..range.end.to_offset(self);
1332 let mut chunks = MultiBufferChunks {
1333 range: range.clone(),
1334 excerpts: self.excerpts.cursor(),
1335 excerpt_chunks: None,
1336 language_aware: language_aware,
1337 };
1338 chunks.seek(range.start);
1339 chunks
1340 }
1341
1342 pub fn offset_to_point(&self, offset: usize) -> Point {
1343 if let Some(excerpt) = self.as_singleton() {
1344 return excerpt.buffer.offset_to_point(offset);
1345 }
1346
1347 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1348 cursor.seek(&offset, Bias::Right, &());
1349 if let Some(excerpt) = cursor.item() {
1350 let (start_offset, start_point) = cursor.start();
1351 let overshoot = offset - start_offset;
1352 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1353 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1354 let buffer_point = excerpt
1355 .buffer
1356 .offset_to_point(excerpt_start_offset + overshoot);
1357 *start_point + (buffer_point - excerpt_start_point)
1358 } else {
1359 self.excerpts.summary().text.lines
1360 }
1361 }
1362
1363 pub fn point_to_offset(&self, point: Point) -> usize {
1364 if let Some(excerpt) = self.as_singleton() {
1365 return excerpt.buffer.point_to_offset(point);
1366 }
1367
1368 let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1369 cursor.seek(&point, Bias::Right, &());
1370 if let Some(excerpt) = cursor.item() {
1371 let (start_point, start_offset) = cursor.start();
1372 let overshoot = point - start_point;
1373 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1374 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1375 let buffer_offset = excerpt
1376 .buffer
1377 .point_to_offset(excerpt_start_point + overshoot);
1378 *start_offset + buffer_offset - excerpt_start_offset
1379 } else {
1380 self.excerpts.summary().text.bytes
1381 }
1382 }
1383
1384 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1385 if let Some(excerpt) = self.as_singleton() {
1386 return excerpt.buffer.point_utf16_to_offset(point);
1387 }
1388
1389 let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1390 cursor.seek(&point, Bias::Right, &());
1391 if let Some(excerpt) = cursor.item() {
1392 let (start_point, start_offset) = cursor.start();
1393 let overshoot = point - start_point;
1394 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1395 let excerpt_start_point = excerpt
1396 .buffer
1397 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1398 let buffer_offset = excerpt
1399 .buffer
1400 .point_utf16_to_offset(excerpt_start_point + overshoot);
1401 *start_offset + (buffer_offset - excerpt_start_offset)
1402 } else {
1403 self.excerpts.summary().text.bytes
1404 }
1405 }
1406
1407 pub fn indent_column_for_line(&self, row: u32) -> u32 {
1408 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1409 buffer
1410 .indent_column_for_line(range.start.row)
1411 .min(range.end.column)
1412 .saturating_sub(range.start.column)
1413 } else {
1414 0
1415 }
1416 }
1417
1418 pub fn line_len(&self, row: u32) -> u32 {
1419 if let Some((_, range)) = self.buffer_line_for_row(row) {
1420 range.end.column - range.start.column
1421 } else {
1422 0
1423 }
1424 }
1425
1426 fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1427 let mut cursor = self.excerpts.cursor::<Point>();
1428 cursor.seek(&Point::new(row, 0), Bias::Right, &());
1429 if let Some(excerpt) = cursor.item() {
1430 let overshoot = row - cursor.start().row;
1431 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1432 let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1433 let buffer_row = excerpt_start.row + overshoot;
1434 let line_start = Point::new(buffer_row, 0);
1435 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1436 return Some((
1437 &excerpt.buffer,
1438 line_start.max(excerpt_start)..line_end.min(excerpt_end),
1439 ));
1440 }
1441 None
1442 }
1443
1444 pub fn max_point(&self) -> Point {
1445 self.text_summary().lines
1446 }
1447
1448 pub fn text_summary(&self) -> TextSummary {
1449 self.excerpts.summary().text
1450 }
1451
1452 pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1453 where
1454 D: TextDimension,
1455 O: ToOffset,
1456 {
1457 let mut summary = D::default();
1458 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1459 let mut cursor = self.excerpts.cursor::<usize>();
1460 cursor.seek(&range.start, Bias::Right, &());
1461 if let Some(excerpt) = cursor.item() {
1462 let mut end_before_newline = cursor.end(&());
1463 if excerpt.has_trailing_newline {
1464 end_before_newline -= 1;
1465 }
1466
1467 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1468 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
1469 let end_in_excerpt =
1470 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
1471 summary.add_assign(
1472 &excerpt
1473 .buffer
1474 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1475 );
1476
1477 if range.end > end_before_newline {
1478 summary.add_assign(&D::from_text_summary(&TextSummary {
1479 bytes: 1,
1480 lines: Point::new(1 as u32, 0),
1481 lines_utf16: PointUtf16::new(1 as u32, 0),
1482 first_line_chars: 0,
1483 last_line_chars: 0,
1484 longest_row: 0,
1485 longest_row_chars: 0,
1486 }));
1487 }
1488
1489 cursor.next(&());
1490 }
1491
1492 if range.end > *cursor.start() {
1493 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1494 &range.end,
1495 Bias::Right,
1496 &(),
1497 )));
1498 if let Some(excerpt) = cursor.item() {
1499 range.end = cmp::max(*cursor.start(), range.end);
1500
1501 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1502 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
1503 summary.add_assign(
1504 &excerpt
1505 .buffer
1506 .text_summary_for_range(excerpt_start..end_in_excerpt),
1507 );
1508 }
1509 }
1510
1511 summary
1512 }
1513
1514 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1515 where
1516 D: TextDimension + Ord + Sub<D, Output = D>,
1517 {
1518 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1519 cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1520 if cursor.item().is_none() {
1521 cursor.next(&());
1522 }
1523
1524 let mut position = D::from_text_summary(&cursor.start().text);
1525 if let Some(excerpt) = cursor.item() {
1526 if excerpt.id == anchor.excerpt_id && excerpt.buffer_id == anchor.buffer_id {
1527 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1528 let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1529 let buffer_position = cmp::min(
1530 excerpt_buffer_end,
1531 anchor.text_anchor.summary::<D>(&excerpt.buffer),
1532 );
1533 if buffer_position > excerpt_buffer_start {
1534 position.add_assign(&(buffer_position - excerpt_buffer_start));
1535 }
1536 }
1537 }
1538 position
1539 }
1540
1541 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1542 where
1543 D: TextDimension + Ord + Sub<D, Output = D>,
1544 I: 'a + IntoIterator<Item = &'a Anchor>,
1545 {
1546 let mut anchors = anchors.into_iter().peekable();
1547 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1548 let mut summaries = Vec::new();
1549 while let Some(anchor) = anchors.peek() {
1550 let excerpt_id = &anchor.excerpt_id;
1551 let buffer_id = anchor.buffer_id;
1552 let excerpt_anchors = iter::from_fn(|| {
1553 let anchor = anchors.peek()?;
1554 if anchor.excerpt_id == *excerpt_id && anchor.buffer_id == buffer_id {
1555 Some(&anchors.next().unwrap().text_anchor)
1556 } else {
1557 None
1558 }
1559 });
1560
1561 cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1562 if cursor.item().is_none() {
1563 cursor.next(&());
1564 }
1565
1566 let position = D::from_text_summary(&cursor.start().text);
1567 if let Some(excerpt) = cursor.item() {
1568 if excerpt.id == *excerpt_id && excerpt.buffer_id == buffer_id {
1569 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1570 let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1571 summaries.extend(
1572 excerpt
1573 .buffer
1574 .summaries_for_anchors::<D, _>(excerpt_anchors)
1575 .map(move |summary| {
1576 let summary = cmp::min(excerpt_buffer_end.clone(), summary);
1577 let mut position = position.clone();
1578 let excerpt_buffer_start = excerpt_buffer_start.clone();
1579 if summary > excerpt_buffer_start {
1580 position.add_assign(&(summary - excerpt_buffer_start));
1581 }
1582 position
1583 }),
1584 );
1585 continue;
1586 }
1587 }
1588
1589 summaries.extend(excerpt_anchors.map(|_| position.clone()));
1590 }
1591
1592 summaries
1593 }
1594
1595 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
1596 where
1597 I: 'a + IntoIterator<Item = &'a Anchor>,
1598 {
1599 let mut anchors = anchors.into_iter().enumerate().peekable();
1600 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1601 let mut result = Vec::new();
1602 while let Some((_, anchor)) = anchors.peek() {
1603 let old_excerpt_id = &anchor.excerpt_id;
1604
1605 // Find the location where this anchor's excerpt should be.
1606 cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
1607 if cursor.item().is_none() {
1608 cursor.next(&());
1609 }
1610
1611 let next_excerpt = cursor.item();
1612 let prev_excerpt = cursor.prev_item();
1613
1614 // Process all of the anchors for this excerpt.
1615 while let Some((_, anchor)) = anchors.peek() {
1616 if anchor.excerpt_id != *old_excerpt_id {
1617 break;
1618 }
1619 let mut kept_position = false;
1620 let (anchor_ix, anchor) = anchors.next().unwrap();
1621 let mut anchor = anchor.clone();
1622
1623 // Leave min and max anchors unchanged.
1624 if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
1625 kept_position = true;
1626 }
1627 // If the old excerpt still exists at this location, then leave
1628 // the anchor unchanged.
1629 else if next_excerpt.map_or(false, |excerpt| {
1630 excerpt.id == *old_excerpt_id && excerpt.contains(&anchor)
1631 }) {
1632 kept_position = true;
1633 }
1634 // If the old excerpt no longer exists at this location, then attempt to
1635 // find an equivalent position for this anchor in an adjacent excerpt.
1636 else {
1637 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
1638 if excerpt.contains(&anchor) {
1639 anchor.excerpt_id = excerpt.id.clone();
1640 kept_position = true;
1641 break;
1642 }
1643 }
1644 }
1645 // If there's no adjacent excerpt that contains the anchor's position,
1646 // then report that the anchor has lost its position.
1647 if !kept_position {
1648 anchor = if let Some(excerpt) = next_excerpt {
1649 let mut text_anchor = excerpt
1650 .range
1651 .start
1652 .bias(anchor.text_anchor.bias, &excerpt.buffer);
1653 if text_anchor
1654 .cmp(&excerpt.range.end, &excerpt.buffer)
1655 .unwrap()
1656 .is_gt()
1657 {
1658 text_anchor = excerpt.range.end.clone();
1659 }
1660 Anchor {
1661 buffer_id: excerpt.buffer_id,
1662 excerpt_id: excerpt.id.clone(),
1663 text_anchor,
1664 }
1665 } else if let Some(excerpt) = prev_excerpt {
1666 let mut text_anchor = excerpt
1667 .range
1668 .end
1669 .bias(anchor.text_anchor.bias, &excerpt.buffer);
1670 if text_anchor
1671 .cmp(&excerpt.range.start, &excerpt.buffer)
1672 .unwrap()
1673 .is_lt()
1674 {
1675 text_anchor = excerpt.range.start.clone();
1676 }
1677 Anchor {
1678 buffer_id: excerpt.buffer_id,
1679 excerpt_id: excerpt.id.clone(),
1680 text_anchor,
1681 }
1682 } else if anchor.text_anchor.bias == Bias::Left {
1683 Anchor::min()
1684 } else {
1685 Anchor::max()
1686 };
1687 }
1688
1689 result.push((anchor_ix, anchor, kept_position));
1690 }
1691 }
1692 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self).unwrap());
1693 result
1694 }
1695
1696 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1697 self.anchor_at(position, Bias::Left)
1698 }
1699
1700 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1701 self.anchor_at(position, Bias::Right)
1702 }
1703
1704 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1705 let offset = position.to_offset(self);
1706 if let Some(excerpt) = self.as_singleton() {
1707 return Anchor {
1708 buffer_id: excerpt.buffer_id,
1709 excerpt_id: excerpt.id.clone(),
1710 text_anchor: excerpt.buffer.anchor_at(offset, bias),
1711 };
1712 }
1713
1714 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1715 cursor.seek(&offset, Bias::Right, &());
1716 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1717 cursor.prev(&());
1718 }
1719 if let Some(excerpt) = cursor.item() {
1720 let mut overshoot = offset.saturating_sub(cursor.start().0);
1721 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1722 overshoot -= 1;
1723 bias = Bias::Right;
1724 }
1725
1726 let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1727 let text_anchor =
1728 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1729 Anchor {
1730 buffer_id: excerpt.buffer_id,
1731 excerpt_id: excerpt.id.clone(),
1732 text_anchor,
1733 }
1734 } else if offset == 0 && bias == Bias::Left {
1735 Anchor::min()
1736 } else {
1737 Anchor::max()
1738 }
1739 }
1740
1741 pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1742 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1743 cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1744 if let Some(excerpt) = cursor.item() {
1745 if excerpt.id == excerpt_id {
1746 let text_anchor = excerpt.clip_anchor(text_anchor);
1747 drop(cursor);
1748 return Anchor {
1749 buffer_id: excerpt.buffer_id,
1750 excerpt_id,
1751 text_anchor,
1752 };
1753 }
1754 }
1755 panic!("excerpt not found");
1756 }
1757
1758 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1759 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
1760 true
1761 } else if let Some((buffer_id, buffer_snapshot)) =
1762 self.buffer_snapshot_for_excerpt(&anchor.excerpt_id)
1763 {
1764 anchor.buffer_id == buffer_id && buffer_snapshot.can_resolve(&anchor.text_anchor)
1765 } else {
1766 false
1767 }
1768 }
1769
1770 pub fn range_contains_excerpt_boundary<T: ToOffset>(&self, range: Range<T>) -> bool {
1771 let start = range.start.to_offset(self);
1772 let end = range.end.to_offset(self);
1773 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1774 cursor.seek(&start, Bias::Right, &());
1775 let start_id = cursor
1776 .item()
1777 .or_else(|| cursor.prev_item())
1778 .map(|excerpt| &excerpt.id);
1779 cursor.seek_forward(&end, Bias::Right, &());
1780 let end_id = cursor
1781 .item()
1782 .or_else(|| cursor.prev_item())
1783 .map(|excerpt| &excerpt.id);
1784 start_id != end_id
1785 }
1786
1787 pub fn parse_count(&self) -> usize {
1788 self.parse_count
1789 }
1790
1791 pub fn enclosing_bracket_ranges<T: ToOffset>(
1792 &self,
1793 range: Range<T>,
1794 ) -> Option<(Range<usize>, Range<usize>)> {
1795 let range = range.start.to_offset(self)..range.end.to_offset(self);
1796
1797 let mut cursor = self.excerpts.cursor::<usize>();
1798 cursor.seek(&range.start, Bias::Right, &());
1799 let start_excerpt = cursor.item();
1800
1801 cursor.seek(&range.end, Bias::Right, &());
1802 let end_excerpt = cursor.item();
1803
1804 start_excerpt
1805 .zip(end_excerpt)
1806 .and_then(|(start_excerpt, end_excerpt)| {
1807 if start_excerpt.id != end_excerpt.id {
1808 return None;
1809 }
1810
1811 let excerpt_buffer_start =
1812 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1813 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1814
1815 let start_in_buffer =
1816 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1817 let end_in_buffer =
1818 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1819 let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1820 .buffer
1821 .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1822
1823 if start_bracket_range.start >= excerpt_buffer_start
1824 && end_bracket_range.end < excerpt_buffer_end
1825 {
1826 start_bracket_range.start =
1827 cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
1828 start_bracket_range.end =
1829 cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
1830 end_bracket_range.start =
1831 cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
1832 end_bracket_range.end =
1833 cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
1834 Some((start_bracket_range, end_bracket_range))
1835 } else {
1836 None
1837 }
1838 })
1839 }
1840
1841 pub fn diagnostics_update_count(&self) -> usize {
1842 self.diagnostics_update_count
1843 }
1844
1845 pub fn language(&self) -> Option<&Arc<Language>> {
1846 self.excerpts
1847 .iter()
1848 .next()
1849 .and_then(|excerpt| excerpt.buffer.language())
1850 }
1851
1852 pub fn is_dirty(&self) -> bool {
1853 self.is_dirty
1854 }
1855
1856 pub fn has_conflict(&self) -> bool {
1857 self.has_conflict
1858 }
1859
1860 pub fn diagnostic_group<'a, O>(
1861 &'a self,
1862 group_id: usize,
1863 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1864 where
1865 O: text::FromAnchor + 'a,
1866 {
1867 self.as_singleton()
1868 .into_iter()
1869 .flat_map(move |excerpt| excerpt.buffer.diagnostic_group(group_id))
1870 }
1871
1872 pub fn diagnostics_in_range<'a, T, O>(
1873 &'a self,
1874 range: Range<T>,
1875 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1876 where
1877 T: 'a + ToOffset,
1878 O: 'a + text::FromAnchor,
1879 {
1880 self.as_singleton().into_iter().flat_map(move |excerpt| {
1881 excerpt
1882 .buffer
1883 .diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
1884 })
1885 }
1886
1887 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1888 let range = range.start.to_offset(self)..range.end.to_offset(self);
1889
1890 let mut cursor = self.excerpts.cursor::<usize>();
1891 cursor.seek(&range.start, Bias::Right, &());
1892 let start_excerpt = cursor.item();
1893
1894 cursor.seek(&range.end, Bias::Right, &());
1895 let end_excerpt = cursor.item();
1896
1897 start_excerpt
1898 .zip(end_excerpt)
1899 .and_then(|(start_excerpt, end_excerpt)| {
1900 if start_excerpt.id != end_excerpt.id {
1901 return None;
1902 }
1903
1904 let excerpt_buffer_start =
1905 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1906 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1907
1908 let start_in_buffer =
1909 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1910 let end_in_buffer =
1911 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1912 let mut ancestor_buffer_range = start_excerpt
1913 .buffer
1914 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
1915 ancestor_buffer_range.start =
1916 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
1917 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
1918
1919 let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
1920 let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
1921 Some(start..end)
1922 })
1923 }
1924
1925 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1926 let excerpt = self.as_singleton()?;
1927 let outline = excerpt.buffer.outline(theme)?;
1928 Some(Outline::new(
1929 outline
1930 .items
1931 .into_iter()
1932 .map(|item| OutlineItem {
1933 depth: item.depth,
1934 range: self.anchor_in_excerpt(excerpt.id.clone(), item.range.start)
1935 ..self.anchor_in_excerpt(excerpt.id.clone(), item.range.end),
1936 text: item.text,
1937 highlight_ranges: item.highlight_ranges,
1938 name_ranges: item.name_ranges,
1939 })
1940 .collect(),
1941 ))
1942 }
1943
1944 fn buffer_snapshot_for_excerpt<'a>(
1945 &'a self,
1946 excerpt_id: &'a ExcerptId,
1947 ) -> Option<(usize, &'a BufferSnapshot)> {
1948 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1949 cursor.seek(&Some(excerpt_id), Bias::Left, &());
1950 if let Some(excerpt) = cursor.item() {
1951 if excerpt.id == *excerpt_id {
1952 return Some((excerpt.buffer_id, &excerpt.buffer));
1953 }
1954 }
1955 None
1956 }
1957
1958 pub fn remote_selections_in_range<'a>(
1959 &'a self,
1960 range: &'a Range<Anchor>,
1961 ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
1962 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1963 cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
1964 cursor
1965 .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
1966 .flat_map(move |excerpt| {
1967 let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
1968 if excerpt.id == range.start.excerpt_id {
1969 query_range.start = range.start.text_anchor.clone();
1970 }
1971 if excerpt.id == range.end.excerpt_id {
1972 query_range.end = range.end.text_anchor.clone();
1973 }
1974
1975 excerpt
1976 .buffer
1977 .remote_selections_in_range(query_range)
1978 .flat_map(move |(replica_id, selections)| {
1979 selections.map(move |selection| {
1980 let mut start = Anchor {
1981 buffer_id: excerpt.buffer_id,
1982 excerpt_id: excerpt.id.clone(),
1983 text_anchor: selection.start.clone(),
1984 };
1985 let mut end = Anchor {
1986 buffer_id: excerpt.buffer_id,
1987 excerpt_id: excerpt.id.clone(),
1988 text_anchor: selection.end.clone(),
1989 };
1990 if range.start.cmp(&start, self).unwrap().is_gt() {
1991 start = range.start.clone();
1992 }
1993 if range.end.cmp(&end, self).unwrap().is_lt() {
1994 end = range.end.clone();
1995 }
1996
1997 (
1998 replica_id,
1999 Selection {
2000 id: selection.id,
2001 start,
2002 end,
2003 reversed: selection.reversed,
2004 goal: selection.goal,
2005 },
2006 )
2007 })
2008 })
2009 })
2010 }
2011}
2012
2013impl History {
2014 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2015 self.transaction_depth += 1;
2016 if self.transaction_depth == 1 {
2017 let id = post_inc(&mut self.next_transaction_id);
2018 self.undo_stack.push(Transaction {
2019 id,
2020 buffer_transactions: Default::default(),
2021 first_edit_at: now,
2022 last_edit_at: now,
2023 });
2024 Some(id)
2025 } else {
2026 None
2027 }
2028 }
2029
2030 fn end_transaction(
2031 &mut self,
2032 now: Instant,
2033 buffer_transactions: HashSet<(usize, TransactionId)>,
2034 ) -> bool {
2035 assert_ne!(self.transaction_depth, 0);
2036 self.transaction_depth -= 1;
2037 if self.transaction_depth == 0 {
2038 if buffer_transactions.is_empty() {
2039 self.undo_stack.pop();
2040 false
2041 } else {
2042 let transaction = self.undo_stack.last_mut().unwrap();
2043 transaction.last_edit_at = now;
2044 transaction.buffer_transactions.extend(buffer_transactions);
2045 true
2046 }
2047 } else {
2048 false
2049 }
2050 }
2051
2052 fn pop_undo(&mut self) -> Option<&Transaction> {
2053 assert_eq!(self.transaction_depth, 0);
2054 if let Some(transaction) = self.undo_stack.pop() {
2055 self.redo_stack.push(transaction);
2056 self.redo_stack.last()
2057 } else {
2058 None
2059 }
2060 }
2061
2062 fn pop_redo(&mut self) -> Option<&Transaction> {
2063 assert_eq!(self.transaction_depth, 0);
2064 if let Some(transaction) = self.redo_stack.pop() {
2065 self.undo_stack.push(transaction);
2066 self.undo_stack.last()
2067 } else {
2068 None
2069 }
2070 }
2071
2072 fn group(&mut self) -> Option<TransactionId> {
2073 let mut new_len = self.undo_stack.len();
2074 let mut transactions = self.undo_stack.iter_mut();
2075
2076 if let Some(mut transaction) = transactions.next_back() {
2077 while let Some(prev_transaction) = transactions.next_back() {
2078 if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
2079 {
2080 transaction = prev_transaction;
2081 new_len -= 1;
2082 } else {
2083 break;
2084 }
2085 }
2086 }
2087
2088 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2089 if let Some(last_transaction) = transactions_to_keep.last_mut() {
2090 if let Some(transaction) = transactions_to_merge.last() {
2091 last_transaction.last_edit_at = transaction.last_edit_at;
2092 }
2093 }
2094
2095 self.undo_stack.truncate(new_len);
2096 self.undo_stack.last().map(|t| t.id)
2097 }
2098}
2099
2100impl Excerpt {
2101 fn new(
2102 id: ExcerptId,
2103 buffer_id: usize,
2104 buffer: BufferSnapshot,
2105 range: Range<text::Anchor>,
2106 has_trailing_newline: bool,
2107 ) -> Self {
2108 Excerpt {
2109 id,
2110 max_buffer_row: range.end.to_point(&buffer).row,
2111 text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
2112 buffer_id,
2113 buffer,
2114 range,
2115 has_trailing_newline,
2116 }
2117 }
2118
2119 fn chunks_in_range<'a>(
2120 &'a self,
2121 range: Range<usize>,
2122 language_aware: bool,
2123 ) -> ExcerptChunks<'a> {
2124 let content_start = self.range.start.to_offset(&self.buffer);
2125 let chunks_start = content_start + range.start;
2126 let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2127
2128 let footer_height = if self.has_trailing_newline
2129 && range.start <= self.text_summary.bytes
2130 && range.end > self.text_summary.bytes
2131 {
2132 1
2133 } else {
2134 0
2135 };
2136
2137 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
2138
2139 ExcerptChunks {
2140 content_chunks,
2141 footer_height,
2142 }
2143 }
2144
2145 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2146 let content_start = self.range.start.to_offset(&self.buffer);
2147 let bytes_start = content_start + range.start;
2148 let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2149 let footer_height = if self.has_trailing_newline
2150 && range.start <= self.text_summary.bytes
2151 && range.end > self.text_summary.bytes
2152 {
2153 1
2154 } else {
2155 0
2156 };
2157 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2158
2159 ExcerptBytes {
2160 content_bytes,
2161 footer_height,
2162 }
2163 }
2164
2165 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2166 if text_anchor
2167 .cmp(&self.range.start, &self.buffer)
2168 .unwrap()
2169 .is_lt()
2170 {
2171 self.range.start.clone()
2172 } else if text_anchor
2173 .cmp(&self.range.end, &self.buffer)
2174 .unwrap()
2175 .is_gt()
2176 {
2177 self.range.end.clone()
2178 } else {
2179 text_anchor
2180 }
2181 }
2182
2183 fn contains(&self, anchor: &Anchor) -> bool {
2184 self.buffer_id == anchor.buffer_id
2185 && self
2186 .range
2187 .start
2188 .cmp(&anchor.text_anchor, &self.buffer)
2189 .unwrap()
2190 .is_le()
2191 && self
2192 .range
2193 .end
2194 .cmp(&anchor.text_anchor, &self.buffer)
2195 .unwrap()
2196 .is_ge()
2197 }
2198}
2199
2200impl fmt::Debug for Excerpt {
2201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2202 f.debug_struct("Excerpt")
2203 .field("id", &self.id)
2204 .field("buffer_id", &self.buffer_id)
2205 .field("range", &self.range)
2206 .field("text_summary", &self.text_summary)
2207 .field("has_trailing_newline", &self.has_trailing_newline)
2208 .finish()
2209 }
2210}
2211
2212impl sum_tree::Item for Excerpt {
2213 type Summary = ExcerptSummary;
2214
2215 fn summary(&self) -> Self::Summary {
2216 let mut text = self.text_summary.clone();
2217 if self.has_trailing_newline {
2218 text += TextSummary::from("\n");
2219 }
2220 ExcerptSummary {
2221 excerpt_id: self.id.clone(),
2222 max_buffer_row: self.max_buffer_row,
2223 text,
2224 }
2225 }
2226}
2227
2228impl sum_tree::Summary for ExcerptSummary {
2229 type Context = ();
2230
2231 fn add_summary(&mut self, summary: &Self, _: &()) {
2232 debug_assert!(summary.excerpt_id > self.excerpt_id);
2233 self.excerpt_id = summary.excerpt_id.clone();
2234 self.text.add_summary(&summary.text, &());
2235 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2236 }
2237}
2238
2239impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2240 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2241 *self += &summary.text;
2242 }
2243}
2244
2245impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2246 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2247 *self += summary.text.bytes;
2248 }
2249}
2250
2251impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2252 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2253 Ord::cmp(self, &cursor_location.text.bytes)
2254 }
2255}
2256
2257impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2258 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2259 Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2260 }
2261}
2262
2263impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2264 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2265 *self += summary.text.lines;
2266 }
2267}
2268
2269impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2270 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2271 *self += summary.text.lines_utf16
2272 }
2273}
2274
2275impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2276 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2277 *self = Some(&summary.excerpt_id);
2278 }
2279}
2280
2281impl<'a> MultiBufferRows<'a> {
2282 pub fn seek(&mut self, row: u32) {
2283 self.buffer_row_range = 0..0;
2284
2285 self.excerpts
2286 .seek_forward(&Point::new(row, 0), Bias::Right, &());
2287 if self.excerpts.item().is_none() {
2288 self.excerpts.prev(&());
2289
2290 if self.excerpts.item().is_none() && row == 0 {
2291 self.buffer_row_range = 0..1;
2292 return;
2293 }
2294 }
2295
2296 if let Some(excerpt) = self.excerpts.item() {
2297 let overshoot = row - self.excerpts.start().row;
2298 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
2299 self.buffer_row_range.start = excerpt_start + overshoot;
2300 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
2301 }
2302 }
2303}
2304
2305impl<'a> Iterator for MultiBufferRows<'a> {
2306 type Item = Option<u32>;
2307
2308 fn next(&mut self) -> Option<Self::Item> {
2309 loop {
2310 if !self.buffer_row_range.is_empty() {
2311 let row = Some(self.buffer_row_range.start);
2312 self.buffer_row_range.start += 1;
2313 return Some(row);
2314 }
2315 self.excerpts.item()?;
2316 self.excerpts.next(&());
2317 let excerpt = self.excerpts.item()?;
2318 self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
2319 self.buffer_row_range.end =
2320 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
2321 }
2322 }
2323}
2324
2325impl<'a> MultiBufferChunks<'a> {
2326 pub fn offset(&self) -> usize {
2327 self.range.start
2328 }
2329
2330 pub fn seek(&mut self, offset: usize) {
2331 self.range.start = offset;
2332 self.excerpts.seek(&offset, Bias::Right, &());
2333 if let Some(excerpt) = self.excerpts.item() {
2334 self.excerpt_chunks = Some(excerpt.chunks_in_range(
2335 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
2336 self.language_aware,
2337 ));
2338 } else {
2339 self.excerpt_chunks = None;
2340 }
2341 }
2342}
2343
2344impl<'a> Iterator for MultiBufferChunks<'a> {
2345 type Item = Chunk<'a>;
2346
2347 fn next(&mut self) -> Option<Self::Item> {
2348 if self.range.is_empty() {
2349 None
2350 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
2351 self.range.start += chunk.text.len();
2352 Some(chunk)
2353 } else {
2354 self.excerpts.next(&());
2355 let excerpt = self.excerpts.item()?;
2356 self.excerpt_chunks = Some(excerpt.chunks_in_range(
2357 0..self.range.end - self.excerpts.start(),
2358 self.language_aware,
2359 ));
2360 self.next()
2361 }
2362 }
2363}
2364
2365impl<'a> MultiBufferBytes<'a> {
2366 fn consume(&mut self, len: usize) {
2367 self.range.start += len;
2368 self.chunk = &self.chunk[len..];
2369
2370 if !self.range.is_empty() && self.chunk.is_empty() {
2371 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
2372 self.chunk = chunk;
2373 } else {
2374 self.excerpts.next(&());
2375 if let Some(excerpt) = self.excerpts.item() {
2376 let mut excerpt_bytes =
2377 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
2378 self.chunk = excerpt_bytes.next().unwrap();
2379 self.excerpt_bytes = Some(excerpt_bytes);
2380 }
2381 }
2382 }
2383 }
2384}
2385
2386impl<'a> Iterator for MultiBufferBytes<'a> {
2387 type Item = &'a [u8];
2388
2389 fn next(&mut self) -> Option<Self::Item> {
2390 let chunk = self.chunk;
2391 if chunk.is_empty() {
2392 None
2393 } else {
2394 self.consume(chunk.len());
2395 Some(chunk)
2396 }
2397 }
2398}
2399
2400impl<'a> io::Read for MultiBufferBytes<'a> {
2401 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2402 let len = cmp::min(buf.len(), self.chunk.len());
2403 buf[..len].copy_from_slice(&self.chunk[..len]);
2404 if len > 0 {
2405 self.consume(len);
2406 }
2407 Ok(len)
2408 }
2409}
2410
2411impl<'a> Iterator for ExcerptBytes<'a> {
2412 type Item = &'a [u8];
2413
2414 fn next(&mut self) -> Option<Self::Item> {
2415 if let Some(chunk) = self.content_bytes.next() {
2416 if !chunk.is_empty() {
2417 return Some(chunk);
2418 }
2419 }
2420
2421 if self.footer_height > 0 {
2422 let result = &NEWLINES[..self.footer_height];
2423 self.footer_height = 0;
2424 return Some(result);
2425 }
2426
2427 None
2428 }
2429}
2430
2431impl<'a> Iterator for ExcerptChunks<'a> {
2432 type Item = Chunk<'a>;
2433
2434 fn next(&mut self) -> Option<Self::Item> {
2435 if let Some(chunk) = self.content_chunks.next() {
2436 return Some(chunk);
2437 }
2438
2439 if self.footer_height > 0 {
2440 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2441 self.footer_height = 0;
2442 return Some(Chunk {
2443 text,
2444 ..Default::default()
2445 });
2446 }
2447
2448 None
2449 }
2450}
2451
2452impl ToOffset for Point {
2453 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2454 snapshot.point_to_offset(*self)
2455 }
2456}
2457
2458impl ToOffset for PointUtf16 {
2459 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2460 snapshot.point_utf16_to_offset(*self)
2461 }
2462}
2463
2464impl ToOffset for usize {
2465 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2466 assert!(*self <= snapshot.len(), "offset is out of range");
2467 *self
2468 }
2469}
2470
2471impl ToPoint for usize {
2472 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2473 snapshot.offset_to_point(*self)
2474 }
2475}
2476
2477impl ToPoint for Point {
2478 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2479 *self
2480 }
2481}
2482
2483pub fn char_kind(c: char) -> CharKind {
2484 if c == '\n' {
2485 CharKind::Newline
2486 } else if c.is_whitespace() {
2487 CharKind::Whitespace
2488 } else if c.is_alphanumeric() || c == '_' {
2489 CharKind::Word
2490 } else {
2491 CharKind::Punctuation
2492 }
2493}
2494
2495#[cfg(test)]
2496mod tests {
2497 use super::*;
2498 use gpui::MutableAppContext;
2499 use language::{Buffer, Rope};
2500 use rand::prelude::*;
2501 use std::env;
2502 use text::{Point, RandomCharIter};
2503 use util::test::sample_text;
2504
2505 #[gpui::test]
2506 fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2507 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2508 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2509
2510 let snapshot = multibuffer.read(cx).snapshot(cx);
2511 assert_eq!(snapshot.text(), buffer.read(cx).text());
2512
2513 assert_eq!(
2514 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2515 (0..buffer.read(cx).row_count())
2516 .map(Some)
2517 .collect::<Vec<_>>()
2518 );
2519
2520 buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2521 let snapshot = multibuffer.read(cx).snapshot(cx);
2522
2523 assert_eq!(snapshot.text(), buffer.read(cx).text());
2524 assert_eq!(
2525 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2526 (0..buffer.read(cx).row_count())
2527 .map(Some)
2528 .collect::<Vec<_>>()
2529 );
2530 }
2531
2532 #[gpui::test]
2533 fn test_remote_multibuffer(cx: &mut MutableAppContext) {
2534 let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
2535 let guest_buffer = cx.add_model(|cx| {
2536 let message = host_buffer.read(cx).to_proto();
2537 Buffer::from_proto(1, message, None, cx).unwrap()
2538 });
2539 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
2540 let snapshot = multibuffer.read(cx).snapshot(cx);
2541 assert_eq!(snapshot.text(), "a");
2542
2543 guest_buffer.update(cx, |buffer, cx| buffer.edit([1..1], "b", cx));
2544 let snapshot = multibuffer.read(cx).snapshot(cx);
2545 assert_eq!(snapshot.text(), "ab");
2546
2547 guest_buffer.update(cx, |buffer, cx| buffer.edit([2..2], "c", cx));
2548 let snapshot = multibuffer.read(cx).snapshot(cx);
2549 assert_eq!(snapshot.text(), "abc");
2550 }
2551
2552 #[gpui::test]
2553 fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2554 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2555 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2556 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2557
2558 let subscription = multibuffer.update(cx, |multibuffer, cx| {
2559 let subscription = multibuffer.subscribe();
2560 multibuffer.push_excerpt(
2561 ExcerptProperties {
2562 buffer: &buffer_1,
2563 range: Point::new(1, 2)..Point::new(2, 5),
2564 },
2565 cx,
2566 );
2567 assert_eq!(
2568 subscription.consume().into_inner(),
2569 [Edit {
2570 old: 0..0,
2571 new: 0..10
2572 }]
2573 );
2574
2575 multibuffer.push_excerpt(
2576 ExcerptProperties {
2577 buffer: &buffer_1,
2578 range: Point::new(3, 3)..Point::new(4, 4),
2579 },
2580 cx,
2581 );
2582 multibuffer.push_excerpt(
2583 ExcerptProperties {
2584 buffer: &buffer_2,
2585 range: Point::new(3, 1)..Point::new(3, 3),
2586 },
2587 cx,
2588 );
2589 assert_eq!(
2590 subscription.consume().into_inner(),
2591 [Edit {
2592 old: 10..10,
2593 new: 10..22
2594 }]
2595 );
2596
2597 subscription
2598 });
2599
2600 let snapshot = multibuffer.read(cx).snapshot(cx);
2601 assert_eq!(
2602 snapshot.text(),
2603 concat!(
2604 "bbbb\n", // Preserve newlines
2605 "ccccc\n", //
2606 "ddd\n", //
2607 "eeee\n", //
2608 "jj" //
2609 )
2610 );
2611 assert_eq!(
2612 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2613 [Some(1), Some(2), Some(3), Some(4), Some(3)]
2614 );
2615 assert_eq!(
2616 snapshot.buffer_rows(2).collect::<Vec<_>>(),
2617 [Some(3), Some(4), Some(3)]
2618 );
2619 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2620 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2621 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(1, 5)));
2622 assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(2, 0)));
2623 assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(4, 0)));
2624 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(2, 0)..Point::new(3, 0)));
2625 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 0)..Point::new(4, 2)));
2626 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 2)..Point::new(4, 2)));
2627
2628 buffer_1.update(cx, |buffer, cx| {
2629 buffer.edit(
2630 [
2631 Point::new(0, 0)..Point::new(0, 0),
2632 Point::new(2, 1)..Point::new(2, 3),
2633 ],
2634 "\n",
2635 cx,
2636 );
2637 });
2638
2639 let snapshot = multibuffer.read(cx).snapshot(cx);
2640 assert_eq!(
2641 snapshot.text(),
2642 concat!(
2643 "bbbb\n", // Preserve newlines
2644 "c\n", //
2645 "cc\n", //
2646 "ddd\n", //
2647 "eeee\n", //
2648 "jj" //
2649 )
2650 );
2651
2652 assert_eq!(
2653 subscription.consume().into_inner(),
2654 [Edit {
2655 old: 6..8,
2656 new: 6..7
2657 }]
2658 );
2659
2660 let snapshot = multibuffer.read(cx).snapshot(cx);
2661 assert_eq!(
2662 snapshot.clip_point(Point::new(0, 5), Bias::Left),
2663 Point::new(0, 4)
2664 );
2665 assert_eq!(
2666 snapshot.clip_point(Point::new(0, 5), Bias::Right),
2667 Point::new(0, 4)
2668 );
2669 assert_eq!(
2670 snapshot.clip_point(Point::new(5, 1), Bias::Right),
2671 Point::new(5, 1)
2672 );
2673 assert_eq!(
2674 snapshot.clip_point(Point::new(5, 2), Bias::Right),
2675 Point::new(5, 2)
2676 );
2677 assert_eq!(
2678 snapshot.clip_point(Point::new(5, 3), Bias::Right),
2679 Point::new(5, 2)
2680 );
2681
2682 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2683 let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2684 multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2685 multibuffer.snapshot(cx)
2686 });
2687
2688 assert_eq!(
2689 snapshot.text(),
2690 concat!(
2691 "bbbb\n", // Preserve newlines
2692 "c\n", //
2693 "cc\n", //
2694 "ddd\n", //
2695 "eeee", //
2696 )
2697 );
2698 }
2699
2700 #[gpui::test]
2701 fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2702 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2703
2704 let snapshot = multibuffer.read(cx).snapshot(cx);
2705 assert_eq!(snapshot.text(), "");
2706 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2707 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2708 }
2709
2710 #[gpui::test]
2711 fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2712 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2713 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2714 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2715 buffer.update(cx, |buffer, cx| {
2716 buffer.edit([0..0], "X", cx);
2717 buffer.edit([5..5], "Y", cx);
2718 });
2719 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2720
2721 assert_eq!(old_snapshot.text(), "abcd");
2722 assert_eq!(new_snapshot.text(), "XabcdY");
2723
2724 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2725 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2726 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2727 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2728 }
2729
2730 #[gpui::test]
2731 fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2732 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2733 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2734 let multibuffer = cx.add_model(|cx| {
2735 let mut multibuffer = MultiBuffer::new(0);
2736 multibuffer.push_excerpt(
2737 ExcerptProperties {
2738 buffer: &buffer_1,
2739 range: 0..4,
2740 },
2741 cx,
2742 );
2743 multibuffer.push_excerpt(
2744 ExcerptProperties {
2745 buffer: &buffer_2,
2746 range: 0..5,
2747 },
2748 cx,
2749 );
2750 multibuffer
2751 });
2752 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2753
2754 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
2755 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
2756 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2757 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2758 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2759 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2760
2761 buffer_1.update(cx, |buffer, cx| {
2762 buffer.edit([0..0], "W", cx);
2763 buffer.edit([5..5], "X", cx);
2764 });
2765 buffer_2.update(cx, |buffer, cx| {
2766 buffer.edit([0..0], "Y", cx);
2767 buffer.edit([6..0], "Z", cx);
2768 });
2769 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2770
2771 assert_eq!(old_snapshot.text(), "abcd\nefghi");
2772 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
2773
2774 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2775 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2776 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
2777 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2778 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2779 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2780 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
2781 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
2782 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
2783 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
2784 }
2785
2786 #[gpui::test]
2787 fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
2788 cx: &mut MutableAppContext,
2789 ) {
2790 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2791 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
2792 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2793
2794 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
2795 // Add an excerpt from buffer 1 that spans this new insertion.
2796 buffer_1.update(cx, |buffer, cx| buffer.edit([4..4], "123", cx));
2797 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
2798 multibuffer.push_excerpt(
2799 ExcerptProperties {
2800 buffer: &buffer_1,
2801 range: 0..7,
2802 },
2803 cx,
2804 )
2805 });
2806
2807 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
2808 assert_eq!(snapshot_1.text(), "abcd123");
2809
2810 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
2811 let (excerpt_id_2, excerpt_id_3, _) = multibuffer.update(cx, |multibuffer, cx| {
2812 multibuffer.remove_excerpts([&excerpt_id_1], cx);
2813 (
2814 multibuffer.push_excerpt(
2815 ExcerptProperties {
2816 buffer: &buffer_2,
2817 range: 0..4,
2818 },
2819 cx,
2820 ),
2821 multibuffer.push_excerpt(
2822 ExcerptProperties {
2823 buffer: &buffer_2,
2824 range: 6..10,
2825 },
2826 cx,
2827 ),
2828 multibuffer.push_excerpt(
2829 ExcerptProperties {
2830 buffer: &buffer_2,
2831 range: 12..16,
2832 },
2833 cx,
2834 ),
2835 )
2836 });
2837 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
2838 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
2839
2840 // The old excerpt id has been reused.
2841 assert_eq!(excerpt_id_2, excerpt_id_1);
2842
2843 // Resolve some anchors from the previous snapshot in the new snapshot.
2844 // Although there is still an excerpt with the same id, it is for
2845 // a different buffer, so we don't attempt to resolve the old text
2846 // anchor in the new buffer.
2847 assert_eq!(
2848 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
2849 0
2850 );
2851 assert_eq!(
2852 snapshot_2.summaries_for_anchors::<usize, _>(&[
2853 snapshot_1.anchor_before(2),
2854 snapshot_1.anchor_after(3)
2855 ]),
2856 vec![0, 0]
2857 );
2858 let refresh =
2859 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
2860 assert_eq!(
2861 refresh,
2862 &[
2863 (0, snapshot_2.anchor_before(0), false),
2864 (1, snapshot_2.anchor_after(0), false),
2865 ]
2866 );
2867
2868 // Replace the middle excerpt with a smaller excerpt in buffer 2,
2869 // that intersects the old excerpt.
2870 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
2871 multibuffer.remove_excerpts([&excerpt_id_3], cx);
2872 multibuffer.insert_excerpt_after(
2873 &excerpt_id_3,
2874 ExcerptProperties {
2875 buffer: &buffer_2,
2876 range: 5..8,
2877 },
2878 cx,
2879 )
2880 });
2881
2882 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
2883 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
2884 assert_ne!(excerpt_id_5, excerpt_id_3);
2885
2886 // Resolve some anchors from the previous snapshot in the new snapshot.
2887 // The anchor in the middle excerpt snaps to the beginning of the
2888 // excerpt, since it is not
2889 let anchors = [
2890 snapshot_2.anchor_before(0),
2891 snapshot_2.anchor_after(2),
2892 snapshot_2.anchor_after(6),
2893 snapshot_2.anchor_after(14),
2894 ];
2895 assert_eq!(
2896 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
2897 &[0, 2, 9, 13]
2898 );
2899
2900 let new_anchors = snapshot_3.refresh_anchors(&anchors);
2901 assert_eq!(
2902 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
2903 &[(0, true), (1, true), (2, true), (3, true)]
2904 );
2905 assert_eq!(
2906 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
2907 &[0, 2, 7, 13]
2908 );
2909 }
2910
2911 #[gpui::test(iterations = 100)]
2912 fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
2913 let operations = env::var("OPERATIONS")
2914 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2915 .unwrap_or(10);
2916
2917 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
2918 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2919 let mut excerpt_ids = Vec::new();
2920 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
2921 let mut anchors = Vec::new();
2922 let mut old_versions = Vec::new();
2923
2924 for _ in 0..operations {
2925 match rng.gen_range(0..100) {
2926 0..=19 if !buffers.is_empty() => {
2927 let buffer = buffers.choose(&mut rng).unwrap();
2928 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
2929 }
2930 20..=29 if !expected_excerpts.is_empty() => {
2931 let mut ids_to_remove = vec![];
2932 for _ in 0..rng.gen_range(1..=3) {
2933 if expected_excerpts.is_empty() {
2934 break;
2935 }
2936
2937 let ix = rng.gen_range(0..expected_excerpts.len());
2938 ids_to_remove.push(excerpt_ids.remove(ix));
2939 let (buffer, range) = expected_excerpts.remove(ix);
2940 let buffer = buffer.read(cx);
2941 log::info!(
2942 "Removing excerpt {}: {:?}",
2943 ix,
2944 buffer
2945 .text_for_range(range.to_offset(&buffer))
2946 .collect::<String>(),
2947 );
2948 }
2949 ids_to_remove.sort_unstable();
2950 multibuffer.update(cx, |multibuffer, cx| {
2951 multibuffer.remove_excerpts(&ids_to_remove, cx)
2952 });
2953 }
2954 30..=39 if !expected_excerpts.is_empty() => {
2955 let multibuffer = multibuffer.read(cx).read(cx);
2956 let offset =
2957 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
2958 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
2959 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2960 anchors.push(multibuffer.anchor_at(offset, bias));
2961 anchors.sort_by(|a, b| a.cmp(&b, &multibuffer).unwrap());
2962 }
2963 40..=44 if !anchors.is_empty() => {
2964 let multibuffer = multibuffer.read(cx).read(cx);
2965
2966 anchors = multibuffer
2967 .refresh_anchors(&anchors)
2968 .into_iter()
2969 .map(|a| a.1)
2970 .collect();
2971
2972 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2973 // overshoot its boundaries.
2974 let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
2975 for anchor in &anchors {
2976 if anchor.excerpt_id == ExcerptId::min()
2977 || anchor.excerpt_id == ExcerptId::max()
2978 {
2979 continue;
2980 }
2981
2982 cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
2983 let excerpt = cursor.item().unwrap();
2984 assert_eq!(excerpt.id, anchor.excerpt_id);
2985 assert!(excerpt.contains(anchor));
2986 }
2987 }
2988 _ => {
2989 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2990 let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
2991 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
2992 buffers.last().unwrap()
2993 } else {
2994 buffers.choose(&mut rng).unwrap()
2995 };
2996
2997 let buffer = buffer_handle.read(cx);
2998 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
2999 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3000 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3001 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
3002 let prev_excerpt_id = excerpt_ids
3003 .get(prev_excerpt_ix)
3004 .cloned()
3005 .unwrap_or(ExcerptId::max());
3006 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3007
3008 log::info!(
3009 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3010 excerpt_ix,
3011 expected_excerpts.len(),
3012 buffer_handle.id(),
3013 buffer.text(),
3014 start_ix..end_ix,
3015 &buffer.text()[start_ix..end_ix]
3016 );
3017
3018 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3019 multibuffer.insert_excerpt_after(
3020 &prev_excerpt_id,
3021 ExcerptProperties {
3022 buffer: &buffer_handle,
3023 range: start_ix..end_ix,
3024 },
3025 cx,
3026 )
3027 });
3028
3029 excerpt_ids.insert(excerpt_ix, excerpt_id);
3030 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
3031 }
3032 }
3033
3034 if rng.gen_bool(0.3) {
3035 multibuffer.update(cx, |multibuffer, cx| {
3036 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3037 })
3038 }
3039
3040 let snapshot = multibuffer.read(cx).snapshot(cx);
3041
3042 let mut excerpt_starts = Vec::new();
3043 let mut expected_text = String::new();
3044 let mut expected_buffer_rows = Vec::new();
3045 for (buffer, range) in &expected_excerpts {
3046 let buffer = buffer.read(cx);
3047 let buffer_range = range.to_offset(buffer);
3048
3049 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
3050 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
3051 expected_text.push('\n');
3052
3053 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
3054 ..=buffer.offset_to_point(buffer_range.end).row;
3055 for row in buffer_row_range {
3056 expected_buffer_rows.push(Some(row));
3057 }
3058 }
3059 // Remove final trailing newline.
3060 if !expected_excerpts.is_empty() {
3061 expected_text.pop();
3062 }
3063
3064 // Always report one buffer row
3065 if expected_buffer_rows.is_empty() {
3066 expected_buffer_rows.push(Some(0));
3067 }
3068
3069 assert_eq!(snapshot.text(), expected_text);
3070 log::info!("MultiBuffer text: {:?}", expected_text);
3071
3072 assert_eq!(
3073 snapshot.buffer_rows(0).collect::<Vec<_>>(),
3074 expected_buffer_rows,
3075 );
3076
3077 for _ in 0..5 {
3078 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
3079 assert_eq!(
3080 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
3081 &expected_buffer_rows[start_row..],
3082 "buffer_rows({})",
3083 start_row
3084 );
3085 }
3086
3087 assert_eq!(
3088 snapshot.max_buffer_row(),
3089 expected_buffer_rows
3090 .into_iter()
3091 .filter_map(|r| r)
3092 .max()
3093 .unwrap()
3094 );
3095
3096 let mut excerpt_starts = excerpt_starts.into_iter();
3097 for (buffer, range) in &expected_excerpts {
3098 let buffer_id = buffer.id();
3099 let buffer = buffer.read(cx);
3100 let buffer_range = range.to_offset(buffer);
3101 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
3102 let buffer_start_point_utf16 =
3103 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
3104
3105 let excerpt_start = excerpt_starts.next().unwrap();
3106 let mut offset = excerpt_start.bytes;
3107 let mut buffer_offset = buffer_range.start;
3108 let mut point = excerpt_start.lines;
3109 let mut buffer_point = buffer_start_point;
3110 let mut point_utf16 = excerpt_start.lines_utf16;
3111 let mut buffer_point_utf16 = buffer_start_point_utf16;
3112 for ch in buffer
3113 .snapshot()
3114 .chunks(buffer_range.clone(), false)
3115 .flat_map(|c| c.text.chars())
3116 {
3117 for _ in 0..ch.len_utf8() {
3118 let left_offset = snapshot.clip_offset(offset, Bias::Left);
3119 let right_offset = snapshot.clip_offset(offset, Bias::Right);
3120 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
3121 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
3122 assert_eq!(
3123 left_offset,
3124 excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
3125 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
3126 offset,
3127 buffer_id,
3128 buffer_offset,
3129 );
3130 assert_eq!(
3131 right_offset,
3132 excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
3133 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
3134 offset,
3135 buffer_id,
3136 buffer_offset,
3137 );
3138
3139 let left_point = snapshot.clip_point(point, Bias::Left);
3140 let right_point = snapshot.clip_point(point, Bias::Right);
3141 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
3142 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
3143 assert_eq!(
3144 left_point,
3145 excerpt_start.lines + (buffer_left_point - buffer_start_point),
3146 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
3147 point,
3148 buffer_id,
3149 buffer_point,
3150 );
3151 assert_eq!(
3152 right_point,
3153 excerpt_start.lines + (buffer_right_point - buffer_start_point),
3154 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
3155 point,
3156 buffer_id,
3157 buffer_point,
3158 );
3159
3160 assert_eq!(
3161 snapshot.point_to_offset(left_point),
3162 left_offset,
3163 "point_to_offset({:?})",
3164 left_point,
3165 );
3166 assert_eq!(
3167 snapshot.offset_to_point(left_offset),
3168 left_point,
3169 "offset_to_point({:?})",
3170 left_offset,
3171 );
3172
3173 offset += 1;
3174 buffer_offset += 1;
3175 if ch == '\n' {
3176 point += Point::new(1, 0);
3177 buffer_point += Point::new(1, 0);
3178 } else {
3179 point += Point::new(0, 1);
3180 buffer_point += Point::new(0, 1);
3181 }
3182 }
3183
3184 for _ in 0..ch.len_utf16() {
3185 let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
3186 let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
3187 let buffer_left_point_utf16 =
3188 buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
3189 let buffer_right_point_utf16 =
3190 buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
3191 assert_eq!(
3192 left_point_utf16,
3193 excerpt_start.lines_utf16
3194 + (buffer_left_point_utf16 - buffer_start_point_utf16),
3195 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
3196 point_utf16,
3197 buffer_id,
3198 buffer_point_utf16,
3199 );
3200 assert_eq!(
3201 right_point_utf16,
3202 excerpt_start.lines_utf16
3203 + (buffer_right_point_utf16 - buffer_start_point_utf16),
3204 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
3205 point_utf16,
3206 buffer_id,
3207 buffer_point_utf16,
3208 );
3209
3210 if ch == '\n' {
3211 point_utf16 += PointUtf16::new(1, 0);
3212 buffer_point_utf16 += PointUtf16::new(1, 0);
3213 } else {
3214 point_utf16 += PointUtf16::new(0, 1);
3215 buffer_point_utf16 += PointUtf16::new(0, 1);
3216 }
3217 }
3218 }
3219 }
3220
3221 for (row, line) in expected_text.split('\n').enumerate() {
3222 assert_eq!(
3223 snapshot.line_len(row as u32),
3224 line.len() as u32,
3225 "line_len({}).",
3226 row
3227 );
3228 }
3229
3230 let text_rope = Rope::from(expected_text.as_str());
3231 for _ in 0..10 {
3232 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3233 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3234
3235 let text_for_range = snapshot
3236 .text_for_range(start_ix..end_ix)
3237 .collect::<String>();
3238 assert_eq!(
3239 text_for_range,
3240 &expected_text[start_ix..end_ix],
3241 "incorrect text for range {:?}",
3242 start_ix..end_ix
3243 );
3244
3245 let excerpted_buffer_ranges =
3246 multibuffer.read(cx).excerpted_buffers(start_ix..end_ix, cx);
3247 let excerpted_buffers_text = excerpted_buffer_ranges
3248 .into_iter()
3249 .map(|(buffer, buffer_range)| {
3250 buffer
3251 .read(cx)
3252 .text_for_range(buffer_range)
3253 .collect::<String>()
3254 })
3255 .collect::<Vec<_>>()
3256 .join("\n");
3257 assert_eq!(excerpted_buffers_text, text_for_range);
3258
3259 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
3260 assert_eq!(
3261 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
3262 expected_summary,
3263 "incorrect summary for range {:?}",
3264 start_ix..end_ix
3265 );
3266 }
3267
3268 // Anchor resolution
3269 for (anchor, resolved_offset) in anchors
3270 .iter()
3271 .zip(snapshot.summaries_for_anchors::<usize, _>(&anchors))
3272 {
3273 assert!(resolved_offset <= snapshot.len());
3274 assert_eq!(
3275 snapshot.summary_for_anchor::<usize>(anchor),
3276 resolved_offset
3277 );
3278 }
3279
3280 for _ in 0..10 {
3281 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3282 assert_eq!(
3283 snapshot.reversed_chars_at(end_ix).collect::<String>(),
3284 expected_text[..end_ix].chars().rev().collect::<String>(),
3285 );
3286 }
3287
3288 for _ in 0..10 {
3289 let end_ix = rng.gen_range(0..=text_rope.len());
3290 let start_ix = rng.gen_range(0..=end_ix);
3291 assert_eq!(
3292 snapshot
3293 .bytes_in_range(start_ix..end_ix)
3294 .flatten()
3295 .copied()
3296 .collect::<Vec<_>>(),
3297 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3298 "bytes_in_range({:?})",
3299 start_ix..end_ix,
3300 );
3301 }
3302 }
3303
3304 let snapshot = multibuffer.read(cx).snapshot(cx);
3305 for (old_snapshot, subscription) in old_versions {
3306 let edits = subscription.consume().into_inner();
3307
3308 log::info!(
3309 "applying subscription edits to old text: {:?}: {:?}",
3310 old_snapshot.text(),
3311 edits,
3312 );
3313
3314 let mut text = old_snapshot.text();
3315 for edit in edits {
3316 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
3317 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
3318 }
3319 assert_eq!(text.to_string(), snapshot.text());
3320 }
3321 }
3322
3323 #[gpui::test]
3324 fn test_history(cx: &mut MutableAppContext) {
3325 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
3326 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
3327 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3328 let group_interval = multibuffer.read(cx).history.group_interval;
3329 multibuffer.update(cx, |multibuffer, cx| {
3330 multibuffer.push_excerpt(
3331 ExcerptProperties {
3332 buffer: &buffer_1,
3333 range: 0..buffer_1.read(cx).len(),
3334 },
3335 cx,
3336 );
3337 multibuffer.push_excerpt(
3338 ExcerptProperties {
3339 buffer: &buffer_2,
3340 range: 0..buffer_2.read(cx).len(),
3341 },
3342 cx,
3343 );
3344 });
3345
3346 let mut now = Instant::now();
3347
3348 multibuffer.update(cx, |multibuffer, cx| {
3349 multibuffer.start_transaction_at(now, cx);
3350 multibuffer.edit(
3351 [
3352 Point::new(0, 0)..Point::new(0, 0),
3353 Point::new(1, 0)..Point::new(1, 0),
3354 ],
3355 "A",
3356 cx,
3357 );
3358 multibuffer.edit(
3359 [
3360 Point::new(0, 1)..Point::new(0, 1),
3361 Point::new(1, 1)..Point::new(1, 1),
3362 ],
3363 "B",
3364 cx,
3365 );
3366 multibuffer.end_transaction_at(now, cx);
3367 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3368
3369 now += 2 * group_interval;
3370 multibuffer.start_transaction_at(now, cx);
3371 multibuffer.edit([2..2], "C", cx);
3372 multibuffer.end_transaction_at(now, cx);
3373 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3374
3375 multibuffer.undo(cx);
3376 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3377
3378 multibuffer.undo(cx);
3379 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3380
3381 multibuffer.redo(cx);
3382 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3383
3384 multibuffer.redo(cx);
3385 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3386
3387 buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
3388 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3389
3390 multibuffer.undo(cx);
3391 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3392
3393 multibuffer.redo(cx);
3394 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3395
3396 multibuffer.redo(cx);
3397 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3398
3399 multibuffer.undo(cx);
3400 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3401
3402 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3403 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3404
3405 multibuffer.undo(cx);
3406 assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
3407 });
3408 }
3409}