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