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