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