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