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 if let Some(excerpt) = self.as_singleton() {
1547 return excerpt
1548 .buffer
1549 .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
1550 .collect();
1551 }
1552
1553 let mut anchors = anchors.into_iter().peekable();
1554 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1555 let mut summaries = Vec::new();
1556 while let Some(anchor) = anchors.peek() {
1557 let excerpt_id = &anchor.excerpt_id;
1558 let buffer_id = anchor.buffer_id;
1559 let excerpt_anchors = iter::from_fn(|| {
1560 let anchor = anchors.peek()?;
1561 if anchor.excerpt_id == *excerpt_id && anchor.buffer_id == buffer_id {
1562 Some(&anchors.next().unwrap().text_anchor)
1563 } else {
1564 None
1565 }
1566 });
1567
1568 cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1569 if cursor.item().is_none() {
1570 cursor.next(&());
1571 }
1572
1573 let position = D::from_text_summary(&cursor.start().text);
1574 if let Some(excerpt) = cursor.item() {
1575 if excerpt.id == *excerpt_id && excerpt.buffer_id == buffer_id {
1576 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1577 let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1578 summaries.extend(
1579 excerpt
1580 .buffer
1581 .summaries_for_anchors::<D, _>(excerpt_anchors)
1582 .map(move |summary| {
1583 let summary = cmp::min(excerpt_buffer_end.clone(), summary);
1584 let mut position = position.clone();
1585 let excerpt_buffer_start = excerpt_buffer_start.clone();
1586 if summary > excerpt_buffer_start {
1587 position.add_assign(&(summary - excerpt_buffer_start));
1588 }
1589 position
1590 }),
1591 );
1592 continue;
1593 }
1594 }
1595
1596 summaries.extend(excerpt_anchors.map(|_| position.clone()));
1597 }
1598
1599 summaries
1600 }
1601
1602 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
1603 where
1604 I: 'a + IntoIterator<Item = &'a Anchor>,
1605 {
1606 let mut anchors = anchors.into_iter().enumerate().peekable();
1607 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1608 let mut result = Vec::new();
1609 while let Some((_, anchor)) = anchors.peek() {
1610 let old_excerpt_id = &anchor.excerpt_id;
1611
1612 // Find the location where this anchor's excerpt should be.
1613 cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
1614 if cursor.item().is_none() {
1615 cursor.next(&());
1616 }
1617
1618 let next_excerpt = cursor.item();
1619 let prev_excerpt = cursor.prev_item();
1620
1621 // Process all of the anchors for this excerpt.
1622 while let Some((_, anchor)) = anchors.peek() {
1623 if anchor.excerpt_id != *old_excerpt_id {
1624 break;
1625 }
1626 let mut kept_position = false;
1627 let (anchor_ix, anchor) = anchors.next().unwrap();
1628 let mut anchor = anchor.clone();
1629
1630 // Leave min and max anchors unchanged.
1631 if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
1632 kept_position = true;
1633 }
1634 // If the old excerpt still exists at this location, then leave
1635 // the anchor unchanged.
1636 else if next_excerpt.map_or(false, |excerpt| {
1637 excerpt.id == *old_excerpt_id && excerpt.contains(&anchor)
1638 }) {
1639 kept_position = true;
1640 }
1641 // If the old excerpt no longer exists at this location, then attempt to
1642 // find an equivalent position for this anchor in an adjacent excerpt.
1643 else {
1644 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
1645 if excerpt.contains(&anchor) {
1646 anchor.excerpt_id = excerpt.id.clone();
1647 kept_position = true;
1648 break;
1649 }
1650 }
1651 }
1652 // If there's no adjacent excerpt that contains the anchor's position,
1653 // then report that the anchor has lost its position.
1654 if !kept_position {
1655 anchor = if let Some(excerpt) = next_excerpt {
1656 let mut text_anchor = excerpt
1657 .range
1658 .start
1659 .bias(anchor.text_anchor.bias, &excerpt.buffer);
1660 if text_anchor
1661 .cmp(&excerpt.range.end, &excerpt.buffer)
1662 .unwrap()
1663 .is_gt()
1664 {
1665 text_anchor = excerpt.range.end.clone();
1666 }
1667 Anchor {
1668 buffer_id: excerpt.buffer_id,
1669 excerpt_id: excerpt.id.clone(),
1670 text_anchor,
1671 }
1672 } else if let Some(excerpt) = prev_excerpt {
1673 let mut text_anchor = excerpt
1674 .range
1675 .end
1676 .bias(anchor.text_anchor.bias, &excerpt.buffer);
1677 if text_anchor
1678 .cmp(&excerpt.range.start, &excerpt.buffer)
1679 .unwrap()
1680 .is_lt()
1681 {
1682 text_anchor = excerpt.range.start.clone();
1683 }
1684 Anchor {
1685 buffer_id: excerpt.buffer_id,
1686 excerpt_id: excerpt.id.clone(),
1687 text_anchor,
1688 }
1689 } else if anchor.text_anchor.bias == Bias::Left {
1690 Anchor::min()
1691 } else {
1692 Anchor::max()
1693 };
1694 }
1695
1696 result.push((anchor_ix, anchor, kept_position));
1697 }
1698 }
1699 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self).unwrap());
1700 result
1701 }
1702
1703 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1704 self.anchor_at(position, Bias::Left)
1705 }
1706
1707 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1708 self.anchor_at(position, Bias::Right)
1709 }
1710
1711 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1712 let offset = position.to_offset(self);
1713 if let Some(excerpt) = self.as_singleton() {
1714 return Anchor {
1715 buffer_id: excerpt.buffer_id,
1716 excerpt_id: excerpt.id.clone(),
1717 text_anchor: excerpt.buffer.anchor_at(offset, bias),
1718 };
1719 }
1720
1721 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1722 cursor.seek(&offset, Bias::Right, &());
1723 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1724 cursor.prev(&());
1725 }
1726 if let Some(excerpt) = cursor.item() {
1727 let mut overshoot = offset.saturating_sub(cursor.start().0);
1728 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1729 overshoot -= 1;
1730 bias = Bias::Right;
1731 }
1732
1733 let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1734 let text_anchor =
1735 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1736 Anchor {
1737 buffer_id: excerpt.buffer_id,
1738 excerpt_id: excerpt.id.clone(),
1739 text_anchor,
1740 }
1741 } else if offset == 0 && bias == Bias::Left {
1742 Anchor::min()
1743 } else {
1744 Anchor::max()
1745 }
1746 }
1747
1748 pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1749 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1750 cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1751 if let Some(excerpt) = cursor.item() {
1752 if excerpt.id == excerpt_id {
1753 let text_anchor = excerpt.clip_anchor(text_anchor);
1754 drop(cursor);
1755 return Anchor {
1756 buffer_id: excerpt.buffer_id,
1757 excerpt_id,
1758 text_anchor,
1759 };
1760 }
1761 }
1762 panic!("excerpt not found");
1763 }
1764
1765 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1766 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
1767 true
1768 } else if let Some((buffer_id, buffer_snapshot)) =
1769 self.buffer_snapshot_for_excerpt(&anchor.excerpt_id)
1770 {
1771 anchor.buffer_id == buffer_id && buffer_snapshot.can_resolve(&anchor.text_anchor)
1772 } else {
1773 false
1774 }
1775 }
1776
1777 pub fn range_contains_excerpt_boundary<T: ToOffset>(&self, range: Range<T>) -> bool {
1778 let start = range.start.to_offset(self);
1779 let end = range.end.to_offset(self);
1780 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1781 cursor.seek(&start, Bias::Right, &());
1782 let start_id = cursor
1783 .item()
1784 .or_else(|| cursor.prev_item())
1785 .map(|excerpt| &excerpt.id);
1786 cursor.seek_forward(&end, Bias::Right, &());
1787 let end_id = cursor
1788 .item()
1789 .or_else(|| cursor.prev_item())
1790 .map(|excerpt| &excerpt.id);
1791 start_id != end_id
1792 }
1793
1794 pub fn parse_count(&self) -> usize {
1795 self.parse_count
1796 }
1797
1798 pub fn enclosing_bracket_ranges<T: ToOffset>(
1799 &self,
1800 range: Range<T>,
1801 ) -> Option<(Range<usize>, Range<usize>)> {
1802 let range = range.start.to_offset(self)..range.end.to_offset(self);
1803
1804 let mut cursor = self.excerpts.cursor::<usize>();
1805 cursor.seek(&range.start, Bias::Right, &());
1806 let start_excerpt = cursor.item();
1807
1808 cursor.seek(&range.end, Bias::Right, &());
1809 let end_excerpt = cursor.item();
1810
1811 start_excerpt
1812 .zip(end_excerpt)
1813 .and_then(|(start_excerpt, end_excerpt)| {
1814 if start_excerpt.id != end_excerpt.id {
1815 return None;
1816 }
1817
1818 let excerpt_buffer_start =
1819 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1820 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1821
1822 let start_in_buffer =
1823 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1824 let end_in_buffer =
1825 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1826 let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1827 .buffer
1828 .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1829
1830 if start_bracket_range.start >= excerpt_buffer_start
1831 && end_bracket_range.end < excerpt_buffer_end
1832 {
1833 start_bracket_range.start =
1834 cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
1835 start_bracket_range.end =
1836 cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
1837 end_bracket_range.start =
1838 cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
1839 end_bracket_range.end =
1840 cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
1841 Some((start_bracket_range, end_bracket_range))
1842 } else {
1843 None
1844 }
1845 })
1846 }
1847
1848 pub fn diagnostics_update_count(&self) -> usize {
1849 self.diagnostics_update_count
1850 }
1851
1852 pub fn language(&self) -> Option<&Arc<Language>> {
1853 self.excerpts
1854 .iter()
1855 .next()
1856 .and_then(|excerpt| excerpt.buffer.language())
1857 }
1858
1859 pub fn is_dirty(&self) -> bool {
1860 self.is_dirty
1861 }
1862
1863 pub fn has_conflict(&self) -> bool {
1864 self.has_conflict
1865 }
1866
1867 pub fn diagnostic_group<'a, O>(
1868 &'a self,
1869 group_id: usize,
1870 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1871 where
1872 O: text::FromAnchor + 'a,
1873 {
1874 self.as_singleton()
1875 .into_iter()
1876 .flat_map(move |excerpt| excerpt.buffer.diagnostic_group(group_id))
1877 }
1878
1879 pub fn diagnostics_in_range<'a, T, O>(
1880 &'a self,
1881 range: Range<T>,
1882 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1883 where
1884 T: 'a + ToOffset,
1885 O: 'a + text::FromAnchor,
1886 {
1887 self.as_singleton().into_iter().flat_map(move |excerpt| {
1888 excerpt
1889 .buffer
1890 .diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
1891 })
1892 }
1893
1894 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1895 let range = range.start.to_offset(self)..range.end.to_offset(self);
1896
1897 let mut cursor = self.excerpts.cursor::<usize>();
1898 cursor.seek(&range.start, Bias::Right, &());
1899 let start_excerpt = cursor.item();
1900
1901 cursor.seek(&range.end, Bias::Right, &());
1902 let end_excerpt = cursor.item();
1903
1904 start_excerpt
1905 .zip(end_excerpt)
1906 .and_then(|(start_excerpt, end_excerpt)| {
1907 if start_excerpt.id != end_excerpt.id {
1908 return None;
1909 }
1910
1911 let excerpt_buffer_start =
1912 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1913 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1914
1915 let start_in_buffer =
1916 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1917 let end_in_buffer =
1918 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1919 let mut ancestor_buffer_range = start_excerpt
1920 .buffer
1921 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
1922 ancestor_buffer_range.start =
1923 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
1924 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
1925
1926 let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
1927 let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
1928 Some(start..end)
1929 })
1930 }
1931
1932 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1933 let excerpt = self.as_singleton()?;
1934 let outline = excerpt.buffer.outline(theme)?;
1935 Some(Outline::new(
1936 outline
1937 .items
1938 .into_iter()
1939 .map(|item| OutlineItem {
1940 depth: item.depth,
1941 range: self.anchor_in_excerpt(excerpt.id.clone(), item.range.start)
1942 ..self.anchor_in_excerpt(excerpt.id.clone(), item.range.end),
1943 text: item.text,
1944 highlight_ranges: item.highlight_ranges,
1945 name_ranges: item.name_ranges,
1946 })
1947 .collect(),
1948 ))
1949 }
1950
1951 fn buffer_snapshot_for_excerpt<'a>(
1952 &'a self,
1953 excerpt_id: &'a ExcerptId,
1954 ) -> Option<(usize, &'a BufferSnapshot)> {
1955 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1956 cursor.seek(&Some(excerpt_id), Bias::Left, &());
1957 if let Some(excerpt) = cursor.item() {
1958 if excerpt.id == *excerpt_id {
1959 return Some((excerpt.buffer_id, &excerpt.buffer));
1960 }
1961 }
1962 None
1963 }
1964
1965 pub fn remote_selections_in_range<'a>(
1966 &'a self,
1967 range: &'a Range<Anchor>,
1968 ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
1969 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1970 cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
1971 cursor
1972 .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
1973 .flat_map(move |excerpt| {
1974 let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
1975 if excerpt.id == range.start.excerpt_id {
1976 query_range.start = range.start.text_anchor.clone();
1977 }
1978 if excerpt.id == range.end.excerpt_id {
1979 query_range.end = range.end.text_anchor.clone();
1980 }
1981
1982 excerpt
1983 .buffer
1984 .remote_selections_in_range(query_range)
1985 .flat_map(move |(replica_id, selections)| {
1986 selections.map(move |selection| {
1987 let mut start = Anchor {
1988 buffer_id: excerpt.buffer_id,
1989 excerpt_id: excerpt.id.clone(),
1990 text_anchor: selection.start.clone(),
1991 };
1992 let mut end = Anchor {
1993 buffer_id: excerpt.buffer_id,
1994 excerpt_id: excerpt.id.clone(),
1995 text_anchor: selection.end.clone(),
1996 };
1997 if range.start.cmp(&start, self).unwrap().is_gt() {
1998 start = range.start.clone();
1999 }
2000 if range.end.cmp(&end, self).unwrap().is_lt() {
2001 end = range.end.clone();
2002 }
2003
2004 (
2005 replica_id,
2006 Selection {
2007 id: selection.id,
2008 start,
2009 end,
2010 reversed: selection.reversed,
2011 goal: selection.goal,
2012 },
2013 )
2014 })
2015 })
2016 })
2017 }
2018}
2019
2020impl History {
2021 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2022 self.transaction_depth += 1;
2023 if self.transaction_depth == 1 {
2024 let id = post_inc(&mut self.next_transaction_id);
2025 self.undo_stack.push(Transaction {
2026 id,
2027 buffer_transactions: Default::default(),
2028 first_edit_at: now,
2029 last_edit_at: now,
2030 });
2031 Some(id)
2032 } else {
2033 None
2034 }
2035 }
2036
2037 fn end_transaction(
2038 &mut self,
2039 now: Instant,
2040 buffer_transactions: HashSet<(usize, TransactionId)>,
2041 ) -> bool {
2042 assert_ne!(self.transaction_depth, 0);
2043 self.transaction_depth -= 1;
2044 if self.transaction_depth == 0 {
2045 if buffer_transactions.is_empty() {
2046 self.undo_stack.pop();
2047 false
2048 } else {
2049 let transaction = self.undo_stack.last_mut().unwrap();
2050 transaction.last_edit_at = now;
2051 transaction.buffer_transactions.extend(buffer_transactions);
2052 true
2053 }
2054 } else {
2055 false
2056 }
2057 }
2058
2059 fn pop_undo(&mut self) -> Option<&Transaction> {
2060 assert_eq!(self.transaction_depth, 0);
2061 if let Some(transaction) = self.undo_stack.pop() {
2062 self.redo_stack.push(transaction);
2063 self.redo_stack.last()
2064 } else {
2065 None
2066 }
2067 }
2068
2069 fn pop_redo(&mut self) -> Option<&Transaction> {
2070 assert_eq!(self.transaction_depth, 0);
2071 if let Some(transaction) = self.redo_stack.pop() {
2072 self.undo_stack.push(transaction);
2073 self.undo_stack.last()
2074 } else {
2075 None
2076 }
2077 }
2078
2079 fn group(&mut self) -> Option<TransactionId> {
2080 let mut new_len = self.undo_stack.len();
2081 let mut transactions = self.undo_stack.iter_mut();
2082
2083 if let Some(mut transaction) = transactions.next_back() {
2084 while let Some(prev_transaction) = transactions.next_back() {
2085 if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
2086 {
2087 transaction = prev_transaction;
2088 new_len -= 1;
2089 } else {
2090 break;
2091 }
2092 }
2093 }
2094
2095 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2096 if let Some(last_transaction) = transactions_to_keep.last_mut() {
2097 if let Some(transaction) = transactions_to_merge.last() {
2098 last_transaction.last_edit_at = transaction.last_edit_at;
2099 }
2100 }
2101
2102 self.undo_stack.truncate(new_len);
2103 self.undo_stack.last().map(|t| t.id)
2104 }
2105}
2106
2107impl Excerpt {
2108 fn new(
2109 id: ExcerptId,
2110 buffer_id: usize,
2111 buffer: BufferSnapshot,
2112 range: Range<text::Anchor>,
2113 has_trailing_newline: bool,
2114 ) -> Self {
2115 Excerpt {
2116 id,
2117 max_buffer_row: range.end.to_point(&buffer).row,
2118 text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
2119 buffer_id,
2120 buffer,
2121 range,
2122 has_trailing_newline,
2123 }
2124 }
2125
2126 fn chunks_in_range<'a>(
2127 &'a self,
2128 range: Range<usize>,
2129 language_aware: bool,
2130 ) -> ExcerptChunks<'a> {
2131 let content_start = self.range.start.to_offset(&self.buffer);
2132 let chunks_start = content_start + range.start;
2133 let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2134
2135 let footer_height = if self.has_trailing_newline
2136 && range.start <= self.text_summary.bytes
2137 && range.end > self.text_summary.bytes
2138 {
2139 1
2140 } else {
2141 0
2142 };
2143
2144 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
2145
2146 ExcerptChunks {
2147 content_chunks,
2148 footer_height,
2149 }
2150 }
2151
2152 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2153 let content_start = self.range.start.to_offset(&self.buffer);
2154 let bytes_start = content_start + range.start;
2155 let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2156 let footer_height = if self.has_trailing_newline
2157 && range.start <= self.text_summary.bytes
2158 && range.end > self.text_summary.bytes
2159 {
2160 1
2161 } else {
2162 0
2163 };
2164 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2165
2166 ExcerptBytes {
2167 content_bytes,
2168 footer_height,
2169 }
2170 }
2171
2172 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2173 if text_anchor
2174 .cmp(&self.range.start, &self.buffer)
2175 .unwrap()
2176 .is_lt()
2177 {
2178 self.range.start.clone()
2179 } else if text_anchor
2180 .cmp(&self.range.end, &self.buffer)
2181 .unwrap()
2182 .is_gt()
2183 {
2184 self.range.end.clone()
2185 } else {
2186 text_anchor
2187 }
2188 }
2189
2190 fn contains(&self, anchor: &Anchor) -> bool {
2191 self.buffer_id == anchor.buffer_id
2192 && self
2193 .range
2194 .start
2195 .cmp(&anchor.text_anchor, &self.buffer)
2196 .unwrap()
2197 .is_le()
2198 && self
2199 .range
2200 .end
2201 .cmp(&anchor.text_anchor, &self.buffer)
2202 .unwrap()
2203 .is_ge()
2204 }
2205}
2206
2207impl fmt::Debug for Excerpt {
2208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2209 f.debug_struct("Excerpt")
2210 .field("id", &self.id)
2211 .field("buffer_id", &self.buffer_id)
2212 .field("range", &self.range)
2213 .field("text_summary", &self.text_summary)
2214 .field("has_trailing_newline", &self.has_trailing_newline)
2215 .finish()
2216 }
2217}
2218
2219impl sum_tree::Item for Excerpt {
2220 type Summary = ExcerptSummary;
2221
2222 fn summary(&self) -> Self::Summary {
2223 let mut text = self.text_summary.clone();
2224 if self.has_trailing_newline {
2225 text += TextSummary::from("\n");
2226 }
2227 ExcerptSummary {
2228 excerpt_id: self.id.clone(),
2229 max_buffer_row: self.max_buffer_row,
2230 text,
2231 }
2232 }
2233}
2234
2235impl sum_tree::Summary for ExcerptSummary {
2236 type Context = ();
2237
2238 fn add_summary(&mut self, summary: &Self, _: &()) {
2239 debug_assert!(summary.excerpt_id > self.excerpt_id);
2240 self.excerpt_id = summary.excerpt_id.clone();
2241 self.text.add_summary(&summary.text, &());
2242 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2243 }
2244}
2245
2246impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2247 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2248 *self += &summary.text;
2249 }
2250}
2251
2252impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2253 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2254 *self += summary.text.bytes;
2255 }
2256}
2257
2258impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2259 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2260 Ord::cmp(self, &cursor_location.text.bytes)
2261 }
2262}
2263
2264impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2265 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2266 Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2267 }
2268}
2269
2270impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2271 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2272 *self += summary.text.lines;
2273 }
2274}
2275
2276impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2277 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2278 *self += summary.text.lines_utf16
2279 }
2280}
2281
2282impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2283 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2284 *self = Some(&summary.excerpt_id);
2285 }
2286}
2287
2288impl<'a> MultiBufferRows<'a> {
2289 pub fn seek(&mut self, row: u32) {
2290 self.buffer_row_range = 0..0;
2291
2292 self.excerpts
2293 .seek_forward(&Point::new(row, 0), Bias::Right, &());
2294 if self.excerpts.item().is_none() {
2295 self.excerpts.prev(&());
2296
2297 if self.excerpts.item().is_none() && row == 0 {
2298 self.buffer_row_range = 0..1;
2299 return;
2300 }
2301 }
2302
2303 if let Some(excerpt) = self.excerpts.item() {
2304 let overshoot = row - self.excerpts.start().row;
2305 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
2306 self.buffer_row_range.start = excerpt_start + overshoot;
2307 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
2308 }
2309 }
2310}
2311
2312impl<'a> Iterator for MultiBufferRows<'a> {
2313 type Item = Option<u32>;
2314
2315 fn next(&mut self) -> Option<Self::Item> {
2316 loop {
2317 if !self.buffer_row_range.is_empty() {
2318 let row = Some(self.buffer_row_range.start);
2319 self.buffer_row_range.start += 1;
2320 return Some(row);
2321 }
2322 self.excerpts.item()?;
2323 self.excerpts.next(&());
2324 let excerpt = self.excerpts.item()?;
2325 self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
2326 self.buffer_row_range.end =
2327 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
2328 }
2329 }
2330}
2331
2332impl<'a> MultiBufferChunks<'a> {
2333 pub fn offset(&self) -> usize {
2334 self.range.start
2335 }
2336
2337 pub fn seek(&mut self, offset: usize) {
2338 self.range.start = offset;
2339 self.excerpts.seek(&offset, Bias::Right, &());
2340 if let Some(excerpt) = self.excerpts.item() {
2341 self.excerpt_chunks = Some(excerpt.chunks_in_range(
2342 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
2343 self.language_aware,
2344 ));
2345 } else {
2346 self.excerpt_chunks = None;
2347 }
2348 }
2349}
2350
2351impl<'a> Iterator for MultiBufferChunks<'a> {
2352 type Item = Chunk<'a>;
2353
2354 fn next(&mut self) -> Option<Self::Item> {
2355 if self.range.is_empty() {
2356 None
2357 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
2358 self.range.start += chunk.text.len();
2359 Some(chunk)
2360 } else {
2361 self.excerpts.next(&());
2362 let excerpt = self.excerpts.item()?;
2363 self.excerpt_chunks = Some(excerpt.chunks_in_range(
2364 0..self.range.end - self.excerpts.start(),
2365 self.language_aware,
2366 ));
2367 self.next()
2368 }
2369 }
2370}
2371
2372impl<'a> MultiBufferBytes<'a> {
2373 fn consume(&mut self, len: usize) {
2374 self.range.start += len;
2375 self.chunk = &self.chunk[len..];
2376
2377 if !self.range.is_empty() && self.chunk.is_empty() {
2378 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
2379 self.chunk = chunk;
2380 } else {
2381 self.excerpts.next(&());
2382 if let Some(excerpt) = self.excerpts.item() {
2383 let mut excerpt_bytes =
2384 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
2385 self.chunk = excerpt_bytes.next().unwrap();
2386 self.excerpt_bytes = Some(excerpt_bytes);
2387 }
2388 }
2389 }
2390 }
2391}
2392
2393impl<'a> Iterator for MultiBufferBytes<'a> {
2394 type Item = &'a [u8];
2395
2396 fn next(&mut self) -> Option<Self::Item> {
2397 let chunk = self.chunk;
2398 if chunk.is_empty() {
2399 None
2400 } else {
2401 self.consume(chunk.len());
2402 Some(chunk)
2403 }
2404 }
2405}
2406
2407impl<'a> io::Read for MultiBufferBytes<'a> {
2408 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2409 let len = cmp::min(buf.len(), self.chunk.len());
2410 buf[..len].copy_from_slice(&self.chunk[..len]);
2411 if len > 0 {
2412 self.consume(len);
2413 }
2414 Ok(len)
2415 }
2416}
2417
2418impl<'a> Iterator for ExcerptBytes<'a> {
2419 type Item = &'a [u8];
2420
2421 fn next(&mut self) -> Option<Self::Item> {
2422 if let Some(chunk) = self.content_bytes.next() {
2423 if !chunk.is_empty() {
2424 return Some(chunk);
2425 }
2426 }
2427
2428 if self.footer_height > 0 {
2429 let result = &NEWLINES[..self.footer_height];
2430 self.footer_height = 0;
2431 return Some(result);
2432 }
2433
2434 None
2435 }
2436}
2437
2438impl<'a> Iterator for ExcerptChunks<'a> {
2439 type Item = Chunk<'a>;
2440
2441 fn next(&mut self) -> Option<Self::Item> {
2442 if let Some(chunk) = self.content_chunks.next() {
2443 return Some(chunk);
2444 }
2445
2446 if self.footer_height > 0 {
2447 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2448 self.footer_height = 0;
2449 return Some(Chunk {
2450 text,
2451 ..Default::default()
2452 });
2453 }
2454
2455 None
2456 }
2457}
2458
2459impl ToOffset for Point {
2460 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2461 snapshot.point_to_offset(*self)
2462 }
2463}
2464
2465impl ToOffset for PointUtf16 {
2466 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2467 snapshot.point_utf16_to_offset(*self)
2468 }
2469}
2470
2471impl ToOffset for usize {
2472 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2473 assert!(*self <= snapshot.len(), "offset is out of range");
2474 *self
2475 }
2476}
2477
2478impl ToPoint for usize {
2479 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2480 snapshot.offset_to_point(*self)
2481 }
2482}
2483
2484impl ToPoint for Point {
2485 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2486 *self
2487 }
2488}
2489
2490pub fn char_kind(c: char) -> CharKind {
2491 if c == '\n' {
2492 CharKind::Newline
2493 } else if c.is_whitespace() {
2494 CharKind::Whitespace
2495 } else if c.is_alphanumeric() || c == '_' {
2496 CharKind::Word
2497 } else {
2498 CharKind::Punctuation
2499 }
2500}
2501
2502#[cfg(test)]
2503mod tests {
2504 use super::*;
2505 use gpui::MutableAppContext;
2506 use language::{Buffer, Rope};
2507 use rand::prelude::*;
2508 use std::env;
2509 use text::{Point, RandomCharIter};
2510 use util::test::sample_text;
2511
2512 #[gpui::test]
2513 fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2514 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2515 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2516
2517 let snapshot = multibuffer.read(cx).snapshot(cx);
2518 assert_eq!(snapshot.text(), buffer.read(cx).text());
2519
2520 assert_eq!(
2521 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2522 (0..buffer.read(cx).row_count())
2523 .map(Some)
2524 .collect::<Vec<_>>()
2525 );
2526
2527 buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2528 let snapshot = multibuffer.read(cx).snapshot(cx);
2529
2530 assert_eq!(snapshot.text(), buffer.read(cx).text());
2531 assert_eq!(
2532 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2533 (0..buffer.read(cx).row_count())
2534 .map(Some)
2535 .collect::<Vec<_>>()
2536 );
2537 }
2538
2539 #[gpui::test]
2540 fn test_remote_multibuffer(cx: &mut MutableAppContext) {
2541 let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
2542 let guest_buffer = cx.add_model(|cx| {
2543 let message = host_buffer.read(cx).to_proto();
2544 Buffer::from_proto(1, message, None, cx).unwrap()
2545 });
2546 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
2547 let snapshot = multibuffer.read(cx).snapshot(cx);
2548 assert_eq!(snapshot.text(), "a");
2549
2550 guest_buffer.update(cx, |buffer, cx| buffer.edit([1..1], "b", cx));
2551 let snapshot = multibuffer.read(cx).snapshot(cx);
2552 assert_eq!(snapshot.text(), "ab");
2553
2554 guest_buffer.update(cx, |buffer, cx| buffer.edit([2..2], "c", cx));
2555 let snapshot = multibuffer.read(cx).snapshot(cx);
2556 assert_eq!(snapshot.text(), "abc");
2557 }
2558
2559 #[gpui::test]
2560 fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2561 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2562 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2563 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2564
2565 let subscription = multibuffer.update(cx, |multibuffer, cx| {
2566 let subscription = multibuffer.subscribe();
2567 multibuffer.push_excerpt(
2568 ExcerptProperties {
2569 buffer: &buffer_1,
2570 range: Point::new(1, 2)..Point::new(2, 5),
2571 },
2572 cx,
2573 );
2574 assert_eq!(
2575 subscription.consume().into_inner(),
2576 [Edit {
2577 old: 0..0,
2578 new: 0..10
2579 }]
2580 );
2581
2582 multibuffer.push_excerpt(
2583 ExcerptProperties {
2584 buffer: &buffer_1,
2585 range: Point::new(3, 3)..Point::new(4, 4),
2586 },
2587 cx,
2588 );
2589 multibuffer.push_excerpt(
2590 ExcerptProperties {
2591 buffer: &buffer_2,
2592 range: Point::new(3, 1)..Point::new(3, 3),
2593 },
2594 cx,
2595 );
2596 assert_eq!(
2597 subscription.consume().into_inner(),
2598 [Edit {
2599 old: 10..10,
2600 new: 10..22
2601 }]
2602 );
2603
2604 subscription
2605 });
2606
2607 let snapshot = multibuffer.read(cx).snapshot(cx);
2608 assert_eq!(
2609 snapshot.text(),
2610 concat!(
2611 "bbbb\n", // Preserve newlines
2612 "ccccc\n", //
2613 "ddd\n", //
2614 "eeee\n", //
2615 "jj" //
2616 )
2617 );
2618 assert_eq!(
2619 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2620 [Some(1), Some(2), Some(3), Some(4), Some(3)]
2621 );
2622 assert_eq!(
2623 snapshot.buffer_rows(2).collect::<Vec<_>>(),
2624 [Some(3), Some(4), Some(3)]
2625 );
2626 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2627 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2628 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(1, 5)));
2629 assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(2, 0)));
2630 assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(4, 0)));
2631 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(2, 0)..Point::new(3, 0)));
2632 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 0)..Point::new(4, 2)));
2633 assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 2)..Point::new(4, 2)));
2634
2635 buffer_1.update(cx, |buffer, cx| {
2636 buffer.edit(
2637 [
2638 Point::new(0, 0)..Point::new(0, 0),
2639 Point::new(2, 1)..Point::new(2, 3),
2640 ],
2641 "\n",
2642 cx,
2643 );
2644 });
2645
2646 let snapshot = multibuffer.read(cx).snapshot(cx);
2647 assert_eq!(
2648 snapshot.text(),
2649 concat!(
2650 "bbbb\n", // Preserve newlines
2651 "c\n", //
2652 "cc\n", //
2653 "ddd\n", //
2654 "eeee\n", //
2655 "jj" //
2656 )
2657 );
2658
2659 assert_eq!(
2660 subscription.consume().into_inner(),
2661 [Edit {
2662 old: 6..8,
2663 new: 6..7
2664 }]
2665 );
2666
2667 let snapshot = multibuffer.read(cx).snapshot(cx);
2668 assert_eq!(
2669 snapshot.clip_point(Point::new(0, 5), Bias::Left),
2670 Point::new(0, 4)
2671 );
2672 assert_eq!(
2673 snapshot.clip_point(Point::new(0, 5), Bias::Right),
2674 Point::new(0, 4)
2675 );
2676 assert_eq!(
2677 snapshot.clip_point(Point::new(5, 1), Bias::Right),
2678 Point::new(5, 1)
2679 );
2680 assert_eq!(
2681 snapshot.clip_point(Point::new(5, 2), Bias::Right),
2682 Point::new(5, 2)
2683 );
2684 assert_eq!(
2685 snapshot.clip_point(Point::new(5, 3), Bias::Right),
2686 Point::new(5, 2)
2687 );
2688
2689 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2690 let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2691 multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2692 multibuffer.snapshot(cx)
2693 });
2694
2695 assert_eq!(
2696 snapshot.text(),
2697 concat!(
2698 "bbbb\n", // Preserve newlines
2699 "c\n", //
2700 "cc\n", //
2701 "ddd\n", //
2702 "eeee", //
2703 )
2704 );
2705 }
2706
2707 #[gpui::test]
2708 fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2709 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2710
2711 let snapshot = multibuffer.read(cx).snapshot(cx);
2712 assert_eq!(snapshot.text(), "");
2713 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2714 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2715 }
2716
2717 #[gpui::test]
2718 fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2719 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2720 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2721 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2722 buffer.update(cx, |buffer, cx| {
2723 buffer.edit([0..0], "X", cx);
2724 buffer.edit([5..5], "Y", cx);
2725 });
2726 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2727
2728 assert_eq!(old_snapshot.text(), "abcd");
2729 assert_eq!(new_snapshot.text(), "XabcdY");
2730
2731 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2732 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2733 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2734 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2735 }
2736
2737 #[gpui::test]
2738 fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2739 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2740 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2741 let multibuffer = cx.add_model(|cx| {
2742 let mut multibuffer = MultiBuffer::new(0);
2743 multibuffer.push_excerpt(
2744 ExcerptProperties {
2745 buffer: &buffer_1,
2746 range: 0..4,
2747 },
2748 cx,
2749 );
2750 multibuffer.push_excerpt(
2751 ExcerptProperties {
2752 buffer: &buffer_2,
2753 range: 0..5,
2754 },
2755 cx,
2756 );
2757 multibuffer
2758 });
2759 let old_snapshot = multibuffer.read(cx).snapshot(cx);
2760
2761 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
2762 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
2763 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2764 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2765 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2766 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2767
2768 buffer_1.update(cx, |buffer, cx| {
2769 buffer.edit([0..0], "W", cx);
2770 buffer.edit([5..5], "X", cx);
2771 });
2772 buffer_2.update(cx, |buffer, cx| {
2773 buffer.edit([0..0], "Y", cx);
2774 buffer.edit([6..0], "Z", cx);
2775 });
2776 let new_snapshot = multibuffer.read(cx).snapshot(cx);
2777
2778 assert_eq!(old_snapshot.text(), "abcd\nefghi");
2779 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
2780
2781 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2782 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2783 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
2784 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2785 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2786 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2787 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
2788 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
2789 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
2790 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
2791 }
2792
2793 #[gpui::test]
2794 fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
2795 cx: &mut MutableAppContext,
2796 ) {
2797 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2798 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
2799 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2800
2801 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
2802 // Add an excerpt from buffer 1 that spans this new insertion.
2803 buffer_1.update(cx, |buffer, cx| buffer.edit([4..4], "123", cx));
2804 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
2805 multibuffer.push_excerpt(
2806 ExcerptProperties {
2807 buffer: &buffer_1,
2808 range: 0..7,
2809 },
2810 cx,
2811 )
2812 });
2813
2814 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
2815 assert_eq!(snapshot_1.text(), "abcd123");
2816
2817 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
2818 let (excerpt_id_2, excerpt_id_3, _) = multibuffer.update(cx, |multibuffer, cx| {
2819 multibuffer.remove_excerpts([&excerpt_id_1], cx);
2820 (
2821 multibuffer.push_excerpt(
2822 ExcerptProperties {
2823 buffer: &buffer_2,
2824 range: 0..4,
2825 },
2826 cx,
2827 ),
2828 multibuffer.push_excerpt(
2829 ExcerptProperties {
2830 buffer: &buffer_2,
2831 range: 6..10,
2832 },
2833 cx,
2834 ),
2835 multibuffer.push_excerpt(
2836 ExcerptProperties {
2837 buffer: &buffer_2,
2838 range: 12..16,
2839 },
2840 cx,
2841 ),
2842 )
2843 });
2844 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
2845 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
2846
2847 // The old excerpt id has been reused.
2848 assert_eq!(excerpt_id_2, excerpt_id_1);
2849
2850 // Resolve some anchors from the previous snapshot in the new snapshot.
2851 // Although there is still an excerpt with the same id, it is for
2852 // a different buffer, so we don't attempt to resolve the old text
2853 // anchor in the new buffer.
2854 assert_eq!(
2855 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
2856 0
2857 );
2858 assert_eq!(
2859 snapshot_2.summaries_for_anchors::<usize, _>(&[
2860 snapshot_1.anchor_before(2),
2861 snapshot_1.anchor_after(3)
2862 ]),
2863 vec![0, 0]
2864 );
2865 let refresh =
2866 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
2867 assert_eq!(
2868 refresh,
2869 &[
2870 (0, snapshot_2.anchor_before(0), false),
2871 (1, snapshot_2.anchor_after(0), false),
2872 ]
2873 );
2874
2875 // Replace the middle excerpt with a smaller excerpt in buffer 2,
2876 // that intersects the old excerpt.
2877 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
2878 multibuffer.remove_excerpts([&excerpt_id_3], cx);
2879 multibuffer.insert_excerpt_after(
2880 &excerpt_id_3,
2881 ExcerptProperties {
2882 buffer: &buffer_2,
2883 range: 5..8,
2884 },
2885 cx,
2886 )
2887 });
2888
2889 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
2890 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
2891 assert_ne!(excerpt_id_5, excerpt_id_3);
2892
2893 // Resolve some anchors from the previous snapshot in the new snapshot.
2894 // The anchor in the middle excerpt snaps to the beginning of the
2895 // excerpt, since it is not
2896 let anchors = [
2897 snapshot_2.anchor_before(0),
2898 snapshot_2.anchor_after(2),
2899 snapshot_2.anchor_after(6),
2900 snapshot_2.anchor_after(14),
2901 ];
2902 assert_eq!(
2903 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
2904 &[0, 2, 9, 13]
2905 );
2906
2907 let new_anchors = snapshot_3.refresh_anchors(&anchors);
2908 assert_eq!(
2909 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
2910 &[(0, true), (1, true), (2, true), (3, true)]
2911 );
2912 assert_eq!(
2913 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
2914 &[0, 2, 7, 13]
2915 );
2916 }
2917
2918 #[gpui::test(iterations = 100)]
2919 fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
2920 let operations = env::var("OPERATIONS")
2921 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2922 .unwrap_or(10);
2923
2924 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
2925 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2926 let mut excerpt_ids = Vec::new();
2927 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
2928 let mut anchors = Vec::new();
2929 let mut old_versions = Vec::new();
2930
2931 for _ in 0..operations {
2932 match rng.gen_range(0..100) {
2933 0..=19 if !buffers.is_empty() => {
2934 let buffer = buffers.choose(&mut rng).unwrap();
2935 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
2936 }
2937 20..=29 if !expected_excerpts.is_empty() => {
2938 let mut ids_to_remove = vec![];
2939 for _ in 0..rng.gen_range(1..=3) {
2940 if expected_excerpts.is_empty() {
2941 break;
2942 }
2943
2944 let ix = rng.gen_range(0..expected_excerpts.len());
2945 ids_to_remove.push(excerpt_ids.remove(ix));
2946 let (buffer, range) = expected_excerpts.remove(ix);
2947 let buffer = buffer.read(cx);
2948 log::info!(
2949 "Removing excerpt {}: {:?}",
2950 ix,
2951 buffer
2952 .text_for_range(range.to_offset(&buffer))
2953 .collect::<String>(),
2954 );
2955 }
2956 ids_to_remove.sort_unstable();
2957 multibuffer.update(cx, |multibuffer, cx| {
2958 multibuffer.remove_excerpts(&ids_to_remove, cx)
2959 });
2960 }
2961 30..=39 if !expected_excerpts.is_empty() => {
2962 let multibuffer = multibuffer.read(cx).read(cx);
2963 let offset =
2964 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
2965 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
2966 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2967 anchors.push(multibuffer.anchor_at(offset, bias));
2968 anchors.sort_by(|a, b| a.cmp(&b, &multibuffer).unwrap());
2969 }
2970 40..=44 if !anchors.is_empty() => {
2971 let multibuffer = multibuffer.read(cx).read(cx);
2972
2973 anchors = multibuffer
2974 .refresh_anchors(&anchors)
2975 .into_iter()
2976 .map(|a| a.1)
2977 .collect();
2978
2979 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2980 // overshoot its boundaries.
2981 let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
2982 for anchor in &anchors {
2983 if anchor.excerpt_id == ExcerptId::min()
2984 || anchor.excerpt_id == ExcerptId::max()
2985 {
2986 continue;
2987 }
2988
2989 cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
2990 let excerpt = cursor.item().unwrap();
2991 assert_eq!(excerpt.id, anchor.excerpt_id);
2992 assert!(excerpt.contains(anchor));
2993 }
2994 }
2995 _ => {
2996 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2997 let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
2998 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
2999 buffers.last().unwrap()
3000 } else {
3001 buffers.choose(&mut rng).unwrap()
3002 };
3003
3004 let buffer = buffer_handle.read(cx);
3005 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
3006 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3007 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3008 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
3009 let prev_excerpt_id = excerpt_ids
3010 .get(prev_excerpt_ix)
3011 .cloned()
3012 .unwrap_or(ExcerptId::max());
3013 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3014
3015 log::info!(
3016 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3017 excerpt_ix,
3018 expected_excerpts.len(),
3019 buffer_handle.id(),
3020 buffer.text(),
3021 start_ix..end_ix,
3022 &buffer.text()[start_ix..end_ix]
3023 );
3024
3025 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3026 multibuffer.insert_excerpt_after(
3027 &prev_excerpt_id,
3028 ExcerptProperties {
3029 buffer: &buffer_handle,
3030 range: start_ix..end_ix,
3031 },
3032 cx,
3033 )
3034 });
3035
3036 excerpt_ids.insert(excerpt_ix, excerpt_id);
3037 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
3038 }
3039 }
3040
3041 if rng.gen_bool(0.3) {
3042 multibuffer.update(cx, |multibuffer, cx| {
3043 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3044 })
3045 }
3046
3047 let snapshot = multibuffer.read(cx).snapshot(cx);
3048
3049 let mut excerpt_starts = Vec::new();
3050 let mut expected_text = String::new();
3051 let mut expected_buffer_rows = Vec::new();
3052 for (buffer, range) in &expected_excerpts {
3053 let buffer = buffer.read(cx);
3054 let buffer_range = range.to_offset(buffer);
3055
3056 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
3057 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
3058 expected_text.push('\n');
3059
3060 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
3061 ..=buffer.offset_to_point(buffer_range.end).row;
3062 for row in buffer_row_range {
3063 expected_buffer_rows.push(Some(row));
3064 }
3065 }
3066 // Remove final trailing newline.
3067 if !expected_excerpts.is_empty() {
3068 expected_text.pop();
3069 }
3070
3071 // Always report one buffer row
3072 if expected_buffer_rows.is_empty() {
3073 expected_buffer_rows.push(Some(0));
3074 }
3075
3076 assert_eq!(snapshot.text(), expected_text);
3077 log::info!("MultiBuffer text: {:?}", expected_text);
3078
3079 assert_eq!(
3080 snapshot.buffer_rows(0).collect::<Vec<_>>(),
3081 expected_buffer_rows,
3082 );
3083
3084 for _ in 0..5 {
3085 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
3086 assert_eq!(
3087 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
3088 &expected_buffer_rows[start_row..],
3089 "buffer_rows({})",
3090 start_row
3091 );
3092 }
3093
3094 assert_eq!(
3095 snapshot.max_buffer_row(),
3096 expected_buffer_rows
3097 .into_iter()
3098 .filter_map(|r| r)
3099 .max()
3100 .unwrap()
3101 );
3102
3103 let mut excerpt_starts = excerpt_starts.into_iter();
3104 for (buffer, range) in &expected_excerpts {
3105 let buffer_id = buffer.id();
3106 let buffer = buffer.read(cx);
3107 let buffer_range = range.to_offset(buffer);
3108 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
3109 let buffer_start_point_utf16 =
3110 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
3111
3112 let excerpt_start = excerpt_starts.next().unwrap();
3113 let mut offset = excerpt_start.bytes;
3114 let mut buffer_offset = buffer_range.start;
3115 let mut point = excerpt_start.lines;
3116 let mut buffer_point = buffer_start_point;
3117 let mut point_utf16 = excerpt_start.lines_utf16;
3118 let mut buffer_point_utf16 = buffer_start_point_utf16;
3119 for ch in buffer
3120 .snapshot()
3121 .chunks(buffer_range.clone(), false)
3122 .flat_map(|c| c.text.chars())
3123 {
3124 for _ in 0..ch.len_utf8() {
3125 let left_offset = snapshot.clip_offset(offset, Bias::Left);
3126 let right_offset = snapshot.clip_offset(offset, Bias::Right);
3127 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
3128 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
3129 assert_eq!(
3130 left_offset,
3131 excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
3132 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
3133 offset,
3134 buffer_id,
3135 buffer_offset,
3136 );
3137 assert_eq!(
3138 right_offset,
3139 excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
3140 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
3141 offset,
3142 buffer_id,
3143 buffer_offset,
3144 );
3145
3146 let left_point = snapshot.clip_point(point, Bias::Left);
3147 let right_point = snapshot.clip_point(point, Bias::Right);
3148 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
3149 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
3150 assert_eq!(
3151 left_point,
3152 excerpt_start.lines + (buffer_left_point - buffer_start_point),
3153 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
3154 point,
3155 buffer_id,
3156 buffer_point,
3157 );
3158 assert_eq!(
3159 right_point,
3160 excerpt_start.lines + (buffer_right_point - buffer_start_point),
3161 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
3162 point,
3163 buffer_id,
3164 buffer_point,
3165 );
3166
3167 assert_eq!(
3168 snapshot.point_to_offset(left_point),
3169 left_offset,
3170 "point_to_offset({:?})",
3171 left_point,
3172 );
3173 assert_eq!(
3174 snapshot.offset_to_point(left_offset),
3175 left_point,
3176 "offset_to_point({:?})",
3177 left_offset,
3178 );
3179
3180 offset += 1;
3181 buffer_offset += 1;
3182 if ch == '\n' {
3183 point += Point::new(1, 0);
3184 buffer_point += Point::new(1, 0);
3185 } else {
3186 point += Point::new(0, 1);
3187 buffer_point += Point::new(0, 1);
3188 }
3189 }
3190
3191 for _ in 0..ch.len_utf16() {
3192 let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
3193 let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
3194 let buffer_left_point_utf16 =
3195 buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
3196 let buffer_right_point_utf16 =
3197 buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
3198 assert_eq!(
3199 left_point_utf16,
3200 excerpt_start.lines_utf16
3201 + (buffer_left_point_utf16 - buffer_start_point_utf16),
3202 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
3203 point_utf16,
3204 buffer_id,
3205 buffer_point_utf16,
3206 );
3207 assert_eq!(
3208 right_point_utf16,
3209 excerpt_start.lines_utf16
3210 + (buffer_right_point_utf16 - buffer_start_point_utf16),
3211 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
3212 point_utf16,
3213 buffer_id,
3214 buffer_point_utf16,
3215 );
3216
3217 if ch == '\n' {
3218 point_utf16 += PointUtf16::new(1, 0);
3219 buffer_point_utf16 += PointUtf16::new(1, 0);
3220 } else {
3221 point_utf16 += PointUtf16::new(0, 1);
3222 buffer_point_utf16 += PointUtf16::new(0, 1);
3223 }
3224 }
3225 }
3226 }
3227
3228 for (row, line) in expected_text.split('\n').enumerate() {
3229 assert_eq!(
3230 snapshot.line_len(row as u32),
3231 line.len() as u32,
3232 "line_len({}).",
3233 row
3234 );
3235 }
3236
3237 let text_rope = Rope::from(expected_text.as_str());
3238 for _ in 0..10 {
3239 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3240 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3241
3242 let text_for_range = snapshot
3243 .text_for_range(start_ix..end_ix)
3244 .collect::<String>();
3245 assert_eq!(
3246 text_for_range,
3247 &expected_text[start_ix..end_ix],
3248 "incorrect text for range {:?}",
3249 start_ix..end_ix
3250 );
3251
3252 let excerpted_buffer_ranges =
3253 multibuffer.read(cx).excerpted_buffers(start_ix..end_ix, cx);
3254 let excerpted_buffers_text = excerpted_buffer_ranges
3255 .into_iter()
3256 .map(|(buffer, buffer_range)| {
3257 buffer
3258 .read(cx)
3259 .text_for_range(buffer_range)
3260 .collect::<String>()
3261 })
3262 .collect::<Vec<_>>()
3263 .join("\n");
3264 assert_eq!(excerpted_buffers_text, text_for_range);
3265
3266 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
3267 assert_eq!(
3268 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
3269 expected_summary,
3270 "incorrect summary for range {:?}",
3271 start_ix..end_ix
3272 );
3273 }
3274
3275 // Anchor resolution
3276 for (anchor, resolved_offset) in anchors
3277 .iter()
3278 .zip(snapshot.summaries_for_anchors::<usize, _>(&anchors))
3279 {
3280 assert!(resolved_offset <= snapshot.len());
3281 assert_eq!(
3282 snapshot.summary_for_anchor::<usize>(anchor),
3283 resolved_offset
3284 );
3285 }
3286
3287 for _ in 0..10 {
3288 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3289 assert_eq!(
3290 snapshot.reversed_chars_at(end_ix).collect::<String>(),
3291 expected_text[..end_ix].chars().rev().collect::<String>(),
3292 );
3293 }
3294
3295 for _ in 0..10 {
3296 let end_ix = rng.gen_range(0..=text_rope.len());
3297 let start_ix = rng.gen_range(0..=end_ix);
3298 assert_eq!(
3299 snapshot
3300 .bytes_in_range(start_ix..end_ix)
3301 .flatten()
3302 .copied()
3303 .collect::<Vec<_>>(),
3304 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3305 "bytes_in_range({:?})",
3306 start_ix..end_ix,
3307 );
3308 }
3309 }
3310
3311 let snapshot = multibuffer.read(cx).snapshot(cx);
3312 for (old_snapshot, subscription) in old_versions {
3313 let edits = subscription.consume().into_inner();
3314
3315 log::info!(
3316 "applying subscription edits to old text: {:?}: {:?}",
3317 old_snapshot.text(),
3318 edits,
3319 );
3320
3321 let mut text = old_snapshot.text();
3322 for edit in edits {
3323 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
3324 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
3325 }
3326 assert_eq!(text.to_string(), snapshot.text());
3327 }
3328 }
3329
3330 #[gpui::test]
3331 fn test_history(cx: &mut MutableAppContext) {
3332 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
3333 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
3334 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3335 let group_interval = multibuffer.read(cx).history.group_interval;
3336 multibuffer.update(cx, |multibuffer, cx| {
3337 multibuffer.push_excerpt(
3338 ExcerptProperties {
3339 buffer: &buffer_1,
3340 range: 0..buffer_1.read(cx).len(),
3341 },
3342 cx,
3343 );
3344 multibuffer.push_excerpt(
3345 ExcerptProperties {
3346 buffer: &buffer_2,
3347 range: 0..buffer_2.read(cx).len(),
3348 },
3349 cx,
3350 );
3351 });
3352
3353 let mut now = Instant::now();
3354
3355 multibuffer.update(cx, |multibuffer, cx| {
3356 multibuffer.start_transaction_at(now, cx);
3357 multibuffer.edit(
3358 [
3359 Point::new(0, 0)..Point::new(0, 0),
3360 Point::new(1, 0)..Point::new(1, 0),
3361 ],
3362 "A",
3363 cx,
3364 );
3365 multibuffer.edit(
3366 [
3367 Point::new(0, 1)..Point::new(0, 1),
3368 Point::new(1, 1)..Point::new(1, 1),
3369 ],
3370 "B",
3371 cx,
3372 );
3373 multibuffer.end_transaction_at(now, cx);
3374 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3375
3376 now += 2 * group_interval;
3377 multibuffer.start_transaction_at(now, cx);
3378 multibuffer.edit([2..2], "C", cx);
3379 multibuffer.end_transaction_at(now, cx);
3380 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3381
3382 multibuffer.undo(cx);
3383 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3384
3385 multibuffer.undo(cx);
3386 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3387
3388 multibuffer.redo(cx);
3389 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3390
3391 multibuffer.redo(cx);
3392 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3393
3394 buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
3395 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3396
3397 multibuffer.undo(cx);
3398 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3399
3400 multibuffer.redo(cx);
3401 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3402
3403 multibuffer.redo(cx);
3404 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3405
3406 multibuffer.undo(cx);
3407 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3408
3409 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3410 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3411
3412 multibuffer.undo(cx);
3413 assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
3414 });
3415 }
3416}