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