1mod anchor;
2
3pub use anchor::{Anchor, AnchorRangeExt};
4use anyhow::{anyhow, Result};
5use clock::ReplicaId;
6use collections::{BTreeMap, Bound, HashMap, HashSet};
7use futures::{channel::mpsc, SinkExt};
8use git::diff::DiffHunk;
9use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task};
10pub use language::Completion;
11use language::{
12 char_kind,
13 language_settings::{language_settings, LanguageSettings},
14 AutoindentMode, Buffer, BufferChunks, BufferSnapshot, CharKind, Chunk, CursorShape,
15 DiagnosticEntry, File, IndentSize, Language, LanguageScope, OffsetRangeExt, OffsetUtf16,
16 Outline, OutlineItem, Point, PointUtf16, Selection, TextDimension, ToOffset as _,
17 ToOffsetUtf16 as _, ToPoint as _, ToPointUtf16 as _, TransactionId, Unclipped,
18};
19use std::{
20 borrow::Cow,
21 cell::{Ref, RefCell},
22 cmp, fmt,
23 future::Future,
24 io,
25 iter::{self, FromIterator},
26 mem,
27 ops::{Range, RangeBounds, Sub},
28 str,
29 sync::Arc,
30 time::{Duration, Instant},
31};
32use sum_tree::{Bias, Cursor, SumTree};
33use text::{
34 locator::Locator,
35 subscription::{Subscription, Topic},
36 Edit, TextSummary,
37};
38use theme::SyntaxTheme;
39use util::post_inc;
40
41const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize];
42
43#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
44pub struct ExcerptId(usize);
45
46pub struct MultiBuffer {
47 snapshot: RefCell<MultiBufferSnapshot>,
48 buffers: RefCell<HashMap<u64, BufferState>>,
49 next_excerpt_id: usize,
50 subscriptions: Topic,
51 singleton: bool,
52 replica_id: ReplicaId,
53 history: History,
54 title: Option<String>,
55}
56
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum Event {
59 ExcerptsAdded {
60 buffer: ModelHandle<Buffer>,
61 predecessor: ExcerptId,
62 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
63 },
64 ExcerptsRemoved {
65 ids: Vec<ExcerptId>,
66 },
67 ExcerptsEdited {
68 ids: Vec<ExcerptId>,
69 },
70 Edited,
71 Reloaded,
72 DiffBaseChanged,
73 LanguageChanged,
74 Reparsed,
75 Saved,
76 FileHandleChanged,
77 Closed,
78 DirtyChanged,
79 DiagnosticsUpdated,
80}
81
82#[derive(Clone)]
83struct History {
84 next_transaction_id: TransactionId,
85 undo_stack: Vec<Transaction>,
86 redo_stack: Vec<Transaction>,
87 transaction_depth: usize,
88 group_interval: Duration,
89}
90
91#[derive(Clone)]
92struct Transaction {
93 id: TransactionId,
94 buffer_transactions: HashMap<u64, text::TransactionId>,
95 first_edit_at: Instant,
96 last_edit_at: Instant,
97 suppress_grouping: bool,
98}
99
100pub trait ToOffset: 'static + fmt::Debug {
101 fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
102}
103
104pub trait ToOffsetUtf16: 'static + fmt::Debug {
105 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16;
106}
107
108pub trait ToPoint: 'static + fmt::Debug {
109 fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
110}
111
112pub trait ToPointUtf16: 'static + fmt::Debug {
113 fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16;
114}
115
116struct BufferState {
117 buffer: ModelHandle<Buffer>,
118 last_version: clock::Global,
119 last_parse_count: usize,
120 last_selections_update_count: usize,
121 last_diagnostics_update_count: usize,
122 last_file_update_count: usize,
123 last_git_diff_update_count: usize,
124 excerpts: Vec<Locator>,
125 _subscriptions: [gpui::Subscription; 2],
126}
127
128#[derive(Clone, Default)]
129pub struct MultiBufferSnapshot {
130 singleton: bool,
131 excerpts: SumTree<Excerpt>,
132 excerpt_ids: SumTree<ExcerptIdMapping>,
133 parse_count: usize,
134 diagnostics_update_count: usize,
135 trailing_excerpt_update_count: usize,
136 git_diff_update_count: usize,
137 edit_count: usize,
138 is_dirty: bool,
139 has_conflict: bool,
140}
141
142pub struct ExcerptBoundary {
143 pub id: ExcerptId,
144 pub row: u32,
145 pub buffer: BufferSnapshot,
146 pub range: ExcerptRange<text::Anchor>,
147 pub starts_new_buffer: bool,
148}
149
150#[derive(Clone)]
151struct Excerpt {
152 id: ExcerptId,
153 locator: Locator,
154 buffer_id: u64,
155 buffer: BufferSnapshot,
156 range: ExcerptRange<text::Anchor>,
157 max_buffer_row: u32,
158 text_summary: TextSummary,
159 has_trailing_newline: bool,
160}
161
162#[derive(Clone, Debug)]
163struct ExcerptIdMapping {
164 id: ExcerptId,
165 locator: Locator,
166}
167
168#[derive(Clone, Debug, Eq, PartialEq)]
169pub struct ExcerptRange<T> {
170 pub context: Range<T>,
171 pub primary: Option<Range<T>>,
172}
173
174#[derive(Clone, Debug, Default)]
175struct ExcerptSummary {
176 excerpt_id: ExcerptId,
177 excerpt_locator: Locator,
178 max_buffer_row: u32,
179 text: TextSummary,
180}
181
182#[derive(Clone)]
183pub struct MultiBufferRows<'a> {
184 buffer_row_range: Range<u32>,
185 excerpts: Cursor<'a, Excerpt, Point>,
186}
187
188pub struct MultiBufferChunks<'a> {
189 range: Range<usize>,
190 excerpts: Cursor<'a, Excerpt, usize>,
191 excerpt_chunks: Option<ExcerptChunks<'a>>,
192 language_aware: bool,
193}
194
195pub struct MultiBufferBytes<'a> {
196 range: Range<usize>,
197 excerpts: Cursor<'a, Excerpt, usize>,
198 excerpt_bytes: Option<ExcerptBytes<'a>>,
199 chunk: &'a [u8],
200}
201
202pub struct ReversedMultiBufferBytes<'a> {
203 range: Range<usize>,
204 excerpts: Cursor<'a, Excerpt, usize>,
205 excerpt_bytes: Option<ExcerptBytes<'a>>,
206 chunk: &'a [u8],
207}
208
209struct ExcerptChunks<'a> {
210 content_chunks: BufferChunks<'a>,
211 footer_height: usize,
212}
213
214struct ExcerptBytes<'a> {
215 content_bytes: text::Bytes<'a>,
216 footer_height: usize,
217}
218
219impl MultiBuffer {
220 pub fn new(replica_id: ReplicaId) -> Self {
221 Self {
222 snapshot: Default::default(),
223 buffers: Default::default(),
224 next_excerpt_id: 1,
225 subscriptions: Default::default(),
226 singleton: false,
227 replica_id,
228 history: History {
229 next_transaction_id: Default::default(),
230 undo_stack: Default::default(),
231 redo_stack: Default::default(),
232 transaction_depth: 0,
233 group_interval: Duration::from_millis(300),
234 },
235 title: Default::default(),
236 }
237 }
238
239 pub fn clone(&self, new_cx: &mut ModelContext<Self>) -> Self {
240 let mut buffers = HashMap::default();
241 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
242 buffers.insert(
243 *buffer_id,
244 BufferState {
245 buffer: buffer_state.buffer.clone(),
246 last_version: buffer_state.last_version.clone(),
247 last_parse_count: buffer_state.last_parse_count,
248 last_selections_update_count: buffer_state.last_selections_update_count,
249 last_diagnostics_update_count: buffer_state.last_diagnostics_update_count,
250 last_file_update_count: buffer_state.last_file_update_count,
251 last_git_diff_update_count: buffer_state.last_git_diff_update_count,
252 excerpts: buffer_state.excerpts.clone(),
253 _subscriptions: [
254 new_cx.observe(&buffer_state.buffer, |_, _, cx| cx.notify()),
255 new_cx.subscribe(&buffer_state.buffer, Self::on_buffer_event),
256 ],
257 },
258 );
259 }
260 Self {
261 snapshot: RefCell::new(self.snapshot.borrow().clone()),
262 buffers: RefCell::new(buffers),
263 next_excerpt_id: 1,
264 subscriptions: Default::default(),
265 singleton: self.singleton,
266 replica_id: self.replica_id,
267 history: self.history.clone(),
268 title: self.title.clone(),
269 }
270 }
271
272 pub fn with_title(mut self, title: String) -> Self {
273 self.title = Some(title);
274 self
275 }
276
277 pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
278 let mut this = Self::new(buffer.read(cx).replica_id());
279 this.singleton = true;
280 this.push_excerpts(
281 buffer,
282 [ExcerptRange {
283 context: text::Anchor::MIN..text::Anchor::MAX,
284 primary: None,
285 }],
286 cx,
287 );
288 this.snapshot.borrow_mut().singleton = true;
289 this
290 }
291
292 pub fn replica_id(&self) -> ReplicaId {
293 self.replica_id
294 }
295
296 pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
297 self.sync(cx);
298 self.snapshot.borrow().clone()
299 }
300
301 pub(crate) fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
302 self.sync(cx);
303 self.snapshot.borrow()
304 }
305
306 pub fn as_singleton(&self) -> Option<ModelHandle<Buffer>> {
307 if self.singleton {
308 return Some(
309 self.buffers
310 .borrow()
311 .values()
312 .next()
313 .unwrap()
314 .buffer
315 .clone(),
316 );
317 } else {
318 None
319 }
320 }
321
322 pub fn is_singleton(&self) -> bool {
323 self.singleton
324 }
325
326 pub fn subscribe(&mut self) -> Subscription {
327 self.subscriptions.subscribe()
328 }
329
330 pub fn is_dirty(&self, cx: &AppContext) -> bool {
331 self.read(cx).is_dirty()
332 }
333
334 pub fn has_conflict(&self, cx: &AppContext) -> bool {
335 self.read(cx).has_conflict()
336 }
337
338 // The `is_empty` signature doesn't match what clippy expects
339 #[allow(clippy::len_without_is_empty)]
340 pub fn len(&self, cx: &AppContext) -> usize {
341 self.read(cx).len()
342 }
343
344 pub fn is_empty(&self, cx: &AppContext) -> bool {
345 self.len(cx) != 0
346 }
347
348 pub fn symbols_containing<T: ToOffset>(
349 &self,
350 offset: T,
351 theme: Option<&SyntaxTheme>,
352 cx: &AppContext,
353 ) -> Option<(u64, Vec<OutlineItem<Anchor>>)> {
354 self.read(cx).symbols_containing(offset, theme)
355 }
356
357 pub fn edit<I, S, T>(
358 &mut self,
359 edits: I,
360 mut autoindent_mode: Option<AutoindentMode>,
361 cx: &mut ModelContext<Self>,
362 ) where
363 I: IntoIterator<Item = (Range<S>, T)>,
364 S: ToOffset,
365 T: Into<Arc<str>>,
366 {
367 if self.buffers.borrow().is_empty() {
368 return;
369 }
370
371 let snapshot = self.read(cx);
372 let edits = edits.into_iter().map(|(range, new_text)| {
373 let mut range = range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot);
374 if range.start > range.end {
375 mem::swap(&mut range.start, &mut range.end);
376 }
377 (range, new_text)
378 });
379
380 if let Some(buffer) = self.as_singleton() {
381 return buffer.update(cx, |buffer, cx| {
382 buffer.edit(edits, autoindent_mode, cx);
383 });
384 }
385
386 let original_indent_columns = match &mut autoindent_mode {
387 Some(AutoindentMode::Block {
388 original_indent_columns,
389 }) => mem::take(original_indent_columns),
390 _ => Default::default(),
391 };
392
393 struct BufferEdit {
394 range: Range<usize>,
395 new_text: Arc<str>,
396 is_insertion: bool,
397 original_indent_column: u32,
398 }
399 let mut buffer_edits: HashMap<u64, Vec<BufferEdit>> = Default::default();
400 let mut edited_excerpt_ids = Vec::new();
401 let mut cursor = snapshot.excerpts.cursor::<usize>();
402 for (ix, (range, new_text)) in edits.enumerate() {
403 let new_text: Arc<str> = new_text.into();
404 let original_indent_column = original_indent_columns.get(ix).copied().unwrap_or(0);
405 cursor.seek(&range.start, Bias::Right, &());
406 if cursor.item().is_none() && range.start == *cursor.start() {
407 cursor.prev(&());
408 }
409 let start_excerpt = cursor.item().expect("start offset out of bounds");
410 let start_overshoot = range.start - cursor.start();
411 let buffer_start = start_excerpt
412 .range
413 .context
414 .start
415 .to_offset(&start_excerpt.buffer)
416 + start_overshoot;
417 edited_excerpt_ids.push(start_excerpt.id);
418
419 cursor.seek(&range.end, Bias::Right, &());
420 if cursor.item().is_none() && range.end == *cursor.start() {
421 cursor.prev(&());
422 }
423 let end_excerpt = cursor.item().expect("end offset out of bounds");
424 let end_overshoot = range.end - cursor.start();
425 let buffer_end = end_excerpt
426 .range
427 .context
428 .start
429 .to_offset(&end_excerpt.buffer)
430 + end_overshoot;
431
432 if start_excerpt.id == end_excerpt.id {
433 buffer_edits
434 .entry(start_excerpt.buffer_id)
435 .or_insert(Vec::new())
436 .push(BufferEdit {
437 range: buffer_start..buffer_end,
438 new_text,
439 is_insertion: true,
440 original_indent_column,
441 });
442 } else {
443 edited_excerpt_ids.push(end_excerpt.id);
444 let start_excerpt_range = buffer_start
445 ..start_excerpt
446 .range
447 .context
448 .end
449 .to_offset(&start_excerpt.buffer);
450 let end_excerpt_range = end_excerpt
451 .range
452 .context
453 .start
454 .to_offset(&end_excerpt.buffer)
455 ..buffer_end;
456 buffer_edits
457 .entry(start_excerpt.buffer_id)
458 .or_insert(Vec::new())
459 .push(BufferEdit {
460 range: start_excerpt_range,
461 new_text: new_text.clone(),
462 is_insertion: true,
463 original_indent_column,
464 });
465 buffer_edits
466 .entry(end_excerpt.buffer_id)
467 .or_insert(Vec::new())
468 .push(BufferEdit {
469 range: end_excerpt_range,
470 new_text: new_text.clone(),
471 is_insertion: false,
472 original_indent_column,
473 });
474
475 cursor.seek(&range.start, Bias::Right, &());
476 cursor.next(&());
477 while let Some(excerpt) = cursor.item() {
478 if excerpt.id == end_excerpt.id {
479 break;
480 }
481 buffer_edits
482 .entry(excerpt.buffer_id)
483 .or_insert(Vec::new())
484 .push(BufferEdit {
485 range: excerpt.range.context.to_offset(&excerpt.buffer),
486 new_text: new_text.clone(),
487 is_insertion: false,
488 original_indent_column,
489 });
490 edited_excerpt_ids.push(excerpt.id);
491 cursor.next(&());
492 }
493 }
494 }
495
496 for (buffer_id, mut edits) in buffer_edits {
497 edits.sort_unstable_by_key(|edit| edit.range.start);
498 self.buffers.borrow()[&buffer_id]
499 .buffer
500 .update(cx, |buffer, cx| {
501 let mut edits = edits.into_iter().peekable();
502 let mut insertions = Vec::new();
503 let mut original_indent_columns = Vec::new();
504 let mut deletions = Vec::new();
505 let empty_str: Arc<str> = "".into();
506 while let Some(BufferEdit {
507 mut range,
508 new_text,
509 mut is_insertion,
510 original_indent_column,
511 }) = edits.next()
512 {
513 while let Some(BufferEdit {
514 range: next_range,
515 is_insertion: next_is_insertion,
516 ..
517 }) = edits.peek()
518 {
519 if range.end >= next_range.start {
520 range.end = cmp::max(next_range.end, range.end);
521 is_insertion |= *next_is_insertion;
522 edits.next();
523 } else {
524 break;
525 }
526 }
527
528 if is_insertion {
529 original_indent_columns.push(original_indent_column);
530 insertions.push((
531 buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
532 new_text.clone(),
533 ));
534 } else if !range.is_empty() {
535 deletions.push((
536 buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
537 empty_str.clone(),
538 ));
539 }
540 }
541
542 let deletion_autoindent_mode =
543 if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
544 Some(AutoindentMode::Block {
545 original_indent_columns: Default::default(),
546 })
547 } else {
548 None
549 };
550 let insertion_autoindent_mode =
551 if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
552 Some(AutoindentMode::Block {
553 original_indent_columns,
554 })
555 } else {
556 None
557 };
558
559 buffer.edit(deletions, deletion_autoindent_mode, cx);
560 buffer.edit(insertions, insertion_autoindent_mode, cx);
561 })
562 }
563
564 cx.emit(Event::ExcerptsEdited {
565 ids: edited_excerpt_ids,
566 });
567 }
568
569 pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
570 self.start_transaction_at(Instant::now(), cx)
571 }
572
573 pub(crate) fn start_transaction_at(
574 &mut self,
575 now: Instant,
576 cx: &mut ModelContext<Self>,
577 ) -> Option<TransactionId> {
578 if let Some(buffer) = self.as_singleton() {
579 return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
580 }
581
582 for BufferState { buffer, .. } in self.buffers.borrow().values() {
583 buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
584 }
585 self.history.start_transaction(now)
586 }
587
588 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
589 self.end_transaction_at(Instant::now(), cx)
590 }
591
592 pub(crate) fn end_transaction_at(
593 &mut self,
594 now: Instant,
595 cx: &mut ModelContext<Self>,
596 ) -> Option<TransactionId> {
597 if let Some(buffer) = self.as_singleton() {
598 return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
599 }
600
601 let mut buffer_transactions = HashMap::default();
602 for BufferState { buffer, .. } in self.buffers.borrow().values() {
603 if let Some(transaction_id) =
604 buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
605 {
606 buffer_transactions.insert(buffer.read(cx).remote_id(), transaction_id);
607 }
608 }
609
610 if self.history.end_transaction(now, buffer_transactions) {
611 let transaction_id = self.history.group().unwrap();
612 Some(transaction_id)
613 } else {
614 None
615 }
616 }
617
618 pub fn finalize_last_transaction(&mut self, cx: &mut ModelContext<Self>) {
619 self.history.finalize_last_transaction();
620 for BufferState { buffer, .. } in self.buffers.borrow().values() {
621 buffer.update(cx, |buffer, _| {
622 buffer.finalize_last_transaction();
623 });
624 }
625 }
626
627 pub fn push_transaction<'a, T>(&mut self, buffer_transactions: T, cx: &mut ModelContext<Self>)
628 where
629 T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
630 {
631 self.history
632 .push_transaction(buffer_transactions, Instant::now(), cx);
633 self.history.finalize_last_transaction();
634 }
635
636 pub fn group_until_transaction(
637 &mut self,
638 transaction_id: TransactionId,
639 cx: &mut ModelContext<Self>,
640 ) {
641 if let Some(buffer) = self.as_singleton() {
642 buffer.update(cx, |buffer, _| {
643 buffer.group_until_transaction(transaction_id)
644 });
645 } else {
646 self.history.group_until(transaction_id);
647 }
648 }
649
650 pub fn set_active_selections(
651 &mut self,
652 selections: &[Selection<Anchor>],
653 line_mode: bool,
654 cursor_shape: CursorShape,
655 cx: &mut ModelContext<Self>,
656 ) {
657 let mut selections_by_buffer: HashMap<u64, Vec<Selection<text::Anchor>>> =
658 Default::default();
659 let snapshot = self.read(cx);
660 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
661 for selection in selections {
662 let start_locator = snapshot.excerpt_locator_for_id(selection.start.excerpt_id);
663 let end_locator = snapshot.excerpt_locator_for_id(selection.end.excerpt_id);
664
665 cursor.seek(&Some(start_locator), Bias::Left, &());
666 while let Some(excerpt) = cursor.item() {
667 if excerpt.locator > *end_locator {
668 break;
669 }
670
671 let mut start = excerpt.range.context.start;
672 let mut end = excerpt.range.context.end;
673 if excerpt.id == selection.start.excerpt_id {
674 start = selection.start.text_anchor;
675 }
676 if excerpt.id == selection.end.excerpt_id {
677 end = selection.end.text_anchor;
678 }
679 selections_by_buffer
680 .entry(excerpt.buffer_id)
681 .or_default()
682 .push(Selection {
683 id: selection.id,
684 start,
685 end,
686 reversed: selection.reversed,
687 goal: selection.goal,
688 });
689
690 cursor.next(&());
691 }
692 }
693
694 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
695 if !selections_by_buffer.contains_key(buffer_id) {
696 buffer_state
697 .buffer
698 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
699 }
700 }
701
702 for (buffer_id, mut selections) in selections_by_buffer {
703 self.buffers.borrow()[&buffer_id]
704 .buffer
705 .update(cx, |buffer, cx| {
706 selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer));
707 let mut selections = selections.into_iter().peekable();
708 let merged_selections = Arc::from_iter(iter::from_fn(|| {
709 let mut selection = selections.next()?;
710 while let Some(next_selection) = selections.peek() {
711 if selection.end.cmp(&next_selection.start, buffer).is_ge() {
712 let next_selection = selections.next().unwrap();
713 if next_selection.end.cmp(&selection.end, buffer).is_ge() {
714 selection.end = next_selection.end;
715 }
716 } else {
717 break;
718 }
719 }
720 Some(selection)
721 }));
722 buffer.set_active_selections(merged_selections, line_mode, cursor_shape, cx);
723 });
724 }
725 }
726
727 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
728 for buffer in self.buffers.borrow().values() {
729 buffer
730 .buffer
731 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
732 }
733 }
734
735 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
736 if let Some(buffer) = self.as_singleton() {
737 return buffer.update(cx, |buffer, cx| buffer.undo(cx));
738 }
739
740 while let Some(transaction) = self.history.pop_undo() {
741 let mut undone = false;
742 for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
743 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
744 undone |= buffer.update(cx, |buffer, cx| {
745 let undo_to = *buffer_transaction_id;
746 if let Some(entry) = buffer.peek_undo_stack() {
747 *buffer_transaction_id = entry.transaction_id();
748 }
749 buffer.undo_to_transaction(undo_to, cx)
750 });
751 }
752 }
753
754 if undone {
755 return Some(transaction.id);
756 }
757 }
758
759 None
760 }
761
762 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
763 if let Some(buffer) = self.as_singleton() {
764 return buffer.update(cx, |buffer, cx| buffer.redo(cx));
765 }
766
767 while let Some(transaction) = self.history.pop_redo() {
768 let mut redone = false;
769 for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
770 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
771 redone |= buffer.update(cx, |buffer, cx| {
772 let redo_to = *buffer_transaction_id;
773 if let Some(entry) = buffer.peek_redo_stack() {
774 *buffer_transaction_id = entry.transaction_id();
775 }
776 buffer.redo_to_transaction(redo_to, cx)
777 });
778 }
779 }
780
781 if redone {
782 return Some(transaction.id);
783 }
784 }
785
786 None
787 }
788
789 pub fn stream_excerpts_with_context_lines(
790 &mut self,
791 excerpts: Vec<(ModelHandle<Buffer>, Vec<Range<text::Anchor>>)>,
792 context_line_count: u32,
793 cx: &mut ModelContext<Self>,
794 ) -> (Task<()>, mpsc::Receiver<Range<Anchor>>) {
795 let (mut tx, rx) = mpsc::channel(256);
796 let task = cx.spawn(|this, mut cx| async move {
797 for (buffer, ranges) in excerpts {
798 let (buffer_id, buffer_snapshot) =
799 buffer.read_with(&cx, |buffer, _| (buffer.remote_id(), buffer.snapshot()));
800
801 let mut excerpt_ranges = Vec::new();
802 let mut range_counts = Vec::new();
803 cx.background()
804 .scoped(|scope| {
805 scope.spawn(async {
806 let (ranges, counts) =
807 build_excerpt_ranges(&buffer_snapshot, &ranges, context_line_count);
808 excerpt_ranges = ranges;
809 range_counts = counts;
810 });
811 })
812 .await;
813
814 let mut ranges = ranges.into_iter();
815 let mut range_counts = range_counts.into_iter();
816 for excerpt_ranges in excerpt_ranges.chunks(100) {
817 let excerpt_ids = this.update(&mut cx, |this, cx| {
818 this.push_excerpts(buffer.clone(), excerpt_ranges.iter().cloned(), cx)
819 });
820
821 for (excerpt_id, range_count) in
822 excerpt_ids.into_iter().zip(range_counts.by_ref())
823 {
824 for range in ranges.by_ref().take(range_count) {
825 let start = Anchor {
826 buffer_id: Some(buffer_id),
827 excerpt_id: excerpt_id.clone(),
828 text_anchor: range.start,
829 };
830 let end = Anchor {
831 buffer_id: Some(buffer_id),
832 excerpt_id: excerpt_id.clone(),
833 text_anchor: range.end,
834 };
835 if tx.send(start..end).await.is_err() {
836 break;
837 }
838 }
839 }
840 }
841 }
842 });
843 (task, rx)
844 }
845
846 pub fn push_excerpts<O>(
847 &mut self,
848 buffer: ModelHandle<Buffer>,
849 ranges: impl IntoIterator<Item = ExcerptRange<O>>,
850 cx: &mut ModelContext<Self>,
851 ) -> Vec<ExcerptId>
852 where
853 O: text::ToOffset,
854 {
855 self.insert_excerpts_after(ExcerptId::max(), buffer, ranges, cx)
856 }
857
858 pub fn push_excerpts_with_context_lines<O>(
859 &mut self,
860 buffer: ModelHandle<Buffer>,
861 ranges: Vec<Range<O>>,
862 context_line_count: u32,
863 cx: &mut ModelContext<Self>,
864 ) -> Vec<Range<Anchor>>
865 where
866 O: text::ToPoint + text::ToOffset,
867 {
868 let buffer_id = buffer.read(cx).remote_id();
869 let buffer_snapshot = buffer.read(cx).snapshot();
870 let (excerpt_ranges, range_counts) =
871 build_excerpt_ranges(&buffer_snapshot, &ranges, context_line_count);
872
873 let excerpt_ids = self.push_excerpts(buffer, excerpt_ranges, cx);
874
875 let mut anchor_ranges = Vec::new();
876 let mut ranges = ranges.into_iter();
877 for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(range_counts.into_iter()) {
878 anchor_ranges.extend(ranges.by_ref().take(range_count).map(|range| {
879 let start = Anchor {
880 buffer_id: Some(buffer_id),
881 excerpt_id: excerpt_id.clone(),
882 text_anchor: buffer_snapshot.anchor_after(range.start),
883 };
884 let end = Anchor {
885 buffer_id: Some(buffer_id),
886 excerpt_id: excerpt_id.clone(),
887 text_anchor: buffer_snapshot.anchor_after(range.end),
888 };
889 start..end
890 }))
891 }
892 anchor_ranges
893 }
894
895 pub fn insert_excerpts_after<O>(
896 &mut self,
897 prev_excerpt_id: ExcerptId,
898 buffer: ModelHandle<Buffer>,
899 ranges: impl IntoIterator<Item = ExcerptRange<O>>,
900 cx: &mut ModelContext<Self>,
901 ) -> Vec<ExcerptId>
902 where
903 O: text::ToOffset,
904 {
905 let mut ids = Vec::new();
906 let mut next_excerpt_id = self.next_excerpt_id;
907 self.insert_excerpts_with_ids_after(
908 prev_excerpt_id,
909 buffer,
910 ranges.into_iter().map(|range| {
911 let id = ExcerptId(post_inc(&mut next_excerpt_id));
912 ids.push(id);
913 (id, range)
914 }),
915 cx,
916 );
917 ids
918 }
919
920 pub fn insert_excerpts_with_ids_after<O>(
921 &mut self,
922 prev_excerpt_id: ExcerptId,
923 buffer: ModelHandle<Buffer>,
924 ranges: impl IntoIterator<Item = (ExcerptId, ExcerptRange<O>)>,
925 cx: &mut ModelContext<Self>,
926 ) where
927 O: text::ToOffset,
928 {
929 assert_eq!(self.history.transaction_depth, 0);
930 let mut ranges = ranges.into_iter().peekable();
931 if ranges.peek().is_none() {
932 return Default::default();
933 }
934
935 self.sync(cx);
936
937 let buffer_id = buffer.read(cx).remote_id();
938 let buffer_snapshot = buffer.read(cx).snapshot();
939
940 let mut buffers = self.buffers.borrow_mut();
941 let buffer_state = buffers.entry(buffer_id).or_insert_with(|| BufferState {
942 last_version: buffer_snapshot.version().clone(),
943 last_parse_count: buffer_snapshot.parse_count(),
944 last_selections_update_count: buffer_snapshot.selections_update_count(),
945 last_diagnostics_update_count: buffer_snapshot.diagnostics_update_count(),
946 last_file_update_count: buffer_snapshot.file_update_count(),
947 last_git_diff_update_count: buffer_snapshot.git_diff_update_count(),
948 excerpts: Default::default(),
949 _subscriptions: [
950 cx.observe(&buffer, |_, _, cx| cx.notify()),
951 cx.subscribe(&buffer, Self::on_buffer_event),
952 ],
953 buffer: buffer.clone(),
954 });
955
956 let mut snapshot = self.snapshot.borrow_mut();
957
958 let mut prev_locator = snapshot.excerpt_locator_for_id(prev_excerpt_id).clone();
959 let mut new_excerpt_ids = mem::take(&mut snapshot.excerpt_ids);
960 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
961 let mut new_excerpts = cursor.slice(&prev_locator, Bias::Right, &());
962 prev_locator = cursor.start().unwrap_or(Locator::min_ref()).clone();
963
964 let edit_start = new_excerpts.summary().text.len;
965 new_excerpts.update_last(
966 |excerpt| {
967 excerpt.has_trailing_newline = true;
968 },
969 &(),
970 );
971
972 let next_locator = if let Some(excerpt) = cursor.item() {
973 excerpt.locator.clone()
974 } else {
975 Locator::max()
976 };
977
978 let mut excerpts = Vec::new();
979 while let Some((id, range)) = ranges.next() {
980 let locator = Locator::between(&prev_locator, &next_locator);
981 if let Err(ix) = buffer_state.excerpts.binary_search(&locator) {
982 buffer_state.excerpts.insert(ix, locator.clone());
983 }
984 let range = ExcerptRange {
985 context: buffer_snapshot.anchor_before(&range.context.start)
986 ..buffer_snapshot.anchor_after(&range.context.end),
987 primary: range.primary.map(|primary| {
988 buffer_snapshot.anchor_before(&primary.start)
989 ..buffer_snapshot.anchor_after(&primary.end)
990 }),
991 };
992 if id.0 >= self.next_excerpt_id {
993 self.next_excerpt_id = id.0 + 1;
994 }
995 excerpts.push((id, range.clone()));
996 let excerpt = Excerpt::new(
997 id,
998 locator.clone(),
999 buffer_id,
1000 buffer_snapshot.clone(),
1001 range,
1002 ranges.peek().is_some() || cursor.item().is_some(),
1003 );
1004 new_excerpts.push(excerpt, &());
1005 prev_locator = locator.clone();
1006 new_excerpt_ids.push(ExcerptIdMapping { id, locator }, &());
1007 }
1008
1009 let edit_end = new_excerpts.summary().text.len;
1010
1011 let suffix = cursor.suffix(&());
1012 let changed_trailing_excerpt = suffix.is_empty();
1013 new_excerpts.append(suffix, &());
1014 drop(cursor);
1015 snapshot.excerpts = new_excerpts;
1016 snapshot.excerpt_ids = new_excerpt_ids;
1017 if changed_trailing_excerpt {
1018 snapshot.trailing_excerpt_update_count += 1;
1019 }
1020
1021 self.subscriptions.publish_mut([Edit {
1022 old: edit_start..edit_start,
1023 new: edit_start..edit_end,
1024 }]);
1025 cx.emit(Event::Edited);
1026 cx.emit(Event::ExcerptsAdded {
1027 buffer,
1028 predecessor: prev_excerpt_id,
1029 excerpts,
1030 });
1031 cx.notify();
1032 }
1033
1034 pub fn clear(&mut self, cx: &mut ModelContext<Self>) {
1035 self.sync(cx);
1036 let ids = self.excerpt_ids();
1037 self.buffers.borrow_mut().clear();
1038 let mut snapshot = self.snapshot.borrow_mut();
1039 let prev_len = snapshot.len();
1040 snapshot.excerpts = Default::default();
1041 snapshot.trailing_excerpt_update_count += 1;
1042 snapshot.is_dirty = false;
1043 snapshot.has_conflict = false;
1044
1045 self.subscriptions.publish_mut([Edit {
1046 old: 0..prev_len,
1047 new: 0..0,
1048 }]);
1049 cx.emit(Event::Edited);
1050 cx.emit(Event::ExcerptsRemoved { ids });
1051 cx.notify();
1052 }
1053
1054 pub fn excerpts_for_buffer(
1055 &self,
1056 buffer: &ModelHandle<Buffer>,
1057 cx: &AppContext,
1058 ) -> Vec<(ExcerptId, ExcerptRange<text::Anchor>)> {
1059 let mut excerpts = Vec::new();
1060 let snapshot = self.read(cx);
1061 let buffers = self.buffers.borrow();
1062 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
1063 for locator in buffers
1064 .get(&buffer.read(cx).remote_id())
1065 .map(|state| &state.excerpts)
1066 .into_iter()
1067 .flatten()
1068 {
1069 cursor.seek_forward(&Some(locator), Bias::Left, &());
1070 if let Some(excerpt) = cursor.item() {
1071 if excerpt.locator == *locator {
1072 excerpts.push((excerpt.id.clone(), excerpt.range.clone()));
1073 }
1074 }
1075 }
1076
1077 excerpts
1078 }
1079
1080 pub fn excerpt_ids(&self) -> Vec<ExcerptId> {
1081 self.snapshot
1082 .borrow()
1083 .excerpts
1084 .iter()
1085 .map(|entry| entry.id)
1086 .collect()
1087 }
1088
1089 pub fn excerpt_containing(
1090 &self,
1091 position: impl ToOffset,
1092 cx: &AppContext,
1093 ) -> Option<(ExcerptId, ModelHandle<Buffer>, Range<text::Anchor>)> {
1094 let snapshot = self.read(cx);
1095 let position = position.to_offset(&snapshot);
1096
1097 let mut cursor = snapshot.excerpts.cursor::<usize>();
1098 cursor.seek(&position, Bias::Right, &());
1099 cursor
1100 .item()
1101 .or_else(|| snapshot.excerpts.last())
1102 .map(|excerpt| {
1103 (
1104 excerpt.id.clone(),
1105 self.buffers
1106 .borrow()
1107 .get(&excerpt.buffer_id)
1108 .unwrap()
1109 .buffer
1110 .clone(),
1111 excerpt.range.context.clone(),
1112 )
1113 })
1114 }
1115
1116 // If point is at the end of the buffer, the last excerpt is returned
1117 pub fn point_to_buffer_offset<T: ToOffset>(
1118 &self,
1119 point: T,
1120 cx: &AppContext,
1121 ) -> Option<(ModelHandle<Buffer>, usize, ExcerptId)> {
1122 let snapshot = self.read(cx);
1123 let offset = point.to_offset(&snapshot);
1124 let mut cursor = snapshot.excerpts.cursor::<usize>();
1125 cursor.seek(&offset, Bias::Right, &());
1126 if cursor.item().is_none() {
1127 cursor.prev(&());
1128 }
1129
1130 cursor.item().map(|excerpt| {
1131 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1132 let buffer_point = excerpt_start + offset - *cursor.start();
1133 let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1134
1135 (buffer, buffer_point, excerpt.id)
1136 })
1137 }
1138
1139 pub fn range_to_buffer_ranges<T: ToOffset>(
1140 &self,
1141 range: Range<T>,
1142 cx: &AppContext,
1143 ) -> Vec<(ModelHandle<Buffer>, Range<usize>, ExcerptId)> {
1144 let snapshot = self.read(cx);
1145 let start = range.start.to_offset(&snapshot);
1146 let end = range.end.to_offset(&snapshot);
1147
1148 let mut result = Vec::new();
1149 let mut cursor = snapshot.excerpts.cursor::<usize>();
1150 cursor.seek(&start, Bias::Right, &());
1151 if cursor.item().is_none() {
1152 cursor.prev(&());
1153 }
1154
1155 while let Some(excerpt) = cursor.item() {
1156 if *cursor.start() > end {
1157 break;
1158 }
1159
1160 let mut end_before_newline = cursor.end(&());
1161 if excerpt.has_trailing_newline {
1162 end_before_newline -= 1;
1163 }
1164 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1165 let start = excerpt_start + (cmp::max(start, *cursor.start()) - *cursor.start());
1166 let end = excerpt_start + (cmp::min(end, end_before_newline) - *cursor.start());
1167 let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1168 result.push((buffer, start..end, excerpt.id));
1169 cursor.next(&());
1170 }
1171
1172 result
1173 }
1174
1175 pub fn remove_excerpts(
1176 &mut self,
1177 excerpt_ids: impl IntoIterator<Item = ExcerptId>,
1178 cx: &mut ModelContext<Self>,
1179 ) {
1180 self.sync(cx);
1181 let ids = excerpt_ids.into_iter().collect::<Vec<_>>();
1182 if ids.is_empty() {
1183 return;
1184 }
1185
1186 let mut buffers = self.buffers.borrow_mut();
1187 let mut snapshot = self.snapshot.borrow_mut();
1188 let mut new_excerpts = SumTree::new();
1189 let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1190 let mut edits = Vec::new();
1191 let mut excerpt_ids = ids.iter().copied().peekable();
1192
1193 while let Some(excerpt_id) = excerpt_ids.next() {
1194 // Seek to the next excerpt to remove, preserving any preceding excerpts.
1195 let locator = snapshot.excerpt_locator_for_id(excerpt_id);
1196 new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
1197
1198 if let Some(mut excerpt) = cursor.item() {
1199 if excerpt.id != excerpt_id {
1200 continue;
1201 }
1202 let mut old_start = cursor.start().1;
1203
1204 // Skip over the removed excerpt.
1205 'remove_excerpts: loop {
1206 if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
1207 buffer_state.excerpts.retain(|l| l != &excerpt.locator);
1208 if buffer_state.excerpts.is_empty() {
1209 buffers.remove(&excerpt.buffer_id);
1210 }
1211 }
1212 cursor.next(&());
1213
1214 // Skip over any subsequent excerpts that are also removed.
1215 while let Some(&next_excerpt_id) = excerpt_ids.peek() {
1216 let next_locator = snapshot.excerpt_locator_for_id(next_excerpt_id);
1217 if let Some(next_excerpt) = cursor.item() {
1218 if next_excerpt.locator == *next_locator {
1219 excerpt_ids.next();
1220 excerpt = next_excerpt;
1221 continue 'remove_excerpts;
1222 }
1223 }
1224 break;
1225 }
1226
1227 break;
1228 }
1229
1230 // When removing the last excerpt, remove the trailing newline from
1231 // the previous excerpt.
1232 if cursor.item().is_none() && old_start > 0 {
1233 old_start -= 1;
1234 new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
1235 }
1236
1237 // Push an edit for the removal of this run of excerpts.
1238 let old_end = cursor.start().1;
1239 let new_start = new_excerpts.summary().text.len;
1240 edits.push(Edit {
1241 old: old_start..old_end,
1242 new: new_start..new_start,
1243 });
1244 }
1245 }
1246 let suffix = cursor.suffix(&());
1247 let changed_trailing_excerpt = suffix.is_empty();
1248 new_excerpts.append(suffix, &());
1249 drop(cursor);
1250 snapshot.excerpts = new_excerpts;
1251
1252 if changed_trailing_excerpt {
1253 snapshot.trailing_excerpt_update_count += 1;
1254 }
1255
1256 self.subscriptions.publish_mut(edits);
1257 cx.emit(Event::Edited);
1258 cx.emit(Event::ExcerptsRemoved { ids });
1259 cx.notify();
1260 }
1261
1262 pub fn wait_for_anchors<'a>(
1263 &self,
1264 anchors: impl 'a + Iterator<Item = Anchor>,
1265 cx: &mut ModelContext<Self>,
1266 ) -> impl 'static + Future<Output = Result<()>> {
1267 let borrow = self.buffers.borrow();
1268 let mut error = None;
1269 let mut futures = Vec::new();
1270 for anchor in anchors {
1271 if let Some(buffer_id) = anchor.buffer_id {
1272 if let Some(buffer) = borrow.get(&buffer_id) {
1273 buffer.buffer.update(cx, |buffer, _| {
1274 futures.push(buffer.wait_for_anchors([anchor.text_anchor]))
1275 });
1276 } else {
1277 error = Some(anyhow!(
1278 "buffer {buffer_id} is not part of this multi-buffer"
1279 ));
1280 break;
1281 }
1282 }
1283 }
1284 async move {
1285 if let Some(error) = error {
1286 Err(error)?;
1287 }
1288 for future in futures {
1289 future.await?;
1290 }
1291 Ok(())
1292 }
1293 }
1294
1295 pub fn text_anchor_for_position<T: ToOffset>(
1296 &self,
1297 position: T,
1298 cx: &AppContext,
1299 ) -> Option<(ModelHandle<Buffer>, language::Anchor)> {
1300 let snapshot = self.read(cx);
1301 let anchor = snapshot.anchor_before(position);
1302 let buffer = self
1303 .buffers
1304 .borrow()
1305 .get(&anchor.buffer_id?)?
1306 .buffer
1307 .clone();
1308 Some((buffer, anchor.text_anchor))
1309 }
1310
1311 fn on_buffer_event(
1312 &mut self,
1313 _: ModelHandle<Buffer>,
1314 event: &language::Event,
1315 cx: &mut ModelContext<Self>,
1316 ) {
1317 cx.emit(match event {
1318 language::Event::Edited => Event::Edited,
1319 language::Event::DirtyChanged => Event::DirtyChanged,
1320 language::Event::Saved => Event::Saved,
1321 language::Event::FileHandleChanged => Event::FileHandleChanged,
1322 language::Event::Reloaded => Event::Reloaded,
1323 language::Event::DiffBaseChanged => Event::DiffBaseChanged,
1324 language::Event::LanguageChanged => Event::LanguageChanged,
1325 language::Event::Reparsed => Event::Reparsed,
1326 language::Event::DiagnosticsUpdated => Event::DiagnosticsUpdated,
1327 language::Event::Closed => Event::Closed,
1328
1329 //
1330 language::Event::Operation(_) => return,
1331 });
1332 }
1333
1334 pub fn all_buffers(&self) -> HashSet<ModelHandle<Buffer>> {
1335 self.buffers
1336 .borrow()
1337 .values()
1338 .map(|state| state.buffer.clone())
1339 .collect()
1340 }
1341
1342 pub fn buffer(&self, buffer_id: u64) -> Option<ModelHandle<Buffer>> {
1343 self.buffers
1344 .borrow()
1345 .get(&buffer_id)
1346 .map(|state| state.buffer.clone())
1347 }
1348
1349 pub fn is_completion_trigger(&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 { return None; };
2760
2761 for (open, close) in enclosing_bracket_ranges {
2762 let len = close.end - open.start;
2763
2764 if let Some((existing_open, existing_close)) = &result {
2765 let existing_len = existing_close.end - existing_open.start;
2766 if len > existing_len {
2767 continue;
2768 }
2769 }
2770
2771 result = Some((open, close));
2772 }
2773
2774 result
2775 }
2776
2777 /// Returns enclosing bracket ranges containing the given range or returns None if the range is
2778 /// not contained in a single excerpt
2779 pub fn enclosing_bracket_ranges<'a, T: ToOffset>(
2780 &'a self,
2781 range: Range<T>,
2782 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2783 let range = range.start.to_offset(self)..range.end.to_offset(self);
2784
2785 self.bracket_ranges(range.clone()).map(|range_pairs| {
2786 range_pairs
2787 .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
2788 })
2789 }
2790
2791 /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
2792 /// not contained in a single excerpt
2793 pub fn bracket_ranges<'a, T: ToOffset>(
2794 &'a self,
2795 range: Range<T>,
2796 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2797 let range = range.start.to_offset(self)..range.end.to_offset(self);
2798 let excerpt = self.excerpt_containing(range.clone());
2799 excerpt.map(|(excerpt, excerpt_offset)| {
2800 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2801 let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2802
2803 let start_in_buffer = excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2804 let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2805
2806 excerpt
2807 .buffer
2808 .bracket_ranges(start_in_buffer..end_in_buffer)
2809 .filter_map(move |(start_bracket_range, end_bracket_range)| {
2810 if start_bracket_range.start < excerpt_buffer_start
2811 || end_bracket_range.end > excerpt_buffer_end
2812 {
2813 return None;
2814 }
2815
2816 let mut start_bracket_range = start_bracket_range.clone();
2817 start_bracket_range.start =
2818 excerpt_offset + (start_bracket_range.start - excerpt_buffer_start);
2819 start_bracket_range.end =
2820 excerpt_offset + (start_bracket_range.end - excerpt_buffer_start);
2821
2822 let mut end_bracket_range = end_bracket_range.clone();
2823 end_bracket_range.start =
2824 excerpt_offset + (end_bracket_range.start - excerpt_buffer_start);
2825 end_bracket_range.end =
2826 excerpt_offset + (end_bracket_range.end - excerpt_buffer_start);
2827 Some((start_bracket_range, end_bracket_range))
2828 })
2829 })
2830 }
2831
2832 pub fn diagnostics_update_count(&self) -> usize {
2833 self.diagnostics_update_count
2834 }
2835
2836 pub fn git_diff_update_count(&self) -> usize {
2837 self.git_diff_update_count
2838 }
2839
2840 pub fn trailing_excerpt_update_count(&self) -> usize {
2841 self.trailing_excerpt_update_count
2842 }
2843
2844 pub fn file_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<dyn File>> {
2845 self.point_to_buffer_offset(point)
2846 .and_then(|(buffer, _)| buffer.file())
2847 }
2848
2849 pub fn language_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<Language>> {
2850 self.point_to_buffer_offset(point)
2851 .and_then(|(buffer, offset)| buffer.language_at(offset))
2852 }
2853
2854 pub fn settings_at<'a, T: ToOffset>(
2855 &'a self,
2856 point: T,
2857 cx: &'a AppContext,
2858 ) -> &'a LanguageSettings {
2859 let mut language = None;
2860 let mut file = None;
2861 if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
2862 language = buffer.language_at(offset);
2863 file = buffer.file();
2864 }
2865 language_settings(language, file, cx)
2866 }
2867
2868 pub fn language_scope_at<'a, T: ToOffset>(&'a self, point: T) -> Option<LanguageScope> {
2869 self.point_to_buffer_offset(point)
2870 .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
2871 }
2872
2873 pub fn language_indent_size_at<T: ToOffset>(
2874 &self,
2875 position: T,
2876 cx: &AppContext,
2877 ) -> Option<IndentSize> {
2878 let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
2879 Some(buffer_snapshot.language_indent_size_at(offset, cx))
2880 }
2881
2882 pub fn is_dirty(&self) -> bool {
2883 self.is_dirty
2884 }
2885
2886 pub fn has_conflict(&self) -> bool {
2887 self.has_conflict
2888 }
2889
2890 pub fn diagnostic_group<'a, O>(
2891 &'a self,
2892 group_id: usize,
2893 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2894 where
2895 O: text::FromAnchor + 'a,
2896 {
2897 self.as_singleton()
2898 .into_iter()
2899 .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2900 }
2901
2902 pub fn diagnostics_in_range<'a, T, O>(
2903 &'a self,
2904 range: Range<T>,
2905 reversed: bool,
2906 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2907 where
2908 T: 'a + ToOffset,
2909 O: 'a + text::FromAnchor + Ord,
2910 {
2911 self.as_singleton()
2912 .into_iter()
2913 .flat_map(move |(_, _, buffer)| {
2914 buffer.diagnostics_in_range(
2915 range.start.to_offset(self)..range.end.to_offset(self),
2916 reversed,
2917 )
2918 })
2919 }
2920
2921 pub fn has_git_diffs(&self) -> bool {
2922 for excerpt in self.excerpts.iter() {
2923 if !excerpt.buffer.git_diff.is_empty() {
2924 return true;
2925 }
2926 }
2927 false
2928 }
2929
2930 pub fn git_diff_hunks_in_range_rev<'a>(
2931 &'a self,
2932 row_range: Range<u32>,
2933 ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2934 let mut cursor = self.excerpts.cursor::<Point>();
2935
2936 cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
2937 if cursor.item().is_none() {
2938 cursor.prev(&());
2939 }
2940
2941 std::iter::from_fn(move || {
2942 let excerpt = cursor.item()?;
2943 let multibuffer_start = *cursor.start();
2944 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2945 if multibuffer_start.row >= row_range.end {
2946 return None;
2947 }
2948
2949 let mut buffer_start = excerpt.range.context.start;
2950 let mut buffer_end = excerpt.range.context.end;
2951 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
2952 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
2953
2954 if row_range.start > multibuffer_start.row {
2955 let buffer_start_point =
2956 excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
2957 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
2958 }
2959
2960 if row_range.end < multibuffer_end.row {
2961 let buffer_end_point =
2962 excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
2963 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
2964 }
2965
2966 let buffer_hunks = excerpt
2967 .buffer
2968 .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
2969 .filter_map(move |hunk| {
2970 let start = multibuffer_start.row
2971 + hunk
2972 .buffer_range
2973 .start
2974 .saturating_sub(excerpt_start_point.row);
2975 let end = multibuffer_start.row
2976 + hunk
2977 .buffer_range
2978 .end
2979 .min(excerpt_end_point.row + 1)
2980 .saturating_sub(excerpt_start_point.row);
2981
2982 Some(DiffHunk {
2983 buffer_range: start..end,
2984 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
2985 })
2986 });
2987
2988 cursor.prev(&());
2989
2990 Some(buffer_hunks)
2991 })
2992 .flatten()
2993 }
2994
2995 pub fn git_diff_hunks_in_range<'a>(
2996 &'a self,
2997 row_range: Range<u32>,
2998 ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2999 let mut cursor = self.excerpts.cursor::<Point>();
3000
3001 cursor.seek(&Point::new(row_range.start, 0), Bias::Right, &());
3002
3003 std::iter::from_fn(move || {
3004 let excerpt = cursor.item()?;
3005 let multibuffer_start = *cursor.start();
3006 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3007 if multibuffer_start.row >= row_range.end {
3008 return None;
3009 }
3010
3011 let mut buffer_start = excerpt.range.context.start;
3012 let mut buffer_end = excerpt.range.context.end;
3013 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3014 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3015
3016 if row_range.start > multibuffer_start.row {
3017 let buffer_start_point =
3018 excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
3019 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3020 }
3021
3022 if row_range.end < multibuffer_end.row {
3023 let buffer_end_point =
3024 excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
3025 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3026 }
3027
3028 let buffer_hunks = excerpt
3029 .buffer
3030 .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3031 .filter_map(move |hunk| {
3032 let start = multibuffer_start.row
3033 + hunk
3034 .buffer_range
3035 .start
3036 .saturating_sub(excerpt_start_point.row);
3037 let end = multibuffer_start.row
3038 + hunk
3039 .buffer_range
3040 .end
3041 .min(excerpt_end_point.row + 1)
3042 .saturating_sub(excerpt_start_point.row);
3043
3044 Some(DiffHunk {
3045 buffer_range: start..end,
3046 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3047 })
3048 });
3049
3050 cursor.next(&());
3051
3052 Some(buffer_hunks)
3053 })
3054 .flatten()
3055 }
3056
3057 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3058 let range = range.start.to_offset(self)..range.end.to_offset(self);
3059
3060 self.excerpt_containing(range.clone())
3061 .and_then(|(excerpt, excerpt_offset)| {
3062 let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3063 let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
3064
3065 let start_in_buffer =
3066 excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
3067 let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
3068 let mut ancestor_buffer_range = excerpt
3069 .buffer
3070 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
3071 ancestor_buffer_range.start =
3072 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
3073 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
3074
3075 let start = excerpt_offset + (ancestor_buffer_range.start - excerpt_buffer_start);
3076 let end = excerpt_offset + (ancestor_buffer_range.end - excerpt_buffer_start);
3077 Some(start..end)
3078 })
3079 }
3080
3081 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3082 let (excerpt_id, _, buffer) = self.as_singleton()?;
3083 let outline = buffer.outline(theme)?;
3084 Some(Outline::new(
3085 outline
3086 .items
3087 .into_iter()
3088 .map(|item| OutlineItem {
3089 depth: item.depth,
3090 range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
3091 ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
3092 text: item.text,
3093 highlight_ranges: item.highlight_ranges,
3094 name_ranges: item.name_ranges,
3095 })
3096 .collect(),
3097 ))
3098 }
3099
3100 pub fn symbols_containing<T: ToOffset>(
3101 &self,
3102 offset: T,
3103 theme: Option<&SyntaxTheme>,
3104 ) -> Option<(u64, Vec<OutlineItem<Anchor>>)> {
3105 let anchor = self.anchor_before(offset);
3106 let excerpt_id = anchor.excerpt_id();
3107 let excerpt = self.excerpt(excerpt_id)?;
3108 Some((
3109 excerpt.buffer_id,
3110 excerpt
3111 .buffer
3112 .symbols_containing(anchor.text_anchor, theme)
3113 .into_iter()
3114 .flatten()
3115 .map(|item| OutlineItem {
3116 depth: item.depth,
3117 range: self.anchor_in_excerpt(excerpt_id, item.range.start)
3118 ..self.anchor_in_excerpt(excerpt_id, item.range.end),
3119 text: item.text,
3120 highlight_ranges: item.highlight_ranges,
3121 name_ranges: item.name_ranges,
3122 })
3123 .collect(),
3124 ))
3125 }
3126
3127 fn excerpt_locator_for_id<'a>(&'a self, id: ExcerptId) -> &'a Locator {
3128 if id == ExcerptId::min() {
3129 Locator::min_ref()
3130 } else if id == ExcerptId::max() {
3131 Locator::max_ref()
3132 } else {
3133 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3134 cursor.seek(&id, Bias::Left, &());
3135 if let Some(entry) = cursor.item() {
3136 if entry.id == id {
3137 return &entry.locator;
3138 }
3139 }
3140 panic!("invalid excerpt id {:?}", id)
3141 }
3142 }
3143
3144 pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<u64> {
3145 Some(self.excerpt(excerpt_id)?.buffer_id)
3146 }
3147
3148 pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3149 Some(&self.excerpt(excerpt_id)?.buffer)
3150 }
3151
3152 fn excerpt<'a>(&'a self, excerpt_id: ExcerptId) -> Option<&'a Excerpt> {
3153 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3154 let locator = self.excerpt_locator_for_id(excerpt_id);
3155 cursor.seek(&Some(locator), Bias::Left, &());
3156 if let Some(excerpt) = cursor.item() {
3157 if excerpt.id == excerpt_id {
3158 return Some(excerpt);
3159 }
3160 }
3161 None
3162 }
3163
3164 /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3165 fn excerpt_containing<'a, T: ToOffset>(
3166 &'a self,
3167 range: Range<T>,
3168 ) -> Option<(&'a Excerpt, usize)> {
3169 let range = range.start.to_offset(self)..range.end.to_offset(self);
3170
3171 let mut cursor = self.excerpts.cursor::<usize>();
3172 cursor.seek(&range.start, Bias::Right, &());
3173 let start_excerpt = cursor.item();
3174
3175 if range.start == range.end {
3176 return start_excerpt.map(|excerpt| (excerpt, *cursor.start()));
3177 }
3178
3179 cursor.seek(&range.end, Bias::Right, &());
3180 let end_excerpt = cursor.item();
3181
3182 start_excerpt
3183 .zip(end_excerpt)
3184 .and_then(|(start_excerpt, end_excerpt)| {
3185 if start_excerpt.id != end_excerpt.id {
3186 return None;
3187 }
3188
3189 Some((start_excerpt, *cursor.start()))
3190 })
3191 }
3192
3193 pub fn remote_selections_in_range<'a>(
3194 &'a self,
3195 range: &'a Range<Anchor>,
3196 ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3197 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3198 let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3199 let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3200 cursor.seek(start_locator, Bias::Left, &());
3201 cursor
3202 .take_while(move |excerpt| excerpt.locator <= *end_locator)
3203 .flat_map(move |excerpt| {
3204 let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3205 if excerpt.id == range.start.excerpt_id {
3206 query_range.start = range.start.text_anchor;
3207 }
3208 if excerpt.id == range.end.excerpt_id {
3209 query_range.end = range.end.text_anchor;
3210 }
3211
3212 excerpt
3213 .buffer
3214 .remote_selections_in_range(query_range)
3215 .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3216 selections.map(move |selection| {
3217 let mut start = Anchor {
3218 buffer_id: Some(excerpt.buffer_id),
3219 excerpt_id: excerpt.id.clone(),
3220 text_anchor: selection.start,
3221 };
3222 let mut end = Anchor {
3223 buffer_id: Some(excerpt.buffer_id),
3224 excerpt_id: excerpt.id.clone(),
3225 text_anchor: selection.end,
3226 };
3227 if range.start.cmp(&start, self).is_gt() {
3228 start = range.start.clone();
3229 }
3230 if range.end.cmp(&end, self).is_lt() {
3231 end = range.end.clone();
3232 }
3233
3234 (
3235 replica_id,
3236 line_mode,
3237 cursor_shape,
3238 Selection {
3239 id: selection.id,
3240 start,
3241 end,
3242 reversed: selection.reversed,
3243 goal: selection.goal,
3244 },
3245 )
3246 })
3247 })
3248 })
3249 }
3250}
3251
3252#[cfg(any(test, feature = "test-support"))]
3253impl MultiBufferSnapshot {
3254 pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3255 let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3256 let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3257 start..end
3258 }
3259}
3260
3261impl History {
3262 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3263 self.transaction_depth += 1;
3264 if self.transaction_depth == 1 {
3265 let id = self.next_transaction_id.tick();
3266 self.undo_stack.push(Transaction {
3267 id,
3268 buffer_transactions: Default::default(),
3269 first_edit_at: now,
3270 last_edit_at: now,
3271 suppress_grouping: false,
3272 });
3273 Some(id)
3274 } else {
3275 None
3276 }
3277 }
3278
3279 fn end_transaction(
3280 &mut self,
3281 now: Instant,
3282 buffer_transactions: HashMap<u64, TransactionId>,
3283 ) -> bool {
3284 assert_ne!(self.transaction_depth, 0);
3285 self.transaction_depth -= 1;
3286 if self.transaction_depth == 0 {
3287 if buffer_transactions.is_empty() {
3288 self.undo_stack.pop();
3289 false
3290 } else {
3291 self.redo_stack.clear();
3292 let transaction = self.undo_stack.last_mut().unwrap();
3293 transaction.last_edit_at = now;
3294 for (buffer_id, transaction_id) in buffer_transactions {
3295 transaction
3296 .buffer_transactions
3297 .entry(buffer_id)
3298 .or_insert(transaction_id);
3299 }
3300 true
3301 }
3302 } else {
3303 false
3304 }
3305 }
3306
3307 fn push_transaction<'a, T>(
3308 &mut self,
3309 buffer_transactions: T,
3310 now: Instant,
3311 cx: &mut ModelContext<MultiBuffer>,
3312 ) where
3313 T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
3314 {
3315 assert_eq!(self.transaction_depth, 0);
3316 let transaction = Transaction {
3317 id: self.next_transaction_id.tick(),
3318 buffer_transactions: buffer_transactions
3319 .into_iter()
3320 .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3321 .collect(),
3322 first_edit_at: now,
3323 last_edit_at: now,
3324 suppress_grouping: false,
3325 };
3326 if !transaction.buffer_transactions.is_empty() {
3327 self.undo_stack.push(transaction);
3328 self.redo_stack.clear();
3329 }
3330 }
3331
3332 fn finalize_last_transaction(&mut self) {
3333 if let Some(transaction) = self.undo_stack.last_mut() {
3334 transaction.suppress_grouping = true;
3335 }
3336 }
3337
3338 fn pop_undo(&mut self) -> Option<&mut Transaction> {
3339 assert_eq!(self.transaction_depth, 0);
3340 if let Some(transaction) = self.undo_stack.pop() {
3341 self.redo_stack.push(transaction);
3342 self.redo_stack.last_mut()
3343 } else {
3344 None
3345 }
3346 }
3347
3348 fn pop_redo(&mut self) -> Option<&mut Transaction> {
3349 assert_eq!(self.transaction_depth, 0);
3350 if let Some(transaction) = self.redo_stack.pop() {
3351 self.undo_stack.push(transaction);
3352 self.undo_stack.last_mut()
3353 } else {
3354 None
3355 }
3356 }
3357
3358 fn group(&mut self) -> Option<TransactionId> {
3359 let mut count = 0;
3360 let mut transactions = self.undo_stack.iter();
3361 if let Some(mut transaction) = transactions.next_back() {
3362 while let Some(prev_transaction) = transactions.next_back() {
3363 if !prev_transaction.suppress_grouping
3364 && transaction.first_edit_at - prev_transaction.last_edit_at
3365 <= self.group_interval
3366 {
3367 transaction = prev_transaction;
3368 count += 1;
3369 } else {
3370 break;
3371 }
3372 }
3373 }
3374 self.group_trailing(count)
3375 }
3376
3377 fn group_until(&mut self, transaction_id: TransactionId) {
3378 let mut count = 0;
3379 for transaction in self.undo_stack.iter().rev() {
3380 if transaction.id == transaction_id {
3381 self.group_trailing(count);
3382 break;
3383 } else if transaction.suppress_grouping {
3384 break;
3385 } else {
3386 count += 1;
3387 }
3388 }
3389 }
3390
3391 fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3392 let new_len = self.undo_stack.len() - n;
3393 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3394 if let Some(last_transaction) = transactions_to_keep.last_mut() {
3395 if let Some(transaction) = transactions_to_merge.last() {
3396 last_transaction.last_edit_at = transaction.last_edit_at;
3397 }
3398 for to_merge in transactions_to_merge {
3399 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3400 last_transaction
3401 .buffer_transactions
3402 .entry(*buffer_id)
3403 .or_insert(*transaction_id);
3404 }
3405 }
3406 }
3407
3408 self.undo_stack.truncate(new_len);
3409 self.undo_stack.last().map(|t| t.id)
3410 }
3411}
3412
3413impl Excerpt {
3414 fn new(
3415 id: ExcerptId,
3416 locator: Locator,
3417 buffer_id: u64,
3418 buffer: BufferSnapshot,
3419 range: ExcerptRange<text::Anchor>,
3420 has_trailing_newline: bool,
3421 ) -> Self {
3422 Excerpt {
3423 id,
3424 locator,
3425 max_buffer_row: range.context.end.to_point(&buffer).row,
3426 text_summary: buffer
3427 .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3428 buffer_id,
3429 buffer,
3430 range,
3431 has_trailing_newline,
3432 }
3433 }
3434
3435 fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3436 let content_start = self.range.context.start.to_offset(&self.buffer);
3437 let chunks_start = content_start + range.start;
3438 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3439
3440 let footer_height = if self.has_trailing_newline
3441 && range.start <= self.text_summary.len
3442 && range.end > self.text_summary.len
3443 {
3444 1
3445 } else {
3446 0
3447 };
3448
3449 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3450
3451 ExcerptChunks {
3452 content_chunks,
3453 footer_height,
3454 }
3455 }
3456
3457 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3458 let content_start = self.range.context.start.to_offset(&self.buffer);
3459 let bytes_start = content_start + range.start;
3460 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3461 let footer_height = if self.has_trailing_newline
3462 && range.start <= self.text_summary.len
3463 && range.end > self.text_summary.len
3464 {
3465 1
3466 } else {
3467 0
3468 };
3469 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3470
3471 ExcerptBytes {
3472 content_bytes,
3473 footer_height,
3474 }
3475 }
3476
3477 fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3478 let content_start = self.range.context.start.to_offset(&self.buffer);
3479 let bytes_start = content_start + range.start;
3480 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3481 let footer_height = if self.has_trailing_newline
3482 && range.start <= self.text_summary.len
3483 && range.end > self.text_summary.len
3484 {
3485 1
3486 } else {
3487 0
3488 };
3489 let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
3490
3491 ExcerptBytes {
3492 content_bytes,
3493 footer_height,
3494 }
3495 }
3496
3497 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3498 if text_anchor
3499 .cmp(&self.range.context.start, &self.buffer)
3500 .is_lt()
3501 {
3502 self.range.context.start
3503 } else if text_anchor
3504 .cmp(&self.range.context.end, &self.buffer)
3505 .is_gt()
3506 {
3507 self.range.context.end
3508 } else {
3509 text_anchor
3510 }
3511 }
3512
3513 fn contains(&self, anchor: &Anchor) -> bool {
3514 Some(self.buffer_id) == anchor.buffer_id
3515 && self
3516 .range
3517 .context
3518 .start
3519 .cmp(&anchor.text_anchor, &self.buffer)
3520 .is_le()
3521 && self
3522 .range
3523 .context
3524 .end
3525 .cmp(&anchor.text_anchor, &self.buffer)
3526 .is_ge()
3527 }
3528}
3529
3530impl ExcerptId {
3531 pub fn min() -> Self {
3532 Self(0)
3533 }
3534
3535 pub fn max() -> Self {
3536 Self(usize::MAX)
3537 }
3538
3539 pub fn to_proto(&self) -> u64 {
3540 self.0 as _
3541 }
3542
3543 pub fn from_proto(proto: u64) -> Self {
3544 Self(proto as _)
3545 }
3546
3547 pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3548 let a = snapshot.excerpt_locator_for_id(*self);
3549 let b = snapshot.excerpt_locator_for_id(*other);
3550 a.cmp(&b).then_with(|| self.0.cmp(&other.0))
3551 }
3552}
3553
3554impl Into<usize> for ExcerptId {
3555 fn into(self) -> usize {
3556 self.0
3557 }
3558}
3559
3560impl fmt::Debug for Excerpt {
3561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3562 f.debug_struct("Excerpt")
3563 .field("id", &self.id)
3564 .field("locator", &self.locator)
3565 .field("buffer_id", &self.buffer_id)
3566 .field("range", &self.range)
3567 .field("text_summary", &self.text_summary)
3568 .field("has_trailing_newline", &self.has_trailing_newline)
3569 .finish()
3570 }
3571}
3572
3573impl sum_tree::Item for Excerpt {
3574 type Summary = ExcerptSummary;
3575
3576 fn summary(&self) -> Self::Summary {
3577 let mut text = self.text_summary.clone();
3578 if self.has_trailing_newline {
3579 text += TextSummary::from("\n");
3580 }
3581 ExcerptSummary {
3582 excerpt_id: self.id,
3583 excerpt_locator: self.locator.clone(),
3584 max_buffer_row: self.max_buffer_row,
3585 text,
3586 }
3587 }
3588}
3589
3590impl sum_tree::Item for ExcerptIdMapping {
3591 type Summary = ExcerptId;
3592
3593 fn summary(&self) -> Self::Summary {
3594 self.id
3595 }
3596}
3597
3598impl sum_tree::KeyedItem for ExcerptIdMapping {
3599 type Key = ExcerptId;
3600
3601 fn key(&self) -> Self::Key {
3602 self.id
3603 }
3604}
3605
3606impl sum_tree::Summary for ExcerptId {
3607 type Context = ();
3608
3609 fn add_summary(&mut self, other: &Self, _: &()) {
3610 *self = *other;
3611 }
3612}
3613
3614impl sum_tree::Summary for ExcerptSummary {
3615 type Context = ();
3616
3617 fn add_summary(&mut self, summary: &Self, _: &()) {
3618 debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3619 self.excerpt_locator = summary.excerpt_locator.clone();
3620 self.text.add_summary(&summary.text, &());
3621 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3622 }
3623}
3624
3625impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3626 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3627 *self += &summary.text;
3628 }
3629}
3630
3631impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3632 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3633 *self += summary.text.len;
3634 }
3635}
3636
3637impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3638 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3639 Ord::cmp(self, &cursor_location.text.len)
3640 }
3641}
3642
3643impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3644 fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3645 Ord::cmp(&Some(self), cursor_location)
3646 }
3647}
3648
3649impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3650 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3651 Ord::cmp(self, &cursor_location.excerpt_locator)
3652 }
3653}
3654
3655impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3656 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3657 *self += summary.text.len_utf16;
3658 }
3659}
3660
3661impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3662 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3663 *self += summary.text.lines;
3664 }
3665}
3666
3667impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3668 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3669 *self += summary.text.lines_utf16()
3670 }
3671}
3672
3673impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3674 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3675 *self = Some(&summary.excerpt_locator);
3676 }
3677}
3678
3679impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3680 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3681 *self = Some(summary.excerpt_id);
3682 }
3683}
3684
3685impl<'a> MultiBufferRows<'a> {
3686 pub fn seek(&mut self, row: u32) {
3687 self.buffer_row_range = 0..0;
3688
3689 self.excerpts
3690 .seek_forward(&Point::new(row, 0), Bias::Right, &());
3691 if self.excerpts.item().is_none() {
3692 self.excerpts.prev(&());
3693
3694 if self.excerpts.item().is_none() && row == 0 {
3695 self.buffer_row_range = 0..1;
3696 return;
3697 }
3698 }
3699
3700 if let Some(excerpt) = self.excerpts.item() {
3701 let overshoot = row - self.excerpts.start().row;
3702 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3703 self.buffer_row_range.start = excerpt_start + overshoot;
3704 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3705 }
3706 }
3707}
3708
3709impl<'a> Iterator for MultiBufferRows<'a> {
3710 type Item = Option<u32>;
3711
3712 fn next(&mut self) -> Option<Self::Item> {
3713 loop {
3714 if !self.buffer_row_range.is_empty() {
3715 let row = Some(self.buffer_row_range.start);
3716 self.buffer_row_range.start += 1;
3717 return Some(row);
3718 }
3719 self.excerpts.item()?;
3720 self.excerpts.next(&());
3721 let excerpt = self.excerpts.item()?;
3722 self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3723 self.buffer_row_range.end =
3724 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3725 }
3726 }
3727}
3728
3729impl<'a> MultiBufferChunks<'a> {
3730 pub fn offset(&self) -> usize {
3731 self.range.start
3732 }
3733
3734 pub fn seek(&mut self, offset: usize) {
3735 self.range.start = offset;
3736 self.excerpts.seek(&offset, Bias::Right, &());
3737 if let Some(excerpt) = self.excerpts.item() {
3738 self.excerpt_chunks = Some(excerpt.chunks_in_range(
3739 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3740 self.language_aware,
3741 ));
3742 } else {
3743 self.excerpt_chunks = None;
3744 }
3745 }
3746}
3747
3748impl<'a> Iterator for MultiBufferChunks<'a> {
3749 type Item = Chunk<'a>;
3750
3751 fn next(&mut self) -> Option<Self::Item> {
3752 if self.range.is_empty() {
3753 None
3754 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3755 self.range.start += chunk.text.len();
3756 Some(chunk)
3757 } else {
3758 self.excerpts.next(&());
3759 let excerpt = self.excerpts.item()?;
3760 self.excerpt_chunks = Some(excerpt.chunks_in_range(
3761 0..self.range.end - self.excerpts.start(),
3762 self.language_aware,
3763 ));
3764 self.next()
3765 }
3766 }
3767}
3768
3769impl<'a> MultiBufferBytes<'a> {
3770 fn consume(&mut self, len: usize) {
3771 self.range.start += len;
3772 self.chunk = &self.chunk[len..];
3773
3774 if !self.range.is_empty() && self.chunk.is_empty() {
3775 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3776 self.chunk = chunk;
3777 } else {
3778 self.excerpts.next(&());
3779 if let Some(excerpt) = self.excerpts.item() {
3780 let mut excerpt_bytes =
3781 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3782 self.chunk = excerpt_bytes.next().unwrap();
3783 self.excerpt_bytes = Some(excerpt_bytes);
3784 }
3785 }
3786 }
3787 }
3788}
3789
3790impl<'a> Iterator for MultiBufferBytes<'a> {
3791 type Item = &'a [u8];
3792
3793 fn next(&mut self) -> Option<Self::Item> {
3794 let chunk = self.chunk;
3795 if chunk.is_empty() {
3796 None
3797 } else {
3798 self.consume(chunk.len());
3799 Some(chunk)
3800 }
3801 }
3802}
3803
3804impl<'a> io::Read for MultiBufferBytes<'a> {
3805 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3806 let len = cmp::min(buf.len(), self.chunk.len());
3807 buf[..len].copy_from_slice(&self.chunk[..len]);
3808 if len > 0 {
3809 self.consume(len);
3810 }
3811 Ok(len)
3812 }
3813}
3814
3815impl<'a> ReversedMultiBufferBytes<'a> {
3816 fn consume(&mut self, len: usize) {
3817 self.range.end -= len;
3818 self.chunk = &self.chunk[..self.chunk.len() - len];
3819
3820 if !self.range.is_empty() && self.chunk.is_empty() {
3821 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3822 self.chunk = chunk;
3823 } else {
3824 self.excerpts.next(&());
3825 if let Some(excerpt) = self.excerpts.item() {
3826 let mut excerpt_bytes =
3827 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3828 self.chunk = excerpt_bytes.next().unwrap();
3829 self.excerpt_bytes = Some(excerpt_bytes);
3830 }
3831 }
3832 }
3833 }
3834}
3835
3836impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
3837 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3838 let len = cmp::min(buf.len(), self.chunk.len());
3839 buf[..len].copy_from_slice(&self.chunk[..len]);
3840 buf[..len].reverse();
3841 if len > 0 {
3842 self.consume(len);
3843 }
3844 Ok(len)
3845 }
3846}
3847impl<'a> Iterator for ExcerptBytes<'a> {
3848 type Item = &'a [u8];
3849
3850 fn next(&mut self) -> Option<Self::Item> {
3851 if let Some(chunk) = self.content_bytes.next() {
3852 if !chunk.is_empty() {
3853 return Some(chunk);
3854 }
3855 }
3856
3857 if self.footer_height > 0 {
3858 let result = &NEWLINES[..self.footer_height];
3859 self.footer_height = 0;
3860 return Some(result);
3861 }
3862
3863 None
3864 }
3865}
3866
3867impl<'a> Iterator for ExcerptChunks<'a> {
3868 type Item = Chunk<'a>;
3869
3870 fn next(&mut self) -> Option<Self::Item> {
3871 if let Some(chunk) = self.content_chunks.next() {
3872 return Some(chunk);
3873 }
3874
3875 if self.footer_height > 0 {
3876 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3877 self.footer_height = 0;
3878 return Some(Chunk {
3879 text,
3880 ..Default::default()
3881 });
3882 }
3883
3884 None
3885 }
3886}
3887
3888impl ToOffset for Point {
3889 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3890 snapshot.point_to_offset(*self)
3891 }
3892}
3893
3894impl ToOffset for usize {
3895 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3896 assert!(*self <= snapshot.len(), "offset is out of range");
3897 *self
3898 }
3899}
3900
3901impl ToOffset for OffsetUtf16 {
3902 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3903 snapshot.offset_utf16_to_offset(*self)
3904 }
3905}
3906
3907impl ToOffset for PointUtf16 {
3908 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3909 snapshot.point_utf16_to_offset(*self)
3910 }
3911}
3912
3913impl ToOffsetUtf16 for OffsetUtf16 {
3914 fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3915 *self
3916 }
3917}
3918
3919impl ToOffsetUtf16 for usize {
3920 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3921 snapshot.offset_to_offset_utf16(*self)
3922 }
3923}
3924
3925impl ToPoint for usize {
3926 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3927 snapshot.offset_to_point(*self)
3928 }
3929}
3930
3931impl ToPoint for Point {
3932 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3933 *self
3934 }
3935}
3936
3937impl ToPointUtf16 for usize {
3938 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3939 snapshot.offset_to_point_utf16(*self)
3940 }
3941}
3942
3943impl ToPointUtf16 for Point {
3944 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3945 snapshot.point_to_point_utf16(*self)
3946 }
3947}
3948
3949impl ToPointUtf16 for PointUtf16 {
3950 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3951 *self
3952 }
3953}
3954
3955fn build_excerpt_ranges<T>(
3956 buffer: &BufferSnapshot,
3957 ranges: &[Range<T>],
3958 context_line_count: u32,
3959) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
3960where
3961 T: text::ToPoint,
3962{
3963 let max_point = buffer.max_point();
3964 let mut range_counts = Vec::new();
3965 let mut excerpt_ranges = Vec::new();
3966 let mut range_iter = ranges
3967 .iter()
3968 .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
3969 .peekable();
3970 while let Some(range) = range_iter.next() {
3971 let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
3972 let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
3973 let mut ranges_in_excerpt = 1;
3974
3975 while let Some(next_range) = range_iter.peek() {
3976 if next_range.start.row <= excerpt_end.row + context_line_count {
3977 excerpt_end =
3978 Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
3979 ranges_in_excerpt += 1;
3980 range_iter.next();
3981 } else {
3982 break;
3983 }
3984 }
3985
3986 excerpt_ranges.push(ExcerptRange {
3987 context: excerpt_start..excerpt_end,
3988 primary: Some(range),
3989 });
3990 range_counts.push(ranges_in_excerpt);
3991 }
3992
3993 (excerpt_ranges, range_counts)
3994}
3995
3996#[cfg(test)]
3997mod tests {
3998 use crate::editor_tests::init_test;
3999
4000 use super::*;
4001 use futures::StreamExt;
4002 use gpui::{AppContext, TestAppContext};
4003 use language::{Buffer, Rope};
4004 use project::{FakeFs, Project};
4005 use rand::prelude::*;
4006 use settings::SettingsStore;
4007 use std::{env, rc::Rc};
4008 use unindent::Unindent;
4009 use util::test::sample_text;
4010
4011 #[gpui::test]
4012 fn test_singleton(cx: &mut AppContext) {
4013 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
4014 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4015
4016 let snapshot = multibuffer.read(cx).snapshot(cx);
4017 assert_eq!(snapshot.text(), buffer.read(cx).text());
4018
4019 assert_eq!(
4020 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4021 (0..buffer.read(cx).row_count())
4022 .map(Some)
4023 .collect::<Vec<_>>()
4024 );
4025
4026 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4027 let snapshot = multibuffer.read(cx).snapshot(cx);
4028
4029 assert_eq!(snapshot.text(), buffer.read(cx).text());
4030 assert_eq!(
4031 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4032 (0..buffer.read(cx).row_count())
4033 .map(Some)
4034 .collect::<Vec<_>>()
4035 );
4036 }
4037
4038 #[gpui::test]
4039 fn test_remote(cx: &mut AppContext) {
4040 let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
4041 let guest_buffer = cx.add_model(|cx| {
4042 let state = host_buffer.read(cx).to_proto();
4043 let ops = cx
4044 .background()
4045 .block(host_buffer.read(cx).serialize_ops(None, cx));
4046 let mut buffer = Buffer::from_proto(1, state, None).unwrap();
4047 buffer
4048 .apply_ops(
4049 ops.into_iter()
4050 .map(|op| language::proto::deserialize_operation(op).unwrap()),
4051 cx,
4052 )
4053 .unwrap();
4054 buffer
4055 });
4056 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4057 let snapshot = multibuffer.read(cx).snapshot(cx);
4058 assert_eq!(snapshot.text(), "a");
4059
4060 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4061 let snapshot = multibuffer.read(cx).snapshot(cx);
4062 assert_eq!(snapshot.text(), "ab");
4063
4064 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4065 let snapshot = multibuffer.read(cx).snapshot(cx);
4066 assert_eq!(snapshot.text(), "abc");
4067 }
4068
4069 #[gpui::test]
4070 fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4071 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
4072 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
4073 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4074
4075 let events = Rc::new(RefCell::new(Vec::<Event>::new()));
4076 multibuffer.update(cx, |_, cx| {
4077 let events = events.clone();
4078 cx.subscribe(&multibuffer, move |_, _, event, _| {
4079 if let Event::Edited = event {
4080 events.borrow_mut().push(event.clone())
4081 }
4082 })
4083 .detach();
4084 });
4085
4086 let subscription = multibuffer.update(cx, |multibuffer, cx| {
4087 let subscription = multibuffer.subscribe();
4088 multibuffer.push_excerpts(
4089 buffer_1.clone(),
4090 [ExcerptRange {
4091 context: Point::new(1, 2)..Point::new(2, 5),
4092 primary: None,
4093 }],
4094 cx,
4095 );
4096 assert_eq!(
4097 subscription.consume().into_inner(),
4098 [Edit {
4099 old: 0..0,
4100 new: 0..10
4101 }]
4102 );
4103
4104 multibuffer.push_excerpts(
4105 buffer_1.clone(),
4106 [ExcerptRange {
4107 context: Point::new(3, 3)..Point::new(4, 4),
4108 primary: None,
4109 }],
4110 cx,
4111 );
4112 multibuffer.push_excerpts(
4113 buffer_2.clone(),
4114 [ExcerptRange {
4115 context: Point::new(3, 1)..Point::new(3, 3),
4116 primary: None,
4117 }],
4118 cx,
4119 );
4120 assert_eq!(
4121 subscription.consume().into_inner(),
4122 [Edit {
4123 old: 10..10,
4124 new: 10..22
4125 }]
4126 );
4127
4128 subscription
4129 });
4130
4131 // Adding excerpts emits an edited event.
4132 assert_eq!(
4133 events.borrow().as_slice(),
4134 &[Event::Edited, Event::Edited, Event::Edited]
4135 );
4136
4137 let snapshot = multibuffer.read(cx).snapshot(cx);
4138 assert_eq!(
4139 snapshot.text(),
4140 concat!(
4141 "bbbb\n", // Preserve newlines
4142 "ccccc\n", //
4143 "ddd\n", //
4144 "eeee\n", //
4145 "jj" //
4146 )
4147 );
4148 assert_eq!(
4149 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4150 [Some(1), Some(2), Some(3), Some(4), Some(3)]
4151 );
4152 assert_eq!(
4153 snapshot.buffer_rows(2).collect::<Vec<_>>(),
4154 [Some(3), Some(4), Some(3)]
4155 );
4156 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
4157 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
4158
4159 assert_eq!(
4160 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4161 &[
4162 (0, "bbbb\nccccc".to_string(), true),
4163 (2, "ddd\neeee".to_string(), false),
4164 (4, "jj".to_string(), true),
4165 ]
4166 );
4167 assert_eq!(
4168 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4169 &[(0, "bbbb\nccccc".to_string(), true)]
4170 );
4171 assert_eq!(
4172 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4173 &[]
4174 );
4175 assert_eq!(
4176 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4177 &[]
4178 );
4179 assert_eq!(
4180 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4181 &[(2, "ddd\neeee".to_string(), false)]
4182 );
4183 assert_eq!(
4184 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4185 &[(2, "ddd\neeee".to_string(), false)]
4186 );
4187 assert_eq!(
4188 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4189 &[(2, "ddd\neeee".to_string(), false)]
4190 );
4191 assert_eq!(
4192 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4193 &[(4, "jj".to_string(), true)]
4194 );
4195 assert_eq!(
4196 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4197 &[]
4198 );
4199
4200 buffer_1.update(cx, |buffer, cx| {
4201 let text = "\n";
4202 buffer.edit(
4203 [
4204 (Point::new(0, 0)..Point::new(0, 0), text),
4205 (Point::new(2, 1)..Point::new(2, 3), text),
4206 ],
4207 None,
4208 cx,
4209 );
4210 });
4211
4212 let snapshot = multibuffer.read(cx).snapshot(cx);
4213 assert_eq!(
4214 snapshot.text(),
4215 concat!(
4216 "bbbb\n", // Preserve newlines
4217 "c\n", //
4218 "cc\n", //
4219 "ddd\n", //
4220 "eeee\n", //
4221 "jj" //
4222 )
4223 );
4224
4225 assert_eq!(
4226 subscription.consume().into_inner(),
4227 [Edit {
4228 old: 6..8,
4229 new: 6..7
4230 }]
4231 );
4232
4233 let snapshot = multibuffer.read(cx).snapshot(cx);
4234 assert_eq!(
4235 snapshot.clip_point(Point::new(0, 5), Bias::Left),
4236 Point::new(0, 4)
4237 );
4238 assert_eq!(
4239 snapshot.clip_point(Point::new(0, 5), Bias::Right),
4240 Point::new(0, 4)
4241 );
4242 assert_eq!(
4243 snapshot.clip_point(Point::new(5, 1), Bias::Right),
4244 Point::new(5, 1)
4245 );
4246 assert_eq!(
4247 snapshot.clip_point(Point::new(5, 2), Bias::Right),
4248 Point::new(5, 2)
4249 );
4250 assert_eq!(
4251 snapshot.clip_point(Point::new(5, 3), Bias::Right),
4252 Point::new(5, 2)
4253 );
4254
4255 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4256 let (buffer_2_excerpt_id, _) =
4257 multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4258 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4259 multibuffer.snapshot(cx)
4260 });
4261
4262 assert_eq!(
4263 snapshot.text(),
4264 concat!(
4265 "bbbb\n", // Preserve newlines
4266 "c\n", //
4267 "cc\n", //
4268 "ddd\n", //
4269 "eeee", //
4270 )
4271 );
4272
4273 fn boundaries_in_range(
4274 range: Range<Point>,
4275 snapshot: &MultiBufferSnapshot,
4276 ) -> Vec<(u32, String, bool)> {
4277 snapshot
4278 .excerpt_boundaries_in_range(range)
4279 .map(|boundary| {
4280 (
4281 boundary.row,
4282 boundary
4283 .buffer
4284 .text_for_range(boundary.range.context)
4285 .collect::<String>(),
4286 boundary.starts_new_buffer,
4287 )
4288 })
4289 .collect::<Vec<_>>()
4290 }
4291 }
4292
4293 #[gpui::test]
4294 fn test_excerpt_events(cx: &mut AppContext) {
4295 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'a'), cx));
4296 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'm'), cx));
4297
4298 let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4299 let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4300 let follower_edit_event_count = Rc::new(RefCell::new(0));
4301
4302 follower_multibuffer.update(cx, |_, cx| {
4303 let follower_edit_event_count = follower_edit_event_count.clone();
4304 cx.subscribe(
4305 &leader_multibuffer,
4306 move |follower, _, event, cx| match event.clone() {
4307 Event::ExcerptsAdded {
4308 buffer,
4309 predecessor,
4310 excerpts,
4311 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4312 Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4313 Event::Edited => {
4314 *follower_edit_event_count.borrow_mut() += 1;
4315 }
4316 _ => {}
4317 },
4318 )
4319 .detach();
4320 });
4321
4322 leader_multibuffer.update(cx, |leader, cx| {
4323 leader.push_excerpts(
4324 buffer_1.clone(),
4325 [
4326 ExcerptRange {
4327 context: 0..8,
4328 primary: None,
4329 },
4330 ExcerptRange {
4331 context: 12..16,
4332 primary: None,
4333 },
4334 ],
4335 cx,
4336 );
4337 leader.insert_excerpts_after(
4338 leader.excerpt_ids()[0],
4339 buffer_2.clone(),
4340 [
4341 ExcerptRange {
4342 context: 0..5,
4343 primary: None,
4344 },
4345 ExcerptRange {
4346 context: 10..15,
4347 primary: None,
4348 },
4349 ],
4350 cx,
4351 )
4352 });
4353 assert_eq!(
4354 leader_multibuffer.read(cx).snapshot(cx).text(),
4355 follower_multibuffer.read(cx).snapshot(cx).text(),
4356 );
4357 assert_eq!(*follower_edit_event_count.borrow(), 2);
4358
4359 leader_multibuffer.update(cx, |leader, cx| {
4360 let excerpt_ids = leader.excerpt_ids();
4361 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4362 });
4363 assert_eq!(
4364 leader_multibuffer.read(cx).snapshot(cx).text(),
4365 follower_multibuffer.read(cx).snapshot(cx).text(),
4366 );
4367 assert_eq!(*follower_edit_event_count.borrow(), 3);
4368
4369 // Removing an empty set of excerpts is a noop.
4370 leader_multibuffer.update(cx, |leader, cx| {
4371 leader.remove_excerpts([], cx);
4372 });
4373 assert_eq!(
4374 leader_multibuffer.read(cx).snapshot(cx).text(),
4375 follower_multibuffer.read(cx).snapshot(cx).text(),
4376 );
4377 assert_eq!(*follower_edit_event_count.borrow(), 3);
4378
4379 // Adding an empty set of excerpts is a noop.
4380 leader_multibuffer.update(cx, |leader, cx| {
4381 leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
4382 });
4383 assert_eq!(
4384 leader_multibuffer.read(cx).snapshot(cx).text(),
4385 follower_multibuffer.read(cx).snapshot(cx).text(),
4386 );
4387 assert_eq!(*follower_edit_event_count.borrow(), 3);
4388
4389 leader_multibuffer.update(cx, |leader, cx| {
4390 leader.clear(cx);
4391 });
4392 assert_eq!(
4393 leader_multibuffer.read(cx).snapshot(cx).text(),
4394 follower_multibuffer.read(cx).snapshot(cx).text(),
4395 );
4396 assert_eq!(*follower_edit_event_count.borrow(), 4);
4397 }
4398
4399 #[gpui::test]
4400 fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4401 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4402 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4403 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4404 multibuffer.push_excerpts_with_context_lines(
4405 buffer.clone(),
4406 vec![
4407 Point::new(3, 2)..Point::new(4, 2),
4408 Point::new(7, 1)..Point::new(7, 3),
4409 Point::new(15, 0)..Point::new(15, 0),
4410 ],
4411 2,
4412 cx,
4413 )
4414 });
4415
4416 let snapshot = multibuffer.read(cx).snapshot(cx);
4417 assert_eq!(
4418 snapshot.text(),
4419 "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4420 );
4421
4422 assert_eq!(
4423 anchor_ranges
4424 .iter()
4425 .map(|range| range.to_point(&snapshot))
4426 .collect::<Vec<_>>(),
4427 vec![
4428 Point::new(2, 2)..Point::new(3, 2),
4429 Point::new(6, 1)..Point::new(6, 3),
4430 Point::new(12, 0)..Point::new(12, 0)
4431 ]
4432 );
4433 }
4434
4435 #[gpui::test]
4436 async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
4437 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4438 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4439 let (task, anchor_ranges) = multibuffer.update(cx, |multibuffer, cx| {
4440 let snapshot = buffer.read(cx);
4441 let ranges = vec![
4442 snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
4443 snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
4444 snapshot.anchor_before(Point::new(15, 0))
4445 ..snapshot.anchor_before(Point::new(15, 0)),
4446 ];
4447 multibuffer.stream_excerpts_with_context_lines(vec![(buffer.clone(), ranges)], 2, cx)
4448 });
4449
4450 let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
4451 // Ensure task is finished when stream completes.
4452 task.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}