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