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