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};
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 buffer: ModelHandle<Buffer>,
792 ranges: Vec<Range<text::Anchor>>,
793 context_line_count: u32,
794 cx: &mut ModelContext<Self>,
795 ) -> mpsc::Receiver<Range<Anchor>> {
796 let (mut tx, rx) = mpsc::channel(256);
797 cx.spawn(|this, mut cx| async move {
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 excerpt_ids.into_iter().zip(range_counts.by_ref())
822 {
823 for range in ranges.by_ref().take(range_count) {
824 let start = Anchor {
825 buffer_id: Some(buffer_id),
826 excerpt_id: excerpt_id.clone(),
827 text_anchor: range.start,
828 };
829 let end = Anchor {
830 buffer_id: Some(buffer_id),
831 excerpt_id: excerpt_id.clone(),
832 text_anchor: range.end,
833 };
834 if tx.send(start..end).await.is_err() {
835 break;
836 }
837 }
838 }
839 }
840 })
841 .detach();
842
843 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(&self, position: Anchor, text: &str, cx: &AppContext) -> bool {
1350 let mut chars = text.chars();
1351 let char = if let Some(char) = chars.next() {
1352 char
1353 } else {
1354 return false;
1355 };
1356 if chars.next().is_some() {
1357 return false;
1358 }
1359
1360 let language = self.language_at(position.clone(), cx);
1361
1362 if char_kind(language.as_ref(), char) == CharKind::Word {
1363 return true;
1364 }
1365
1366 let snapshot = self.snapshot(cx);
1367 let anchor = snapshot.anchor_before(position);
1368 anchor
1369 .buffer_id
1370 .and_then(|buffer_id| {
1371 let buffer = self.buffers.borrow().get(&buffer_id)?.buffer.clone();
1372 Some(
1373 buffer
1374 .read(cx)
1375 .completion_triggers()
1376 .iter()
1377 .any(|string| string == text),
1378 )
1379 })
1380 .unwrap_or(false)
1381 }
1382
1383 pub fn language_at<'a, T: ToOffset>(
1384 &self,
1385 point: T,
1386 cx: &'a AppContext,
1387 ) -> Option<Arc<Language>> {
1388 self.point_to_buffer_offset(point, cx)
1389 .and_then(|(buffer, offset, _)| buffer.read(cx).language_at(offset))
1390 }
1391
1392 pub fn settings_at<'a, T: ToOffset>(
1393 &self,
1394 point: T,
1395 cx: &'a AppContext,
1396 ) -> &'a LanguageSettings {
1397 let mut language = None;
1398 let mut file = None;
1399 if let Some((buffer, offset, _)) = self.point_to_buffer_offset(point, cx) {
1400 let buffer = buffer.read(cx);
1401 language = buffer.language_at(offset);
1402 file = buffer.file();
1403 }
1404 language_settings(language.as_ref(), file, cx)
1405 }
1406
1407 pub fn for_each_buffer(&self, mut f: impl FnMut(&ModelHandle<Buffer>)) {
1408 self.buffers
1409 .borrow()
1410 .values()
1411 .for_each(|state| f(&state.buffer))
1412 }
1413
1414 pub fn title<'a>(&'a self, cx: &'a AppContext) -> Cow<'a, str> {
1415 if let Some(title) = self.title.as_ref() {
1416 return title.into();
1417 }
1418
1419 if let Some(buffer) = self.as_singleton() {
1420 if let Some(file) = buffer.read(cx).file() {
1421 return file.file_name(cx).to_string_lossy();
1422 }
1423 }
1424
1425 "untitled".into()
1426 }
1427
1428 #[cfg(test)]
1429 pub fn is_parsing(&self, cx: &AppContext) -> bool {
1430 self.as_singleton().unwrap().read(cx).is_parsing()
1431 }
1432
1433 fn sync(&self, cx: &AppContext) {
1434 let mut snapshot = self.snapshot.borrow_mut();
1435 let mut excerpts_to_edit = Vec::new();
1436 let mut reparsed = false;
1437 let mut diagnostics_updated = false;
1438 let mut git_diff_updated = false;
1439 let mut is_dirty = false;
1440 let mut has_conflict = false;
1441 let mut edited = false;
1442 let mut buffers = self.buffers.borrow_mut();
1443 for buffer_state in buffers.values_mut() {
1444 let buffer = buffer_state.buffer.read(cx);
1445 let version = buffer.version();
1446 let parse_count = buffer.parse_count();
1447 let selections_update_count = buffer.selections_update_count();
1448 let diagnostics_update_count = buffer.diagnostics_update_count();
1449 let file_update_count = buffer.file_update_count();
1450 let git_diff_update_count = buffer.git_diff_update_count();
1451
1452 let buffer_edited = version.changed_since(&buffer_state.last_version);
1453 let buffer_reparsed = parse_count > buffer_state.last_parse_count;
1454 let buffer_selections_updated =
1455 selections_update_count > buffer_state.last_selections_update_count;
1456 let buffer_diagnostics_updated =
1457 diagnostics_update_count > buffer_state.last_diagnostics_update_count;
1458 let buffer_file_updated = file_update_count > buffer_state.last_file_update_count;
1459 let buffer_git_diff_updated =
1460 git_diff_update_count > buffer_state.last_git_diff_update_count;
1461 if buffer_edited
1462 || buffer_reparsed
1463 || buffer_selections_updated
1464 || buffer_diagnostics_updated
1465 || buffer_file_updated
1466 || buffer_git_diff_updated
1467 {
1468 buffer_state.last_version = version;
1469 buffer_state.last_parse_count = parse_count;
1470 buffer_state.last_selections_update_count = selections_update_count;
1471 buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1472 buffer_state.last_file_update_count = file_update_count;
1473 buffer_state.last_git_diff_update_count = git_diff_update_count;
1474 excerpts_to_edit.extend(
1475 buffer_state
1476 .excerpts
1477 .iter()
1478 .map(|locator| (locator, buffer_state.buffer.clone(), buffer_edited)),
1479 );
1480 }
1481
1482 edited |= buffer_edited;
1483 reparsed |= buffer_reparsed;
1484 diagnostics_updated |= buffer_diagnostics_updated;
1485 git_diff_updated |= buffer_git_diff_updated;
1486 is_dirty |= buffer.is_dirty();
1487 has_conflict |= buffer.has_conflict();
1488 }
1489 if edited {
1490 snapshot.edit_count += 1;
1491 }
1492 if reparsed {
1493 snapshot.parse_count += 1;
1494 }
1495 if diagnostics_updated {
1496 snapshot.diagnostics_update_count += 1;
1497 }
1498 if git_diff_updated {
1499 snapshot.git_diff_update_count += 1;
1500 }
1501 snapshot.is_dirty = is_dirty;
1502 snapshot.has_conflict = has_conflict;
1503
1504 excerpts_to_edit.sort_unstable_by_key(|(locator, _, _)| *locator);
1505
1506 let mut edits = Vec::new();
1507 let mut new_excerpts = SumTree::new();
1508 let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1509
1510 for (locator, buffer, buffer_edited) in excerpts_to_edit {
1511 new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
1512 let old_excerpt = cursor.item().unwrap();
1513 let buffer = buffer.read(cx);
1514 let buffer_id = buffer.remote_id();
1515
1516 let mut new_excerpt;
1517 if buffer_edited {
1518 edits.extend(
1519 buffer
1520 .edits_since_in_range::<usize>(
1521 old_excerpt.buffer.version(),
1522 old_excerpt.range.context.clone(),
1523 )
1524 .map(|mut edit| {
1525 let excerpt_old_start = cursor.start().1;
1526 let excerpt_new_start = new_excerpts.summary().text.len;
1527 edit.old.start += excerpt_old_start;
1528 edit.old.end += excerpt_old_start;
1529 edit.new.start += excerpt_new_start;
1530 edit.new.end += excerpt_new_start;
1531 edit
1532 }),
1533 );
1534
1535 new_excerpt = Excerpt::new(
1536 old_excerpt.id,
1537 locator.clone(),
1538 buffer_id,
1539 buffer.snapshot(),
1540 old_excerpt.range.clone(),
1541 old_excerpt.has_trailing_newline,
1542 );
1543 } else {
1544 new_excerpt = old_excerpt.clone();
1545 new_excerpt.buffer = buffer.snapshot();
1546 }
1547
1548 new_excerpts.push(new_excerpt, &());
1549 cursor.next(&());
1550 }
1551 new_excerpts.append(cursor.suffix(&()), &());
1552
1553 drop(cursor);
1554 snapshot.excerpts = new_excerpts;
1555
1556 self.subscriptions.publish(edits);
1557 }
1558}
1559
1560#[cfg(any(test, feature = "test-support"))]
1561impl MultiBuffer {
1562 pub fn build_simple(text: &str, cx: &mut gpui::AppContext) -> ModelHandle<Self> {
1563 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
1564 cx.add_model(|cx| Self::singleton(buffer, cx))
1565 }
1566
1567 pub fn build_multi<const COUNT: usize>(
1568 excerpts: [(&str, Vec<Range<Point>>); COUNT],
1569 cx: &mut gpui::AppContext,
1570 ) -> ModelHandle<Self> {
1571 let multi = cx.add_model(|_| Self::new(0));
1572 for (text, ranges) in excerpts {
1573 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
1574 let excerpt_ranges = ranges.into_iter().map(|range| ExcerptRange {
1575 context: range,
1576 primary: None,
1577 });
1578 multi.update(cx, |multi, cx| {
1579 multi.push_excerpts(buffer, excerpt_ranges, cx)
1580 });
1581 }
1582
1583 multi
1584 }
1585
1586 pub fn build_from_buffer(
1587 buffer: ModelHandle<Buffer>,
1588 cx: &mut gpui::AppContext,
1589 ) -> ModelHandle<Self> {
1590 cx.add_model(|cx| Self::singleton(buffer, cx))
1591 }
1592
1593 pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> ModelHandle<Self> {
1594 cx.add_model(|cx| {
1595 let mut multibuffer = MultiBuffer::new(0);
1596 let mutation_count = rng.gen_range(1..=5);
1597 multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1598 multibuffer
1599 })
1600 }
1601
1602 pub fn randomly_edit(
1603 &mut self,
1604 rng: &mut impl rand::Rng,
1605 edit_count: usize,
1606 cx: &mut ModelContext<Self>,
1607 ) {
1608 use util::RandomCharIter;
1609
1610 let snapshot = self.read(cx);
1611 let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1612 let mut last_end = None;
1613 for _ in 0..edit_count {
1614 if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1615 break;
1616 }
1617
1618 let new_start = last_end.map_or(0, |last_end| last_end + 1);
1619 let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1620 let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1621 last_end = Some(end);
1622
1623 let mut range = start..end;
1624 if rng.gen_bool(0.2) {
1625 mem::swap(&mut range.start, &mut range.end);
1626 }
1627
1628 let new_text_len = rng.gen_range(0..10);
1629 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1630
1631 edits.push((range, new_text.into()));
1632 }
1633 log::info!("mutating multi-buffer with {:?}", edits);
1634 drop(snapshot);
1635
1636 self.edit(edits, None, cx);
1637 }
1638
1639 pub fn randomly_edit_excerpts(
1640 &mut self,
1641 rng: &mut impl rand::Rng,
1642 mutation_count: usize,
1643 cx: &mut ModelContext<Self>,
1644 ) {
1645 use rand::prelude::*;
1646 use std::env;
1647 use util::RandomCharIter;
1648
1649 let max_excerpts = env::var("MAX_EXCERPTS")
1650 .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1651 .unwrap_or(5);
1652
1653 let mut buffers = Vec::new();
1654 for _ in 0..mutation_count {
1655 if rng.gen_bool(0.05) {
1656 log::info!("Clearing multi-buffer");
1657 self.clear(cx);
1658 continue;
1659 }
1660
1661 let excerpt_ids = self.excerpt_ids();
1662 if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1663 let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1664 let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1665 buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
1666 let buffer = buffers.last().unwrap().read(cx);
1667 log::info!(
1668 "Creating new buffer {} with text: {:?}",
1669 buffer.remote_id(),
1670 buffer.text()
1671 );
1672 buffers.last().unwrap().clone()
1673 } else {
1674 self.buffers
1675 .borrow()
1676 .values()
1677 .choose(rng)
1678 .unwrap()
1679 .buffer
1680 .clone()
1681 };
1682
1683 let buffer = buffer_handle.read(cx);
1684 let buffer_text = buffer.text();
1685 let ranges = (0..rng.gen_range(0..5))
1686 .map(|_| {
1687 let end_ix =
1688 buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1689 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1690 ExcerptRange {
1691 context: start_ix..end_ix,
1692 primary: None,
1693 }
1694 })
1695 .collect::<Vec<_>>();
1696 log::info!(
1697 "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
1698 buffer_handle.read(cx).remote_id(),
1699 ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
1700 ranges
1701 .iter()
1702 .map(|r| &buffer_text[r.context.clone()])
1703 .collect::<Vec<_>>()
1704 );
1705
1706 let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
1707 log::info!("Inserted with ids: {:?}", excerpt_id);
1708 } else {
1709 let remove_count = rng.gen_range(1..=excerpt_ids.len());
1710 let mut excerpts_to_remove = excerpt_ids
1711 .choose_multiple(rng, remove_count)
1712 .cloned()
1713 .collect::<Vec<_>>();
1714 let snapshot = self.snapshot.borrow();
1715 excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &*snapshot));
1716 drop(snapshot);
1717 log::info!("Removing excerpts {:?}", excerpts_to_remove);
1718 self.remove_excerpts(excerpts_to_remove, cx);
1719 }
1720 }
1721 }
1722
1723 pub fn randomly_mutate(
1724 &mut self,
1725 rng: &mut impl rand::Rng,
1726 mutation_count: usize,
1727 cx: &mut ModelContext<Self>,
1728 ) {
1729 use rand::prelude::*;
1730
1731 if rng.gen_bool(0.7) || self.singleton {
1732 let buffer = self
1733 .buffers
1734 .borrow()
1735 .values()
1736 .choose(rng)
1737 .map(|state| state.buffer.clone());
1738
1739 if let Some(buffer) = buffer {
1740 buffer.update(cx, |buffer, cx| {
1741 if rng.gen() {
1742 buffer.randomly_edit(rng, mutation_count, cx);
1743 } else {
1744 buffer.randomly_undo_redo(rng, cx);
1745 }
1746 });
1747 } else {
1748 self.randomly_edit(rng, mutation_count, cx);
1749 }
1750 } else {
1751 self.randomly_edit_excerpts(rng, mutation_count, cx);
1752 }
1753
1754 self.check_invariants(cx);
1755 }
1756
1757 fn check_invariants(&self, cx: &mut ModelContext<Self>) {
1758 let snapshot = self.read(cx);
1759 let excerpts = snapshot.excerpts.items(&());
1760 let excerpt_ids = snapshot.excerpt_ids.items(&());
1761
1762 for (ix, excerpt) in excerpts.iter().enumerate() {
1763 if ix == 0 {
1764 if excerpt.locator <= Locator::min() {
1765 panic!("invalid first excerpt locator {:?}", excerpt.locator);
1766 }
1767 } else {
1768 if excerpt.locator <= excerpts[ix - 1].locator {
1769 panic!("excerpts are out-of-order: {:?}", excerpts);
1770 }
1771 }
1772 }
1773
1774 for (ix, entry) in excerpt_ids.iter().enumerate() {
1775 if ix == 0 {
1776 if entry.id.cmp(&ExcerptId::min(), &*snapshot).is_le() {
1777 panic!("invalid first excerpt id {:?}", entry.id);
1778 }
1779 } else {
1780 if entry.id <= excerpt_ids[ix - 1].id {
1781 panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
1782 }
1783 }
1784 }
1785 }
1786}
1787
1788impl Entity for MultiBuffer {
1789 type Event = Event;
1790}
1791
1792impl MultiBufferSnapshot {
1793 pub fn text(&self) -> String {
1794 self.chunks(0..self.len(), false)
1795 .map(|chunk| chunk.text)
1796 .collect()
1797 }
1798
1799 pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1800 let mut offset = position.to_offset(self);
1801 let mut cursor = self.excerpts.cursor::<usize>();
1802 cursor.seek(&offset, Bias::Left, &());
1803 let mut excerpt_chunks = cursor.item().map(|excerpt| {
1804 let end_before_footer = cursor.start() + excerpt.text_summary.len;
1805 let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1806 let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1807 excerpt.buffer.reversed_chunks_in_range(start..end)
1808 });
1809 iter::from_fn(move || {
1810 if offset == *cursor.start() {
1811 cursor.prev(&());
1812 let excerpt = cursor.item()?;
1813 excerpt_chunks = Some(
1814 excerpt
1815 .buffer
1816 .reversed_chunks_in_range(excerpt.range.context.clone()),
1817 );
1818 }
1819
1820 let excerpt = cursor.item().unwrap();
1821 if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1822 offset -= 1;
1823 Some("\n")
1824 } else {
1825 let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1826 offset -= chunk.len();
1827 Some(chunk)
1828 }
1829 })
1830 .flat_map(|c| c.chars().rev())
1831 }
1832
1833 pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1834 let offset = position.to_offset(self);
1835 self.text_for_range(offset..self.len())
1836 .flat_map(|chunk| chunk.chars())
1837 }
1838
1839 pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
1840 self.chunks(range, false).map(|chunk| chunk.text)
1841 }
1842
1843 pub fn is_line_blank(&self, row: u32) -> bool {
1844 self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1845 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1846 }
1847
1848 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1849 where
1850 T: ToOffset,
1851 {
1852 let position = position.to_offset(self);
1853 position == self.clip_offset(position, Bias::Left)
1854 && self
1855 .bytes_in_range(position..self.len())
1856 .flatten()
1857 .copied()
1858 .take(needle.len())
1859 .eq(needle.bytes())
1860 }
1861
1862 pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1863 let mut start = start.to_offset(self);
1864 let mut end = start;
1865 let mut next_chars = self.chars_at(start).peekable();
1866 let mut prev_chars = self.reversed_chars_at(start).peekable();
1867
1868 let language = self.language_at(start);
1869 let kind = |c| char_kind(language, c);
1870 let word_kind = cmp::max(
1871 prev_chars.peek().copied().map(kind),
1872 next_chars.peek().copied().map(kind),
1873 );
1874
1875 for ch in prev_chars {
1876 if Some(kind(ch)) == word_kind && ch != '\n' {
1877 start -= ch.len_utf8();
1878 } else {
1879 break;
1880 }
1881 }
1882
1883 for ch in next_chars {
1884 if Some(kind(ch)) == word_kind && ch != '\n' {
1885 end += ch.len_utf8();
1886 } else {
1887 break;
1888 }
1889 }
1890
1891 (start..end, word_kind)
1892 }
1893
1894 pub fn as_singleton(&self) -> Option<(&ExcerptId, u64, &BufferSnapshot)> {
1895 if self.singleton {
1896 self.excerpts
1897 .iter()
1898 .next()
1899 .map(|e| (&e.id, e.buffer_id, &e.buffer))
1900 } else {
1901 None
1902 }
1903 }
1904
1905 pub fn len(&self) -> usize {
1906 self.excerpts.summary().text.len
1907 }
1908
1909 pub fn is_empty(&self) -> bool {
1910 self.excerpts.summary().text.len == 0
1911 }
1912
1913 pub fn max_buffer_row(&self) -> u32 {
1914 self.excerpts.summary().max_buffer_row
1915 }
1916
1917 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1918 if let Some((_, _, buffer)) = self.as_singleton() {
1919 return buffer.clip_offset(offset, bias);
1920 }
1921
1922 let mut cursor = self.excerpts.cursor::<usize>();
1923 cursor.seek(&offset, Bias::Right, &());
1924 let overshoot = if let Some(excerpt) = cursor.item() {
1925 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1926 let buffer_offset = excerpt
1927 .buffer
1928 .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1929 buffer_offset.saturating_sub(excerpt_start)
1930 } else {
1931 0
1932 };
1933 cursor.start() + overshoot
1934 }
1935
1936 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1937 if let Some((_, _, buffer)) = self.as_singleton() {
1938 return buffer.clip_point(point, bias);
1939 }
1940
1941 let mut cursor = self.excerpts.cursor::<Point>();
1942 cursor.seek(&point, Bias::Right, &());
1943 let overshoot = if let Some(excerpt) = cursor.item() {
1944 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
1945 let buffer_point = excerpt
1946 .buffer
1947 .clip_point(excerpt_start + (point - cursor.start()), bias);
1948 buffer_point.saturating_sub(excerpt_start)
1949 } else {
1950 Point::zero()
1951 };
1952 *cursor.start() + overshoot
1953 }
1954
1955 pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
1956 if let Some((_, _, buffer)) = self.as_singleton() {
1957 return buffer.clip_offset_utf16(offset, bias);
1958 }
1959
1960 let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
1961 cursor.seek(&offset, Bias::Right, &());
1962 let overshoot = if let Some(excerpt) = cursor.item() {
1963 let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
1964 let buffer_offset = excerpt
1965 .buffer
1966 .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
1967 OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
1968 } else {
1969 OffsetUtf16(0)
1970 };
1971 *cursor.start() + overshoot
1972 }
1973
1974 pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
1975 if let Some((_, _, buffer)) = self.as_singleton() {
1976 return buffer.clip_point_utf16(point, bias);
1977 }
1978
1979 let mut cursor = self.excerpts.cursor::<PointUtf16>();
1980 cursor.seek(&point.0, Bias::Right, &());
1981 let overshoot = if let Some(excerpt) = cursor.item() {
1982 let excerpt_start = excerpt
1983 .buffer
1984 .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
1985 let buffer_point = excerpt
1986 .buffer
1987 .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
1988 buffer_point.saturating_sub(excerpt_start)
1989 } else {
1990 PointUtf16::zero()
1991 };
1992 *cursor.start() + overshoot
1993 }
1994
1995 pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
1996 let range = range.start.to_offset(self)..range.end.to_offset(self);
1997 let mut excerpts = self.excerpts.cursor::<usize>();
1998 excerpts.seek(&range.start, Bias::Right, &());
1999
2000 let mut chunk = &[][..];
2001 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2002 let mut excerpt_bytes = excerpt
2003 .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
2004 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2005 Some(excerpt_bytes)
2006 } else {
2007 None
2008 };
2009 MultiBufferBytes {
2010 range,
2011 excerpts,
2012 excerpt_bytes,
2013 chunk,
2014 }
2015 }
2016
2017 pub fn reversed_bytes_in_range<T: ToOffset>(
2018 &self,
2019 range: Range<T>,
2020 ) -> ReversedMultiBufferBytes {
2021 let range = range.start.to_offset(self)..range.end.to_offset(self);
2022 let mut excerpts = self.excerpts.cursor::<usize>();
2023 excerpts.seek(&range.end, Bias::Left, &());
2024
2025 let mut chunk = &[][..];
2026 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2027 let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
2028 range.start - excerpts.start()..range.end - excerpts.start(),
2029 );
2030 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2031 Some(excerpt_bytes)
2032 } else {
2033 None
2034 };
2035
2036 ReversedMultiBufferBytes {
2037 range,
2038 excerpts,
2039 excerpt_bytes,
2040 chunk,
2041 }
2042 }
2043
2044 pub fn buffer_rows(&self, start_row: u32) -> MultiBufferRows {
2045 let mut result = MultiBufferRows {
2046 buffer_row_range: 0..0,
2047 excerpts: self.excerpts.cursor(),
2048 };
2049 result.seek(start_row);
2050 result
2051 }
2052
2053 pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
2054 let range = range.start.to_offset(self)..range.end.to_offset(self);
2055 let mut chunks = MultiBufferChunks {
2056 range: range.clone(),
2057 excerpts: self.excerpts.cursor(),
2058 excerpt_chunks: None,
2059 language_aware,
2060 };
2061 chunks.seek(range.start);
2062 chunks
2063 }
2064
2065 pub fn offset_to_point(&self, offset: usize) -> Point {
2066 if let Some((_, _, buffer)) = self.as_singleton() {
2067 return buffer.offset_to_point(offset);
2068 }
2069
2070 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
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(&excerpt.buffer);
2077 let buffer_point = excerpt
2078 .buffer
2079 .offset_to_point(excerpt_start_offset + overshoot);
2080 *start_point + (buffer_point - excerpt_start_point)
2081 } else {
2082 self.excerpts.summary().text.lines
2083 }
2084 }
2085
2086 pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
2087 if let Some((_, _, buffer)) = self.as_singleton() {
2088 return buffer.offset_to_point_utf16(offset);
2089 }
2090
2091 let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
2092 cursor.seek(&offset, Bias::Right, &());
2093 if let Some(excerpt) = cursor.item() {
2094 let (start_offset, start_point) = cursor.start();
2095 let overshoot = offset - start_offset;
2096 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2097 let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2098 let buffer_point = excerpt
2099 .buffer
2100 .offset_to_point_utf16(excerpt_start_offset + overshoot);
2101 *start_point + (buffer_point - excerpt_start_point)
2102 } else {
2103 self.excerpts.summary().text.lines_utf16()
2104 }
2105 }
2106
2107 pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
2108 if let Some((_, _, buffer)) = self.as_singleton() {
2109 return buffer.point_to_point_utf16(point);
2110 }
2111
2112 let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
2113 cursor.seek(&point, Bias::Right, &());
2114 if let Some(excerpt) = cursor.item() {
2115 let (start_offset, start_point) = cursor.start();
2116 let overshoot = point - start_offset;
2117 let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2118 let excerpt_start_point_utf16 =
2119 excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2120 let buffer_point = excerpt
2121 .buffer
2122 .point_to_point_utf16(excerpt_start_point + overshoot);
2123 *start_point + (buffer_point - excerpt_start_point_utf16)
2124 } else {
2125 self.excerpts.summary().text.lines_utf16()
2126 }
2127 }
2128
2129 pub fn point_to_offset(&self, point: Point) -> usize {
2130 if let Some((_, _, buffer)) = self.as_singleton() {
2131 return buffer.point_to_offset(point);
2132 }
2133
2134 let mut cursor = self.excerpts.cursor::<(Point, usize)>();
2135 cursor.seek(&point, Bias::Right, &());
2136 if let Some(excerpt) = cursor.item() {
2137 let (start_point, start_offset) = cursor.start();
2138 let overshoot = point - start_point;
2139 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2140 let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2141 let buffer_offset = excerpt
2142 .buffer
2143 .point_to_offset(excerpt_start_point + overshoot);
2144 *start_offset + buffer_offset - excerpt_start_offset
2145 } else {
2146 self.excerpts.summary().text.len
2147 }
2148 }
2149
2150 pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2151 if let Some((_, _, buffer)) = self.as_singleton() {
2152 return buffer.offset_utf16_to_offset(offset_utf16);
2153 }
2154
2155 let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2156 cursor.seek(&offset_utf16, Bias::Right, &());
2157 if let Some(excerpt) = cursor.item() {
2158 let (start_offset_utf16, start_offset) = cursor.start();
2159 let overshoot = offset_utf16 - start_offset_utf16;
2160 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2161 let excerpt_start_offset_utf16 =
2162 excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2163 let buffer_offset = excerpt
2164 .buffer
2165 .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2166 *start_offset + (buffer_offset - excerpt_start_offset)
2167 } else {
2168 self.excerpts.summary().text.len
2169 }
2170 }
2171
2172 pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2173 if let Some((_, _, buffer)) = self.as_singleton() {
2174 return buffer.offset_to_offset_utf16(offset);
2175 }
2176
2177 let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2178 cursor.seek(&offset, Bias::Right, &());
2179 if let Some(excerpt) = cursor.item() {
2180 let (start_offset, start_offset_utf16) = cursor.start();
2181 let overshoot = offset - start_offset;
2182 let excerpt_start_offset_utf16 =
2183 excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2184 let excerpt_start_offset = excerpt
2185 .buffer
2186 .offset_utf16_to_offset(excerpt_start_offset_utf16);
2187 let buffer_offset_utf16 = excerpt
2188 .buffer
2189 .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2190 *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2191 } else {
2192 self.excerpts.summary().text.len_utf16
2193 }
2194 }
2195
2196 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2197 if let Some((_, _, buffer)) = self.as_singleton() {
2198 return buffer.point_utf16_to_offset(point);
2199 }
2200
2201 let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2202 cursor.seek(&point, Bias::Right, &());
2203 if let Some(excerpt) = cursor.item() {
2204 let (start_point, start_offset) = cursor.start();
2205 let overshoot = point - start_point;
2206 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2207 let excerpt_start_point = excerpt
2208 .buffer
2209 .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2210 let buffer_offset = excerpt
2211 .buffer
2212 .point_utf16_to_offset(excerpt_start_point + overshoot);
2213 *start_offset + (buffer_offset - excerpt_start_offset)
2214 } else {
2215 self.excerpts.summary().text.len
2216 }
2217 }
2218
2219 pub fn point_to_buffer_offset<T: ToOffset>(
2220 &self,
2221 point: T,
2222 ) -> Option<(&BufferSnapshot, usize)> {
2223 let offset = point.to_offset(&self);
2224 let mut cursor = self.excerpts.cursor::<usize>();
2225 cursor.seek(&offset, Bias::Right, &());
2226 if cursor.item().is_none() {
2227 cursor.prev(&());
2228 }
2229
2230 cursor.item().map(|excerpt| {
2231 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2232 let buffer_point = excerpt_start + offset - *cursor.start();
2233 (&excerpt.buffer, buffer_point)
2234 })
2235 }
2236
2237 pub fn suggested_indents(
2238 &self,
2239 rows: impl IntoIterator<Item = u32>,
2240 cx: &AppContext,
2241 ) -> BTreeMap<u32, IndentSize> {
2242 let mut result = BTreeMap::new();
2243
2244 let mut rows_for_excerpt = Vec::new();
2245 let mut cursor = self.excerpts.cursor::<Point>();
2246 let mut rows = rows.into_iter().peekable();
2247 let mut prev_row = u32::MAX;
2248 let mut prev_language_indent_size = IndentSize::default();
2249
2250 while let Some(row) = rows.next() {
2251 cursor.seek(&Point::new(row, 0), Bias::Right, &());
2252 let excerpt = match cursor.item() {
2253 Some(excerpt) => excerpt,
2254 _ => continue,
2255 };
2256
2257 // Retrieve the language and indent size once for each disjoint region being indented.
2258 let single_indent_size = if row.saturating_sub(1) == prev_row {
2259 prev_language_indent_size
2260 } else {
2261 excerpt
2262 .buffer
2263 .language_indent_size_at(Point::new(row, 0), cx)
2264 };
2265 prev_language_indent_size = single_indent_size;
2266 prev_row = row;
2267
2268 let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2269 let start_multibuffer_row = cursor.start().row;
2270
2271 rows_for_excerpt.push(row);
2272 while let Some(next_row) = rows.peek().copied() {
2273 if cursor.end(&()).row > next_row {
2274 rows_for_excerpt.push(next_row);
2275 rows.next();
2276 } else {
2277 break;
2278 }
2279 }
2280
2281 let buffer_rows = rows_for_excerpt
2282 .drain(..)
2283 .map(|row| start_buffer_row + row - start_multibuffer_row);
2284 let buffer_indents = excerpt
2285 .buffer
2286 .suggested_indents(buffer_rows, single_indent_size);
2287 let multibuffer_indents = buffer_indents
2288 .into_iter()
2289 .map(|(row, indent)| (start_multibuffer_row + row - start_buffer_row, indent));
2290 result.extend(multibuffer_indents);
2291 }
2292
2293 result
2294 }
2295
2296 pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2297 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2298 let mut size = buffer.indent_size_for_line(range.start.row);
2299 size.len = size
2300 .len
2301 .min(range.end.column)
2302 .saturating_sub(range.start.column);
2303 size
2304 } else {
2305 IndentSize::spaces(0)
2306 }
2307 }
2308
2309 pub fn line_len(&self, row: u32) -> u32 {
2310 if let Some((_, range)) = self.buffer_line_for_row(row) {
2311 range.end.column - range.start.column
2312 } else {
2313 0
2314 }
2315 }
2316
2317 pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
2318 let mut cursor = self.excerpts.cursor::<Point>();
2319 let point = Point::new(row, 0);
2320 cursor.seek(&point, Bias::Right, &());
2321 if cursor.item().is_none() && *cursor.start() == point {
2322 cursor.prev(&());
2323 }
2324 if let Some(excerpt) = cursor.item() {
2325 let overshoot = row - cursor.start().row;
2326 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2327 let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2328 let buffer_row = excerpt_start.row + overshoot;
2329 let line_start = Point::new(buffer_row, 0);
2330 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2331 return Some((
2332 &excerpt.buffer,
2333 line_start.max(excerpt_start)..line_end.min(excerpt_end),
2334 ));
2335 }
2336 None
2337 }
2338
2339 pub fn max_point(&self) -> Point {
2340 self.text_summary().lines
2341 }
2342
2343 pub fn text_summary(&self) -> TextSummary {
2344 self.excerpts.summary().text.clone()
2345 }
2346
2347 pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2348 where
2349 D: TextDimension,
2350 O: ToOffset,
2351 {
2352 let mut summary = D::default();
2353 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2354 let mut cursor = self.excerpts.cursor::<usize>();
2355 cursor.seek(&range.start, Bias::Right, &());
2356 if let Some(excerpt) = cursor.item() {
2357 let mut end_before_newline = cursor.end(&());
2358 if excerpt.has_trailing_newline {
2359 end_before_newline -= 1;
2360 }
2361
2362 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2363 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2364 let end_in_excerpt =
2365 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2366 summary.add_assign(
2367 &excerpt
2368 .buffer
2369 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2370 );
2371
2372 if range.end > end_before_newline {
2373 summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2374 }
2375
2376 cursor.next(&());
2377 }
2378
2379 if range.end > *cursor.start() {
2380 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2381 &range.end,
2382 Bias::Right,
2383 &(),
2384 )));
2385 if let Some(excerpt) = cursor.item() {
2386 range.end = cmp::max(*cursor.start(), range.end);
2387
2388 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2389 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2390 summary.add_assign(
2391 &excerpt
2392 .buffer
2393 .text_summary_for_range(excerpt_start..end_in_excerpt),
2394 );
2395 }
2396 }
2397
2398 summary
2399 }
2400
2401 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2402 where
2403 D: TextDimension + Ord + Sub<D, Output = D>,
2404 {
2405 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2406 let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2407
2408 cursor.seek(locator, Bias::Left, &());
2409 if cursor.item().is_none() {
2410 cursor.next(&());
2411 }
2412
2413 let mut position = D::from_text_summary(&cursor.start().text);
2414 if let Some(excerpt) = cursor.item() {
2415 if excerpt.id == anchor.excerpt_id {
2416 let excerpt_buffer_start =
2417 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2418 let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2419 let buffer_position = cmp::min(
2420 excerpt_buffer_end,
2421 anchor.text_anchor.summary::<D>(&excerpt.buffer),
2422 );
2423 if buffer_position > excerpt_buffer_start {
2424 position.add_assign(&(buffer_position - excerpt_buffer_start));
2425 }
2426 }
2427 }
2428 position
2429 }
2430
2431 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2432 where
2433 D: TextDimension + Ord + Sub<D, Output = D>,
2434 I: 'a + IntoIterator<Item = &'a Anchor>,
2435 {
2436 if let Some((_, _, buffer)) = self.as_singleton() {
2437 return buffer
2438 .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2439 .collect();
2440 }
2441
2442 let mut anchors = anchors.into_iter().peekable();
2443 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2444 let mut summaries = Vec::new();
2445 while let Some(anchor) = anchors.peek() {
2446 let excerpt_id = anchor.excerpt_id;
2447 let excerpt_anchors = iter::from_fn(|| {
2448 let anchor = anchors.peek()?;
2449 if anchor.excerpt_id == excerpt_id {
2450 Some(&anchors.next().unwrap().text_anchor)
2451 } else {
2452 None
2453 }
2454 });
2455
2456 let locator = self.excerpt_locator_for_id(excerpt_id);
2457 cursor.seek_forward(locator, Bias::Left, &());
2458 if cursor.item().is_none() {
2459 cursor.next(&());
2460 }
2461
2462 let position = D::from_text_summary(&cursor.start().text);
2463 if let Some(excerpt) = cursor.item() {
2464 if excerpt.id == excerpt_id {
2465 let excerpt_buffer_start =
2466 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2467 let excerpt_buffer_end =
2468 excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2469 summaries.extend(
2470 excerpt
2471 .buffer
2472 .summaries_for_anchors::<D, _>(excerpt_anchors)
2473 .map(move |summary| {
2474 let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2475 let mut position = position.clone();
2476 let excerpt_buffer_start = excerpt_buffer_start.clone();
2477 if summary > excerpt_buffer_start {
2478 position.add_assign(&(summary - excerpt_buffer_start));
2479 }
2480 position
2481 }),
2482 );
2483 continue;
2484 }
2485 }
2486
2487 summaries.extend(excerpt_anchors.map(|_| position.clone()));
2488 }
2489
2490 summaries
2491 }
2492
2493 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2494 where
2495 I: 'a + IntoIterator<Item = &'a Anchor>,
2496 {
2497 let mut anchors = anchors.into_iter().enumerate().peekable();
2498 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2499 cursor.next(&());
2500
2501 let mut result = Vec::new();
2502
2503 while let Some((_, anchor)) = anchors.peek() {
2504 let old_excerpt_id = anchor.excerpt_id;
2505
2506 // Find the location where this anchor's excerpt should be.
2507 let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2508 cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2509
2510 if cursor.item().is_none() {
2511 cursor.next(&());
2512 }
2513
2514 let next_excerpt = cursor.item();
2515 let prev_excerpt = cursor.prev_item();
2516
2517 // Process all of the anchors for this excerpt.
2518 while let Some((_, anchor)) = anchors.peek() {
2519 if anchor.excerpt_id != old_excerpt_id {
2520 break;
2521 }
2522 let (anchor_ix, anchor) = anchors.next().unwrap();
2523 let mut anchor = *anchor;
2524
2525 // Leave min and max anchors unchanged if invalid or
2526 // if the old excerpt still exists at this location
2527 let mut kept_position = next_excerpt
2528 .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2529 || old_excerpt_id == ExcerptId::max()
2530 || old_excerpt_id == ExcerptId::min();
2531
2532 // If the old excerpt no longer exists at this location, then attempt to
2533 // find an equivalent position for this anchor in an adjacent excerpt.
2534 if !kept_position {
2535 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2536 if excerpt.contains(&anchor) {
2537 anchor.excerpt_id = excerpt.id.clone();
2538 kept_position = true;
2539 break;
2540 }
2541 }
2542 }
2543
2544 // If there's no adjacent excerpt that contains the anchor's position,
2545 // then report that the anchor has lost its position.
2546 if !kept_position {
2547 anchor = if let Some(excerpt) = next_excerpt {
2548 let mut text_anchor = excerpt
2549 .range
2550 .context
2551 .start
2552 .bias(anchor.text_anchor.bias, &excerpt.buffer);
2553 if text_anchor
2554 .cmp(&excerpt.range.context.end, &excerpt.buffer)
2555 .is_gt()
2556 {
2557 text_anchor = excerpt.range.context.end;
2558 }
2559 Anchor {
2560 buffer_id: Some(excerpt.buffer_id),
2561 excerpt_id: excerpt.id.clone(),
2562 text_anchor,
2563 }
2564 } else if let Some(excerpt) = prev_excerpt {
2565 let mut text_anchor = excerpt
2566 .range
2567 .context
2568 .end
2569 .bias(anchor.text_anchor.bias, &excerpt.buffer);
2570 if text_anchor
2571 .cmp(&excerpt.range.context.start, &excerpt.buffer)
2572 .is_lt()
2573 {
2574 text_anchor = excerpt.range.context.start;
2575 }
2576 Anchor {
2577 buffer_id: Some(excerpt.buffer_id),
2578 excerpt_id: excerpt.id.clone(),
2579 text_anchor,
2580 }
2581 } else if anchor.text_anchor.bias == Bias::Left {
2582 Anchor::min()
2583 } else {
2584 Anchor::max()
2585 };
2586 }
2587
2588 result.push((anchor_ix, anchor, kept_position));
2589 }
2590 }
2591 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2592 result
2593 }
2594
2595 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2596 self.anchor_at(position, Bias::Left)
2597 }
2598
2599 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2600 self.anchor_at(position, Bias::Right)
2601 }
2602
2603 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2604 let offset = position.to_offset(self);
2605 if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2606 return Anchor {
2607 buffer_id: Some(buffer_id),
2608 excerpt_id: excerpt_id.clone(),
2609 text_anchor: buffer.anchor_at(offset, bias),
2610 };
2611 }
2612
2613 let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2614 cursor.seek(&offset, Bias::Right, &());
2615 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2616 cursor.prev(&());
2617 }
2618 if let Some(excerpt) = cursor.item() {
2619 let mut overshoot = offset.saturating_sub(cursor.start().0);
2620 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2621 overshoot -= 1;
2622 bias = Bias::Right;
2623 }
2624
2625 let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2626 let text_anchor =
2627 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2628 Anchor {
2629 buffer_id: Some(excerpt.buffer_id),
2630 excerpt_id: excerpt.id.clone(),
2631 text_anchor,
2632 }
2633 } else if offset == 0 && bias == Bias::Left {
2634 Anchor::min()
2635 } else {
2636 Anchor::max()
2637 }
2638 }
2639
2640 pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
2641 let locator = self.excerpt_locator_for_id(excerpt_id);
2642 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2643 cursor.seek(locator, Bias::Left, &());
2644 if let Some(excerpt) = cursor.item() {
2645 if excerpt.id == excerpt_id {
2646 let text_anchor = excerpt.clip_anchor(text_anchor);
2647 drop(cursor);
2648 return Anchor {
2649 buffer_id: Some(excerpt.buffer_id),
2650 excerpt_id,
2651 text_anchor,
2652 };
2653 }
2654 }
2655 panic!("excerpt not found");
2656 }
2657
2658 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2659 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2660 true
2661 } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
2662 excerpt.buffer.can_resolve(&anchor.text_anchor)
2663 } else {
2664 false
2665 }
2666 }
2667
2668 pub fn excerpts(
2669 &self,
2670 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
2671 self.excerpts
2672 .iter()
2673 .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
2674 }
2675
2676 pub fn excerpt_boundaries_in_range<R, T>(
2677 &self,
2678 range: R,
2679 ) -> impl Iterator<Item = ExcerptBoundary> + '_
2680 where
2681 R: RangeBounds<T>,
2682 T: ToOffset,
2683 {
2684 let start_offset;
2685 let start = match range.start_bound() {
2686 Bound::Included(start) => {
2687 start_offset = start.to_offset(self);
2688 Bound::Included(start_offset)
2689 }
2690 Bound::Excluded(start) => {
2691 start_offset = start.to_offset(self);
2692 Bound::Excluded(start_offset)
2693 }
2694 Bound::Unbounded => {
2695 start_offset = 0;
2696 Bound::Unbounded
2697 }
2698 };
2699 let end = match range.end_bound() {
2700 Bound::Included(end) => Bound::Included(end.to_offset(self)),
2701 Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2702 Bound::Unbounded => Bound::Unbounded,
2703 };
2704 let bounds = (start, end);
2705
2706 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2707 cursor.seek(&start_offset, Bias::Right, &());
2708 if cursor.item().is_none() {
2709 cursor.prev(&());
2710 }
2711 if !bounds.contains(&cursor.start().0) {
2712 cursor.next(&());
2713 }
2714
2715 let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2716 std::iter::from_fn(move || {
2717 if self.singleton {
2718 None
2719 } else if bounds.contains(&cursor.start().0) {
2720 let excerpt = cursor.item()?;
2721 let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2722 let boundary = ExcerptBoundary {
2723 id: excerpt.id.clone(),
2724 row: cursor.start().1.row,
2725 buffer: excerpt.buffer.clone(),
2726 range: excerpt.range.clone(),
2727 starts_new_buffer,
2728 };
2729
2730 prev_buffer_id = Some(excerpt.buffer_id);
2731 cursor.next(&());
2732 Some(boundary)
2733 } else {
2734 None
2735 }
2736 })
2737 }
2738
2739 pub fn edit_count(&self) -> usize {
2740 self.edit_count
2741 }
2742
2743 pub fn parse_count(&self) -> usize {
2744 self.parse_count
2745 }
2746
2747 /// Returns the smallest enclosing bracket ranges containing the given range or
2748 /// None if no brackets contain range or the range is not contained in a single
2749 /// excerpt
2750 pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
2751 &self,
2752 range: Range<T>,
2753 ) -> Option<(Range<usize>, Range<usize>)> {
2754 let range = range.start.to_offset(self)..range.end.to_offset(self);
2755
2756 // Get the ranges of the innermost pair of brackets.
2757 let mut result: Option<(Range<usize>, Range<usize>)> = None;
2758
2759 let Some(enclosing_bracket_ranges) = self.enclosing_bracket_ranges(range.clone()) else {
2760 return None;
2761 };
2762
2763 for (open, close) in enclosing_bracket_ranges {
2764 let len = close.end - open.start;
2765
2766 if let Some((existing_open, existing_close)) = &result {
2767 let existing_len = existing_close.end - existing_open.start;
2768 if len > existing_len {
2769 continue;
2770 }
2771 }
2772
2773 result = Some((open, close));
2774 }
2775
2776 result
2777 }
2778
2779 /// Returns enclosing bracket ranges containing the given range or returns None if the range is
2780 /// not contained in a single excerpt
2781 pub fn enclosing_bracket_ranges<'a, T: ToOffset>(
2782 &'a self,
2783 range: Range<T>,
2784 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2785 let range = range.start.to_offset(self)..range.end.to_offset(self);
2786
2787 self.bracket_ranges(range.clone()).map(|range_pairs| {
2788 range_pairs
2789 .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
2790 })
2791 }
2792
2793 /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
2794 /// not contained in a single excerpt
2795 pub fn bracket_ranges<'a, T: ToOffset>(
2796 &'a self,
2797 range: Range<T>,
2798 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2799 let range = range.start.to_offset(self)..range.end.to_offset(self);
2800 let excerpt = self.excerpt_containing(range.clone());
2801 excerpt.map(|(excerpt, excerpt_offset)| {
2802 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2803 let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2804
2805 let start_in_buffer = excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2806 let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2807
2808 excerpt
2809 .buffer
2810 .bracket_ranges(start_in_buffer..end_in_buffer)
2811 .filter_map(move |(start_bracket_range, end_bracket_range)| {
2812 if start_bracket_range.start < excerpt_buffer_start
2813 || end_bracket_range.end > excerpt_buffer_end
2814 {
2815 return None;
2816 }
2817
2818 let mut start_bracket_range = start_bracket_range.clone();
2819 start_bracket_range.start =
2820 excerpt_offset + (start_bracket_range.start - excerpt_buffer_start);
2821 start_bracket_range.end =
2822 excerpt_offset + (start_bracket_range.end - excerpt_buffer_start);
2823
2824 let mut end_bracket_range = end_bracket_range.clone();
2825 end_bracket_range.start =
2826 excerpt_offset + (end_bracket_range.start - excerpt_buffer_start);
2827 end_bracket_range.end =
2828 excerpt_offset + (end_bracket_range.end - excerpt_buffer_start);
2829 Some((start_bracket_range, end_bracket_range))
2830 })
2831 })
2832 }
2833
2834 pub fn diagnostics_update_count(&self) -> usize {
2835 self.diagnostics_update_count
2836 }
2837
2838 pub fn git_diff_update_count(&self) -> usize {
2839 self.git_diff_update_count
2840 }
2841
2842 pub fn trailing_excerpt_update_count(&self) -> usize {
2843 self.trailing_excerpt_update_count
2844 }
2845
2846 pub fn file_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<dyn File>> {
2847 self.point_to_buffer_offset(point)
2848 .and_then(|(buffer, _)| buffer.file())
2849 }
2850
2851 pub fn language_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<Language>> {
2852 self.point_to_buffer_offset(point)
2853 .and_then(|(buffer, offset)| buffer.language_at(offset))
2854 }
2855
2856 pub fn settings_at<'a, T: ToOffset>(
2857 &'a self,
2858 point: T,
2859 cx: &'a AppContext,
2860 ) -> &'a LanguageSettings {
2861 let mut language = None;
2862 let mut file = None;
2863 if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
2864 language = buffer.language_at(offset);
2865 file = buffer.file();
2866 }
2867 language_settings(language, file, cx)
2868 }
2869
2870 pub fn language_scope_at<'a, T: ToOffset>(&'a self, point: T) -> Option<LanguageScope> {
2871 self.point_to_buffer_offset(point)
2872 .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
2873 }
2874
2875 pub fn language_indent_size_at<T: ToOffset>(
2876 &self,
2877 position: T,
2878 cx: &AppContext,
2879 ) -> Option<IndentSize> {
2880 let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
2881 Some(buffer_snapshot.language_indent_size_at(offset, cx))
2882 }
2883
2884 pub fn is_dirty(&self) -> bool {
2885 self.is_dirty
2886 }
2887
2888 pub fn has_conflict(&self) -> bool {
2889 self.has_conflict
2890 }
2891
2892 pub fn diagnostic_group<'a, O>(
2893 &'a self,
2894 group_id: usize,
2895 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2896 where
2897 O: text::FromAnchor + 'a,
2898 {
2899 self.as_singleton()
2900 .into_iter()
2901 .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2902 }
2903
2904 pub fn diagnostics_in_range<'a, T, O>(
2905 &'a self,
2906 range: Range<T>,
2907 reversed: bool,
2908 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2909 where
2910 T: 'a + ToOffset,
2911 O: 'a + text::FromAnchor + Ord,
2912 {
2913 self.as_singleton()
2914 .into_iter()
2915 .flat_map(move |(_, _, buffer)| {
2916 buffer.diagnostics_in_range(
2917 range.start.to_offset(self)..range.end.to_offset(self),
2918 reversed,
2919 )
2920 })
2921 }
2922
2923 pub fn has_git_diffs(&self) -> bool {
2924 for excerpt in self.excerpts.iter() {
2925 if !excerpt.buffer.git_diff.is_empty() {
2926 return true;
2927 }
2928 }
2929 false
2930 }
2931
2932 pub fn git_diff_hunks_in_range_rev<'a>(
2933 &'a self,
2934 row_range: Range<u32>,
2935 ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2936 let mut cursor = self.excerpts.cursor::<Point>();
2937
2938 cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
2939 if cursor.item().is_none() {
2940 cursor.prev(&());
2941 }
2942
2943 std::iter::from_fn(move || {
2944 let excerpt = cursor.item()?;
2945 let multibuffer_start = *cursor.start();
2946 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2947 if multibuffer_start.row >= row_range.end {
2948 return None;
2949 }
2950
2951 let mut buffer_start = excerpt.range.context.start;
2952 let mut buffer_end = excerpt.range.context.end;
2953 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
2954 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
2955
2956 if row_range.start > multibuffer_start.row {
2957 let buffer_start_point =
2958 excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
2959 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
2960 }
2961
2962 if row_range.end < multibuffer_end.row {
2963 let buffer_end_point =
2964 excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
2965 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
2966 }
2967
2968 let buffer_hunks = excerpt
2969 .buffer
2970 .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
2971 .filter_map(move |hunk| {
2972 let start = multibuffer_start.row
2973 + hunk
2974 .buffer_range
2975 .start
2976 .saturating_sub(excerpt_start_point.row);
2977 let end = multibuffer_start.row
2978 + hunk
2979 .buffer_range
2980 .end
2981 .min(excerpt_end_point.row + 1)
2982 .saturating_sub(excerpt_start_point.row);
2983
2984 Some(DiffHunk {
2985 buffer_range: start..end,
2986 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
2987 })
2988 });
2989
2990 cursor.prev(&());
2991
2992 Some(buffer_hunks)
2993 })
2994 .flatten()
2995 }
2996
2997 pub fn git_diff_hunks_in_range<'a>(
2998 &'a self,
2999 row_range: Range<u32>,
3000 ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
3001 let mut cursor = self.excerpts.cursor::<Point>();
3002
3003 cursor.seek(&Point::new(row_range.start, 0), Bias::Right, &());
3004
3005 std::iter::from_fn(move || {
3006 let excerpt = cursor.item()?;
3007 let multibuffer_start = *cursor.start();
3008 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3009 if multibuffer_start.row >= row_range.end {
3010 return None;
3011 }
3012
3013 let mut buffer_start = excerpt.range.context.start;
3014 let mut buffer_end = excerpt.range.context.end;
3015 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3016 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3017
3018 if row_range.start > multibuffer_start.row {
3019 let buffer_start_point =
3020 excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
3021 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3022 }
3023
3024 if row_range.end < multibuffer_end.row {
3025 let buffer_end_point =
3026 excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
3027 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3028 }
3029
3030 let buffer_hunks = excerpt
3031 .buffer
3032 .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3033 .filter_map(move |hunk| {
3034 let start = multibuffer_start.row
3035 + hunk
3036 .buffer_range
3037 .start
3038 .saturating_sub(excerpt_start_point.row);
3039 let end = multibuffer_start.row
3040 + hunk
3041 .buffer_range
3042 .end
3043 .min(excerpt_end_point.row + 1)
3044 .saturating_sub(excerpt_start_point.row);
3045
3046 Some(DiffHunk {
3047 buffer_range: start..end,
3048 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3049 })
3050 });
3051
3052 cursor.next(&());
3053
3054 Some(buffer_hunks)
3055 })
3056 .flatten()
3057 }
3058
3059 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3060 let range = range.start.to_offset(self)..range.end.to_offset(self);
3061
3062 self.excerpt_containing(range.clone())
3063 .and_then(|(excerpt, excerpt_offset)| {
3064 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3065 let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
3066
3067 let start_in_buffer =
3068 excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
3069 let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
3070 let mut ancestor_buffer_range = excerpt
3071 .buffer
3072 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
3073 ancestor_buffer_range.start =
3074 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
3075 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
3076
3077 let start = excerpt_offset + (ancestor_buffer_range.start - excerpt_buffer_start);
3078 let end = excerpt_offset + (ancestor_buffer_range.end - excerpt_buffer_start);
3079 Some(start..end)
3080 })
3081 }
3082
3083 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3084 let (excerpt_id, _, buffer) = self.as_singleton()?;
3085 let outline = buffer.outline(theme)?;
3086 Some(Outline::new(
3087 outline
3088 .items
3089 .into_iter()
3090 .map(|item| OutlineItem {
3091 depth: item.depth,
3092 range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
3093 ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
3094 text: item.text,
3095 highlight_ranges: item.highlight_ranges,
3096 name_ranges: item.name_ranges,
3097 })
3098 .collect(),
3099 ))
3100 }
3101
3102 pub fn symbols_containing<T: ToOffset>(
3103 &self,
3104 offset: T,
3105 theme: Option<&SyntaxTheme>,
3106 ) -> Option<(u64, Vec<OutlineItem<Anchor>>)> {
3107 let anchor = self.anchor_before(offset);
3108 let excerpt_id = anchor.excerpt_id();
3109 let excerpt = self.excerpt(excerpt_id)?;
3110 Some((
3111 excerpt.buffer_id,
3112 excerpt
3113 .buffer
3114 .symbols_containing(anchor.text_anchor, theme)
3115 .into_iter()
3116 .flatten()
3117 .map(|item| OutlineItem {
3118 depth: item.depth,
3119 range: self.anchor_in_excerpt(excerpt_id, item.range.start)
3120 ..self.anchor_in_excerpt(excerpt_id, item.range.end),
3121 text: item.text,
3122 highlight_ranges: item.highlight_ranges,
3123 name_ranges: item.name_ranges,
3124 })
3125 .collect(),
3126 ))
3127 }
3128
3129 fn excerpt_locator_for_id<'a>(&'a self, id: ExcerptId) -> &'a Locator {
3130 if id == ExcerptId::min() {
3131 Locator::min_ref()
3132 } else if id == ExcerptId::max() {
3133 Locator::max_ref()
3134 } else {
3135 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3136 cursor.seek(&id, Bias::Left, &());
3137 if let Some(entry) = cursor.item() {
3138 if entry.id == id {
3139 return &entry.locator;
3140 }
3141 }
3142 panic!("invalid excerpt id {:?}", id)
3143 }
3144 }
3145
3146 pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<u64> {
3147 Some(self.excerpt(excerpt_id)?.buffer_id)
3148 }
3149
3150 pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3151 Some(&self.excerpt(excerpt_id)?.buffer)
3152 }
3153
3154 fn excerpt<'a>(&'a self, excerpt_id: ExcerptId) -> Option<&'a Excerpt> {
3155 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3156 let locator = self.excerpt_locator_for_id(excerpt_id);
3157 cursor.seek(&Some(locator), Bias::Left, &());
3158 if let Some(excerpt) = cursor.item() {
3159 if excerpt.id == excerpt_id {
3160 return Some(excerpt);
3161 }
3162 }
3163 None
3164 }
3165
3166 /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3167 fn excerpt_containing<'a, T: ToOffset>(
3168 &'a self,
3169 range: Range<T>,
3170 ) -> Option<(&'a Excerpt, usize)> {
3171 let range = range.start.to_offset(self)..range.end.to_offset(self);
3172
3173 let mut cursor = self.excerpts.cursor::<usize>();
3174 cursor.seek(&range.start, Bias::Right, &());
3175 let start_excerpt = cursor.item();
3176
3177 if range.start == range.end {
3178 return start_excerpt.map(|excerpt| (excerpt, *cursor.start()));
3179 }
3180
3181 cursor.seek(&range.end, Bias::Right, &());
3182 let end_excerpt = cursor.item();
3183
3184 start_excerpt
3185 .zip(end_excerpt)
3186 .and_then(|(start_excerpt, end_excerpt)| {
3187 if start_excerpt.id != end_excerpt.id {
3188 return None;
3189 }
3190
3191 Some((start_excerpt, *cursor.start()))
3192 })
3193 }
3194
3195 pub fn remote_selections_in_range<'a>(
3196 &'a self,
3197 range: &'a Range<Anchor>,
3198 ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3199 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3200 let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3201 let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3202 cursor.seek(start_locator, Bias::Left, &());
3203 cursor
3204 .take_while(move |excerpt| excerpt.locator <= *end_locator)
3205 .flat_map(move |excerpt| {
3206 let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3207 if excerpt.id == range.start.excerpt_id {
3208 query_range.start = range.start.text_anchor;
3209 }
3210 if excerpt.id == range.end.excerpt_id {
3211 query_range.end = range.end.text_anchor;
3212 }
3213
3214 excerpt
3215 .buffer
3216 .remote_selections_in_range(query_range)
3217 .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3218 selections.map(move |selection| {
3219 let mut start = Anchor {
3220 buffer_id: Some(excerpt.buffer_id),
3221 excerpt_id: excerpt.id.clone(),
3222 text_anchor: selection.start,
3223 };
3224 let mut end = Anchor {
3225 buffer_id: Some(excerpt.buffer_id),
3226 excerpt_id: excerpt.id.clone(),
3227 text_anchor: selection.end,
3228 };
3229 if range.start.cmp(&start, self).is_gt() {
3230 start = range.start.clone();
3231 }
3232 if range.end.cmp(&end, self).is_lt() {
3233 end = range.end.clone();
3234 }
3235
3236 (
3237 replica_id,
3238 line_mode,
3239 cursor_shape,
3240 Selection {
3241 id: selection.id,
3242 start,
3243 end,
3244 reversed: selection.reversed,
3245 goal: selection.goal,
3246 },
3247 )
3248 })
3249 })
3250 })
3251 }
3252}
3253
3254#[cfg(any(test, feature = "test-support"))]
3255impl MultiBufferSnapshot {
3256 pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3257 let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3258 let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3259 start..end
3260 }
3261}
3262
3263impl History {
3264 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3265 self.transaction_depth += 1;
3266 if self.transaction_depth == 1 {
3267 let id = self.next_transaction_id.tick();
3268 self.undo_stack.push(Transaction {
3269 id,
3270 buffer_transactions: Default::default(),
3271 first_edit_at: now,
3272 last_edit_at: now,
3273 suppress_grouping: false,
3274 });
3275 Some(id)
3276 } else {
3277 None
3278 }
3279 }
3280
3281 fn end_transaction(
3282 &mut self,
3283 now: Instant,
3284 buffer_transactions: HashMap<u64, TransactionId>,
3285 ) -> bool {
3286 assert_ne!(self.transaction_depth, 0);
3287 self.transaction_depth -= 1;
3288 if self.transaction_depth == 0 {
3289 if buffer_transactions.is_empty() {
3290 self.undo_stack.pop();
3291 false
3292 } else {
3293 self.redo_stack.clear();
3294 let transaction = self.undo_stack.last_mut().unwrap();
3295 transaction.last_edit_at = now;
3296 for (buffer_id, transaction_id) in buffer_transactions {
3297 transaction
3298 .buffer_transactions
3299 .entry(buffer_id)
3300 .or_insert(transaction_id);
3301 }
3302 true
3303 }
3304 } else {
3305 false
3306 }
3307 }
3308
3309 fn push_transaction<'a, T>(
3310 &mut self,
3311 buffer_transactions: T,
3312 now: Instant,
3313 cx: &mut ModelContext<MultiBuffer>,
3314 ) where
3315 T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
3316 {
3317 assert_eq!(self.transaction_depth, 0);
3318 let transaction = Transaction {
3319 id: self.next_transaction_id.tick(),
3320 buffer_transactions: buffer_transactions
3321 .into_iter()
3322 .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3323 .collect(),
3324 first_edit_at: now,
3325 last_edit_at: now,
3326 suppress_grouping: false,
3327 };
3328 if !transaction.buffer_transactions.is_empty() {
3329 self.undo_stack.push(transaction);
3330 self.redo_stack.clear();
3331 }
3332 }
3333
3334 fn finalize_last_transaction(&mut self) {
3335 if let Some(transaction) = self.undo_stack.last_mut() {
3336 transaction.suppress_grouping = true;
3337 }
3338 }
3339
3340 fn pop_undo(&mut self) -> Option<&mut Transaction> {
3341 assert_eq!(self.transaction_depth, 0);
3342 if let Some(transaction) = self.undo_stack.pop() {
3343 self.redo_stack.push(transaction);
3344 self.redo_stack.last_mut()
3345 } else {
3346 None
3347 }
3348 }
3349
3350 fn pop_redo(&mut self) -> Option<&mut Transaction> {
3351 assert_eq!(self.transaction_depth, 0);
3352 if let Some(transaction) = self.redo_stack.pop() {
3353 self.undo_stack.push(transaction);
3354 self.undo_stack.last_mut()
3355 } else {
3356 None
3357 }
3358 }
3359
3360 fn group(&mut self) -> Option<TransactionId> {
3361 let mut count = 0;
3362 let mut transactions = self.undo_stack.iter();
3363 if let Some(mut transaction) = transactions.next_back() {
3364 while let Some(prev_transaction) = transactions.next_back() {
3365 if !prev_transaction.suppress_grouping
3366 && transaction.first_edit_at - prev_transaction.last_edit_at
3367 <= self.group_interval
3368 {
3369 transaction = prev_transaction;
3370 count += 1;
3371 } else {
3372 break;
3373 }
3374 }
3375 }
3376 self.group_trailing(count)
3377 }
3378
3379 fn group_until(&mut self, transaction_id: TransactionId) {
3380 let mut count = 0;
3381 for transaction in self.undo_stack.iter().rev() {
3382 if transaction.id == transaction_id {
3383 self.group_trailing(count);
3384 break;
3385 } else if transaction.suppress_grouping {
3386 break;
3387 } else {
3388 count += 1;
3389 }
3390 }
3391 }
3392
3393 fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3394 let new_len = self.undo_stack.len() - n;
3395 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3396 if let Some(last_transaction) = transactions_to_keep.last_mut() {
3397 if let Some(transaction) = transactions_to_merge.last() {
3398 last_transaction.last_edit_at = transaction.last_edit_at;
3399 }
3400 for to_merge in transactions_to_merge {
3401 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3402 last_transaction
3403 .buffer_transactions
3404 .entry(*buffer_id)
3405 .or_insert(*transaction_id);
3406 }
3407 }
3408 }
3409
3410 self.undo_stack.truncate(new_len);
3411 self.undo_stack.last().map(|t| t.id)
3412 }
3413}
3414
3415impl Excerpt {
3416 fn new(
3417 id: ExcerptId,
3418 locator: Locator,
3419 buffer_id: u64,
3420 buffer: BufferSnapshot,
3421 range: ExcerptRange<text::Anchor>,
3422 has_trailing_newline: bool,
3423 ) -> Self {
3424 Excerpt {
3425 id,
3426 locator,
3427 max_buffer_row: range.context.end.to_point(&buffer).row,
3428 text_summary: buffer
3429 .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3430 buffer_id,
3431 buffer,
3432 range,
3433 has_trailing_newline,
3434 }
3435 }
3436
3437 fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3438 let content_start = self.range.context.start.to_offset(&self.buffer);
3439 let chunks_start = content_start + range.start;
3440 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3441
3442 let footer_height = if self.has_trailing_newline
3443 && range.start <= self.text_summary.len
3444 && range.end > self.text_summary.len
3445 {
3446 1
3447 } else {
3448 0
3449 };
3450
3451 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3452
3453 ExcerptChunks {
3454 content_chunks,
3455 footer_height,
3456 }
3457 }
3458
3459 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3460 let content_start = self.range.context.start.to_offset(&self.buffer);
3461 let bytes_start = content_start + range.start;
3462 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3463 let footer_height = if self.has_trailing_newline
3464 && range.start <= self.text_summary.len
3465 && range.end > self.text_summary.len
3466 {
3467 1
3468 } else {
3469 0
3470 };
3471 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3472
3473 ExcerptBytes {
3474 content_bytes,
3475 footer_height,
3476 }
3477 }
3478
3479 fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3480 let content_start = self.range.context.start.to_offset(&self.buffer);
3481 let bytes_start = content_start + range.start;
3482 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3483 let footer_height = if self.has_trailing_newline
3484 && range.start <= self.text_summary.len
3485 && range.end > self.text_summary.len
3486 {
3487 1
3488 } else {
3489 0
3490 };
3491 let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
3492
3493 ExcerptBytes {
3494 content_bytes,
3495 footer_height,
3496 }
3497 }
3498
3499 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3500 if text_anchor
3501 .cmp(&self.range.context.start, &self.buffer)
3502 .is_lt()
3503 {
3504 self.range.context.start
3505 } else if text_anchor
3506 .cmp(&self.range.context.end, &self.buffer)
3507 .is_gt()
3508 {
3509 self.range.context.end
3510 } else {
3511 text_anchor
3512 }
3513 }
3514
3515 fn contains(&self, anchor: &Anchor) -> bool {
3516 Some(self.buffer_id) == anchor.buffer_id
3517 && self
3518 .range
3519 .context
3520 .start
3521 .cmp(&anchor.text_anchor, &self.buffer)
3522 .is_le()
3523 && self
3524 .range
3525 .context
3526 .end
3527 .cmp(&anchor.text_anchor, &self.buffer)
3528 .is_ge()
3529 }
3530}
3531
3532impl ExcerptId {
3533 pub fn min() -> Self {
3534 Self(0)
3535 }
3536
3537 pub fn max() -> Self {
3538 Self(usize::MAX)
3539 }
3540
3541 pub fn to_proto(&self) -> u64 {
3542 self.0 as _
3543 }
3544
3545 pub fn from_proto(proto: u64) -> Self {
3546 Self(proto as _)
3547 }
3548
3549 pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3550 let a = snapshot.excerpt_locator_for_id(*self);
3551 let b = snapshot.excerpt_locator_for_id(*other);
3552 a.cmp(&b).then_with(|| self.0.cmp(&other.0))
3553 }
3554}
3555
3556impl Into<usize> for ExcerptId {
3557 fn into(self) -> usize {
3558 self.0
3559 }
3560}
3561
3562impl fmt::Debug for Excerpt {
3563 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3564 f.debug_struct("Excerpt")
3565 .field("id", &self.id)
3566 .field("locator", &self.locator)
3567 .field("buffer_id", &self.buffer_id)
3568 .field("range", &self.range)
3569 .field("text_summary", &self.text_summary)
3570 .field("has_trailing_newline", &self.has_trailing_newline)
3571 .finish()
3572 }
3573}
3574
3575impl sum_tree::Item for Excerpt {
3576 type Summary = ExcerptSummary;
3577
3578 fn summary(&self) -> Self::Summary {
3579 let mut text = self.text_summary.clone();
3580 if self.has_trailing_newline {
3581 text += TextSummary::from("\n");
3582 }
3583 ExcerptSummary {
3584 excerpt_id: self.id,
3585 excerpt_locator: self.locator.clone(),
3586 max_buffer_row: self.max_buffer_row,
3587 text,
3588 }
3589 }
3590}
3591
3592impl sum_tree::Item for ExcerptIdMapping {
3593 type Summary = ExcerptId;
3594
3595 fn summary(&self) -> Self::Summary {
3596 self.id
3597 }
3598}
3599
3600impl sum_tree::KeyedItem for ExcerptIdMapping {
3601 type Key = ExcerptId;
3602
3603 fn key(&self) -> Self::Key {
3604 self.id
3605 }
3606}
3607
3608impl sum_tree::Summary for ExcerptId {
3609 type Context = ();
3610
3611 fn add_summary(&mut self, other: &Self, _: &()) {
3612 *self = *other;
3613 }
3614}
3615
3616impl sum_tree::Summary for ExcerptSummary {
3617 type Context = ();
3618
3619 fn add_summary(&mut self, summary: &Self, _: &()) {
3620 debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3621 self.excerpt_locator = summary.excerpt_locator.clone();
3622 self.text.add_summary(&summary.text, &());
3623 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3624 }
3625}
3626
3627impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3628 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3629 *self += &summary.text;
3630 }
3631}
3632
3633impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3634 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3635 *self += summary.text.len;
3636 }
3637}
3638
3639impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3640 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3641 Ord::cmp(self, &cursor_location.text.len)
3642 }
3643}
3644
3645impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3646 fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3647 Ord::cmp(&Some(self), cursor_location)
3648 }
3649}
3650
3651impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3652 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3653 Ord::cmp(self, &cursor_location.excerpt_locator)
3654 }
3655}
3656
3657impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3658 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3659 *self += summary.text.len_utf16;
3660 }
3661}
3662
3663impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3664 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3665 *self += summary.text.lines;
3666 }
3667}
3668
3669impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3670 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3671 *self += summary.text.lines_utf16()
3672 }
3673}
3674
3675impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3676 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3677 *self = Some(&summary.excerpt_locator);
3678 }
3679}
3680
3681impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3682 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3683 *self = Some(summary.excerpt_id);
3684 }
3685}
3686
3687impl<'a> MultiBufferRows<'a> {
3688 pub fn seek(&mut self, row: u32) {
3689 self.buffer_row_range = 0..0;
3690
3691 self.excerpts
3692 .seek_forward(&Point::new(row, 0), Bias::Right, &());
3693 if self.excerpts.item().is_none() {
3694 self.excerpts.prev(&());
3695
3696 if self.excerpts.item().is_none() && row == 0 {
3697 self.buffer_row_range = 0..1;
3698 return;
3699 }
3700 }
3701
3702 if let Some(excerpt) = self.excerpts.item() {
3703 let overshoot = row - self.excerpts.start().row;
3704 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3705 self.buffer_row_range.start = excerpt_start + overshoot;
3706 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3707 }
3708 }
3709}
3710
3711impl<'a> Iterator for MultiBufferRows<'a> {
3712 type Item = Option<u32>;
3713
3714 fn next(&mut self) -> Option<Self::Item> {
3715 loop {
3716 if !self.buffer_row_range.is_empty() {
3717 let row = Some(self.buffer_row_range.start);
3718 self.buffer_row_range.start += 1;
3719 return Some(row);
3720 }
3721 self.excerpts.item()?;
3722 self.excerpts.next(&());
3723 let excerpt = self.excerpts.item()?;
3724 self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3725 self.buffer_row_range.end =
3726 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3727 }
3728 }
3729}
3730
3731impl<'a> MultiBufferChunks<'a> {
3732 pub fn offset(&self) -> usize {
3733 self.range.start
3734 }
3735
3736 pub fn seek(&mut self, offset: usize) {
3737 self.range.start = offset;
3738 self.excerpts.seek(&offset, Bias::Right, &());
3739 if let Some(excerpt) = self.excerpts.item() {
3740 self.excerpt_chunks = Some(excerpt.chunks_in_range(
3741 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3742 self.language_aware,
3743 ));
3744 } else {
3745 self.excerpt_chunks = None;
3746 }
3747 }
3748}
3749
3750impl<'a> Iterator for MultiBufferChunks<'a> {
3751 type Item = Chunk<'a>;
3752
3753 fn next(&mut self) -> Option<Self::Item> {
3754 if self.range.is_empty() {
3755 None
3756 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3757 self.range.start += chunk.text.len();
3758 Some(chunk)
3759 } else {
3760 self.excerpts.next(&());
3761 let excerpt = self.excerpts.item()?;
3762 self.excerpt_chunks = Some(excerpt.chunks_in_range(
3763 0..self.range.end - self.excerpts.start(),
3764 self.language_aware,
3765 ));
3766 self.next()
3767 }
3768 }
3769}
3770
3771impl<'a> MultiBufferBytes<'a> {
3772 fn consume(&mut self, len: usize) {
3773 self.range.start += len;
3774 self.chunk = &self.chunk[len..];
3775
3776 if !self.range.is_empty() && self.chunk.is_empty() {
3777 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3778 self.chunk = chunk;
3779 } else {
3780 self.excerpts.next(&());
3781 if let Some(excerpt) = self.excerpts.item() {
3782 let mut excerpt_bytes =
3783 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3784 self.chunk = excerpt_bytes.next().unwrap();
3785 self.excerpt_bytes = Some(excerpt_bytes);
3786 }
3787 }
3788 }
3789 }
3790}
3791
3792impl<'a> Iterator for MultiBufferBytes<'a> {
3793 type Item = &'a [u8];
3794
3795 fn next(&mut self) -> Option<Self::Item> {
3796 let chunk = self.chunk;
3797 if chunk.is_empty() {
3798 None
3799 } else {
3800 self.consume(chunk.len());
3801 Some(chunk)
3802 }
3803 }
3804}
3805
3806impl<'a> io::Read for MultiBufferBytes<'a> {
3807 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3808 let len = cmp::min(buf.len(), self.chunk.len());
3809 buf[..len].copy_from_slice(&self.chunk[..len]);
3810 if len > 0 {
3811 self.consume(len);
3812 }
3813 Ok(len)
3814 }
3815}
3816
3817impl<'a> ReversedMultiBufferBytes<'a> {
3818 fn consume(&mut self, len: usize) {
3819 self.range.end -= len;
3820 self.chunk = &self.chunk[..self.chunk.len() - len];
3821
3822 if !self.range.is_empty() && self.chunk.is_empty() {
3823 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3824 self.chunk = chunk;
3825 } else {
3826 self.excerpts.next(&());
3827 if let Some(excerpt) = self.excerpts.item() {
3828 let mut excerpt_bytes =
3829 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3830 self.chunk = excerpt_bytes.next().unwrap();
3831 self.excerpt_bytes = Some(excerpt_bytes);
3832 }
3833 }
3834 }
3835 }
3836}
3837
3838impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
3839 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3840 let len = cmp::min(buf.len(), self.chunk.len());
3841 buf[..len].copy_from_slice(&self.chunk[..len]);
3842 buf[..len].reverse();
3843 if len > 0 {
3844 self.consume(len);
3845 }
3846 Ok(len)
3847 }
3848}
3849impl<'a> Iterator for ExcerptBytes<'a> {
3850 type Item = &'a [u8];
3851
3852 fn next(&mut self) -> Option<Self::Item> {
3853 if let Some(chunk) = self.content_bytes.next() {
3854 if !chunk.is_empty() {
3855 return Some(chunk);
3856 }
3857 }
3858
3859 if self.footer_height > 0 {
3860 let result = &NEWLINES[..self.footer_height];
3861 self.footer_height = 0;
3862 return Some(result);
3863 }
3864
3865 None
3866 }
3867}
3868
3869impl<'a> Iterator for ExcerptChunks<'a> {
3870 type Item = Chunk<'a>;
3871
3872 fn next(&mut self) -> Option<Self::Item> {
3873 if let Some(chunk) = self.content_chunks.next() {
3874 return Some(chunk);
3875 }
3876
3877 if self.footer_height > 0 {
3878 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3879 self.footer_height = 0;
3880 return Some(Chunk {
3881 text,
3882 ..Default::default()
3883 });
3884 }
3885
3886 None
3887 }
3888}
3889
3890impl ToOffset for Point {
3891 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3892 snapshot.point_to_offset(*self)
3893 }
3894}
3895
3896impl ToOffset for usize {
3897 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3898 assert!(*self <= snapshot.len(), "offset is out of range");
3899 *self
3900 }
3901}
3902
3903impl ToOffset for OffsetUtf16 {
3904 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3905 snapshot.offset_utf16_to_offset(*self)
3906 }
3907}
3908
3909impl ToOffset for PointUtf16 {
3910 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3911 snapshot.point_utf16_to_offset(*self)
3912 }
3913}
3914
3915impl ToOffsetUtf16 for OffsetUtf16 {
3916 fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3917 *self
3918 }
3919}
3920
3921impl ToOffsetUtf16 for usize {
3922 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3923 snapshot.offset_to_offset_utf16(*self)
3924 }
3925}
3926
3927impl ToPoint for usize {
3928 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3929 snapshot.offset_to_point(*self)
3930 }
3931}
3932
3933impl ToPoint for Point {
3934 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3935 *self
3936 }
3937}
3938
3939impl ToPointUtf16 for usize {
3940 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3941 snapshot.offset_to_point_utf16(*self)
3942 }
3943}
3944
3945impl ToPointUtf16 for Point {
3946 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3947 snapshot.point_to_point_utf16(*self)
3948 }
3949}
3950
3951impl ToPointUtf16 for PointUtf16 {
3952 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3953 *self
3954 }
3955}
3956
3957fn build_excerpt_ranges<T>(
3958 buffer: &BufferSnapshot,
3959 ranges: &[Range<T>],
3960 context_line_count: u32,
3961) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
3962where
3963 T: text::ToPoint,
3964{
3965 let max_point = buffer.max_point();
3966 let mut range_counts = Vec::new();
3967 let mut excerpt_ranges = Vec::new();
3968 let mut range_iter = ranges
3969 .iter()
3970 .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
3971 .peekable();
3972 while let Some(range) = range_iter.next() {
3973 let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
3974 let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
3975 let mut ranges_in_excerpt = 1;
3976
3977 while let Some(next_range) = range_iter.peek() {
3978 if next_range.start.row <= excerpt_end.row + context_line_count {
3979 excerpt_end =
3980 Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
3981 ranges_in_excerpt += 1;
3982 range_iter.next();
3983 } else {
3984 break;
3985 }
3986 }
3987
3988 excerpt_ranges.push(ExcerptRange {
3989 context: excerpt_start..excerpt_end,
3990 primary: Some(range),
3991 });
3992 range_counts.push(ranges_in_excerpt);
3993 }
3994
3995 (excerpt_ranges, range_counts)
3996}
3997
3998#[cfg(test)]
3999mod tests {
4000 use crate::editor_tests::init_test;
4001
4002 use super::*;
4003 use futures::StreamExt;
4004 use gpui::{AppContext, TestAppContext};
4005 use language::{Buffer, Rope};
4006 use project::{FakeFs, Project};
4007 use rand::prelude::*;
4008 use settings::SettingsStore;
4009 use std::{env, rc::Rc};
4010 use unindent::Unindent;
4011 use util::test::sample_text;
4012
4013 #[gpui::test]
4014 fn test_singleton(cx: &mut AppContext) {
4015 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
4016 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4017
4018 let snapshot = multibuffer.read(cx).snapshot(cx);
4019 assert_eq!(snapshot.text(), buffer.read(cx).text());
4020
4021 assert_eq!(
4022 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4023 (0..buffer.read(cx).row_count())
4024 .map(Some)
4025 .collect::<Vec<_>>()
4026 );
4027
4028 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4029 let snapshot = multibuffer.read(cx).snapshot(cx);
4030
4031 assert_eq!(snapshot.text(), buffer.read(cx).text());
4032 assert_eq!(
4033 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4034 (0..buffer.read(cx).row_count())
4035 .map(Some)
4036 .collect::<Vec<_>>()
4037 );
4038 }
4039
4040 #[gpui::test]
4041 fn test_remote(cx: &mut AppContext) {
4042 let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
4043 let guest_buffer = cx.add_model(|cx| {
4044 let state = host_buffer.read(cx).to_proto();
4045 let ops = cx
4046 .background()
4047 .block(host_buffer.read(cx).serialize_ops(None, cx));
4048 let mut buffer = Buffer::from_proto(1, state, None).unwrap();
4049 buffer
4050 .apply_ops(
4051 ops.into_iter()
4052 .map(|op| language::proto::deserialize_operation(op).unwrap()),
4053 cx,
4054 )
4055 .unwrap();
4056 buffer
4057 });
4058 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4059 let snapshot = multibuffer.read(cx).snapshot(cx);
4060 assert_eq!(snapshot.text(), "a");
4061
4062 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4063 let snapshot = multibuffer.read(cx).snapshot(cx);
4064 assert_eq!(snapshot.text(), "ab");
4065
4066 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4067 let snapshot = multibuffer.read(cx).snapshot(cx);
4068 assert_eq!(snapshot.text(), "abc");
4069 }
4070
4071 #[gpui::test]
4072 fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4073 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
4074 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
4075 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4076
4077 let events = Rc::new(RefCell::new(Vec::<Event>::new()));
4078 multibuffer.update(cx, |_, cx| {
4079 let events = events.clone();
4080 cx.subscribe(&multibuffer, move |_, _, event, _| {
4081 if let Event::Edited = event {
4082 events.borrow_mut().push(event.clone())
4083 }
4084 })
4085 .detach();
4086 });
4087
4088 let subscription = multibuffer.update(cx, |multibuffer, cx| {
4089 let subscription = multibuffer.subscribe();
4090 multibuffer.push_excerpts(
4091 buffer_1.clone(),
4092 [ExcerptRange {
4093 context: Point::new(1, 2)..Point::new(2, 5),
4094 primary: None,
4095 }],
4096 cx,
4097 );
4098 assert_eq!(
4099 subscription.consume().into_inner(),
4100 [Edit {
4101 old: 0..0,
4102 new: 0..10
4103 }]
4104 );
4105
4106 multibuffer.push_excerpts(
4107 buffer_1.clone(),
4108 [ExcerptRange {
4109 context: Point::new(3, 3)..Point::new(4, 4),
4110 primary: None,
4111 }],
4112 cx,
4113 );
4114 multibuffer.push_excerpts(
4115 buffer_2.clone(),
4116 [ExcerptRange {
4117 context: Point::new(3, 1)..Point::new(3, 3),
4118 primary: None,
4119 }],
4120 cx,
4121 );
4122 assert_eq!(
4123 subscription.consume().into_inner(),
4124 [Edit {
4125 old: 10..10,
4126 new: 10..22
4127 }]
4128 );
4129
4130 subscription
4131 });
4132
4133 // Adding excerpts emits an edited event.
4134 assert_eq!(
4135 events.borrow().as_slice(),
4136 &[Event::Edited, Event::Edited, Event::Edited]
4137 );
4138
4139 let snapshot = multibuffer.read(cx).snapshot(cx);
4140 assert_eq!(
4141 snapshot.text(),
4142 concat!(
4143 "bbbb\n", // Preserve newlines
4144 "ccccc\n", //
4145 "ddd\n", //
4146 "eeee\n", //
4147 "jj" //
4148 )
4149 );
4150 assert_eq!(
4151 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4152 [Some(1), Some(2), Some(3), Some(4), Some(3)]
4153 );
4154 assert_eq!(
4155 snapshot.buffer_rows(2).collect::<Vec<_>>(),
4156 [Some(3), Some(4), Some(3)]
4157 );
4158 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
4159 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
4160
4161 assert_eq!(
4162 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4163 &[
4164 (0, "bbbb\nccccc".to_string(), true),
4165 (2, "ddd\neeee".to_string(), false),
4166 (4, "jj".to_string(), true),
4167 ]
4168 );
4169 assert_eq!(
4170 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4171 &[(0, "bbbb\nccccc".to_string(), true)]
4172 );
4173 assert_eq!(
4174 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4175 &[]
4176 );
4177 assert_eq!(
4178 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4179 &[]
4180 );
4181 assert_eq!(
4182 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4183 &[(2, "ddd\neeee".to_string(), false)]
4184 );
4185 assert_eq!(
4186 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4187 &[(2, "ddd\neeee".to_string(), false)]
4188 );
4189 assert_eq!(
4190 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4191 &[(2, "ddd\neeee".to_string(), false)]
4192 );
4193 assert_eq!(
4194 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4195 &[(4, "jj".to_string(), true)]
4196 );
4197 assert_eq!(
4198 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4199 &[]
4200 );
4201
4202 buffer_1.update(cx, |buffer, cx| {
4203 let text = "\n";
4204 buffer.edit(
4205 [
4206 (Point::new(0, 0)..Point::new(0, 0), text),
4207 (Point::new(2, 1)..Point::new(2, 3), text),
4208 ],
4209 None,
4210 cx,
4211 );
4212 });
4213
4214 let snapshot = multibuffer.read(cx).snapshot(cx);
4215 assert_eq!(
4216 snapshot.text(),
4217 concat!(
4218 "bbbb\n", // Preserve newlines
4219 "c\n", //
4220 "cc\n", //
4221 "ddd\n", //
4222 "eeee\n", //
4223 "jj" //
4224 )
4225 );
4226
4227 assert_eq!(
4228 subscription.consume().into_inner(),
4229 [Edit {
4230 old: 6..8,
4231 new: 6..7
4232 }]
4233 );
4234
4235 let snapshot = multibuffer.read(cx).snapshot(cx);
4236 assert_eq!(
4237 snapshot.clip_point(Point::new(0, 5), Bias::Left),
4238 Point::new(0, 4)
4239 );
4240 assert_eq!(
4241 snapshot.clip_point(Point::new(0, 5), Bias::Right),
4242 Point::new(0, 4)
4243 );
4244 assert_eq!(
4245 snapshot.clip_point(Point::new(5, 1), Bias::Right),
4246 Point::new(5, 1)
4247 );
4248 assert_eq!(
4249 snapshot.clip_point(Point::new(5, 2), Bias::Right),
4250 Point::new(5, 2)
4251 );
4252 assert_eq!(
4253 snapshot.clip_point(Point::new(5, 3), Bias::Right),
4254 Point::new(5, 2)
4255 );
4256
4257 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4258 let (buffer_2_excerpt_id, _) =
4259 multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4260 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4261 multibuffer.snapshot(cx)
4262 });
4263
4264 assert_eq!(
4265 snapshot.text(),
4266 concat!(
4267 "bbbb\n", // Preserve newlines
4268 "c\n", //
4269 "cc\n", //
4270 "ddd\n", //
4271 "eeee", //
4272 )
4273 );
4274
4275 fn boundaries_in_range(
4276 range: Range<Point>,
4277 snapshot: &MultiBufferSnapshot,
4278 ) -> Vec<(u32, String, bool)> {
4279 snapshot
4280 .excerpt_boundaries_in_range(range)
4281 .map(|boundary| {
4282 (
4283 boundary.row,
4284 boundary
4285 .buffer
4286 .text_for_range(boundary.range.context)
4287 .collect::<String>(),
4288 boundary.starts_new_buffer,
4289 )
4290 })
4291 .collect::<Vec<_>>()
4292 }
4293 }
4294
4295 #[gpui::test]
4296 fn test_excerpt_events(cx: &mut AppContext) {
4297 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'a'), cx));
4298 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'm'), cx));
4299
4300 let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4301 let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4302 let follower_edit_event_count = Rc::new(RefCell::new(0));
4303
4304 follower_multibuffer.update(cx, |_, cx| {
4305 let follower_edit_event_count = follower_edit_event_count.clone();
4306 cx.subscribe(
4307 &leader_multibuffer,
4308 move |follower, _, event, cx| match event.clone() {
4309 Event::ExcerptsAdded {
4310 buffer,
4311 predecessor,
4312 excerpts,
4313 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4314 Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4315 Event::Edited => {
4316 *follower_edit_event_count.borrow_mut() += 1;
4317 }
4318 _ => {}
4319 },
4320 )
4321 .detach();
4322 });
4323
4324 leader_multibuffer.update(cx, |leader, cx| {
4325 leader.push_excerpts(
4326 buffer_1.clone(),
4327 [
4328 ExcerptRange {
4329 context: 0..8,
4330 primary: None,
4331 },
4332 ExcerptRange {
4333 context: 12..16,
4334 primary: None,
4335 },
4336 ],
4337 cx,
4338 );
4339 leader.insert_excerpts_after(
4340 leader.excerpt_ids()[0],
4341 buffer_2.clone(),
4342 [
4343 ExcerptRange {
4344 context: 0..5,
4345 primary: None,
4346 },
4347 ExcerptRange {
4348 context: 10..15,
4349 primary: None,
4350 },
4351 ],
4352 cx,
4353 )
4354 });
4355 assert_eq!(
4356 leader_multibuffer.read(cx).snapshot(cx).text(),
4357 follower_multibuffer.read(cx).snapshot(cx).text(),
4358 );
4359 assert_eq!(*follower_edit_event_count.borrow(), 2);
4360
4361 leader_multibuffer.update(cx, |leader, cx| {
4362 let excerpt_ids = leader.excerpt_ids();
4363 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4364 });
4365 assert_eq!(
4366 leader_multibuffer.read(cx).snapshot(cx).text(),
4367 follower_multibuffer.read(cx).snapshot(cx).text(),
4368 );
4369 assert_eq!(*follower_edit_event_count.borrow(), 3);
4370
4371 // Removing an empty set of excerpts is a noop.
4372 leader_multibuffer.update(cx, |leader, cx| {
4373 leader.remove_excerpts([], cx);
4374 });
4375 assert_eq!(
4376 leader_multibuffer.read(cx).snapshot(cx).text(),
4377 follower_multibuffer.read(cx).snapshot(cx).text(),
4378 );
4379 assert_eq!(*follower_edit_event_count.borrow(), 3);
4380
4381 // Adding an empty set of excerpts is a noop.
4382 leader_multibuffer.update(cx, |leader, cx| {
4383 leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
4384 });
4385 assert_eq!(
4386 leader_multibuffer.read(cx).snapshot(cx).text(),
4387 follower_multibuffer.read(cx).snapshot(cx).text(),
4388 );
4389 assert_eq!(*follower_edit_event_count.borrow(), 3);
4390
4391 leader_multibuffer.update(cx, |leader, cx| {
4392 leader.clear(cx);
4393 });
4394 assert_eq!(
4395 leader_multibuffer.read(cx).snapshot(cx).text(),
4396 follower_multibuffer.read(cx).snapshot(cx).text(),
4397 );
4398 assert_eq!(*follower_edit_event_count.borrow(), 4);
4399 }
4400
4401 #[gpui::test]
4402 fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4403 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4404 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4405 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4406 multibuffer.push_excerpts_with_context_lines(
4407 buffer.clone(),
4408 vec![
4409 Point::new(3, 2)..Point::new(4, 2),
4410 Point::new(7, 1)..Point::new(7, 3),
4411 Point::new(15, 0)..Point::new(15, 0),
4412 ],
4413 2,
4414 cx,
4415 )
4416 });
4417
4418 let snapshot = multibuffer.read(cx).snapshot(cx);
4419 assert_eq!(
4420 snapshot.text(),
4421 "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4422 );
4423
4424 assert_eq!(
4425 anchor_ranges
4426 .iter()
4427 .map(|range| range.to_point(&snapshot))
4428 .collect::<Vec<_>>(),
4429 vec![
4430 Point::new(2, 2)..Point::new(3, 2),
4431 Point::new(6, 1)..Point::new(6, 3),
4432 Point::new(12, 0)..Point::new(12, 0)
4433 ]
4434 );
4435 }
4436
4437 #[gpui::test]
4438 async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
4439 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4440 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4441 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4442 let snapshot = buffer.read(cx);
4443 let ranges = vec![
4444 snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
4445 snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
4446 snapshot.anchor_before(Point::new(15, 0))
4447 ..snapshot.anchor_before(Point::new(15, 0)),
4448 ];
4449 multibuffer.stream_excerpts_with_context_lines(buffer.clone(), ranges, 2, cx)
4450 });
4451
4452 let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
4453
4454 let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4455 assert_eq!(
4456 snapshot.text(),
4457 "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4458 );
4459
4460 assert_eq!(
4461 anchor_ranges
4462 .iter()
4463 .map(|range| range.to_point(&snapshot))
4464 .collect::<Vec<_>>(),
4465 vec![
4466 Point::new(2, 2)..Point::new(3, 2),
4467 Point::new(6, 1)..Point::new(6, 3),
4468 Point::new(12, 0)..Point::new(12, 0)
4469 ]
4470 );
4471 }
4472
4473 #[gpui::test]
4474 fn test_empty_multibuffer(cx: &mut AppContext) {
4475 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4476
4477 let snapshot = multibuffer.read(cx).snapshot(cx);
4478 assert_eq!(snapshot.text(), "");
4479 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
4480 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
4481 }
4482
4483 #[gpui::test]
4484 fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
4485 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4486 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4487 let old_snapshot = multibuffer.read(cx).snapshot(cx);
4488 buffer.update(cx, |buffer, cx| {
4489 buffer.edit([(0..0, "X")], None, cx);
4490 buffer.edit([(5..5, "Y")], None, cx);
4491 });
4492 let new_snapshot = multibuffer.read(cx).snapshot(cx);
4493
4494 assert_eq!(old_snapshot.text(), "abcd");
4495 assert_eq!(new_snapshot.text(), "XabcdY");
4496
4497 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4498 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4499 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
4500 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
4501 }
4502
4503 #[gpui::test]
4504 fn test_multibuffer_anchors(cx: &mut AppContext) {
4505 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4506 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
4507 let multibuffer = cx.add_model(|cx| {
4508 let mut multibuffer = MultiBuffer::new(0);
4509 multibuffer.push_excerpts(
4510 buffer_1.clone(),
4511 [ExcerptRange {
4512 context: 0..4,
4513 primary: None,
4514 }],
4515 cx,
4516 );
4517 multibuffer.push_excerpts(
4518 buffer_2.clone(),
4519 [ExcerptRange {
4520 context: 0..5,
4521 primary: None,
4522 }],
4523 cx,
4524 );
4525 multibuffer
4526 });
4527 let old_snapshot = multibuffer.read(cx).snapshot(cx);
4528
4529 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
4530 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
4531 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4532 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4533 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4534 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4535
4536 buffer_1.update(cx, |buffer, cx| {
4537 buffer.edit([(0..0, "W")], None, cx);
4538 buffer.edit([(5..5, "X")], None, cx);
4539 });
4540 buffer_2.update(cx, |buffer, cx| {
4541 buffer.edit([(0..0, "Y")], None, cx);
4542 buffer.edit([(6..6, "Z")], None, cx);
4543 });
4544 let new_snapshot = multibuffer.read(cx).snapshot(cx);
4545
4546 assert_eq!(old_snapshot.text(), "abcd\nefghi");
4547 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
4548
4549 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4550 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4551 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
4552 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
4553 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
4554 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
4555 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
4556 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
4557 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
4558 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
4559 }
4560
4561 #[gpui::test]
4562 fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
4563 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4564 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
4565 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4566
4567 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
4568 // Add an excerpt from buffer 1 that spans this new insertion.
4569 buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
4570 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
4571 multibuffer
4572 .push_excerpts(
4573 buffer_1.clone(),
4574 [ExcerptRange {
4575 context: 0..7,
4576 primary: None,
4577 }],
4578 cx,
4579 )
4580 .pop()
4581 .unwrap()
4582 });
4583
4584 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
4585 assert_eq!(snapshot_1.text(), "abcd123");
4586
4587 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
4588 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
4589 multibuffer.remove_excerpts([excerpt_id_1], cx);
4590 let mut ids = multibuffer
4591 .push_excerpts(
4592 buffer_2.clone(),
4593 [
4594 ExcerptRange {
4595 context: 0..4,
4596 primary: None,
4597 },
4598 ExcerptRange {
4599 context: 6..10,
4600 primary: None,
4601 },
4602 ExcerptRange {
4603 context: 12..16,
4604 primary: None,
4605 },
4606 ],
4607 cx,
4608 )
4609 .into_iter();
4610 (ids.next().unwrap(), ids.next().unwrap())
4611 });
4612 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
4613 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
4614
4615 // The old excerpt id doesn't get reused.
4616 assert_ne!(excerpt_id_2, excerpt_id_1);
4617
4618 // Resolve some anchors from the previous snapshot in the new snapshot.
4619 // The current excerpts are from a different buffer, so we don't attempt to
4620 // resolve the old text anchor in the new buffer.
4621 assert_eq!(
4622 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
4623 0
4624 );
4625 assert_eq!(
4626 snapshot_2.summaries_for_anchors::<usize, _>(&[
4627 snapshot_1.anchor_before(2),
4628 snapshot_1.anchor_after(3)
4629 ]),
4630 vec![0, 0]
4631 );
4632
4633 // Refresh anchors from the old snapshot. The return value indicates that both
4634 // anchors lost their original excerpt.
4635 let refresh =
4636 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
4637 assert_eq!(
4638 refresh,
4639 &[
4640 (0, snapshot_2.anchor_before(0), false),
4641 (1, snapshot_2.anchor_after(0), false),
4642 ]
4643 );
4644
4645 // Replace the middle excerpt with a smaller excerpt in buffer 2,
4646 // that intersects the old excerpt.
4647 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
4648 multibuffer.remove_excerpts([excerpt_id_3], cx);
4649 multibuffer
4650 .insert_excerpts_after(
4651 excerpt_id_2,
4652 buffer_2.clone(),
4653 [ExcerptRange {
4654 context: 5..8,
4655 primary: None,
4656 }],
4657 cx,
4658 )
4659 .pop()
4660 .unwrap()
4661 });
4662
4663 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
4664 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
4665 assert_ne!(excerpt_id_5, excerpt_id_3);
4666
4667 // Resolve some anchors from the previous snapshot in the new snapshot.
4668 // The third anchor can't be resolved, since its excerpt has been removed,
4669 // so it resolves to the same position as its predecessor.
4670 let anchors = [
4671 snapshot_2.anchor_before(0),
4672 snapshot_2.anchor_after(2),
4673 snapshot_2.anchor_after(6),
4674 snapshot_2.anchor_after(14),
4675 ];
4676 assert_eq!(
4677 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
4678 &[0, 2, 9, 13]
4679 );
4680
4681 let new_anchors = snapshot_3.refresh_anchors(&anchors);
4682 assert_eq!(
4683 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
4684 &[(0, true), (1, true), (2, true), (3, true)]
4685 );
4686 assert_eq!(
4687 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
4688 &[0, 2, 7, 13]
4689 );
4690 }
4691
4692 #[gpui::test]
4693 async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
4694 use git::diff::DiffHunkStatus;
4695 init_test(cx, |_| {});
4696
4697 let fs = FakeFs::new(cx.background());
4698 let project = Project::test(fs, [], cx).await;
4699
4700 // buffer has two modified hunks with two rows each
4701 let buffer_1 = project
4702 .update(cx, |project, cx| {
4703 project.create_buffer(
4704 "
4705 1.zero
4706 1.ONE
4707 1.TWO
4708 1.three
4709 1.FOUR
4710 1.FIVE
4711 1.six
4712 "
4713 .unindent()
4714 .as_str(),
4715 None,
4716 cx,
4717 )
4718 })
4719 .unwrap();
4720 buffer_1.update(cx, |buffer, cx| {
4721 buffer.set_diff_base(
4722 Some(
4723 "
4724 1.zero
4725 1.one
4726 1.two
4727 1.three
4728 1.four
4729 1.five
4730 1.six
4731 "
4732 .unindent(),
4733 ),
4734 cx,
4735 );
4736 });
4737
4738 // buffer has a deletion hunk and an insertion hunk
4739 let buffer_2 = project
4740 .update(cx, |project, cx| {
4741 project.create_buffer(
4742 "
4743 2.zero
4744 2.one
4745 2.two
4746 2.three
4747 2.four
4748 2.five
4749 2.six
4750 "
4751 .unindent()
4752 .as_str(),
4753 None,
4754 cx,
4755 )
4756 })
4757 .unwrap();
4758 buffer_2.update(cx, |buffer, cx| {
4759 buffer.set_diff_base(
4760 Some(
4761 "
4762 2.zero
4763 2.one
4764 2.one-and-a-half
4765 2.two
4766 2.three
4767 2.four
4768 2.six
4769 "
4770 .unindent(),
4771 ),
4772 cx,
4773 );
4774 });
4775
4776 cx.foreground().run_until_parked();
4777
4778 let multibuffer = cx.add_model(|cx| {
4779 let mut multibuffer = MultiBuffer::new(0);
4780 multibuffer.push_excerpts(
4781 buffer_1.clone(),
4782 [
4783 // excerpt ends in the middle of a modified hunk
4784 ExcerptRange {
4785 context: Point::new(0, 0)..Point::new(1, 5),
4786 primary: Default::default(),
4787 },
4788 // excerpt begins in the middle of a modified hunk
4789 ExcerptRange {
4790 context: Point::new(5, 0)..Point::new(6, 5),
4791 primary: Default::default(),
4792 },
4793 ],
4794 cx,
4795 );
4796 multibuffer.push_excerpts(
4797 buffer_2.clone(),
4798 [
4799 // excerpt ends at a deletion
4800 ExcerptRange {
4801 context: Point::new(0, 0)..Point::new(1, 5),
4802 primary: Default::default(),
4803 },
4804 // excerpt starts at a deletion
4805 ExcerptRange {
4806 context: Point::new(2, 0)..Point::new(2, 5),
4807 primary: Default::default(),
4808 },
4809 // excerpt fully contains a deletion hunk
4810 ExcerptRange {
4811 context: Point::new(1, 0)..Point::new(2, 5),
4812 primary: Default::default(),
4813 },
4814 // excerpt fully contains an insertion hunk
4815 ExcerptRange {
4816 context: Point::new(4, 0)..Point::new(6, 5),
4817 primary: Default::default(),
4818 },
4819 ],
4820 cx,
4821 );
4822 multibuffer
4823 });
4824
4825 let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
4826
4827 assert_eq!(
4828 snapshot.text(),
4829 "
4830 1.zero
4831 1.ONE
4832 1.FIVE
4833 1.six
4834 2.zero
4835 2.one
4836 2.two
4837 2.one
4838 2.two
4839 2.four
4840 2.five
4841 2.six"
4842 .unindent()
4843 );
4844
4845 let expected = [
4846 (DiffHunkStatus::Modified, 1..2),
4847 (DiffHunkStatus::Modified, 2..3),
4848 //TODO: Define better when and where removed hunks show up at range extremities
4849 (DiffHunkStatus::Removed, 6..6),
4850 (DiffHunkStatus::Removed, 8..8),
4851 (DiffHunkStatus::Added, 10..11),
4852 ];
4853
4854 assert_eq!(
4855 snapshot
4856 .git_diff_hunks_in_range(0..12)
4857 .map(|hunk| (hunk.status(), hunk.buffer_range))
4858 .collect::<Vec<_>>(),
4859 &expected,
4860 );
4861
4862 assert_eq!(
4863 snapshot
4864 .git_diff_hunks_in_range_rev(0..12)
4865 .map(|hunk| (hunk.status(), hunk.buffer_range))
4866 .collect::<Vec<_>>(),
4867 expected
4868 .iter()
4869 .rev()
4870 .cloned()
4871 .collect::<Vec<_>>()
4872 .as_slice(),
4873 );
4874 }
4875
4876 #[gpui::test(iterations = 100)]
4877 fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
4878 let operations = env::var("OPERATIONS")
4879 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4880 .unwrap_or(10);
4881
4882 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
4883 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4884 let mut excerpt_ids = Vec::<ExcerptId>::new();
4885 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
4886 let mut anchors = Vec::new();
4887 let mut old_versions = Vec::new();
4888
4889 for _ in 0..operations {
4890 match rng.gen_range(0..100) {
4891 0..=19 if !buffers.is_empty() => {
4892 let buffer = buffers.choose(&mut rng).unwrap();
4893 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
4894 }
4895 20..=29 if !expected_excerpts.is_empty() => {
4896 let mut ids_to_remove = vec![];
4897 for _ in 0..rng.gen_range(1..=3) {
4898 if expected_excerpts.is_empty() {
4899 break;
4900 }
4901
4902 let ix = rng.gen_range(0..expected_excerpts.len());
4903 ids_to_remove.push(excerpt_ids.remove(ix));
4904 let (buffer, range) = expected_excerpts.remove(ix);
4905 let buffer = buffer.read(cx);
4906 log::info!(
4907 "Removing excerpt {}: {:?}",
4908 ix,
4909 buffer
4910 .text_for_range(range.to_offset(buffer))
4911 .collect::<String>(),
4912 );
4913 }
4914 let snapshot = multibuffer.read(cx).read(cx);
4915 ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
4916 drop(snapshot);
4917 multibuffer.update(cx, |multibuffer, cx| {
4918 multibuffer.remove_excerpts(ids_to_remove, cx)
4919 });
4920 }
4921 30..=39 if !expected_excerpts.is_empty() => {
4922 let multibuffer = multibuffer.read(cx).read(cx);
4923 let offset =
4924 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
4925 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
4926 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
4927 anchors.push(multibuffer.anchor_at(offset, bias));
4928 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
4929 }
4930 40..=44 if !anchors.is_empty() => {
4931 let multibuffer = multibuffer.read(cx).read(cx);
4932 let prev_len = anchors.len();
4933 anchors = multibuffer
4934 .refresh_anchors(&anchors)
4935 .into_iter()
4936 .map(|a| a.1)
4937 .collect();
4938
4939 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
4940 // overshoot its boundaries.
4941 assert_eq!(anchors.len(), prev_len);
4942 for anchor in &anchors {
4943 if anchor.excerpt_id == ExcerptId::min()
4944 || anchor.excerpt_id == ExcerptId::max()
4945 {
4946 continue;
4947 }
4948
4949 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
4950 assert_eq!(excerpt.id, anchor.excerpt_id);
4951 assert!(excerpt.contains(anchor));
4952 }
4953 }
4954 _ => {
4955 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
4956 let base_text = util::RandomCharIter::new(&mut rng)
4957 .take(10)
4958 .collect::<String>();
4959 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
4960 buffers.last().unwrap()
4961 } else {
4962 buffers.choose(&mut rng).unwrap()
4963 };
4964
4965 let buffer = buffer_handle.read(cx);
4966 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
4967 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4968 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
4969 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
4970 let prev_excerpt_id = excerpt_ids
4971 .get(prev_excerpt_ix)
4972 .cloned()
4973 .unwrap_or_else(ExcerptId::max);
4974 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
4975
4976 log::info!(
4977 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
4978 excerpt_ix,
4979 expected_excerpts.len(),
4980 buffer_handle.read(cx).remote_id(),
4981 buffer.text(),
4982 start_ix..end_ix,
4983 &buffer.text()[start_ix..end_ix]
4984 );
4985
4986 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
4987 multibuffer
4988 .insert_excerpts_after(
4989 prev_excerpt_id,
4990 buffer_handle.clone(),
4991 [ExcerptRange {
4992 context: start_ix..end_ix,
4993 primary: None,
4994 }],
4995 cx,
4996 )
4997 .pop()
4998 .unwrap()
4999 });
5000
5001 excerpt_ids.insert(excerpt_ix, excerpt_id);
5002 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
5003 }
5004 }
5005
5006 if rng.gen_bool(0.3) {
5007 multibuffer.update(cx, |multibuffer, cx| {
5008 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
5009 })
5010 }
5011
5012 let snapshot = multibuffer.read(cx).snapshot(cx);
5013
5014 let mut excerpt_starts = Vec::new();
5015 let mut expected_text = String::new();
5016 let mut expected_buffer_rows = Vec::new();
5017 for (buffer, range) in &expected_excerpts {
5018 let buffer = buffer.read(cx);
5019 let buffer_range = range.to_offset(buffer);
5020
5021 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5022 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5023 expected_text.push('\n');
5024
5025 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5026 ..=buffer.offset_to_point(buffer_range.end).row;
5027 for row in buffer_row_range {
5028 expected_buffer_rows.push(Some(row));
5029 }
5030 }
5031 // Remove final trailing newline.
5032 if !expected_excerpts.is_empty() {
5033 expected_text.pop();
5034 }
5035
5036 // Always report one buffer row
5037 if expected_buffer_rows.is_empty() {
5038 expected_buffer_rows.push(Some(0));
5039 }
5040
5041 assert_eq!(snapshot.text(), expected_text);
5042 log::info!("MultiBuffer text: {:?}", expected_text);
5043
5044 assert_eq!(
5045 snapshot.buffer_rows(0).collect::<Vec<_>>(),
5046 expected_buffer_rows,
5047 );
5048
5049 for _ in 0..5 {
5050 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5051 assert_eq!(
5052 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
5053 &expected_buffer_rows[start_row..],
5054 "buffer_rows({})",
5055 start_row
5056 );
5057 }
5058
5059 assert_eq!(
5060 snapshot.max_buffer_row(),
5061 expected_buffer_rows.into_iter().flatten().max().unwrap()
5062 );
5063
5064 let mut excerpt_starts = excerpt_starts.into_iter();
5065 for (buffer, range) in &expected_excerpts {
5066 let buffer = buffer.read(cx);
5067 let buffer_id = buffer.remote_id();
5068 let buffer_range = range.to_offset(buffer);
5069 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5070 let buffer_start_point_utf16 =
5071 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5072
5073 let excerpt_start = excerpt_starts.next().unwrap();
5074 let mut offset = excerpt_start.len;
5075 let mut buffer_offset = buffer_range.start;
5076 let mut point = excerpt_start.lines;
5077 let mut buffer_point = buffer_start_point;
5078 let mut point_utf16 = excerpt_start.lines_utf16();
5079 let mut buffer_point_utf16 = buffer_start_point_utf16;
5080 for ch in buffer
5081 .snapshot()
5082 .chunks(buffer_range.clone(), false)
5083 .flat_map(|c| c.text.chars())
5084 {
5085 for _ in 0..ch.len_utf8() {
5086 let left_offset = snapshot.clip_offset(offset, Bias::Left);
5087 let right_offset = snapshot.clip_offset(offset, Bias::Right);
5088 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5089 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5090 assert_eq!(
5091 left_offset,
5092 excerpt_start.len + (buffer_left_offset - buffer_range.start),
5093 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5094 offset,
5095 buffer_id,
5096 buffer_offset,
5097 );
5098 assert_eq!(
5099 right_offset,
5100 excerpt_start.len + (buffer_right_offset - buffer_range.start),
5101 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5102 offset,
5103 buffer_id,
5104 buffer_offset,
5105 );
5106
5107 let left_point = snapshot.clip_point(point, Bias::Left);
5108 let right_point = snapshot.clip_point(point, Bias::Right);
5109 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5110 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5111 assert_eq!(
5112 left_point,
5113 excerpt_start.lines + (buffer_left_point - buffer_start_point),
5114 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5115 point,
5116 buffer_id,
5117 buffer_point,
5118 );
5119 assert_eq!(
5120 right_point,
5121 excerpt_start.lines + (buffer_right_point - buffer_start_point),
5122 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5123 point,
5124 buffer_id,
5125 buffer_point,
5126 );
5127
5128 assert_eq!(
5129 snapshot.point_to_offset(left_point),
5130 left_offset,
5131 "point_to_offset({:?})",
5132 left_point,
5133 );
5134 assert_eq!(
5135 snapshot.offset_to_point(left_offset),
5136 left_point,
5137 "offset_to_point({:?})",
5138 left_offset,
5139 );
5140
5141 offset += 1;
5142 buffer_offset += 1;
5143 if ch == '\n' {
5144 point += Point::new(1, 0);
5145 buffer_point += Point::new(1, 0);
5146 } else {
5147 point += Point::new(0, 1);
5148 buffer_point += Point::new(0, 1);
5149 }
5150 }
5151
5152 for _ in 0..ch.len_utf16() {
5153 let left_point_utf16 =
5154 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5155 let right_point_utf16 =
5156 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5157 let buffer_left_point_utf16 =
5158 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5159 let buffer_right_point_utf16 =
5160 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5161 assert_eq!(
5162 left_point_utf16,
5163 excerpt_start.lines_utf16()
5164 + (buffer_left_point_utf16 - buffer_start_point_utf16),
5165 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5166 point_utf16,
5167 buffer_id,
5168 buffer_point_utf16,
5169 );
5170 assert_eq!(
5171 right_point_utf16,
5172 excerpt_start.lines_utf16()
5173 + (buffer_right_point_utf16 - buffer_start_point_utf16),
5174 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5175 point_utf16,
5176 buffer_id,
5177 buffer_point_utf16,
5178 );
5179
5180 if ch == '\n' {
5181 point_utf16 += PointUtf16::new(1, 0);
5182 buffer_point_utf16 += PointUtf16::new(1, 0);
5183 } else {
5184 point_utf16 += PointUtf16::new(0, 1);
5185 buffer_point_utf16 += PointUtf16::new(0, 1);
5186 }
5187 }
5188 }
5189 }
5190
5191 for (row, line) in expected_text.split('\n').enumerate() {
5192 assert_eq!(
5193 snapshot.line_len(row as u32),
5194 line.len() as u32,
5195 "line_len({}).",
5196 row
5197 );
5198 }
5199
5200 let text_rope = Rope::from(expected_text.as_str());
5201 for _ in 0..10 {
5202 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5203 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5204
5205 let text_for_range = snapshot
5206 .text_for_range(start_ix..end_ix)
5207 .collect::<String>();
5208 assert_eq!(
5209 text_for_range,
5210 &expected_text[start_ix..end_ix],
5211 "incorrect text for range {:?}",
5212 start_ix..end_ix
5213 );
5214
5215 let excerpted_buffer_ranges = multibuffer
5216 .read(cx)
5217 .range_to_buffer_ranges(start_ix..end_ix, cx);
5218 let excerpted_buffers_text = excerpted_buffer_ranges
5219 .iter()
5220 .map(|(buffer, buffer_range, _)| {
5221 buffer
5222 .read(cx)
5223 .text_for_range(buffer_range.clone())
5224 .collect::<String>()
5225 })
5226 .collect::<Vec<_>>()
5227 .join("\n");
5228 assert_eq!(excerpted_buffers_text, text_for_range);
5229 if !expected_excerpts.is_empty() {
5230 assert!(!excerpted_buffer_ranges.is_empty());
5231 }
5232
5233 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5234 assert_eq!(
5235 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5236 expected_summary,
5237 "incorrect summary for range {:?}",
5238 start_ix..end_ix
5239 );
5240 }
5241
5242 // Anchor resolution
5243 let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5244 assert_eq!(anchors.len(), summaries.len());
5245 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5246 assert!(resolved_offset <= snapshot.len());
5247 assert_eq!(
5248 snapshot.summary_for_anchor::<usize>(anchor),
5249 resolved_offset
5250 );
5251 }
5252
5253 for _ in 0..10 {
5254 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5255 assert_eq!(
5256 snapshot.reversed_chars_at(end_ix).collect::<String>(),
5257 expected_text[..end_ix].chars().rev().collect::<String>(),
5258 );
5259 }
5260
5261 for _ in 0..10 {
5262 let end_ix = rng.gen_range(0..=text_rope.len());
5263 let start_ix = rng.gen_range(0..=end_ix);
5264 assert_eq!(
5265 snapshot
5266 .bytes_in_range(start_ix..end_ix)
5267 .flatten()
5268 .copied()
5269 .collect::<Vec<_>>(),
5270 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
5271 "bytes_in_range({:?})",
5272 start_ix..end_ix,
5273 );
5274 }
5275 }
5276
5277 let snapshot = multibuffer.read(cx).snapshot(cx);
5278 for (old_snapshot, subscription) in old_versions {
5279 let edits = subscription.consume().into_inner();
5280
5281 log::info!(
5282 "applying subscription edits to old text: {:?}: {:?}",
5283 old_snapshot.text(),
5284 edits,
5285 );
5286
5287 let mut text = old_snapshot.text();
5288 for edit in edits {
5289 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
5290 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
5291 }
5292 assert_eq!(text.to_string(), snapshot.text());
5293 }
5294 }
5295
5296 #[gpui::test]
5297 fn test_history(cx: &mut AppContext) {
5298 cx.set_global(SettingsStore::test(cx));
5299
5300 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
5301 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
5302 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
5303 let group_interval = multibuffer.read(cx).history.group_interval;
5304 multibuffer.update(cx, |multibuffer, cx| {
5305 multibuffer.push_excerpts(
5306 buffer_1.clone(),
5307 [ExcerptRange {
5308 context: 0..buffer_1.read(cx).len(),
5309 primary: None,
5310 }],
5311 cx,
5312 );
5313 multibuffer.push_excerpts(
5314 buffer_2.clone(),
5315 [ExcerptRange {
5316 context: 0..buffer_2.read(cx).len(),
5317 primary: None,
5318 }],
5319 cx,
5320 );
5321 });
5322
5323 let mut now = Instant::now();
5324
5325 multibuffer.update(cx, |multibuffer, cx| {
5326 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5327 multibuffer.edit(
5328 [
5329 (Point::new(0, 0)..Point::new(0, 0), "A"),
5330 (Point::new(1, 0)..Point::new(1, 0), "A"),
5331 ],
5332 None,
5333 cx,
5334 );
5335 multibuffer.edit(
5336 [
5337 (Point::new(0, 1)..Point::new(0, 1), "B"),
5338 (Point::new(1, 1)..Point::new(1, 1), "B"),
5339 ],
5340 None,
5341 cx,
5342 );
5343 multibuffer.end_transaction_at(now, cx);
5344 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5345
5346 // Edit buffer 1 through the multibuffer
5347 now += 2 * group_interval;
5348 multibuffer.start_transaction_at(now, cx);
5349 multibuffer.edit([(2..2, "C")], None, cx);
5350 multibuffer.end_transaction_at(now, cx);
5351 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5352
5353 // Edit buffer 1 independently
5354 buffer_1.update(cx, |buffer_1, cx| {
5355 buffer_1.start_transaction_at(now);
5356 buffer_1.edit([(3..3, "D")], None, cx);
5357 buffer_1.end_transaction_at(now, cx);
5358
5359 now += 2 * group_interval;
5360 buffer_1.start_transaction_at(now);
5361 buffer_1.edit([(4..4, "E")], None, cx);
5362 buffer_1.end_transaction_at(now, cx);
5363 });
5364 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5365
5366 // An undo in the multibuffer undoes the multibuffer transaction
5367 // and also any individual buffer edits that have occurred since
5368 // that transaction.
5369 multibuffer.undo(cx);
5370 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5371
5372 multibuffer.undo(cx);
5373 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5374
5375 multibuffer.redo(cx);
5376 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5377
5378 multibuffer.redo(cx);
5379 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5380
5381 // Undo buffer 2 independently.
5382 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5383 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5384
5385 // An undo in the multibuffer undoes the components of the
5386 // the last multibuffer transaction that are not already undone.
5387 multibuffer.undo(cx);
5388 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5389
5390 multibuffer.undo(cx);
5391 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5392
5393 multibuffer.redo(cx);
5394 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5395
5396 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5397 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5398
5399 // Redo stack gets cleared after an edit.
5400 now += 2 * group_interval;
5401 multibuffer.start_transaction_at(now, cx);
5402 multibuffer.edit([(0..0, "X")], None, cx);
5403 multibuffer.end_transaction_at(now, cx);
5404 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5405 multibuffer.redo(cx);
5406 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5407 multibuffer.undo(cx);
5408 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5409 multibuffer.undo(cx);
5410 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5411
5412 // Transactions can be grouped manually.
5413 multibuffer.redo(cx);
5414 multibuffer.redo(cx);
5415 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5416 multibuffer.group_until_transaction(transaction_1, cx);
5417 multibuffer.undo(cx);
5418 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5419 multibuffer.redo(cx);
5420 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5421 });
5422 }
5423}