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