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