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 self.find_anchor_in_excerpt(excerpt_id, text_anchor)
2621 .unwrap_or_else(|| panic!("excerpt not found"))
2622 }
2623
2624 pub fn find_anchor_in_excerpt(
2625 &self,
2626 excerpt_id: ExcerptId,
2627 text_anchor: text::Anchor,
2628 ) -> Option<Anchor> {
2629 let locator = self.excerpt_locator_for_id(excerpt_id);
2630 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2631 cursor.seek(locator, Bias::Left, &());
2632 if let Some(excerpt) = cursor.item() {
2633 if excerpt.id == excerpt_id {
2634 let text_anchor = excerpt.clip_anchor(text_anchor);
2635 drop(cursor);
2636 return Some(Anchor {
2637 buffer_id: Some(excerpt.buffer_id),
2638 excerpt_id,
2639 text_anchor,
2640 });
2641 }
2642 }
2643
2644 None
2645 }
2646
2647 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2648 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2649 true
2650 } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
2651 excerpt.buffer.can_resolve(&anchor.text_anchor)
2652 } else {
2653 false
2654 }
2655 }
2656
2657 pub fn excerpts(
2658 &self,
2659 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
2660 self.excerpts
2661 .iter()
2662 .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
2663 }
2664
2665 pub fn excerpt_boundaries_in_range<R, T>(
2666 &self,
2667 range: R,
2668 ) -> impl Iterator<Item = ExcerptBoundary> + '_
2669 where
2670 R: RangeBounds<T>,
2671 T: ToOffset,
2672 {
2673 let start_offset;
2674 let start = match range.start_bound() {
2675 Bound::Included(start) => {
2676 start_offset = start.to_offset(self);
2677 Bound::Included(start_offset)
2678 }
2679 Bound::Excluded(start) => {
2680 start_offset = start.to_offset(self);
2681 Bound::Excluded(start_offset)
2682 }
2683 Bound::Unbounded => {
2684 start_offset = 0;
2685 Bound::Unbounded
2686 }
2687 };
2688 let end = match range.end_bound() {
2689 Bound::Included(end) => Bound::Included(end.to_offset(self)),
2690 Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2691 Bound::Unbounded => Bound::Unbounded,
2692 };
2693 let bounds = (start, end);
2694
2695 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2696 cursor.seek(&start_offset, Bias::Right, &());
2697 if cursor.item().is_none() {
2698 cursor.prev(&());
2699 }
2700 if !bounds.contains(&cursor.start().0) {
2701 cursor.next(&());
2702 }
2703
2704 let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2705 std::iter::from_fn(move || {
2706 if self.singleton {
2707 None
2708 } else if bounds.contains(&cursor.start().0) {
2709 let excerpt = cursor.item()?;
2710 let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2711 let boundary = ExcerptBoundary {
2712 id: excerpt.id.clone(),
2713 row: cursor.start().1.row,
2714 buffer: excerpt.buffer.clone(),
2715 range: excerpt.range.clone(),
2716 starts_new_buffer,
2717 };
2718
2719 prev_buffer_id = Some(excerpt.buffer_id);
2720 cursor.next(&());
2721 Some(boundary)
2722 } else {
2723 None
2724 }
2725 })
2726 }
2727
2728 pub fn edit_count(&self) -> usize {
2729 self.edit_count
2730 }
2731
2732 pub fn parse_count(&self) -> usize {
2733 self.parse_count
2734 }
2735
2736 /// Returns the smallest enclosing bracket ranges containing the given range or
2737 /// None if no brackets contain range or the range is not contained in a single
2738 /// excerpt
2739 pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
2740 &self,
2741 range: Range<T>,
2742 ) -> Option<(Range<usize>, Range<usize>)> {
2743 let range = range.start.to_offset(self)..range.end.to_offset(self);
2744
2745 // Get the ranges of the innermost pair of brackets.
2746 let mut result: Option<(Range<usize>, Range<usize>)> = None;
2747
2748 let Some(enclosing_bracket_ranges) = self.enclosing_bracket_ranges(range.clone()) else { return None; };
2749
2750 for (open, close) in enclosing_bracket_ranges {
2751 let len = close.end - open.start;
2752
2753 if let Some((existing_open, existing_close)) = &result {
2754 let existing_len = existing_close.end - existing_open.start;
2755 if len > existing_len {
2756 continue;
2757 }
2758 }
2759
2760 result = Some((open, close));
2761 }
2762
2763 result
2764 }
2765
2766 /// Returns enclosing bracket ranges containing the given range or returns None if the range is
2767 /// not contained in a single excerpt
2768 pub fn enclosing_bracket_ranges<'a, T: ToOffset>(
2769 &'a self,
2770 range: Range<T>,
2771 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2772 let range = range.start.to_offset(self)..range.end.to_offset(self);
2773
2774 self.bracket_ranges(range.clone()).map(|range_pairs| {
2775 range_pairs
2776 .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
2777 })
2778 }
2779
2780 /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
2781 /// not contained in a single excerpt
2782 pub fn bracket_ranges<'a, T: ToOffset>(
2783 &'a self,
2784 range: Range<T>,
2785 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2786 let range = range.start.to_offset(self)..range.end.to_offset(self);
2787 let excerpt = self.excerpt_containing(range.clone());
2788 excerpt.map(|(excerpt, excerpt_offset)| {
2789 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2790 let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2791
2792 let start_in_buffer = excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2793 let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2794
2795 excerpt
2796 .buffer
2797 .bracket_ranges(start_in_buffer..end_in_buffer)
2798 .filter_map(move |(start_bracket_range, end_bracket_range)| {
2799 if start_bracket_range.start < excerpt_buffer_start
2800 || end_bracket_range.end > excerpt_buffer_end
2801 {
2802 return None;
2803 }
2804
2805 let mut start_bracket_range = start_bracket_range.clone();
2806 start_bracket_range.start =
2807 excerpt_offset + (start_bracket_range.start - excerpt_buffer_start);
2808 start_bracket_range.end =
2809 excerpt_offset + (start_bracket_range.end - excerpt_buffer_start);
2810
2811 let mut end_bracket_range = end_bracket_range.clone();
2812 end_bracket_range.start =
2813 excerpt_offset + (end_bracket_range.start - excerpt_buffer_start);
2814 end_bracket_range.end =
2815 excerpt_offset + (end_bracket_range.end - excerpt_buffer_start);
2816 Some((start_bracket_range, end_bracket_range))
2817 })
2818 })
2819 }
2820
2821 pub fn diagnostics_update_count(&self) -> usize {
2822 self.diagnostics_update_count
2823 }
2824
2825 pub fn git_diff_update_count(&self) -> usize {
2826 self.git_diff_update_count
2827 }
2828
2829 pub fn trailing_excerpt_update_count(&self) -> usize {
2830 self.trailing_excerpt_update_count
2831 }
2832
2833 pub fn file_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<dyn File>> {
2834 self.point_to_buffer_offset(point)
2835 .and_then(|(buffer, _)| buffer.file())
2836 }
2837
2838 pub fn language_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<Language>> {
2839 self.point_to_buffer_offset(point)
2840 .and_then(|(buffer, offset)| buffer.language_at(offset))
2841 }
2842
2843 pub fn settings_at<'a, T: ToOffset>(
2844 &'a self,
2845 point: T,
2846 cx: &'a AppContext,
2847 ) -> &'a LanguageSettings {
2848 let mut language = None;
2849 let mut file = None;
2850 if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
2851 language = buffer.language_at(offset);
2852 file = buffer.file();
2853 }
2854 language_settings(language, file, cx)
2855 }
2856
2857 pub fn language_scope_at<'a, T: ToOffset>(&'a self, point: T) -> Option<LanguageScope> {
2858 self.point_to_buffer_offset(point)
2859 .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
2860 }
2861
2862 pub fn language_indent_size_at<T: ToOffset>(
2863 &self,
2864 position: T,
2865 cx: &AppContext,
2866 ) -> Option<IndentSize> {
2867 let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
2868 Some(buffer_snapshot.language_indent_size_at(offset, cx))
2869 }
2870
2871 pub fn is_dirty(&self) -> bool {
2872 self.is_dirty
2873 }
2874
2875 pub fn has_conflict(&self) -> bool {
2876 self.has_conflict
2877 }
2878
2879 pub fn diagnostic_group<'a, O>(
2880 &'a self,
2881 group_id: usize,
2882 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2883 where
2884 O: text::FromAnchor + 'a,
2885 {
2886 self.as_singleton()
2887 .into_iter()
2888 .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2889 }
2890
2891 pub fn diagnostics_in_range<'a, T, O>(
2892 &'a self,
2893 range: Range<T>,
2894 reversed: bool,
2895 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2896 where
2897 T: 'a + ToOffset,
2898 O: 'a + text::FromAnchor + Ord,
2899 {
2900 self.as_singleton()
2901 .into_iter()
2902 .flat_map(move |(_, _, buffer)| {
2903 buffer.diagnostics_in_range(
2904 range.start.to_offset(self)..range.end.to_offset(self),
2905 reversed,
2906 )
2907 })
2908 }
2909
2910 pub fn has_git_diffs(&self) -> bool {
2911 for excerpt in self.excerpts.iter() {
2912 if !excerpt.buffer.git_diff.is_empty() {
2913 return true;
2914 }
2915 }
2916 false
2917 }
2918
2919 pub fn git_diff_hunks_in_range_rev<'a>(
2920 &'a self,
2921 row_range: Range<u32>,
2922 ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2923 let mut cursor = self.excerpts.cursor::<Point>();
2924
2925 cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
2926 if cursor.item().is_none() {
2927 cursor.prev(&());
2928 }
2929
2930 std::iter::from_fn(move || {
2931 let excerpt = cursor.item()?;
2932 let multibuffer_start = *cursor.start();
2933 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2934 if multibuffer_start.row >= row_range.end {
2935 return None;
2936 }
2937
2938 let mut buffer_start = excerpt.range.context.start;
2939 let mut buffer_end = excerpt.range.context.end;
2940 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
2941 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
2942
2943 if row_range.start > multibuffer_start.row {
2944 let buffer_start_point =
2945 excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
2946 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
2947 }
2948
2949 if row_range.end < multibuffer_end.row {
2950 let buffer_end_point =
2951 excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
2952 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
2953 }
2954
2955 let buffer_hunks = excerpt
2956 .buffer
2957 .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
2958 .filter_map(move |hunk| {
2959 let start = multibuffer_start.row
2960 + hunk
2961 .buffer_range
2962 .start
2963 .saturating_sub(excerpt_start_point.row);
2964 let end = multibuffer_start.row
2965 + hunk
2966 .buffer_range
2967 .end
2968 .min(excerpt_end_point.row + 1)
2969 .saturating_sub(excerpt_start_point.row);
2970
2971 Some(DiffHunk {
2972 buffer_range: start..end,
2973 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
2974 })
2975 });
2976
2977 cursor.prev(&());
2978
2979 Some(buffer_hunks)
2980 })
2981 .flatten()
2982 }
2983
2984 pub fn git_diff_hunks_in_range<'a>(
2985 &'a self,
2986 row_range: Range<u32>,
2987 ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2988 let mut cursor = self.excerpts.cursor::<Point>();
2989
2990 cursor.seek(&Point::new(row_range.start, 0), Bias::Right, &());
2991
2992 std::iter::from_fn(move || {
2993 let excerpt = cursor.item()?;
2994 let multibuffer_start = *cursor.start();
2995 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2996 if multibuffer_start.row >= row_range.end {
2997 return None;
2998 }
2999
3000 let mut buffer_start = excerpt.range.context.start;
3001 let mut buffer_end = excerpt.range.context.end;
3002 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3003 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3004
3005 if row_range.start > multibuffer_start.row {
3006 let buffer_start_point =
3007 excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
3008 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3009 }
3010
3011 if row_range.end < multibuffer_end.row {
3012 let buffer_end_point =
3013 excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
3014 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3015 }
3016
3017 let buffer_hunks = excerpt
3018 .buffer
3019 .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3020 .filter_map(move |hunk| {
3021 let start = multibuffer_start.row
3022 + hunk
3023 .buffer_range
3024 .start
3025 .saturating_sub(excerpt_start_point.row);
3026 let end = multibuffer_start.row
3027 + hunk
3028 .buffer_range
3029 .end
3030 .min(excerpt_end_point.row + 1)
3031 .saturating_sub(excerpt_start_point.row);
3032
3033 Some(DiffHunk {
3034 buffer_range: start..end,
3035 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3036 })
3037 });
3038
3039 cursor.next(&());
3040
3041 Some(buffer_hunks)
3042 })
3043 .flatten()
3044 }
3045
3046 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3047 let range = range.start.to_offset(self)..range.end.to_offset(self);
3048
3049 self.excerpt_containing(range.clone())
3050 .and_then(|(excerpt, excerpt_offset)| {
3051 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3052 let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
3053
3054 let start_in_buffer =
3055 excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
3056 let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
3057 let mut ancestor_buffer_range = excerpt
3058 .buffer
3059 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
3060 ancestor_buffer_range.start =
3061 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
3062 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
3063
3064 let start = excerpt_offset + (ancestor_buffer_range.start - excerpt_buffer_start);
3065 let end = excerpt_offset + (ancestor_buffer_range.end - excerpt_buffer_start);
3066 Some(start..end)
3067 })
3068 }
3069
3070 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3071 let (excerpt_id, _, buffer) = self.as_singleton()?;
3072 let outline = buffer.outline(theme)?;
3073 Some(Outline::new(
3074 outline
3075 .items
3076 .into_iter()
3077 .map(|item| OutlineItem {
3078 depth: item.depth,
3079 range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
3080 ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
3081 text: item.text,
3082 highlight_ranges: item.highlight_ranges,
3083 name_ranges: item.name_ranges,
3084 })
3085 .collect(),
3086 ))
3087 }
3088
3089 pub fn symbols_containing<T: ToOffset>(
3090 &self,
3091 offset: T,
3092 theme: Option<&SyntaxTheme>,
3093 ) -> Option<(u64, Vec<OutlineItem<Anchor>>)> {
3094 let anchor = self.anchor_before(offset);
3095 let excerpt_id = anchor.excerpt_id();
3096 let excerpt = self.excerpt(excerpt_id)?;
3097 Some((
3098 excerpt.buffer_id,
3099 excerpt
3100 .buffer
3101 .symbols_containing(anchor.text_anchor, theme)
3102 .into_iter()
3103 .flatten()
3104 .map(|item| OutlineItem {
3105 depth: item.depth,
3106 range: self.anchor_in_excerpt(excerpt_id, item.range.start)
3107 ..self.anchor_in_excerpt(excerpt_id, item.range.end),
3108 text: item.text,
3109 highlight_ranges: item.highlight_ranges,
3110 name_ranges: item.name_ranges,
3111 })
3112 .collect(),
3113 ))
3114 }
3115
3116 fn excerpt_locator_for_id<'a>(&'a self, id: ExcerptId) -> &'a Locator {
3117 if id == ExcerptId::min() {
3118 Locator::min_ref()
3119 } else if id == ExcerptId::max() {
3120 Locator::max_ref()
3121 } else {
3122 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3123 cursor.seek(&id, Bias::Left, &());
3124 if let Some(entry) = cursor.item() {
3125 if entry.id == id {
3126 return &entry.locator;
3127 }
3128 }
3129 panic!("invalid excerpt id {:?}", id)
3130 }
3131 }
3132
3133 pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<u64> {
3134 Some(self.excerpt(excerpt_id)?.buffer_id)
3135 }
3136
3137 pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3138 Some(&self.excerpt(excerpt_id)?.buffer)
3139 }
3140
3141 fn excerpt<'a>(&'a self, excerpt_id: ExcerptId) -> Option<&'a Excerpt> {
3142 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3143 let locator = self.excerpt_locator_for_id(excerpt_id);
3144 cursor.seek(&Some(locator), Bias::Left, &());
3145 if let Some(excerpt) = cursor.item() {
3146 if excerpt.id == excerpt_id {
3147 return Some(excerpt);
3148 }
3149 }
3150 None
3151 }
3152
3153 /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3154 fn excerpt_containing<'a, T: ToOffset>(
3155 &'a self,
3156 range: Range<T>,
3157 ) -> Option<(&'a Excerpt, usize)> {
3158 let range = range.start.to_offset(self)..range.end.to_offset(self);
3159
3160 let mut cursor = self.excerpts.cursor::<usize>();
3161 cursor.seek(&range.start, Bias::Right, &());
3162 let start_excerpt = cursor.item();
3163
3164 if range.start == range.end {
3165 return start_excerpt.map(|excerpt| (excerpt, *cursor.start()));
3166 }
3167
3168 cursor.seek(&range.end, Bias::Right, &());
3169 let end_excerpt = cursor.item();
3170
3171 start_excerpt
3172 .zip(end_excerpt)
3173 .and_then(|(start_excerpt, end_excerpt)| {
3174 if start_excerpt.id != end_excerpt.id {
3175 return None;
3176 }
3177
3178 Some((start_excerpt, *cursor.start()))
3179 })
3180 }
3181
3182 pub fn remote_selections_in_range<'a>(
3183 &'a self,
3184 range: &'a Range<Anchor>,
3185 ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3186 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3187 let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3188 let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3189 cursor.seek(start_locator, Bias::Left, &());
3190 cursor
3191 .take_while(move |excerpt| excerpt.locator <= *end_locator)
3192 .flat_map(move |excerpt| {
3193 let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3194 if excerpt.id == range.start.excerpt_id {
3195 query_range.start = range.start.text_anchor;
3196 }
3197 if excerpt.id == range.end.excerpt_id {
3198 query_range.end = range.end.text_anchor;
3199 }
3200
3201 excerpt
3202 .buffer
3203 .remote_selections_in_range(query_range)
3204 .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3205 selections.map(move |selection| {
3206 let mut start = Anchor {
3207 buffer_id: Some(excerpt.buffer_id),
3208 excerpt_id: excerpt.id.clone(),
3209 text_anchor: selection.start,
3210 };
3211 let mut end = Anchor {
3212 buffer_id: Some(excerpt.buffer_id),
3213 excerpt_id: excerpt.id.clone(),
3214 text_anchor: selection.end,
3215 };
3216 if range.start.cmp(&start, self).is_gt() {
3217 start = range.start.clone();
3218 }
3219 if range.end.cmp(&end, self).is_lt() {
3220 end = range.end.clone();
3221 }
3222
3223 (
3224 replica_id,
3225 line_mode,
3226 cursor_shape,
3227 Selection {
3228 id: selection.id,
3229 start,
3230 end,
3231 reversed: selection.reversed,
3232 goal: selection.goal,
3233 },
3234 )
3235 })
3236 })
3237 })
3238 }
3239}
3240
3241#[cfg(any(test, feature = "test-support"))]
3242impl MultiBufferSnapshot {
3243 pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3244 let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3245 let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3246 start..end
3247 }
3248}
3249
3250impl History {
3251 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3252 self.transaction_depth += 1;
3253 if self.transaction_depth == 1 {
3254 let id = self.next_transaction_id.tick();
3255 self.undo_stack.push(Transaction {
3256 id,
3257 buffer_transactions: Default::default(),
3258 first_edit_at: now,
3259 last_edit_at: now,
3260 suppress_grouping: false,
3261 });
3262 Some(id)
3263 } else {
3264 None
3265 }
3266 }
3267
3268 fn end_transaction(
3269 &mut self,
3270 now: Instant,
3271 buffer_transactions: HashMap<u64, TransactionId>,
3272 ) -> bool {
3273 assert_ne!(self.transaction_depth, 0);
3274 self.transaction_depth -= 1;
3275 if self.transaction_depth == 0 {
3276 if buffer_transactions.is_empty() {
3277 self.undo_stack.pop();
3278 false
3279 } else {
3280 self.redo_stack.clear();
3281 let transaction = self.undo_stack.last_mut().unwrap();
3282 transaction.last_edit_at = now;
3283 for (buffer_id, transaction_id) in buffer_transactions {
3284 transaction
3285 .buffer_transactions
3286 .entry(buffer_id)
3287 .or_insert(transaction_id);
3288 }
3289 true
3290 }
3291 } else {
3292 false
3293 }
3294 }
3295
3296 fn push_transaction<'a, T>(
3297 &mut self,
3298 buffer_transactions: T,
3299 now: Instant,
3300 cx: &mut ModelContext<MultiBuffer>,
3301 ) where
3302 T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
3303 {
3304 assert_eq!(self.transaction_depth, 0);
3305 let transaction = Transaction {
3306 id: self.next_transaction_id.tick(),
3307 buffer_transactions: buffer_transactions
3308 .into_iter()
3309 .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3310 .collect(),
3311 first_edit_at: now,
3312 last_edit_at: now,
3313 suppress_grouping: false,
3314 };
3315 if !transaction.buffer_transactions.is_empty() {
3316 self.undo_stack.push(transaction);
3317 self.redo_stack.clear();
3318 }
3319 }
3320
3321 fn finalize_last_transaction(&mut self) {
3322 if let Some(transaction) = self.undo_stack.last_mut() {
3323 transaction.suppress_grouping = true;
3324 }
3325 }
3326
3327 fn pop_undo(&mut self) -> Option<&mut Transaction> {
3328 assert_eq!(self.transaction_depth, 0);
3329 if let Some(transaction) = self.undo_stack.pop() {
3330 self.redo_stack.push(transaction);
3331 self.redo_stack.last_mut()
3332 } else {
3333 None
3334 }
3335 }
3336
3337 fn pop_redo(&mut self) -> Option<&mut Transaction> {
3338 assert_eq!(self.transaction_depth, 0);
3339 if let Some(transaction) = self.redo_stack.pop() {
3340 self.undo_stack.push(transaction);
3341 self.undo_stack.last_mut()
3342 } else {
3343 None
3344 }
3345 }
3346
3347 fn group(&mut self) -> Option<TransactionId> {
3348 let mut count = 0;
3349 let mut transactions = self.undo_stack.iter();
3350 if let Some(mut transaction) = transactions.next_back() {
3351 while let Some(prev_transaction) = transactions.next_back() {
3352 if !prev_transaction.suppress_grouping
3353 && transaction.first_edit_at - prev_transaction.last_edit_at
3354 <= self.group_interval
3355 {
3356 transaction = prev_transaction;
3357 count += 1;
3358 } else {
3359 break;
3360 }
3361 }
3362 }
3363 self.group_trailing(count)
3364 }
3365
3366 fn group_until(&mut self, transaction_id: TransactionId) {
3367 let mut count = 0;
3368 for transaction in self.undo_stack.iter().rev() {
3369 if transaction.id == transaction_id {
3370 self.group_trailing(count);
3371 break;
3372 } else if transaction.suppress_grouping {
3373 break;
3374 } else {
3375 count += 1;
3376 }
3377 }
3378 }
3379
3380 fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3381 let new_len = self.undo_stack.len() - n;
3382 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3383 if let Some(last_transaction) = transactions_to_keep.last_mut() {
3384 if let Some(transaction) = transactions_to_merge.last() {
3385 last_transaction.last_edit_at = transaction.last_edit_at;
3386 }
3387 for to_merge in transactions_to_merge {
3388 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3389 last_transaction
3390 .buffer_transactions
3391 .entry(*buffer_id)
3392 .or_insert(*transaction_id);
3393 }
3394 }
3395 }
3396
3397 self.undo_stack.truncate(new_len);
3398 self.undo_stack.last().map(|t| t.id)
3399 }
3400}
3401
3402impl Excerpt {
3403 fn new(
3404 id: ExcerptId,
3405 locator: Locator,
3406 buffer_id: u64,
3407 buffer: BufferSnapshot,
3408 range: ExcerptRange<text::Anchor>,
3409 has_trailing_newline: bool,
3410 ) -> Self {
3411 Excerpt {
3412 id,
3413 locator,
3414 max_buffer_row: range.context.end.to_point(&buffer).row,
3415 text_summary: buffer
3416 .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3417 buffer_id,
3418 buffer,
3419 range,
3420 has_trailing_newline,
3421 }
3422 }
3423
3424 fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3425 let content_start = self.range.context.start.to_offset(&self.buffer);
3426 let chunks_start = content_start + range.start;
3427 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3428
3429 let footer_height = if self.has_trailing_newline
3430 && range.start <= self.text_summary.len
3431 && range.end > self.text_summary.len
3432 {
3433 1
3434 } else {
3435 0
3436 };
3437
3438 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3439
3440 ExcerptChunks {
3441 content_chunks,
3442 footer_height,
3443 }
3444 }
3445
3446 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3447 let content_start = self.range.context.start.to_offset(&self.buffer);
3448 let bytes_start = content_start + range.start;
3449 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3450 let footer_height = if self.has_trailing_newline
3451 && range.start <= self.text_summary.len
3452 && range.end > self.text_summary.len
3453 {
3454 1
3455 } else {
3456 0
3457 };
3458 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3459
3460 ExcerptBytes {
3461 content_bytes,
3462 footer_height,
3463 }
3464 }
3465
3466 fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3467 let content_start = self.range.context.start.to_offset(&self.buffer);
3468 let bytes_start = content_start + range.start;
3469 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3470 let footer_height = if self.has_trailing_newline
3471 && range.start <= self.text_summary.len
3472 && range.end > self.text_summary.len
3473 {
3474 1
3475 } else {
3476 0
3477 };
3478 let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
3479
3480 ExcerptBytes {
3481 content_bytes,
3482 footer_height,
3483 }
3484 }
3485
3486 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3487 if text_anchor
3488 .cmp(&self.range.context.start, &self.buffer)
3489 .is_lt()
3490 {
3491 self.range.context.start
3492 } else if text_anchor
3493 .cmp(&self.range.context.end, &self.buffer)
3494 .is_gt()
3495 {
3496 self.range.context.end
3497 } else {
3498 text_anchor
3499 }
3500 }
3501
3502 fn contains(&self, anchor: &Anchor) -> bool {
3503 Some(self.buffer_id) == anchor.buffer_id
3504 && self
3505 .range
3506 .context
3507 .start
3508 .cmp(&anchor.text_anchor, &self.buffer)
3509 .is_le()
3510 && self
3511 .range
3512 .context
3513 .end
3514 .cmp(&anchor.text_anchor, &self.buffer)
3515 .is_ge()
3516 }
3517}
3518
3519impl ExcerptId {
3520 pub fn min() -> Self {
3521 Self(0)
3522 }
3523
3524 pub fn max() -> Self {
3525 Self(usize::MAX)
3526 }
3527
3528 pub fn to_proto(&self) -> u64 {
3529 self.0 as _
3530 }
3531
3532 pub fn from_proto(proto: u64) -> Self {
3533 Self(proto as _)
3534 }
3535
3536 pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3537 let a = snapshot.excerpt_locator_for_id(*self);
3538 let b = snapshot.excerpt_locator_for_id(*other);
3539 a.cmp(&b).then_with(|| self.0.cmp(&other.0))
3540 }
3541}
3542
3543impl Into<usize> for ExcerptId {
3544 fn into(self) -> usize {
3545 self.0
3546 }
3547}
3548
3549impl fmt::Debug for Excerpt {
3550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3551 f.debug_struct("Excerpt")
3552 .field("id", &self.id)
3553 .field("locator", &self.locator)
3554 .field("buffer_id", &self.buffer_id)
3555 .field("range", &self.range)
3556 .field("text_summary", &self.text_summary)
3557 .field("has_trailing_newline", &self.has_trailing_newline)
3558 .finish()
3559 }
3560}
3561
3562impl sum_tree::Item for Excerpt {
3563 type Summary = ExcerptSummary;
3564
3565 fn summary(&self) -> Self::Summary {
3566 let mut text = self.text_summary.clone();
3567 if self.has_trailing_newline {
3568 text += TextSummary::from("\n");
3569 }
3570 ExcerptSummary {
3571 excerpt_id: self.id,
3572 excerpt_locator: self.locator.clone(),
3573 max_buffer_row: self.max_buffer_row,
3574 text,
3575 }
3576 }
3577}
3578
3579impl sum_tree::Item for ExcerptIdMapping {
3580 type Summary = ExcerptId;
3581
3582 fn summary(&self) -> Self::Summary {
3583 self.id
3584 }
3585}
3586
3587impl sum_tree::KeyedItem for ExcerptIdMapping {
3588 type Key = ExcerptId;
3589
3590 fn key(&self) -> Self::Key {
3591 self.id
3592 }
3593}
3594
3595impl sum_tree::Summary for ExcerptId {
3596 type Context = ();
3597
3598 fn add_summary(&mut self, other: &Self, _: &()) {
3599 *self = *other;
3600 }
3601}
3602
3603impl sum_tree::Summary for ExcerptSummary {
3604 type Context = ();
3605
3606 fn add_summary(&mut self, summary: &Self, _: &()) {
3607 debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3608 self.excerpt_locator = summary.excerpt_locator.clone();
3609 self.text.add_summary(&summary.text, &());
3610 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3611 }
3612}
3613
3614impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3615 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3616 *self += &summary.text;
3617 }
3618}
3619
3620impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3621 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3622 *self += summary.text.len;
3623 }
3624}
3625
3626impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3627 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3628 Ord::cmp(self, &cursor_location.text.len)
3629 }
3630}
3631
3632impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3633 fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3634 Ord::cmp(&Some(self), cursor_location)
3635 }
3636}
3637
3638impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3639 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3640 Ord::cmp(self, &cursor_location.excerpt_locator)
3641 }
3642}
3643
3644impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3645 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3646 *self += summary.text.len_utf16;
3647 }
3648}
3649
3650impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3651 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3652 *self += summary.text.lines;
3653 }
3654}
3655
3656impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3657 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3658 *self += summary.text.lines_utf16()
3659 }
3660}
3661
3662impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3663 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3664 *self = Some(&summary.excerpt_locator);
3665 }
3666}
3667
3668impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3669 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3670 *self = Some(summary.excerpt_id);
3671 }
3672}
3673
3674impl<'a> MultiBufferRows<'a> {
3675 pub fn seek(&mut self, row: u32) {
3676 self.buffer_row_range = 0..0;
3677
3678 self.excerpts
3679 .seek_forward(&Point::new(row, 0), Bias::Right, &());
3680 if self.excerpts.item().is_none() {
3681 self.excerpts.prev(&());
3682
3683 if self.excerpts.item().is_none() && row == 0 {
3684 self.buffer_row_range = 0..1;
3685 return;
3686 }
3687 }
3688
3689 if let Some(excerpt) = self.excerpts.item() {
3690 let overshoot = row - self.excerpts.start().row;
3691 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3692 self.buffer_row_range.start = excerpt_start + overshoot;
3693 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3694 }
3695 }
3696}
3697
3698impl<'a> Iterator for MultiBufferRows<'a> {
3699 type Item = Option<u32>;
3700
3701 fn next(&mut self) -> Option<Self::Item> {
3702 loop {
3703 if !self.buffer_row_range.is_empty() {
3704 let row = Some(self.buffer_row_range.start);
3705 self.buffer_row_range.start += 1;
3706 return Some(row);
3707 }
3708 self.excerpts.item()?;
3709 self.excerpts.next(&());
3710 let excerpt = self.excerpts.item()?;
3711 self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3712 self.buffer_row_range.end =
3713 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3714 }
3715 }
3716}
3717
3718impl<'a> MultiBufferChunks<'a> {
3719 pub fn offset(&self) -> usize {
3720 self.range.start
3721 }
3722
3723 pub fn seek(&mut self, offset: usize) {
3724 self.range.start = offset;
3725 self.excerpts.seek(&offset, Bias::Right, &());
3726 if let Some(excerpt) = self.excerpts.item() {
3727 self.excerpt_chunks = Some(excerpt.chunks_in_range(
3728 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3729 self.language_aware,
3730 ));
3731 } else {
3732 self.excerpt_chunks = None;
3733 }
3734 }
3735}
3736
3737impl<'a> Iterator for MultiBufferChunks<'a> {
3738 type Item = Chunk<'a>;
3739
3740 fn next(&mut self) -> Option<Self::Item> {
3741 if self.range.is_empty() {
3742 None
3743 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3744 self.range.start += chunk.text.len();
3745 Some(chunk)
3746 } else {
3747 self.excerpts.next(&());
3748 let excerpt = self.excerpts.item()?;
3749 self.excerpt_chunks = Some(excerpt.chunks_in_range(
3750 0..self.range.end - self.excerpts.start(),
3751 self.language_aware,
3752 ));
3753 self.next()
3754 }
3755 }
3756}
3757
3758impl<'a> MultiBufferBytes<'a> {
3759 fn consume(&mut self, len: usize) {
3760 self.range.start += len;
3761 self.chunk = &self.chunk[len..];
3762
3763 if !self.range.is_empty() && self.chunk.is_empty() {
3764 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3765 self.chunk = chunk;
3766 } else {
3767 self.excerpts.next(&());
3768 if let Some(excerpt) = self.excerpts.item() {
3769 let mut excerpt_bytes =
3770 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3771 self.chunk = excerpt_bytes.next().unwrap();
3772 self.excerpt_bytes = Some(excerpt_bytes);
3773 }
3774 }
3775 }
3776 }
3777}
3778
3779impl<'a> Iterator for MultiBufferBytes<'a> {
3780 type Item = &'a [u8];
3781
3782 fn next(&mut self) -> Option<Self::Item> {
3783 let chunk = self.chunk;
3784 if chunk.is_empty() {
3785 None
3786 } else {
3787 self.consume(chunk.len());
3788 Some(chunk)
3789 }
3790 }
3791}
3792
3793impl<'a> io::Read for MultiBufferBytes<'a> {
3794 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3795 let len = cmp::min(buf.len(), self.chunk.len());
3796 buf[..len].copy_from_slice(&self.chunk[..len]);
3797 if len > 0 {
3798 self.consume(len);
3799 }
3800 Ok(len)
3801 }
3802}
3803
3804impl<'a> ReversedMultiBufferBytes<'a> {
3805 fn consume(&mut self, len: usize) {
3806 self.range.end -= len;
3807 self.chunk = &self.chunk[..self.chunk.len() - len];
3808
3809 if !self.range.is_empty() && self.chunk.is_empty() {
3810 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3811 self.chunk = chunk;
3812 } else {
3813 self.excerpts.next(&());
3814 if let Some(excerpt) = self.excerpts.item() {
3815 let mut excerpt_bytes =
3816 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3817 self.chunk = excerpt_bytes.next().unwrap();
3818 self.excerpt_bytes = Some(excerpt_bytes);
3819 }
3820 }
3821 }
3822 }
3823}
3824
3825impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
3826 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3827 let len = cmp::min(buf.len(), self.chunk.len());
3828 buf[..len].copy_from_slice(&self.chunk[..len]);
3829 buf[..len].reverse();
3830 if len > 0 {
3831 self.consume(len);
3832 }
3833 Ok(len)
3834 }
3835}
3836impl<'a> Iterator for ExcerptBytes<'a> {
3837 type Item = &'a [u8];
3838
3839 fn next(&mut self) -> Option<Self::Item> {
3840 if let Some(chunk) = self.content_bytes.next() {
3841 if !chunk.is_empty() {
3842 return Some(chunk);
3843 }
3844 }
3845
3846 if self.footer_height > 0 {
3847 let result = &NEWLINES[..self.footer_height];
3848 self.footer_height = 0;
3849 return Some(result);
3850 }
3851
3852 None
3853 }
3854}
3855
3856impl<'a> Iterator for ExcerptChunks<'a> {
3857 type Item = Chunk<'a>;
3858
3859 fn next(&mut self) -> Option<Self::Item> {
3860 if let Some(chunk) = self.content_chunks.next() {
3861 return Some(chunk);
3862 }
3863
3864 if self.footer_height > 0 {
3865 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3866 self.footer_height = 0;
3867 return Some(Chunk {
3868 text,
3869 ..Default::default()
3870 });
3871 }
3872
3873 None
3874 }
3875}
3876
3877impl ToOffset for Point {
3878 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3879 snapshot.point_to_offset(*self)
3880 }
3881}
3882
3883impl ToOffset for usize {
3884 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3885 assert!(*self <= snapshot.len(), "offset is out of range");
3886 *self
3887 }
3888}
3889
3890impl ToOffset for OffsetUtf16 {
3891 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3892 snapshot.offset_utf16_to_offset(*self)
3893 }
3894}
3895
3896impl ToOffset for PointUtf16 {
3897 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3898 snapshot.point_utf16_to_offset(*self)
3899 }
3900}
3901
3902impl ToOffsetUtf16 for OffsetUtf16 {
3903 fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3904 *self
3905 }
3906}
3907
3908impl ToOffsetUtf16 for usize {
3909 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3910 snapshot.offset_to_offset_utf16(*self)
3911 }
3912}
3913
3914impl ToPoint for usize {
3915 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3916 snapshot.offset_to_point(*self)
3917 }
3918}
3919
3920impl ToPoint for Point {
3921 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3922 *self
3923 }
3924}
3925
3926impl ToPointUtf16 for usize {
3927 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3928 snapshot.offset_to_point_utf16(*self)
3929 }
3930}
3931
3932impl ToPointUtf16 for Point {
3933 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3934 snapshot.point_to_point_utf16(*self)
3935 }
3936}
3937
3938impl ToPointUtf16 for PointUtf16 {
3939 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3940 *self
3941 }
3942}
3943
3944fn build_excerpt_ranges<T>(
3945 buffer: &BufferSnapshot,
3946 ranges: &[Range<T>],
3947 context_line_count: u32,
3948) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
3949where
3950 T: text::ToPoint,
3951{
3952 let max_point = buffer.max_point();
3953 let mut range_counts = Vec::new();
3954 let mut excerpt_ranges = Vec::new();
3955 let mut range_iter = ranges
3956 .iter()
3957 .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
3958 .peekable();
3959 while let Some(range) = range_iter.next() {
3960 let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
3961 let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
3962 let mut ranges_in_excerpt = 1;
3963
3964 while let Some(next_range) = range_iter.peek() {
3965 if next_range.start.row <= excerpt_end.row + context_line_count {
3966 excerpt_end =
3967 Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
3968 ranges_in_excerpt += 1;
3969 range_iter.next();
3970 } else {
3971 break;
3972 }
3973 }
3974
3975 excerpt_ranges.push(ExcerptRange {
3976 context: excerpt_start..excerpt_end,
3977 primary: Some(range),
3978 });
3979 range_counts.push(ranges_in_excerpt);
3980 }
3981
3982 (excerpt_ranges, range_counts)
3983}
3984
3985#[cfg(test)]
3986mod tests {
3987 use crate::editor_tests::init_test;
3988
3989 use super::*;
3990 use futures::StreamExt;
3991 use gpui::{AppContext, TestAppContext};
3992 use language::{Buffer, Rope};
3993 use project::{FakeFs, Project};
3994 use rand::prelude::*;
3995 use settings::SettingsStore;
3996 use std::{env, rc::Rc};
3997 use unindent::Unindent;
3998 use util::test::sample_text;
3999
4000 #[gpui::test]
4001 fn test_singleton(cx: &mut AppContext) {
4002 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
4003 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4004
4005 let snapshot = multibuffer.read(cx).snapshot(cx);
4006 assert_eq!(snapshot.text(), buffer.read(cx).text());
4007
4008 assert_eq!(
4009 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4010 (0..buffer.read(cx).row_count())
4011 .map(Some)
4012 .collect::<Vec<_>>()
4013 );
4014
4015 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4016 let snapshot = multibuffer.read(cx).snapshot(cx);
4017
4018 assert_eq!(snapshot.text(), buffer.read(cx).text());
4019 assert_eq!(
4020 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4021 (0..buffer.read(cx).row_count())
4022 .map(Some)
4023 .collect::<Vec<_>>()
4024 );
4025 }
4026
4027 #[gpui::test]
4028 fn test_remote(cx: &mut AppContext) {
4029 let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
4030 let guest_buffer = cx.add_model(|cx| {
4031 let state = host_buffer.read(cx).to_proto();
4032 let ops = cx
4033 .background()
4034 .block(host_buffer.read(cx).serialize_ops(None, cx));
4035 let mut buffer = Buffer::from_proto(1, state, None).unwrap();
4036 buffer
4037 .apply_ops(
4038 ops.into_iter()
4039 .map(|op| language::proto::deserialize_operation(op).unwrap()),
4040 cx,
4041 )
4042 .unwrap();
4043 buffer
4044 });
4045 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4046 let snapshot = multibuffer.read(cx).snapshot(cx);
4047 assert_eq!(snapshot.text(), "a");
4048
4049 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4050 let snapshot = multibuffer.read(cx).snapshot(cx);
4051 assert_eq!(snapshot.text(), "ab");
4052
4053 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4054 let snapshot = multibuffer.read(cx).snapshot(cx);
4055 assert_eq!(snapshot.text(), "abc");
4056 }
4057
4058 #[gpui::test]
4059 fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4060 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
4061 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
4062 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4063
4064 let events = Rc::new(RefCell::new(Vec::<Event>::new()));
4065 multibuffer.update(cx, |_, cx| {
4066 let events = events.clone();
4067 cx.subscribe(&multibuffer, move |_, _, event, _| {
4068 if let Event::Edited = event {
4069 events.borrow_mut().push(event.clone())
4070 }
4071 })
4072 .detach();
4073 });
4074
4075 let subscription = multibuffer.update(cx, |multibuffer, cx| {
4076 let subscription = multibuffer.subscribe();
4077 multibuffer.push_excerpts(
4078 buffer_1.clone(),
4079 [ExcerptRange {
4080 context: Point::new(1, 2)..Point::new(2, 5),
4081 primary: None,
4082 }],
4083 cx,
4084 );
4085 assert_eq!(
4086 subscription.consume().into_inner(),
4087 [Edit {
4088 old: 0..0,
4089 new: 0..10
4090 }]
4091 );
4092
4093 multibuffer.push_excerpts(
4094 buffer_1.clone(),
4095 [ExcerptRange {
4096 context: Point::new(3, 3)..Point::new(4, 4),
4097 primary: None,
4098 }],
4099 cx,
4100 );
4101 multibuffer.push_excerpts(
4102 buffer_2.clone(),
4103 [ExcerptRange {
4104 context: Point::new(3, 1)..Point::new(3, 3),
4105 primary: None,
4106 }],
4107 cx,
4108 );
4109 assert_eq!(
4110 subscription.consume().into_inner(),
4111 [Edit {
4112 old: 10..10,
4113 new: 10..22
4114 }]
4115 );
4116
4117 subscription
4118 });
4119
4120 // Adding excerpts emits an edited event.
4121 assert_eq!(
4122 events.borrow().as_slice(),
4123 &[Event::Edited, Event::Edited, Event::Edited]
4124 );
4125
4126 let snapshot = multibuffer.read(cx).snapshot(cx);
4127 assert_eq!(
4128 snapshot.text(),
4129 concat!(
4130 "bbbb\n", // Preserve newlines
4131 "ccccc\n", //
4132 "ddd\n", //
4133 "eeee\n", //
4134 "jj" //
4135 )
4136 );
4137 assert_eq!(
4138 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4139 [Some(1), Some(2), Some(3), Some(4), Some(3)]
4140 );
4141 assert_eq!(
4142 snapshot.buffer_rows(2).collect::<Vec<_>>(),
4143 [Some(3), Some(4), Some(3)]
4144 );
4145 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
4146 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
4147
4148 assert_eq!(
4149 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4150 &[
4151 (0, "bbbb\nccccc".to_string(), true),
4152 (2, "ddd\neeee".to_string(), false),
4153 (4, "jj".to_string(), true),
4154 ]
4155 );
4156 assert_eq!(
4157 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4158 &[(0, "bbbb\nccccc".to_string(), true)]
4159 );
4160 assert_eq!(
4161 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4162 &[]
4163 );
4164 assert_eq!(
4165 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4166 &[]
4167 );
4168 assert_eq!(
4169 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4170 &[(2, "ddd\neeee".to_string(), false)]
4171 );
4172 assert_eq!(
4173 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4174 &[(2, "ddd\neeee".to_string(), false)]
4175 );
4176 assert_eq!(
4177 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4178 &[(2, "ddd\neeee".to_string(), false)]
4179 );
4180 assert_eq!(
4181 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4182 &[(4, "jj".to_string(), true)]
4183 );
4184 assert_eq!(
4185 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4186 &[]
4187 );
4188
4189 buffer_1.update(cx, |buffer, cx| {
4190 let text = "\n";
4191 buffer.edit(
4192 [
4193 (Point::new(0, 0)..Point::new(0, 0), text),
4194 (Point::new(2, 1)..Point::new(2, 3), text),
4195 ],
4196 None,
4197 cx,
4198 );
4199 });
4200
4201 let snapshot = multibuffer.read(cx).snapshot(cx);
4202 assert_eq!(
4203 snapshot.text(),
4204 concat!(
4205 "bbbb\n", // Preserve newlines
4206 "c\n", //
4207 "cc\n", //
4208 "ddd\n", //
4209 "eeee\n", //
4210 "jj" //
4211 )
4212 );
4213
4214 assert_eq!(
4215 subscription.consume().into_inner(),
4216 [Edit {
4217 old: 6..8,
4218 new: 6..7
4219 }]
4220 );
4221
4222 let snapshot = multibuffer.read(cx).snapshot(cx);
4223 assert_eq!(
4224 snapshot.clip_point(Point::new(0, 5), Bias::Left),
4225 Point::new(0, 4)
4226 );
4227 assert_eq!(
4228 snapshot.clip_point(Point::new(0, 5), Bias::Right),
4229 Point::new(0, 4)
4230 );
4231 assert_eq!(
4232 snapshot.clip_point(Point::new(5, 1), Bias::Right),
4233 Point::new(5, 1)
4234 );
4235 assert_eq!(
4236 snapshot.clip_point(Point::new(5, 2), Bias::Right),
4237 Point::new(5, 2)
4238 );
4239 assert_eq!(
4240 snapshot.clip_point(Point::new(5, 3), Bias::Right),
4241 Point::new(5, 2)
4242 );
4243
4244 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4245 let (buffer_2_excerpt_id, _) =
4246 multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4247 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4248 multibuffer.snapshot(cx)
4249 });
4250
4251 assert_eq!(
4252 snapshot.text(),
4253 concat!(
4254 "bbbb\n", // Preserve newlines
4255 "c\n", //
4256 "cc\n", //
4257 "ddd\n", //
4258 "eeee", //
4259 )
4260 );
4261
4262 fn boundaries_in_range(
4263 range: Range<Point>,
4264 snapshot: &MultiBufferSnapshot,
4265 ) -> Vec<(u32, String, bool)> {
4266 snapshot
4267 .excerpt_boundaries_in_range(range)
4268 .map(|boundary| {
4269 (
4270 boundary.row,
4271 boundary
4272 .buffer
4273 .text_for_range(boundary.range.context)
4274 .collect::<String>(),
4275 boundary.starts_new_buffer,
4276 )
4277 })
4278 .collect::<Vec<_>>()
4279 }
4280 }
4281
4282 #[gpui::test]
4283 fn test_excerpt_events(cx: &mut AppContext) {
4284 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'a'), cx));
4285 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'm'), cx));
4286
4287 let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4288 let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4289 let follower_edit_event_count = Rc::new(RefCell::new(0));
4290
4291 follower_multibuffer.update(cx, |_, cx| {
4292 let follower_edit_event_count = follower_edit_event_count.clone();
4293 cx.subscribe(
4294 &leader_multibuffer,
4295 move |follower, _, event, cx| match event.clone() {
4296 Event::ExcerptsAdded {
4297 buffer,
4298 predecessor,
4299 excerpts,
4300 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4301 Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4302 Event::Edited => {
4303 *follower_edit_event_count.borrow_mut() += 1;
4304 }
4305 _ => {}
4306 },
4307 )
4308 .detach();
4309 });
4310
4311 leader_multibuffer.update(cx, |leader, cx| {
4312 leader.push_excerpts(
4313 buffer_1.clone(),
4314 [
4315 ExcerptRange {
4316 context: 0..8,
4317 primary: None,
4318 },
4319 ExcerptRange {
4320 context: 12..16,
4321 primary: None,
4322 },
4323 ],
4324 cx,
4325 );
4326 leader.insert_excerpts_after(
4327 leader.excerpt_ids()[0],
4328 buffer_2.clone(),
4329 [
4330 ExcerptRange {
4331 context: 0..5,
4332 primary: None,
4333 },
4334 ExcerptRange {
4335 context: 10..15,
4336 primary: None,
4337 },
4338 ],
4339 cx,
4340 )
4341 });
4342 assert_eq!(
4343 leader_multibuffer.read(cx).snapshot(cx).text(),
4344 follower_multibuffer.read(cx).snapshot(cx).text(),
4345 );
4346 assert_eq!(*follower_edit_event_count.borrow(), 2);
4347
4348 leader_multibuffer.update(cx, |leader, cx| {
4349 let excerpt_ids = leader.excerpt_ids();
4350 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4351 });
4352 assert_eq!(
4353 leader_multibuffer.read(cx).snapshot(cx).text(),
4354 follower_multibuffer.read(cx).snapshot(cx).text(),
4355 );
4356 assert_eq!(*follower_edit_event_count.borrow(), 3);
4357
4358 // Removing an empty set of excerpts is a noop.
4359 leader_multibuffer.update(cx, |leader, cx| {
4360 leader.remove_excerpts([], cx);
4361 });
4362 assert_eq!(
4363 leader_multibuffer.read(cx).snapshot(cx).text(),
4364 follower_multibuffer.read(cx).snapshot(cx).text(),
4365 );
4366 assert_eq!(*follower_edit_event_count.borrow(), 3);
4367
4368 // Adding an empty set of excerpts is a noop.
4369 leader_multibuffer.update(cx, |leader, cx| {
4370 leader.push_excerpts::<usize>(buffer_2.clone(), [], 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(), 3);
4377
4378 leader_multibuffer.update(cx, |leader, cx| {
4379 leader.clear(cx);
4380 });
4381 assert_eq!(
4382 leader_multibuffer.read(cx).snapshot(cx).text(),
4383 follower_multibuffer.read(cx).snapshot(cx).text(),
4384 );
4385 assert_eq!(*follower_edit_event_count.borrow(), 4);
4386 }
4387
4388 #[gpui::test]
4389 fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4390 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4391 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4392 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4393 multibuffer.push_excerpts_with_context_lines(
4394 buffer.clone(),
4395 vec![
4396 Point::new(3, 2)..Point::new(4, 2),
4397 Point::new(7, 1)..Point::new(7, 3),
4398 Point::new(15, 0)..Point::new(15, 0),
4399 ],
4400 2,
4401 cx,
4402 )
4403 });
4404
4405 let snapshot = multibuffer.read(cx).snapshot(cx);
4406 assert_eq!(
4407 snapshot.text(),
4408 "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4409 );
4410
4411 assert_eq!(
4412 anchor_ranges
4413 .iter()
4414 .map(|range| range.to_point(&snapshot))
4415 .collect::<Vec<_>>(),
4416 vec![
4417 Point::new(2, 2)..Point::new(3, 2),
4418 Point::new(6, 1)..Point::new(6, 3),
4419 Point::new(12, 0)..Point::new(12, 0)
4420 ]
4421 );
4422 }
4423
4424 #[gpui::test]
4425 async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
4426 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4427 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4428 let (task, anchor_ranges) = multibuffer.update(cx, |multibuffer, cx| {
4429 let snapshot = buffer.read(cx);
4430 let ranges = vec![
4431 snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
4432 snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
4433 snapshot.anchor_before(Point::new(15, 0))
4434 ..snapshot.anchor_before(Point::new(15, 0)),
4435 ];
4436 multibuffer.stream_excerpts_with_context_lines(vec![(buffer.clone(), ranges)], 2, cx)
4437 });
4438
4439 let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
4440 // Ensure task is finished when stream completes.
4441 task.await;
4442
4443 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4444 assert_eq!(
4445 snapshot.text(),
4446 "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4447 );
4448
4449 assert_eq!(
4450 anchor_ranges
4451 .iter()
4452 .map(|range| range.to_point(&snapshot))
4453 .collect::<Vec<_>>(),
4454 vec![
4455 Point::new(2, 2)..Point::new(3, 2),
4456 Point::new(6, 1)..Point::new(6, 3),
4457 Point::new(12, 0)..Point::new(12, 0)
4458 ]
4459 );
4460 }
4461
4462 #[gpui::test]
4463 fn test_empty_multibuffer(cx: &mut AppContext) {
4464 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4465
4466 let snapshot = multibuffer.read(cx).snapshot(cx);
4467 assert_eq!(snapshot.text(), "");
4468 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
4469 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
4470 }
4471
4472 #[gpui::test]
4473 fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
4474 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4475 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4476 let old_snapshot = multibuffer.read(cx).snapshot(cx);
4477 buffer.update(cx, |buffer, cx| {
4478 buffer.edit([(0..0, "X")], None, cx);
4479 buffer.edit([(5..5, "Y")], None, cx);
4480 });
4481 let new_snapshot = multibuffer.read(cx).snapshot(cx);
4482
4483 assert_eq!(old_snapshot.text(), "abcd");
4484 assert_eq!(new_snapshot.text(), "XabcdY");
4485
4486 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4487 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4488 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
4489 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
4490 }
4491
4492 #[gpui::test]
4493 fn test_multibuffer_anchors(cx: &mut AppContext) {
4494 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4495 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
4496 let multibuffer = cx.add_model(|cx| {
4497 let mut multibuffer = MultiBuffer::new(0);
4498 multibuffer.push_excerpts(
4499 buffer_1.clone(),
4500 [ExcerptRange {
4501 context: 0..4,
4502 primary: None,
4503 }],
4504 cx,
4505 );
4506 multibuffer.push_excerpts(
4507 buffer_2.clone(),
4508 [ExcerptRange {
4509 context: 0..5,
4510 primary: None,
4511 }],
4512 cx,
4513 );
4514 multibuffer
4515 });
4516 let old_snapshot = multibuffer.read(cx).snapshot(cx);
4517
4518 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
4519 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
4520 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4521 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4522 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4523 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4524
4525 buffer_1.update(cx, |buffer, cx| {
4526 buffer.edit([(0..0, "W")], None, cx);
4527 buffer.edit([(5..5, "X")], None, cx);
4528 });
4529 buffer_2.update(cx, |buffer, cx| {
4530 buffer.edit([(0..0, "Y")], None, cx);
4531 buffer.edit([(6..6, "Z")], None, cx);
4532 });
4533 let new_snapshot = multibuffer.read(cx).snapshot(cx);
4534
4535 assert_eq!(old_snapshot.text(), "abcd\nefghi");
4536 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
4537
4538 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4539 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4540 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
4541 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
4542 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
4543 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
4544 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
4545 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
4546 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
4547 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
4548 }
4549
4550 #[gpui::test]
4551 fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
4552 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4553 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
4554 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4555
4556 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
4557 // Add an excerpt from buffer 1 that spans this new insertion.
4558 buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
4559 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
4560 multibuffer
4561 .push_excerpts(
4562 buffer_1.clone(),
4563 [ExcerptRange {
4564 context: 0..7,
4565 primary: None,
4566 }],
4567 cx,
4568 )
4569 .pop()
4570 .unwrap()
4571 });
4572
4573 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
4574 assert_eq!(snapshot_1.text(), "abcd123");
4575
4576 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
4577 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
4578 multibuffer.remove_excerpts([excerpt_id_1], cx);
4579 let mut ids = multibuffer
4580 .push_excerpts(
4581 buffer_2.clone(),
4582 [
4583 ExcerptRange {
4584 context: 0..4,
4585 primary: None,
4586 },
4587 ExcerptRange {
4588 context: 6..10,
4589 primary: None,
4590 },
4591 ExcerptRange {
4592 context: 12..16,
4593 primary: None,
4594 },
4595 ],
4596 cx,
4597 )
4598 .into_iter();
4599 (ids.next().unwrap(), ids.next().unwrap())
4600 });
4601 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
4602 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
4603
4604 // The old excerpt id doesn't get reused.
4605 assert_ne!(excerpt_id_2, excerpt_id_1);
4606
4607 // Resolve some anchors from the previous snapshot in the new snapshot.
4608 // The current excerpts are from a different buffer, so we don't attempt to
4609 // resolve the old text anchor in the new buffer.
4610 assert_eq!(
4611 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
4612 0
4613 );
4614 assert_eq!(
4615 snapshot_2.summaries_for_anchors::<usize, _>(&[
4616 snapshot_1.anchor_before(2),
4617 snapshot_1.anchor_after(3)
4618 ]),
4619 vec![0, 0]
4620 );
4621
4622 // Refresh anchors from the old snapshot. The return value indicates that both
4623 // anchors lost their original excerpt.
4624 let refresh =
4625 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
4626 assert_eq!(
4627 refresh,
4628 &[
4629 (0, snapshot_2.anchor_before(0), false),
4630 (1, snapshot_2.anchor_after(0), false),
4631 ]
4632 );
4633
4634 // Replace the middle excerpt with a smaller excerpt in buffer 2,
4635 // that intersects the old excerpt.
4636 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
4637 multibuffer.remove_excerpts([excerpt_id_3], cx);
4638 multibuffer
4639 .insert_excerpts_after(
4640 excerpt_id_2,
4641 buffer_2.clone(),
4642 [ExcerptRange {
4643 context: 5..8,
4644 primary: None,
4645 }],
4646 cx,
4647 )
4648 .pop()
4649 .unwrap()
4650 });
4651
4652 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
4653 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
4654 assert_ne!(excerpt_id_5, excerpt_id_3);
4655
4656 // Resolve some anchors from the previous snapshot in the new snapshot.
4657 // The third anchor can't be resolved, since its excerpt has been removed,
4658 // so it resolves to the same position as its predecessor.
4659 let anchors = [
4660 snapshot_2.anchor_before(0),
4661 snapshot_2.anchor_after(2),
4662 snapshot_2.anchor_after(6),
4663 snapshot_2.anchor_after(14),
4664 ];
4665 assert_eq!(
4666 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
4667 &[0, 2, 9, 13]
4668 );
4669
4670 let new_anchors = snapshot_3.refresh_anchors(&anchors);
4671 assert_eq!(
4672 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
4673 &[(0, true), (1, true), (2, true), (3, true)]
4674 );
4675 assert_eq!(
4676 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
4677 &[0, 2, 7, 13]
4678 );
4679 }
4680
4681 #[gpui::test]
4682 async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
4683 use git::diff::DiffHunkStatus;
4684 init_test(cx, |_| {});
4685
4686 let fs = FakeFs::new(cx.background());
4687 let project = Project::test(fs, [], cx).await;
4688
4689 // buffer has two modified hunks with two rows each
4690 let buffer_1 = project
4691 .update(cx, |project, cx| {
4692 project.create_buffer(
4693 "
4694 1.zero
4695 1.ONE
4696 1.TWO
4697 1.three
4698 1.FOUR
4699 1.FIVE
4700 1.six
4701 "
4702 .unindent()
4703 .as_str(),
4704 None,
4705 cx,
4706 )
4707 })
4708 .unwrap();
4709 buffer_1.update(cx, |buffer, cx| {
4710 buffer.set_diff_base(
4711 Some(
4712 "
4713 1.zero
4714 1.one
4715 1.two
4716 1.three
4717 1.four
4718 1.five
4719 1.six
4720 "
4721 .unindent(),
4722 ),
4723 cx,
4724 );
4725 });
4726
4727 // buffer has a deletion hunk and an insertion hunk
4728 let buffer_2 = project
4729 .update(cx, |project, cx| {
4730 project.create_buffer(
4731 "
4732 2.zero
4733 2.one
4734 2.two
4735 2.three
4736 2.four
4737 2.five
4738 2.six
4739 "
4740 .unindent()
4741 .as_str(),
4742 None,
4743 cx,
4744 )
4745 })
4746 .unwrap();
4747 buffer_2.update(cx, |buffer, cx| {
4748 buffer.set_diff_base(
4749 Some(
4750 "
4751 2.zero
4752 2.one
4753 2.one-and-a-half
4754 2.two
4755 2.three
4756 2.four
4757 2.six
4758 "
4759 .unindent(),
4760 ),
4761 cx,
4762 );
4763 });
4764
4765 cx.foreground().run_until_parked();
4766
4767 let multibuffer = cx.add_model(|cx| {
4768 let mut multibuffer = MultiBuffer::new(0);
4769 multibuffer.push_excerpts(
4770 buffer_1.clone(),
4771 [
4772 // excerpt ends in the middle of a modified hunk
4773 ExcerptRange {
4774 context: Point::new(0, 0)..Point::new(1, 5),
4775 primary: Default::default(),
4776 },
4777 // excerpt begins in the middle of a modified hunk
4778 ExcerptRange {
4779 context: Point::new(5, 0)..Point::new(6, 5),
4780 primary: Default::default(),
4781 },
4782 ],
4783 cx,
4784 );
4785 multibuffer.push_excerpts(
4786 buffer_2.clone(),
4787 [
4788 // excerpt ends at a deletion
4789 ExcerptRange {
4790 context: Point::new(0, 0)..Point::new(1, 5),
4791 primary: Default::default(),
4792 },
4793 // excerpt starts at a deletion
4794 ExcerptRange {
4795 context: Point::new(2, 0)..Point::new(2, 5),
4796 primary: Default::default(),
4797 },
4798 // excerpt fully contains a deletion hunk
4799 ExcerptRange {
4800 context: Point::new(1, 0)..Point::new(2, 5),
4801 primary: Default::default(),
4802 },
4803 // excerpt fully contains an insertion hunk
4804 ExcerptRange {
4805 context: Point::new(4, 0)..Point::new(6, 5),
4806 primary: Default::default(),
4807 },
4808 ],
4809 cx,
4810 );
4811 multibuffer
4812 });
4813
4814 let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
4815
4816 assert_eq!(
4817 snapshot.text(),
4818 "
4819 1.zero
4820 1.ONE
4821 1.FIVE
4822 1.six
4823 2.zero
4824 2.one
4825 2.two
4826 2.one
4827 2.two
4828 2.four
4829 2.five
4830 2.six"
4831 .unindent()
4832 );
4833
4834 let expected = [
4835 (DiffHunkStatus::Modified, 1..2),
4836 (DiffHunkStatus::Modified, 2..3),
4837 //TODO: Define better when and where removed hunks show up at range extremities
4838 (DiffHunkStatus::Removed, 6..6),
4839 (DiffHunkStatus::Removed, 8..8),
4840 (DiffHunkStatus::Added, 10..11),
4841 ];
4842
4843 assert_eq!(
4844 snapshot
4845 .git_diff_hunks_in_range(0..12)
4846 .map(|hunk| (hunk.status(), hunk.buffer_range))
4847 .collect::<Vec<_>>(),
4848 &expected,
4849 );
4850
4851 assert_eq!(
4852 snapshot
4853 .git_diff_hunks_in_range_rev(0..12)
4854 .map(|hunk| (hunk.status(), hunk.buffer_range))
4855 .collect::<Vec<_>>(),
4856 expected
4857 .iter()
4858 .rev()
4859 .cloned()
4860 .collect::<Vec<_>>()
4861 .as_slice(),
4862 );
4863 }
4864
4865 #[gpui::test(iterations = 100)]
4866 fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
4867 let operations = env::var("OPERATIONS")
4868 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4869 .unwrap_or(10);
4870
4871 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
4872 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4873 let mut excerpt_ids = Vec::<ExcerptId>::new();
4874 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
4875 let mut anchors = Vec::new();
4876 let mut old_versions = Vec::new();
4877
4878 for _ in 0..operations {
4879 match rng.gen_range(0..100) {
4880 0..=19 if !buffers.is_empty() => {
4881 let buffer = buffers.choose(&mut rng).unwrap();
4882 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
4883 }
4884 20..=29 if !expected_excerpts.is_empty() => {
4885 let mut ids_to_remove = vec![];
4886 for _ in 0..rng.gen_range(1..=3) {
4887 if expected_excerpts.is_empty() {
4888 break;
4889 }
4890
4891 let ix = rng.gen_range(0..expected_excerpts.len());
4892 ids_to_remove.push(excerpt_ids.remove(ix));
4893 let (buffer, range) = expected_excerpts.remove(ix);
4894 let buffer = buffer.read(cx);
4895 log::info!(
4896 "Removing excerpt {}: {:?}",
4897 ix,
4898 buffer
4899 .text_for_range(range.to_offset(buffer))
4900 .collect::<String>(),
4901 );
4902 }
4903 let snapshot = multibuffer.read(cx).read(cx);
4904 ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
4905 drop(snapshot);
4906 multibuffer.update(cx, |multibuffer, cx| {
4907 multibuffer.remove_excerpts(ids_to_remove, cx)
4908 });
4909 }
4910 30..=39 if !expected_excerpts.is_empty() => {
4911 let multibuffer = multibuffer.read(cx).read(cx);
4912 let offset =
4913 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
4914 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
4915 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
4916 anchors.push(multibuffer.anchor_at(offset, bias));
4917 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
4918 }
4919 40..=44 if !anchors.is_empty() => {
4920 let multibuffer = multibuffer.read(cx).read(cx);
4921 let prev_len = anchors.len();
4922 anchors = multibuffer
4923 .refresh_anchors(&anchors)
4924 .into_iter()
4925 .map(|a| a.1)
4926 .collect();
4927
4928 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
4929 // overshoot its boundaries.
4930 assert_eq!(anchors.len(), prev_len);
4931 for anchor in &anchors {
4932 if anchor.excerpt_id == ExcerptId::min()
4933 || anchor.excerpt_id == ExcerptId::max()
4934 {
4935 continue;
4936 }
4937
4938 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
4939 assert_eq!(excerpt.id, anchor.excerpt_id);
4940 assert!(excerpt.contains(anchor));
4941 }
4942 }
4943 _ => {
4944 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
4945 let base_text = util::RandomCharIter::new(&mut rng)
4946 .take(10)
4947 .collect::<String>();
4948 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
4949 buffers.last().unwrap()
4950 } else {
4951 buffers.choose(&mut rng).unwrap()
4952 };
4953
4954 let buffer = buffer_handle.read(cx);
4955 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
4956 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4957 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
4958 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
4959 let prev_excerpt_id = excerpt_ids
4960 .get(prev_excerpt_ix)
4961 .cloned()
4962 .unwrap_or_else(ExcerptId::max);
4963 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
4964
4965 log::info!(
4966 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
4967 excerpt_ix,
4968 expected_excerpts.len(),
4969 buffer_handle.read(cx).remote_id(),
4970 buffer.text(),
4971 start_ix..end_ix,
4972 &buffer.text()[start_ix..end_ix]
4973 );
4974
4975 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
4976 multibuffer
4977 .insert_excerpts_after(
4978 prev_excerpt_id,
4979 buffer_handle.clone(),
4980 [ExcerptRange {
4981 context: start_ix..end_ix,
4982 primary: None,
4983 }],
4984 cx,
4985 )
4986 .pop()
4987 .unwrap()
4988 });
4989
4990 excerpt_ids.insert(excerpt_ix, excerpt_id);
4991 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
4992 }
4993 }
4994
4995 if rng.gen_bool(0.3) {
4996 multibuffer.update(cx, |multibuffer, cx| {
4997 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
4998 })
4999 }
5000
5001 let snapshot = multibuffer.read(cx).snapshot(cx);
5002
5003 let mut excerpt_starts = Vec::new();
5004 let mut expected_text = String::new();
5005 let mut expected_buffer_rows = Vec::new();
5006 for (buffer, range) in &expected_excerpts {
5007 let buffer = buffer.read(cx);
5008 let buffer_range = range.to_offset(buffer);
5009
5010 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5011 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5012 expected_text.push('\n');
5013
5014 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5015 ..=buffer.offset_to_point(buffer_range.end).row;
5016 for row in buffer_row_range {
5017 expected_buffer_rows.push(Some(row));
5018 }
5019 }
5020 // Remove final trailing newline.
5021 if !expected_excerpts.is_empty() {
5022 expected_text.pop();
5023 }
5024
5025 // Always report one buffer row
5026 if expected_buffer_rows.is_empty() {
5027 expected_buffer_rows.push(Some(0));
5028 }
5029
5030 assert_eq!(snapshot.text(), expected_text);
5031 log::info!("MultiBuffer text: {:?}", expected_text);
5032
5033 assert_eq!(
5034 snapshot.buffer_rows(0).collect::<Vec<_>>(),
5035 expected_buffer_rows,
5036 );
5037
5038 for _ in 0..5 {
5039 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5040 assert_eq!(
5041 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
5042 &expected_buffer_rows[start_row..],
5043 "buffer_rows({})",
5044 start_row
5045 );
5046 }
5047
5048 assert_eq!(
5049 snapshot.max_buffer_row(),
5050 expected_buffer_rows.into_iter().flatten().max().unwrap()
5051 );
5052
5053 let mut excerpt_starts = excerpt_starts.into_iter();
5054 for (buffer, range) in &expected_excerpts {
5055 let buffer = buffer.read(cx);
5056 let buffer_id = buffer.remote_id();
5057 let buffer_range = range.to_offset(buffer);
5058 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5059 let buffer_start_point_utf16 =
5060 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5061
5062 let excerpt_start = excerpt_starts.next().unwrap();
5063 let mut offset = excerpt_start.len;
5064 let mut buffer_offset = buffer_range.start;
5065 let mut point = excerpt_start.lines;
5066 let mut buffer_point = buffer_start_point;
5067 let mut point_utf16 = excerpt_start.lines_utf16();
5068 let mut buffer_point_utf16 = buffer_start_point_utf16;
5069 for ch in buffer
5070 .snapshot()
5071 .chunks(buffer_range.clone(), false)
5072 .flat_map(|c| c.text.chars())
5073 {
5074 for _ in 0..ch.len_utf8() {
5075 let left_offset = snapshot.clip_offset(offset, Bias::Left);
5076 let right_offset = snapshot.clip_offset(offset, Bias::Right);
5077 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5078 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5079 assert_eq!(
5080 left_offset,
5081 excerpt_start.len + (buffer_left_offset - buffer_range.start),
5082 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5083 offset,
5084 buffer_id,
5085 buffer_offset,
5086 );
5087 assert_eq!(
5088 right_offset,
5089 excerpt_start.len + (buffer_right_offset - buffer_range.start),
5090 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5091 offset,
5092 buffer_id,
5093 buffer_offset,
5094 );
5095
5096 let left_point = snapshot.clip_point(point, Bias::Left);
5097 let right_point = snapshot.clip_point(point, Bias::Right);
5098 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5099 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5100 assert_eq!(
5101 left_point,
5102 excerpt_start.lines + (buffer_left_point - buffer_start_point),
5103 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5104 point,
5105 buffer_id,
5106 buffer_point,
5107 );
5108 assert_eq!(
5109 right_point,
5110 excerpt_start.lines + (buffer_right_point - buffer_start_point),
5111 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5112 point,
5113 buffer_id,
5114 buffer_point,
5115 );
5116
5117 assert_eq!(
5118 snapshot.point_to_offset(left_point),
5119 left_offset,
5120 "point_to_offset({:?})",
5121 left_point,
5122 );
5123 assert_eq!(
5124 snapshot.offset_to_point(left_offset),
5125 left_point,
5126 "offset_to_point({:?})",
5127 left_offset,
5128 );
5129
5130 offset += 1;
5131 buffer_offset += 1;
5132 if ch == '\n' {
5133 point += Point::new(1, 0);
5134 buffer_point += Point::new(1, 0);
5135 } else {
5136 point += Point::new(0, 1);
5137 buffer_point += Point::new(0, 1);
5138 }
5139 }
5140
5141 for _ in 0..ch.len_utf16() {
5142 let left_point_utf16 =
5143 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5144 let right_point_utf16 =
5145 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5146 let buffer_left_point_utf16 =
5147 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5148 let buffer_right_point_utf16 =
5149 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5150 assert_eq!(
5151 left_point_utf16,
5152 excerpt_start.lines_utf16()
5153 + (buffer_left_point_utf16 - buffer_start_point_utf16),
5154 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5155 point_utf16,
5156 buffer_id,
5157 buffer_point_utf16,
5158 );
5159 assert_eq!(
5160 right_point_utf16,
5161 excerpt_start.lines_utf16()
5162 + (buffer_right_point_utf16 - buffer_start_point_utf16),
5163 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5164 point_utf16,
5165 buffer_id,
5166 buffer_point_utf16,
5167 );
5168
5169 if ch == '\n' {
5170 point_utf16 += PointUtf16::new(1, 0);
5171 buffer_point_utf16 += PointUtf16::new(1, 0);
5172 } else {
5173 point_utf16 += PointUtf16::new(0, 1);
5174 buffer_point_utf16 += PointUtf16::new(0, 1);
5175 }
5176 }
5177 }
5178 }
5179
5180 for (row, line) in expected_text.split('\n').enumerate() {
5181 assert_eq!(
5182 snapshot.line_len(row as u32),
5183 line.len() as u32,
5184 "line_len({}).",
5185 row
5186 );
5187 }
5188
5189 let text_rope = Rope::from(expected_text.as_str());
5190 for _ in 0..10 {
5191 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5192 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5193
5194 let text_for_range = snapshot
5195 .text_for_range(start_ix..end_ix)
5196 .collect::<String>();
5197 assert_eq!(
5198 text_for_range,
5199 &expected_text[start_ix..end_ix],
5200 "incorrect text for range {:?}",
5201 start_ix..end_ix
5202 );
5203
5204 let excerpted_buffer_ranges = multibuffer
5205 .read(cx)
5206 .range_to_buffer_ranges(start_ix..end_ix, cx);
5207 let excerpted_buffers_text = excerpted_buffer_ranges
5208 .iter()
5209 .map(|(buffer, buffer_range, _)| {
5210 buffer
5211 .read(cx)
5212 .text_for_range(buffer_range.clone())
5213 .collect::<String>()
5214 })
5215 .collect::<Vec<_>>()
5216 .join("\n");
5217 assert_eq!(excerpted_buffers_text, text_for_range);
5218 if !expected_excerpts.is_empty() {
5219 assert!(!excerpted_buffer_ranges.is_empty());
5220 }
5221
5222 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5223 assert_eq!(
5224 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5225 expected_summary,
5226 "incorrect summary for range {:?}",
5227 start_ix..end_ix
5228 );
5229 }
5230
5231 // Anchor resolution
5232 let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5233 assert_eq!(anchors.len(), summaries.len());
5234 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5235 assert!(resolved_offset <= snapshot.len());
5236 assert_eq!(
5237 snapshot.summary_for_anchor::<usize>(anchor),
5238 resolved_offset
5239 );
5240 }
5241
5242 for _ in 0..10 {
5243 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5244 assert_eq!(
5245 snapshot.reversed_chars_at(end_ix).collect::<String>(),
5246 expected_text[..end_ix].chars().rev().collect::<String>(),
5247 );
5248 }
5249
5250 for _ in 0..10 {
5251 let end_ix = rng.gen_range(0..=text_rope.len());
5252 let start_ix = rng.gen_range(0..=end_ix);
5253 assert_eq!(
5254 snapshot
5255 .bytes_in_range(start_ix..end_ix)
5256 .flatten()
5257 .copied()
5258 .collect::<Vec<_>>(),
5259 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
5260 "bytes_in_range({:?})",
5261 start_ix..end_ix,
5262 );
5263 }
5264 }
5265
5266 let snapshot = multibuffer.read(cx).snapshot(cx);
5267 for (old_snapshot, subscription) in old_versions {
5268 let edits = subscription.consume().into_inner();
5269
5270 log::info!(
5271 "applying subscription edits to old text: {:?}: {:?}",
5272 old_snapshot.text(),
5273 edits,
5274 );
5275
5276 let mut text = old_snapshot.text();
5277 for edit in edits {
5278 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
5279 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
5280 }
5281 assert_eq!(text.to_string(), snapshot.text());
5282 }
5283 }
5284
5285 #[gpui::test]
5286 fn test_history(cx: &mut AppContext) {
5287 cx.set_global(SettingsStore::test(cx));
5288
5289 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
5290 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
5291 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
5292 let group_interval = multibuffer.read(cx).history.group_interval;
5293 multibuffer.update(cx, |multibuffer, cx| {
5294 multibuffer.push_excerpts(
5295 buffer_1.clone(),
5296 [ExcerptRange {
5297 context: 0..buffer_1.read(cx).len(),
5298 primary: None,
5299 }],
5300 cx,
5301 );
5302 multibuffer.push_excerpts(
5303 buffer_2.clone(),
5304 [ExcerptRange {
5305 context: 0..buffer_2.read(cx).len(),
5306 primary: None,
5307 }],
5308 cx,
5309 );
5310 });
5311
5312 let mut now = Instant::now();
5313
5314 multibuffer.update(cx, |multibuffer, cx| {
5315 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5316 multibuffer.edit(
5317 [
5318 (Point::new(0, 0)..Point::new(0, 0), "A"),
5319 (Point::new(1, 0)..Point::new(1, 0), "A"),
5320 ],
5321 None,
5322 cx,
5323 );
5324 multibuffer.edit(
5325 [
5326 (Point::new(0, 1)..Point::new(0, 1), "B"),
5327 (Point::new(1, 1)..Point::new(1, 1), "B"),
5328 ],
5329 None,
5330 cx,
5331 );
5332 multibuffer.end_transaction_at(now, cx);
5333 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5334
5335 // Edit buffer 1 through the multibuffer
5336 now += 2 * group_interval;
5337 multibuffer.start_transaction_at(now, cx);
5338 multibuffer.edit([(2..2, "C")], None, cx);
5339 multibuffer.end_transaction_at(now, cx);
5340 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5341
5342 // Edit buffer 1 independently
5343 buffer_1.update(cx, |buffer_1, cx| {
5344 buffer_1.start_transaction_at(now);
5345 buffer_1.edit([(3..3, "D")], None, cx);
5346 buffer_1.end_transaction_at(now, cx);
5347
5348 now += 2 * group_interval;
5349 buffer_1.start_transaction_at(now);
5350 buffer_1.edit([(4..4, "E")], None, cx);
5351 buffer_1.end_transaction_at(now, cx);
5352 });
5353 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5354
5355 // An undo in the multibuffer undoes the multibuffer transaction
5356 // and also any individual buffer edits that have occurred since
5357 // that transaction.
5358 multibuffer.undo(cx);
5359 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5360
5361 multibuffer.undo(cx);
5362 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5363
5364 multibuffer.redo(cx);
5365 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5366
5367 multibuffer.redo(cx);
5368 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5369
5370 // Undo buffer 2 independently.
5371 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5372 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5373
5374 // An undo in the multibuffer undoes the components of the
5375 // the last multibuffer transaction that are not already undone.
5376 multibuffer.undo(cx);
5377 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5378
5379 multibuffer.undo(cx);
5380 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5381
5382 multibuffer.redo(cx);
5383 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5384
5385 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5386 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5387
5388 // Redo stack gets cleared after an edit.
5389 now += 2 * group_interval;
5390 multibuffer.start_transaction_at(now, cx);
5391 multibuffer.edit([(0..0, "X")], None, cx);
5392 multibuffer.end_transaction_at(now, cx);
5393 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5394 multibuffer.redo(cx);
5395 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5396 multibuffer.undo(cx);
5397 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5398 multibuffer.undo(cx);
5399 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5400
5401 // Transactions can be grouped manually.
5402 multibuffer.redo(cx);
5403 multibuffer.redo(cx);
5404 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5405 multibuffer.group_until_transaction(transaction_1, cx);
5406 multibuffer.undo(cx);
5407 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5408 multibuffer.redo(cx);
5409 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5410 });
5411 }
5412}