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