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