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