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