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