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