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,
671 excerpt_id: excerpt_id.clone(),
672 text_anchor: buffer_snapshot.anchor_after(range.start),
673 };
674 let end = Anchor {
675 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 ) -> (ModelHandle<Buffer>, language::Anchor) {
917 let snapshot = self.read(cx);
918 let anchor = snapshot.anchor_before(position);
919 (
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 let buffer = self.buffers.borrow()[&anchor.buffer_id].buffer.clone();
992 buffer
993 .read(cx)
994 .completion_triggers()
995 .iter()
996 .any(|string| string == text)
997 }
998
999 pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
1000 self.buffers
1001 .borrow()
1002 .values()
1003 .next()
1004 .and_then(|state| state.buffer.read(cx).language())
1005 }
1006
1007 pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
1008 self.as_singleton()?.read(cx).file()
1009 }
1010
1011 pub fn title(&self, cx: &AppContext) -> String {
1012 if let Some(title) = self.title.clone() {
1013 title
1014 } else if let Some(file) = self.file(cx) {
1015 file.file_name(cx).to_string_lossy().into()
1016 } else {
1017 "untitled".into()
1018 }
1019 }
1020
1021 #[cfg(test)]
1022 pub fn is_parsing(&self, cx: &AppContext) -> bool {
1023 self.as_singleton().unwrap().read(cx).is_parsing()
1024 }
1025
1026 fn sync(&self, cx: &AppContext) {
1027 let mut snapshot = self.snapshot.borrow_mut();
1028 let mut excerpts_to_edit = Vec::new();
1029 let mut reparsed = false;
1030 let mut diagnostics_updated = false;
1031 let mut is_dirty = false;
1032 let mut has_conflict = false;
1033 let mut buffers = self.buffers.borrow_mut();
1034 for buffer_state in buffers.values_mut() {
1035 let buffer = buffer_state.buffer.read(cx);
1036 let version = buffer.version();
1037 let parse_count = buffer.parse_count();
1038 let selections_update_count = buffer.selections_update_count();
1039 let diagnostics_update_count = buffer.diagnostics_update_count();
1040 let file_update_count = buffer.file_update_count();
1041
1042 let buffer_edited = version.changed_since(&buffer_state.last_version);
1043 let buffer_reparsed = parse_count > buffer_state.last_parse_count;
1044 let buffer_selections_updated =
1045 selections_update_count > buffer_state.last_selections_update_count;
1046 let buffer_diagnostics_updated =
1047 diagnostics_update_count > buffer_state.last_diagnostics_update_count;
1048 let buffer_file_updated = file_update_count > buffer_state.last_file_update_count;
1049 if buffer_edited
1050 || buffer_reparsed
1051 || buffer_selections_updated
1052 || buffer_diagnostics_updated
1053 || buffer_file_updated
1054 {
1055 buffer_state.last_version = version;
1056 buffer_state.last_parse_count = parse_count;
1057 buffer_state.last_selections_update_count = selections_update_count;
1058 buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1059 buffer_state.last_file_update_count = file_update_count;
1060 excerpts_to_edit.extend(
1061 buffer_state
1062 .excerpts
1063 .iter()
1064 .map(|excerpt_id| (excerpt_id, buffer_state.buffer.clone(), buffer_edited)),
1065 );
1066 }
1067
1068 reparsed |= buffer_reparsed;
1069 diagnostics_updated |= buffer_diagnostics_updated;
1070 is_dirty |= buffer.is_dirty();
1071 has_conflict |= buffer.has_conflict();
1072 }
1073 if reparsed {
1074 snapshot.parse_count += 1;
1075 }
1076 if diagnostics_updated {
1077 snapshot.diagnostics_update_count += 1;
1078 }
1079 snapshot.is_dirty = is_dirty;
1080 snapshot.has_conflict = has_conflict;
1081
1082 excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
1083
1084 let mut edits = Vec::new();
1085 let mut new_excerpts = SumTree::new();
1086 let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
1087
1088 for (id, buffer, buffer_edited) in excerpts_to_edit {
1089 new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
1090 let old_excerpt = cursor.item().unwrap();
1091 let buffer_id = buffer.id();
1092 let buffer = buffer.read(cx);
1093
1094 let mut new_excerpt;
1095 if buffer_edited {
1096 edits.extend(
1097 buffer
1098 .edits_since_in_range::<usize>(
1099 old_excerpt.buffer.version(),
1100 old_excerpt.range.clone(),
1101 )
1102 .map(|mut edit| {
1103 let excerpt_old_start = cursor.start().1;
1104 let excerpt_new_start = new_excerpts.summary().text.bytes;
1105 edit.old.start += excerpt_old_start;
1106 edit.old.end += excerpt_old_start;
1107 edit.new.start += excerpt_new_start;
1108 edit.new.end += excerpt_new_start;
1109 edit
1110 }),
1111 );
1112
1113 new_excerpt = Excerpt::new(
1114 id.clone(),
1115 buffer_id,
1116 buffer.snapshot(),
1117 old_excerpt.range.clone(),
1118 old_excerpt.has_trailing_newline,
1119 );
1120 } else {
1121 new_excerpt = old_excerpt.clone();
1122 new_excerpt.buffer = buffer.snapshot();
1123 }
1124
1125 new_excerpts.push(new_excerpt, &());
1126 cursor.next(&());
1127 }
1128 new_excerpts.push_tree(cursor.suffix(&()), &());
1129
1130 drop(cursor);
1131 snapshot.excerpts = new_excerpts;
1132
1133 self.subscriptions.publish(edits);
1134 }
1135}
1136
1137#[cfg(any(test, feature = "test-support"))]
1138impl MultiBuffer {
1139 pub fn randomly_edit(
1140 &mut self,
1141 rng: &mut impl rand::Rng,
1142 count: usize,
1143 cx: &mut ModelContext<Self>,
1144 ) {
1145 use text::RandomCharIter;
1146
1147 let snapshot = self.read(cx);
1148 let mut old_ranges: Vec<Range<usize>> = Vec::new();
1149 for _ in 0..count {
1150 let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1151 if last_end > snapshot.len() {
1152 break;
1153 }
1154 let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
1155 let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1156 old_ranges.push(start_ix..end_ix);
1157 }
1158 let new_text_len = rng.gen_range(0..10);
1159 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1160 log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
1161 drop(snapshot);
1162
1163 self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1164 }
1165
1166 pub fn randomly_edit_excerpts(
1167 &mut self,
1168 rng: &mut impl rand::Rng,
1169 mutation_count: usize,
1170 cx: &mut ModelContext<Self>,
1171 ) {
1172 use rand::prelude::*;
1173 use std::env;
1174 use text::RandomCharIter;
1175
1176 let max_excerpts = env::var("MAX_EXCERPTS")
1177 .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1178 .unwrap_or(5);
1179
1180 let mut buffers = Vec::new();
1181 for _ in 0..mutation_count {
1182 let excerpt_ids = self
1183 .buffers
1184 .borrow()
1185 .values()
1186 .flat_map(|b| &b.excerpts)
1187 .cloned()
1188 .collect::<Vec<_>>();
1189 if excerpt_ids.len() == 0 || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1190 let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1191 let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1192 buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
1193 let buffer = buffers.last().unwrap();
1194 log::info!(
1195 "Creating new buffer {} with text: {:?}",
1196 buffer.id(),
1197 buffer.read(cx).text()
1198 );
1199 buffers.last().unwrap().clone()
1200 } else {
1201 self.buffers
1202 .borrow()
1203 .values()
1204 .choose(rng)
1205 .unwrap()
1206 .buffer
1207 .clone()
1208 };
1209
1210 let buffer = buffer_handle.read(cx);
1211 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1212 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1213 log::info!(
1214 "Inserting excerpt from buffer {} and range {:?}: {:?}",
1215 buffer_handle.id(),
1216 start_ix..end_ix,
1217 &buffer.text()[start_ix..end_ix]
1218 );
1219
1220 let excerpt_id = self.push_excerpts(buffer_handle.clone(), [start_ix..end_ix], cx);
1221 log::info!("Inserted with id: {:?}", excerpt_id);
1222 } else {
1223 let remove_count = rng.gen_range(1..=excerpt_ids.len());
1224 let mut excerpts_to_remove = excerpt_ids
1225 .choose_multiple(rng, remove_count)
1226 .cloned()
1227 .collect::<Vec<_>>();
1228 excerpts_to_remove.sort();
1229 log::info!("Removing excerpts {:?}", excerpts_to_remove);
1230 self.remove_excerpts(&excerpts_to_remove, cx);
1231 }
1232 }
1233 }
1234
1235 pub fn randomly_mutate(
1236 &mut self,
1237 rng: &mut impl rand::Rng,
1238 mutation_count: usize,
1239 cx: &mut ModelContext<Self>,
1240 ) {
1241 if rng.gen_bool(0.7) || self.singleton {
1242 self.randomly_edit(rng, mutation_count, cx);
1243 } else {
1244 self.randomly_edit_excerpts(rng, mutation_count, cx);
1245 }
1246 }
1247}
1248
1249impl Entity for MultiBuffer {
1250 type Event = language::Event;
1251}
1252
1253impl MultiBufferSnapshot {
1254 pub fn text(&self) -> String {
1255 self.chunks(0..self.len(), false)
1256 .map(|chunk| chunk.text)
1257 .collect()
1258 }
1259
1260 pub fn reversed_chars_at<'a, T: ToOffset>(
1261 &'a self,
1262 position: T,
1263 ) -> impl Iterator<Item = char> + 'a {
1264 let mut offset = position.to_offset(self);
1265 let mut cursor = self.excerpts.cursor::<usize>();
1266 cursor.seek(&offset, Bias::Left, &());
1267 let mut excerpt_chunks = cursor.item().map(|excerpt| {
1268 let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
1269 let start = excerpt.range.start.to_offset(&excerpt.buffer);
1270 let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1271 excerpt.buffer.reversed_chunks_in_range(start..end)
1272 });
1273 iter::from_fn(move || {
1274 if offset == *cursor.start() {
1275 cursor.prev(&());
1276 let excerpt = cursor.item()?;
1277 excerpt_chunks = Some(
1278 excerpt
1279 .buffer
1280 .reversed_chunks_in_range(excerpt.range.clone()),
1281 );
1282 }
1283
1284 let excerpt = cursor.item().unwrap();
1285 if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1286 offset -= 1;
1287 Some("\n")
1288 } else {
1289 let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1290 offset -= chunk.len();
1291 Some(chunk)
1292 }
1293 })
1294 .flat_map(|c| c.chars().rev())
1295 }
1296
1297 pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1298 let offset = position.to_offset(self);
1299 self.text_for_range(offset..self.len())
1300 .flat_map(|chunk| chunk.chars())
1301 }
1302
1303 pub fn text_for_range<'a, T: ToOffset>(
1304 &'a self,
1305 range: Range<T>,
1306 ) -> impl Iterator<Item = &'a str> {
1307 self.chunks(range, false).map(|chunk| chunk.text)
1308 }
1309
1310 pub fn is_line_blank(&self, row: u32) -> bool {
1311 self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1312 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1313 }
1314
1315 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1316 where
1317 T: ToOffset,
1318 {
1319 let position = position.to_offset(self);
1320 position == self.clip_offset(position, Bias::Left)
1321 && self
1322 .bytes_in_range(position..self.len())
1323 .flatten()
1324 .copied()
1325 .take(needle.len())
1326 .eq(needle.bytes())
1327 }
1328
1329 pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1330 let mut start = start.to_offset(self);
1331 let mut end = start;
1332 let mut next_chars = self.chars_at(start).peekable();
1333 let mut prev_chars = self.reversed_chars_at(start).peekable();
1334 let word_kind = cmp::max(
1335 prev_chars.peek().copied().map(char_kind),
1336 next_chars.peek().copied().map(char_kind),
1337 );
1338
1339 for ch in prev_chars {
1340 if Some(char_kind(ch)) == word_kind {
1341 start -= ch.len_utf8();
1342 } else {
1343 break;
1344 }
1345 }
1346
1347 for ch in next_chars {
1348 if Some(char_kind(ch)) == word_kind {
1349 end += ch.len_utf8();
1350 } else {
1351 break;
1352 }
1353 }
1354
1355 (start..end, word_kind)
1356 }
1357
1358 fn as_singleton(&self) -> Option<&Excerpt> {
1359 if self.singleton {
1360 self.excerpts.iter().next()
1361 } else {
1362 None
1363 }
1364 }
1365
1366 pub fn len(&self) -> usize {
1367 self.excerpts.summary().text.bytes
1368 }
1369
1370 pub fn max_buffer_row(&self) -> u32 {
1371 self.excerpts.summary().max_buffer_row
1372 }
1373
1374 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1375 if let Some(excerpt) = self.as_singleton() {
1376 return excerpt.buffer.clip_offset(offset, bias);
1377 }
1378
1379 let mut cursor = self.excerpts.cursor::<usize>();
1380 cursor.seek(&offset, Bias::Right, &());
1381 let overshoot = if let Some(excerpt) = cursor.item() {
1382 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1383 let buffer_offset = excerpt
1384 .buffer
1385 .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1386 buffer_offset.saturating_sub(excerpt_start)
1387 } else {
1388 0
1389 };
1390 cursor.start() + overshoot
1391 }
1392
1393 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1394 if let Some(excerpt) = self.as_singleton() {
1395 return excerpt.buffer.clip_point(point, bias);
1396 }
1397
1398 let mut cursor = self.excerpts.cursor::<Point>();
1399 cursor.seek(&point, Bias::Right, &());
1400 let overshoot = if let Some(excerpt) = cursor.item() {
1401 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1402 let buffer_point = excerpt
1403 .buffer
1404 .clip_point(excerpt_start + (point - cursor.start()), bias);
1405 buffer_point.saturating_sub(excerpt_start)
1406 } else {
1407 Point::zero()
1408 };
1409 *cursor.start() + overshoot
1410 }
1411
1412 pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1413 if let Some(excerpt) = self.as_singleton() {
1414 return excerpt.buffer.clip_point_utf16(point, bias);
1415 }
1416
1417 let mut cursor = self.excerpts.cursor::<PointUtf16>();
1418 cursor.seek(&point, Bias::Right, &());
1419 let overshoot = if let Some(excerpt) = cursor.item() {
1420 let excerpt_start = excerpt
1421 .buffer
1422 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1423 let buffer_point = excerpt
1424 .buffer
1425 .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1426 buffer_point.saturating_sub(excerpt_start)
1427 } else {
1428 PointUtf16::zero()
1429 };
1430 *cursor.start() + overshoot
1431 }
1432
1433 pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1434 let range = range.start.to_offset(self)..range.end.to_offset(self);
1435 let mut excerpts = self.excerpts.cursor::<usize>();
1436 excerpts.seek(&range.start, Bias::Right, &());
1437
1438 let mut chunk = &[][..];
1439 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1440 let mut excerpt_bytes = excerpt
1441 .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1442 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1443 Some(excerpt_bytes)
1444 } else {
1445 None
1446 };
1447
1448 MultiBufferBytes {
1449 range,
1450 excerpts,
1451 excerpt_bytes,
1452 chunk,
1453 }
1454 }
1455
1456 pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1457 let mut result = MultiBufferRows {
1458 buffer_row_range: 0..0,
1459 excerpts: self.excerpts.cursor(),
1460 };
1461 result.seek(start_row);
1462 result
1463 }
1464
1465 pub fn chunks<'a, T: ToOffset>(
1466 &'a self,
1467 range: Range<T>,
1468 language_aware: bool,
1469 ) -> MultiBufferChunks<'a> {
1470 let range = range.start.to_offset(self)..range.end.to_offset(self);
1471 let mut chunks = MultiBufferChunks {
1472 range: range.clone(),
1473 excerpts: self.excerpts.cursor(),
1474 excerpt_chunks: None,
1475 language_aware,
1476 };
1477 chunks.seek(range.start);
1478 chunks
1479 }
1480
1481 pub fn offset_to_point(&self, offset: usize) -> Point {
1482 if let Some(excerpt) = self.as_singleton() {
1483 return excerpt.buffer.offset_to_point(offset);
1484 }
1485
1486 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1487 cursor.seek(&offset, Bias::Right, &());
1488 if let Some(excerpt) = cursor.item() {
1489 let (start_offset, start_point) = cursor.start();
1490 let overshoot = offset - start_offset;
1491 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1492 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1493 let buffer_point = excerpt
1494 .buffer
1495 .offset_to_point(excerpt_start_offset + overshoot);
1496 *start_point + (buffer_point - excerpt_start_point)
1497 } else {
1498 self.excerpts.summary().text.lines
1499 }
1500 }
1501
1502 pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1503 if let Some(excerpt) = self.as_singleton() {
1504 return excerpt.buffer.offset_to_point_utf16(offset);
1505 }
1506
1507 let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
1508 cursor.seek(&offset, Bias::Right, &());
1509 if let Some(excerpt) = cursor.item() {
1510 let (start_offset, start_point) = cursor.start();
1511 let overshoot = offset - start_offset;
1512 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1513 let excerpt_start_point = excerpt.range.start.to_point_utf16(&excerpt.buffer);
1514 let buffer_point = excerpt
1515 .buffer
1516 .offset_to_point_utf16(excerpt_start_offset + overshoot);
1517 *start_point + (buffer_point - excerpt_start_point)
1518 } else {
1519 self.excerpts.summary().text.lines_utf16
1520 }
1521 }
1522
1523 pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1524 if let Some(excerpt) = self.as_singleton() {
1525 return excerpt.buffer.point_to_point_utf16(point);
1526 }
1527
1528 let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
1529 cursor.seek(&point, Bias::Right, &());
1530 if let Some(excerpt) = cursor.item() {
1531 let (start_offset, start_point) = cursor.start();
1532 let overshoot = point - start_offset;
1533 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1534 let excerpt_start_point_utf16 = excerpt.range.start.to_point_utf16(&excerpt.buffer);
1535 let buffer_point = excerpt
1536 .buffer
1537 .point_to_point_utf16(excerpt_start_point + overshoot);
1538 *start_point + (buffer_point - excerpt_start_point_utf16)
1539 } else {
1540 self.excerpts.summary().text.lines_utf16
1541 }
1542 }
1543
1544 pub fn point_to_offset(&self, point: Point) -> usize {
1545 if let Some(excerpt) = self.as_singleton() {
1546 return excerpt.buffer.point_to_offset(point);
1547 }
1548
1549 let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1550 cursor.seek(&point, Bias::Right, &());
1551 if let Some(excerpt) = cursor.item() {
1552 let (start_point, start_offset) = cursor.start();
1553 let overshoot = point - start_point;
1554 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1555 let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1556 let buffer_offset = excerpt
1557 .buffer
1558 .point_to_offset(excerpt_start_point + overshoot);
1559 *start_offset + buffer_offset - excerpt_start_offset
1560 } else {
1561 self.excerpts.summary().text.bytes
1562 }
1563 }
1564
1565 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1566 if let Some(excerpt) = self.as_singleton() {
1567 return excerpt.buffer.point_utf16_to_offset(point);
1568 }
1569
1570 let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1571 cursor.seek(&point, Bias::Right, &());
1572 if let Some(excerpt) = cursor.item() {
1573 let (start_point, start_offset) = cursor.start();
1574 let overshoot = point - start_point;
1575 let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1576 let excerpt_start_point = excerpt
1577 .buffer
1578 .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1579 let buffer_offset = excerpt
1580 .buffer
1581 .point_utf16_to_offset(excerpt_start_point + overshoot);
1582 *start_offset + (buffer_offset - excerpt_start_offset)
1583 } else {
1584 self.excerpts.summary().text.bytes
1585 }
1586 }
1587
1588 pub fn indent_column_for_line(&self, row: u32) -> u32 {
1589 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1590 buffer
1591 .indent_column_for_line(range.start.row)
1592 .min(range.end.column)
1593 .saturating_sub(range.start.column)
1594 } else {
1595 0
1596 }
1597 }
1598
1599 pub fn line_len(&self, row: u32) -> u32 {
1600 if let Some((_, range)) = self.buffer_line_for_row(row) {
1601 range.end.column - range.start.column
1602 } else {
1603 0
1604 }
1605 }
1606
1607 fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1608 let mut cursor = self.excerpts.cursor::<Point>();
1609 cursor.seek(&Point::new(row, 0), Bias::Right, &());
1610 if let Some(excerpt) = cursor.item() {
1611 let overshoot = row - cursor.start().row;
1612 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1613 let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1614 let buffer_row = excerpt_start.row + overshoot;
1615 let line_start = Point::new(buffer_row, 0);
1616 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1617 return Some((
1618 &excerpt.buffer,
1619 line_start.max(excerpt_start)..line_end.min(excerpt_end),
1620 ));
1621 }
1622 None
1623 }
1624
1625 pub fn max_point(&self) -> Point {
1626 self.text_summary().lines
1627 }
1628
1629 pub fn text_summary(&self) -> TextSummary {
1630 self.excerpts.summary().text
1631 }
1632
1633 pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1634 where
1635 D: TextDimension,
1636 O: ToOffset,
1637 {
1638 let mut summary = D::default();
1639 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1640 let mut cursor = self.excerpts.cursor::<usize>();
1641 cursor.seek(&range.start, Bias::Right, &());
1642 if let Some(excerpt) = cursor.item() {
1643 let mut end_before_newline = cursor.end(&());
1644 if excerpt.has_trailing_newline {
1645 end_before_newline -= 1;
1646 }
1647
1648 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1649 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
1650 let end_in_excerpt =
1651 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
1652 summary.add_assign(
1653 &excerpt
1654 .buffer
1655 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1656 );
1657
1658 if range.end > end_before_newline {
1659 summary.add_assign(&D::from_text_summary(&TextSummary {
1660 bytes: 1,
1661 lines: Point::new(1 as u32, 0),
1662 lines_utf16: PointUtf16::new(1 as u32, 0),
1663 first_line_chars: 0,
1664 last_line_chars: 0,
1665 longest_row: 0,
1666 longest_row_chars: 0,
1667 }));
1668 }
1669
1670 cursor.next(&());
1671 }
1672
1673 if range.end > *cursor.start() {
1674 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1675 &range.end,
1676 Bias::Right,
1677 &(),
1678 )));
1679 if let Some(excerpt) = cursor.item() {
1680 range.end = cmp::max(*cursor.start(), range.end);
1681
1682 let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1683 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
1684 summary.add_assign(
1685 &excerpt
1686 .buffer
1687 .text_summary_for_range(excerpt_start..end_in_excerpt),
1688 );
1689 }
1690 }
1691
1692 summary
1693 }
1694
1695 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1696 where
1697 D: TextDimension + Ord + Sub<D, Output = D>,
1698 {
1699 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1700 cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1701 if cursor.item().is_none() {
1702 cursor.next(&());
1703 }
1704
1705 let mut position = D::from_text_summary(&cursor.start().text);
1706 if let Some(excerpt) = cursor.item() {
1707 if excerpt.id == anchor.excerpt_id && excerpt.buffer_id == anchor.buffer_id {
1708 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1709 let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1710 let buffer_position = cmp::min(
1711 excerpt_buffer_end,
1712 anchor.text_anchor.summary::<D>(&excerpt.buffer),
1713 );
1714 if buffer_position > excerpt_buffer_start {
1715 position.add_assign(&(buffer_position - excerpt_buffer_start));
1716 }
1717 }
1718 }
1719 position
1720 }
1721
1722 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1723 where
1724 D: TextDimension + Ord + Sub<D, Output = D>,
1725 I: 'a + IntoIterator<Item = &'a Anchor>,
1726 {
1727 if let Some(excerpt) = self.as_singleton() {
1728 return excerpt
1729 .buffer
1730 .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
1731 .collect();
1732 }
1733
1734 let mut anchors = anchors.into_iter().peekable();
1735 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1736 let mut summaries = Vec::new();
1737 while let Some(anchor) = anchors.peek() {
1738 let excerpt_id = &anchor.excerpt_id;
1739 let buffer_id = anchor.buffer_id;
1740 let excerpt_anchors = iter::from_fn(|| {
1741 let anchor = anchors.peek()?;
1742 if anchor.excerpt_id == *excerpt_id && anchor.buffer_id == buffer_id {
1743 Some(&anchors.next().unwrap().text_anchor)
1744 } else {
1745 None
1746 }
1747 });
1748
1749 cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1750 if cursor.item().is_none() {
1751 cursor.next(&());
1752 }
1753
1754 let position = D::from_text_summary(&cursor.start().text);
1755 if let Some(excerpt) = cursor.item() {
1756 if excerpt.id == *excerpt_id && excerpt.buffer_id == buffer_id {
1757 let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1758 let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1759 summaries.extend(
1760 excerpt
1761 .buffer
1762 .summaries_for_anchors::<D, _>(excerpt_anchors)
1763 .map(move |summary| {
1764 let summary = cmp::min(excerpt_buffer_end.clone(), summary);
1765 let mut position = position.clone();
1766 let excerpt_buffer_start = excerpt_buffer_start.clone();
1767 if summary > excerpt_buffer_start {
1768 position.add_assign(&(summary - excerpt_buffer_start));
1769 }
1770 position
1771 }),
1772 );
1773 continue;
1774 }
1775 }
1776
1777 summaries.extend(excerpt_anchors.map(|_| position.clone()));
1778 }
1779
1780 summaries
1781 }
1782
1783 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
1784 where
1785 I: 'a + IntoIterator<Item = &'a Anchor>,
1786 {
1787 let mut anchors = anchors.into_iter().enumerate().peekable();
1788 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1789 let mut result = Vec::new();
1790 while let Some((_, anchor)) = anchors.peek() {
1791 let old_excerpt_id = &anchor.excerpt_id;
1792
1793 // Find the location where this anchor's excerpt should be.
1794 cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
1795 if cursor.item().is_none() {
1796 cursor.next(&());
1797 }
1798
1799 let next_excerpt = cursor.item();
1800 let prev_excerpt = cursor.prev_item();
1801
1802 // Process all of the anchors for this excerpt.
1803 while let Some((_, anchor)) = anchors.peek() {
1804 if anchor.excerpt_id != *old_excerpt_id {
1805 break;
1806 }
1807 let mut kept_position = false;
1808 let (anchor_ix, anchor) = anchors.next().unwrap();
1809 let mut anchor = anchor.clone();
1810
1811 // Leave min and max anchors unchanged.
1812 if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
1813 kept_position = true;
1814 }
1815 // If the old excerpt still exists at this location, then leave
1816 // the anchor unchanged.
1817 else if next_excerpt.map_or(false, |excerpt| {
1818 excerpt.id == *old_excerpt_id && excerpt.contains(&anchor)
1819 }) {
1820 kept_position = true;
1821 }
1822 // If the old excerpt no longer exists at this location, then attempt to
1823 // find an equivalent position for this anchor in an adjacent excerpt.
1824 else {
1825 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
1826 if excerpt.contains(&anchor) {
1827 anchor.excerpt_id = excerpt.id.clone();
1828 kept_position = true;
1829 break;
1830 }
1831 }
1832 }
1833 // If there's no adjacent excerpt that contains the anchor's position,
1834 // then report that the anchor has lost its position.
1835 if !kept_position {
1836 anchor = if let Some(excerpt) = next_excerpt {
1837 let mut text_anchor = excerpt
1838 .range
1839 .start
1840 .bias(anchor.text_anchor.bias, &excerpt.buffer);
1841 if text_anchor
1842 .cmp(&excerpt.range.end, &excerpt.buffer)
1843 .unwrap()
1844 .is_gt()
1845 {
1846 text_anchor = excerpt.range.end.clone();
1847 }
1848 Anchor {
1849 buffer_id: excerpt.buffer_id,
1850 excerpt_id: excerpt.id.clone(),
1851 text_anchor,
1852 }
1853 } else if let Some(excerpt) = prev_excerpt {
1854 let mut text_anchor = excerpt
1855 .range
1856 .end
1857 .bias(anchor.text_anchor.bias, &excerpt.buffer);
1858 if text_anchor
1859 .cmp(&excerpt.range.start, &excerpt.buffer)
1860 .unwrap()
1861 .is_lt()
1862 {
1863 text_anchor = excerpt.range.start.clone();
1864 }
1865 Anchor {
1866 buffer_id: excerpt.buffer_id,
1867 excerpt_id: excerpt.id.clone(),
1868 text_anchor,
1869 }
1870 } else if anchor.text_anchor.bias == Bias::Left {
1871 Anchor::min()
1872 } else {
1873 Anchor::max()
1874 };
1875 }
1876
1877 result.push((anchor_ix, anchor, kept_position));
1878 }
1879 }
1880 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self).unwrap());
1881 result
1882 }
1883
1884 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1885 self.anchor_at(position, Bias::Left)
1886 }
1887
1888 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1889 self.anchor_at(position, Bias::Right)
1890 }
1891
1892 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1893 let offset = position.to_offset(self);
1894 if let Some(excerpt) = self.as_singleton() {
1895 return Anchor {
1896 buffer_id: excerpt.buffer_id,
1897 excerpt_id: excerpt.id.clone(),
1898 text_anchor: excerpt.buffer.anchor_at(offset, bias),
1899 };
1900 }
1901
1902 let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1903 cursor.seek(&offset, Bias::Right, &());
1904 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1905 cursor.prev(&());
1906 }
1907 if let Some(excerpt) = cursor.item() {
1908 let mut overshoot = offset.saturating_sub(cursor.start().0);
1909 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1910 overshoot -= 1;
1911 bias = Bias::Right;
1912 }
1913
1914 let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1915 let text_anchor =
1916 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1917 Anchor {
1918 buffer_id: excerpt.buffer_id,
1919 excerpt_id: excerpt.id.clone(),
1920 text_anchor,
1921 }
1922 } else if offset == 0 && bias == Bias::Left {
1923 Anchor::min()
1924 } else {
1925 Anchor::max()
1926 }
1927 }
1928
1929 pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1930 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1931 cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1932 if let Some(excerpt) = cursor.item() {
1933 if excerpt.id == excerpt_id {
1934 let text_anchor = excerpt.clip_anchor(text_anchor);
1935 drop(cursor);
1936 return Anchor {
1937 buffer_id: excerpt.buffer_id,
1938 excerpt_id,
1939 text_anchor,
1940 };
1941 }
1942 }
1943 panic!("excerpt not found");
1944 }
1945
1946 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1947 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
1948 true
1949 } else if let Some((buffer_id, buffer_snapshot)) =
1950 self.buffer_snapshot_for_excerpt(&anchor.excerpt_id)
1951 {
1952 anchor.buffer_id == buffer_id && buffer_snapshot.can_resolve(&anchor.text_anchor)
1953 } else {
1954 false
1955 }
1956 }
1957
1958 pub fn excerpt_boundaries_in_range<'a, R, T>(
1959 &'a self,
1960 range: R,
1961 ) -> impl Iterator<Item = ExcerptBoundary> + 'a
1962 where
1963 R: RangeBounds<T>,
1964 T: ToOffset,
1965 {
1966 let start_offset;
1967 let start = match range.start_bound() {
1968 Bound::Included(start) => {
1969 start_offset = start.to_offset(self);
1970 Bound::Included(start_offset)
1971 }
1972 Bound::Excluded(start) => {
1973 start_offset = start.to_offset(self);
1974 Bound::Excluded(start_offset)
1975 }
1976 Bound::Unbounded => {
1977 start_offset = 0;
1978 Bound::Unbounded
1979 }
1980 };
1981 let end = match range.end_bound() {
1982 Bound::Included(end) => Bound::Included(end.to_offset(self)),
1983 Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
1984 Bound::Unbounded => Bound::Unbounded,
1985 };
1986 let bounds = (start, end);
1987
1988 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1989 cursor.seek(&start_offset, Bias::Right, &());
1990 if cursor.item().is_none() {
1991 cursor.prev(&());
1992 }
1993 if !bounds.contains(&cursor.start().0) {
1994 cursor.next(&());
1995 }
1996
1997 let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
1998 std::iter::from_fn(move || {
1999 if self.singleton {
2000 None
2001 } else if bounds.contains(&cursor.start().0) {
2002 let excerpt = cursor.item()?;
2003 let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2004 let boundary = ExcerptBoundary {
2005 row: cursor.start().1.row,
2006 buffer: excerpt.buffer.clone(),
2007 range: excerpt.range.clone(),
2008 starts_new_buffer,
2009 };
2010
2011 prev_buffer_id = Some(excerpt.buffer_id);
2012 cursor.next(&());
2013 Some(boundary)
2014 } else {
2015 None
2016 }
2017 })
2018 }
2019
2020 pub fn parse_count(&self) -> usize {
2021 self.parse_count
2022 }
2023
2024 pub fn enclosing_bracket_ranges<T: ToOffset>(
2025 &self,
2026 range: Range<T>,
2027 ) -> Option<(Range<usize>, Range<usize>)> {
2028 let range = range.start.to_offset(self)..range.end.to_offset(self);
2029
2030 let mut cursor = self.excerpts.cursor::<usize>();
2031 cursor.seek(&range.start, Bias::Right, &());
2032 let start_excerpt = cursor.item();
2033
2034 cursor.seek(&range.end, Bias::Right, &());
2035 let end_excerpt = cursor.item();
2036
2037 start_excerpt
2038 .zip(end_excerpt)
2039 .and_then(|(start_excerpt, end_excerpt)| {
2040 if start_excerpt.id != end_excerpt.id {
2041 return None;
2042 }
2043
2044 let excerpt_buffer_start =
2045 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
2046 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
2047
2048 let start_in_buffer =
2049 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2050 let end_in_buffer =
2051 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2052 let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
2053 .buffer
2054 .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
2055
2056 if start_bracket_range.start >= excerpt_buffer_start
2057 && end_bracket_range.end < excerpt_buffer_end
2058 {
2059 start_bracket_range.start =
2060 cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
2061 start_bracket_range.end =
2062 cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
2063 end_bracket_range.start =
2064 cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
2065 end_bracket_range.end =
2066 cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
2067 Some((start_bracket_range, end_bracket_range))
2068 } else {
2069 None
2070 }
2071 })
2072 }
2073
2074 pub fn diagnostics_update_count(&self) -> usize {
2075 self.diagnostics_update_count
2076 }
2077
2078 pub fn trailing_excerpt_update_count(&self) -> usize {
2079 self.trailing_excerpt_update_count
2080 }
2081
2082 pub fn language(&self) -> Option<&Arc<Language>> {
2083 self.excerpts
2084 .iter()
2085 .next()
2086 .and_then(|excerpt| excerpt.buffer.language())
2087 }
2088
2089 pub fn is_dirty(&self) -> bool {
2090 self.is_dirty
2091 }
2092
2093 pub fn has_conflict(&self) -> bool {
2094 self.has_conflict
2095 }
2096
2097 pub fn diagnostic_group<'a, O>(
2098 &'a self,
2099 group_id: usize,
2100 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2101 where
2102 O: text::FromAnchor + 'a,
2103 {
2104 self.as_singleton()
2105 .into_iter()
2106 .flat_map(move |excerpt| excerpt.buffer.diagnostic_group(group_id))
2107 }
2108
2109 pub fn diagnostics_in_range<'a, T, O>(
2110 &'a self,
2111 range: Range<T>,
2112 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2113 where
2114 T: 'a + ToOffset,
2115 O: 'a + text::FromAnchor,
2116 {
2117 self.as_singleton().into_iter().flat_map(move |excerpt| {
2118 excerpt
2119 .buffer
2120 .diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
2121 })
2122 }
2123
2124 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2125 let range = range.start.to_offset(self)..range.end.to_offset(self);
2126
2127 let mut cursor = self.excerpts.cursor::<usize>();
2128 cursor.seek(&range.start, Bias::Right, &());
2129 let start_excerpt = cursor.item();
2130
2131 cursor.seek(&range.end, Bias::Right, &());
2132 let end_excerpt = cursor.item();
2133
2134 start_excerpt
2135 .zip(end_excerpt)
2136 .and_then(|(start_excerpt, end_excerpt)| {
2137 if start_excerpt.id != end_excerpt.id {
2138 return None;
2139 }
2140
2141 let excerpt_buffer_start =
2142 start_excerpt.range.start.to_offset(&start_excerpt.buffer);
2143 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
2144
2145 let start_in_buffer =
2146 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2147 let end_in_buffer =
2148 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2149 let mut ancestor_buffer_range = start_excerpt
2150 .buffer
2151 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2152 ancestor_buffer_range.start =
2153 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2154 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2155
2156 let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
2157 let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
2158 Some(start..end)
2159 })
2160 }
2161
2162 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2163 let excerpt = self.as_singleton()?;
2164 let outline = excerpt.buffer.outline(theme)?;
2165 Some(Outline::new(
2166 outline
2167 .items
2168 .into_iter()
2169 .map(|item| OutlineItem {
2170 depth: item.depth,
2171 range: self.anchor_in_excerpt(excerpt.id.clone(), item.range.start)
2172 ..self.anchor_in_excerpt(excerpt.id.clone(), item.range.end),
2173 text: item.text,
2174 highlight_ranges: item.highlight_ranges,
2175 name_ranges: item.name_ranges,
2176 })
2177 .collect(),
2178 ))
2179 }
2180
2181 fn buffer_snapshot_for_excerpt<'a>(
2182 &'a self,
2183 excerpt_id: &'a ExcerptId,
2184 ) -> Option<(usize, &'a BufferSnapshot)> {
2185 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2186 cursor.seek(&Some(excerpt_id), Bias::Left, &());
2187 if let Some(excerpt) = cursor.item() {
2188 if excerpt.id == *excerpt_id {
2189 return Some((excerpt.buffer_id, &excerpt.buffer));
2190 }
2191 }
2192 None
2193 }
2194
2195 pub fn remote_selections_in_range<'a>(
2196 &'a self,
2197 range: &'a Range<Anchor>,
2198 ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
2199 let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2200 cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
2201 cursor
2202 .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
2203 .flat_map(move |excerpt| {
2204 let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
2205 if excerpt.id == range.start.excerpt_id {
2206 query_range.start = range.start.text_anchor.clone();
2207 }
2208 if excerpt.id == range.end.excerpt_id {
2209 query_range.end = range.end.text_anchor.clone();
2210 }
2211
2212 excerpt
2213 .buffer
2214 .remote_selections_in_range(query_range)
2215 .flat_map(move |(replica_id, selections)| {
2216 selections.map(move |selection| {
2217 let mut start = Anchor {
2218 buffer_id: excerpt.buffer_id,
2219 excerpt_id: excerpt.id.clone(),
2220 text_anchor: selection.start.clone(),
2221 };
2222 let mut end = Anchor {
2223 buffer_id: excerpt.buffer_id,
2224 excerpt_id: excerpt.id.clone(),
2225 text_anchor: selection.end.clone(),
2226 };
2227 if range.start.cmp(&start, self).unwrap().is_gt() {
2228 start = range.start.clone();
2229 }
2230 if range.end.cmp(&end, self).unwrap().is_lt() {
2231 end = range.end.clone();
2232 }
2233
2234 (
2235 replica_id,
2236 Selection {
2237 id: selection.id,
2238 start,
2239 end,
2240 reversed: selection.reversed,
2241 goal: selection.goal,
2242 },
2243 )
2244 })
2245 })
2246 })
2247 }
2248}
2249
2250impl History {
2251 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2252 self.transaction_depth += 1;
2253 if self.transaction_depth == 1 {
2254 let id = self.next_transaction_id.tick();
2255 self.undo_stack.push(Transaction {
2256 id,
2257 buffer_transactions: Default::default(),
2258 first_edit_at: now,
2259 last_edit_at: now,
2260 suppress_grouping: false,
2261 });
2262 Some(id)
2263 } else {
2264 None
2265 }
2266 }
2267
2268 fn end_transaction(
2269 &mut self,
2270 now: Instant,
2271 buffer_transactions: HashMap<usize, TransactionId>,
2272 ) -> bool {
2273 assert_ne!(self.transaction_depth, 0);
2274 self.transaction_depth -= 1;
2275 if self.transaction_depth == 0 {
2276 if buffer_transactions.is_empty() {
2277 self.undo_stack.pop();
2278 false
2279 } else {
2280 let transaction = self.undo_stack.last_mut().unwrap();
2281 transaction.last_edit_at = now;
2282 for (buffer_id, transaction_id) in buffer_transactions {
2283 transaction
2284 .buffer_transactions
2285 .entry(buffer_id)
2286 .or_insert(transaction_id);
2287 }
2288 true
2289 }
2290 } else {
2291 false
2292 }
2293 }
2294
2295 fn push_transaction<'a, T>(&mut self, buffer_transactions: T, now: Instant)
2296 where
2297 T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
2298 {
2299 assert_eq!(self.transaction_depth, 0);
2300 let transaction = Transaction {
2301 id: self.next_transaction_id.tick(),
2302 buffer_transactions: buffer_transactions
2303 .into_iter()
2304 .map(|(buffer, transaction)| (buffer.id(), transaction.id))
2305 .collect(),
2306 first_edit_at: now,
2307 last_edit_at: now,
2308 suppress_grouping: false,
2309 };
2310 if !transaction.buffer_transactions.is_empty() {
2311 self.undo_stack.push(transaction);
2312 }
2313 }
2314
2315 fn finalize_last_transaction(&mut self) {
2316 if let Some(transaction) = self.undo_stack.last_mut() {
2317 transaction.suppress_grouping = true;
2318 }
2319 }
2320
2321 fn pop_undo(&mut self) -> Option<&mut Transaction> {
2322 assert_eq!(self.transaction_depth, 0);
2323 if let Some(transaction) = self.undo_stack.pop() {
2324 self.redo_stack.push(transaction);
2325 self.redo_stack.last_mut()
2326 } else {
2327 None
2328 }
2329 }
2330
2331 fn pop_redo(&mut self) -> Option<&mut Transaction> {
2332 assert_eq!(self.transaction_depth, 0);
2333 if let Some(transaction) = self.redo_stack.pop() {
2334 self.undo_stack.push(transaction);
2335 self.undo_stack.last_mut()
2336 } else {
2337 None
2338 }
2339 }
2340
2341 fn group(&mut self) -> Option<TransactionId> {
2342 let mut new_len = self.undo_stack.len();
2343 let mut transactions = self.undo_stack.iter_mut();
2344
2345 if let Some(mut transaction) = transactions.next_back() {
2346 while let Some(prev_transaction) = transactions.next_back() {
2347 if !prev_transaction.suppress_grouping
2348 && transaction.first_edit_at - prev_transaction.last_edit_at
2349 <= self.group_interval
2350 {
2351 transaction = prev_transaction;
2352 new_len -= 1;
2353 } else {
2354 break;
2355 }
2356 }
2357 }
2358
2359 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2360 if let Some(last_transaction) = transactions_to_keep.last_mut() {
2361 if let Some(transaction) = transactions_to_merge.last() {
2362 last_transaction.last_edit_at = transaction.last_edit_at;
2363 }
2364 for to_merge in transactions_to_merge {
2365 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
2366 last_transaction
2367 .buffer_transactions
2368 .entry(*buffer_id)
2369 .or_insert(*transaction_id);
2370 }
2371 }
2372 }
2373
2374 self.undo_stack.truncate(new_len);
2375 self.undo_stack.last().map(|t| t.id)
2376 }
2377}
2378
2379impl Excerpt {
2380 fn new(
2381 id: ExcerptId,
2382 buffer_id: usize,
2383 buffer: BufferSnapshot,
2384 range: Range<text::Anchor>,
2385 has_trailing_newline: bool,
2386 ) -> Self {
2387 Excerpt {
2388 id,
2389 max_buffer_row: range.end.to_point(&buffer).row,
2390 text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
2391 buffer_id,
2392 buffer,
2393 range,
2394 has_trailing_newline,
2395 }
2396 }
2397
2398 fn chunks_in_range<'a>(
2399 &'a self,
2400 range: Range<usize>,
2401 language_aware: bool,
2402 ) -> ExcerptChunks<'a> {
2403 let content_start = self.range.start.to_offset(&self.buffer);
2404 let chunks_start = content_start + range.start;
2405 let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2406
2407 let footer_height = if self.has_trailing_newline
2408 && range.start <= self.text_summary.bytes
2409 && range.end > self.text_summary.bytes
2410 {
2411 1
2412 } else {
2413 0
2414 };
2415
2416 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
2417
2418 ExcerptChunks {
2419 content_chunks,
2420 footer_height,
2421 }
2422 }
2423
2424 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2425 let content_start = self.range.start.to_offset(&self.buffer);
2426 let bytes_start = content_start + range.start;
2427 let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2428 let footer_height = if self.has_trailing_newline
2429 && range.start <= self.text_summary.bytes
2430 && range.end > self.text_summary.bytes
2431 {
2432 1
2433 } else {
2434 0
2435 };
2436 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2437
2438 ExcerptBytes {
2439 content_bytes,
2440 footer_height,
2441 }
2442 }
2443
2444 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2445 if text_anchor
2446 .cmp(&self.range.start, &self.buffer)
2447 .unwrap()
2448 .is_lt()
2449 {
2450 self.range.start.clone()
2451 } else if text_anchor
2452 .cmp(&self.range.end, &self.buffer)
2453 .unwrap()
2454 .is_gt()
2455 {
2456 self.range.end.clone()
2457 } else {
2458 text_anchor
2459 }
2460 }
2461
2462 fn contains(&self, anchor: &Anchor) -> bool {
2463 self.buffer_id == anchor.buffer_id
2464 && self
2465 .range
2466 .start
2467 .cmp(&anchor.text_anchor, &self.buffer)
2468 .unwrap()
2469 .is_le()
2470 && self
2471 .range
2472 .end
2473 .cmp(&anchor.text_anchor, &self.buffer)
2474 .unwrap()
2475 .is_ge()
2476 }
2477}
2478
2479impl fmt::Debug for Excerpt {
2480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2481 f.debug_struct("Excerpt")
2482 .field("id", &self.id)
2483 .field("buffer_id", &self.buffer_id)
2484 .field("range", &self.range)
2485 .field("text_summary", &self.text_summary)
2486 .field("has_trailing_newline", &self.has_trailing_newline)
2487 .finish()
2488 }
2489}
2490
2491impl sum_tree::Item for Excerpt {
2492 type Summary = ExcerptSummary;
2493
2494 fn summary(&self) -> Self::Summary {
2495 let mut text = self.text_summary.clone();
2496 if self.has_trailing_newline {
2497 text += TextSummary::from("\n");
2498 }
2499 ExcerptSummary {
2500 excerpt_id: self.id.clone(),
2501 max_buffer_row: self.max_buffer_row,
2502 text,
2503 }
2504 }
2505}
2506
2507impl sum_tree::Summary for ExcerptSummary {
2508 type Context = ();
2509
2510 fn add_summary(&mut self, summary: &Self, _: &()) {
2511 debug_assert!(summary.excerpt_id > self.excerpt_id);
2512 self.excerpt_id = summary.excerpt_id.clone();
2513 self.text.add_summary(&summary.text, &());
2514 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2515 }
2516}
2517
2518impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2519 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2520 *self += &summary.text;
2521 }
2522}
2523
2524impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2525 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2526 *self += summary.text.bytes;
2527 }
2528}
2529
2530impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2531 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2532 Ord::cmp(self, &cursor_location.text.bytes)
2533 }
2534}
2535
2536impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2537 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2538 Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2539 }
2540}
2541
2542impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2543 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2544 *self += summary.text.lines;
2545 }
2546}
2547
2548impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2549 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2550 *self += summary.text.lines_utf16
2551 }
2552}
2553
2554impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2555 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2556 *self = Some(&summary.excerpt_id);
2557 }
2558}
2559
2560impl<'a> MultiBufferRows<'a> {
2561 pub fn seek(&mut self, row: u32) {
2562 self.buffer_row_range = 0..0;
2563
2564 self.excerpts
2565 .seek_forward(&Point::new(row, 0), Bias::Right, &());
2566 if self.excerpts.item().is_none() {
2567 self.excerpts.prev(&());
2568
2569 if self.excerpts.item().is_none() && row == 0 {
2570 self.buffer_row_range = 0..1;
2571 return;
2572 }
2573 }
2574
2575 if let Some(excerpt) = self.excerpts.item() {
2576 let overshoot = row - self.excerpts.start().row;
2577 let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
2578 self.buffer_row_range.start = excerpt_start + overshoot;
2579 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
2580 }
2581 }
2582}
2583
2584impl<'a> Iterator for MultiBufferRows<'a> {
2585 type Item = Option<u32>;
2586
2587 fn next(&mut self) -> Option<Self::Item> {
2588 loop {
2589 if !self.buffer_row_range.is_empty() {
2590 let row = Some(self.buffer_row_range.start);
2591 self.buffer_row_range.start += 1;
2592 return Some(row);
2593 }
2594 self.excerpts.item()?;
2595 self.excerpts.next(&());
2596 let excerpt = self.excerpts.item()?;
2597 self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
2598 self.buffer_row_range.end =
2599 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
2600 }
2601 }
2602}
2603
2604impl<'a> MultiBufferChunks<'a> {
2605 pub fn offset(&self) -> usize {
2606 self.range.start
2607 }
2608
2609 pub fn seek(&mut self, offset: usize) {
2610 self.range.start = offset;
2611 self.excerpts.seek(&offset, Bias::Right, &());
2612 if let Some(excerpt) = self.excerpts.item() {
2613 self.excerpt_chunks = Some(excerpt.chunks_in_range(
2614 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
2615 self.language_aware,
2616 ));
2617 } else {
2618 self.excerpt_chunks = None;
2619 }
2620 }
2621}
2622
2623impl<'a> Iterator for MultiBufferChunks<'a> {
2624 type Item = Chunk<'a>;
2625
2626 fn next(&mut self) -> Option<Self::Item> {
2627 if self.range.is_empty() {
2628 None
2629 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
2630 self.range.start += chunk.text.len();
2631 Some(chunk)
2632 } else {
2633 self.excerpts.next(&());
2634 let excerpt = self.excerpts.item()?;
2635 self.excerpt_chunks = Some(excerpt.chunks_in_range(
2636 0..self.range.end - self.excerpts.start(),
2637 self.language_aware,
2638 ));
2639 self.next()
2640 }
2641 }
2642}
2643
2644impl<'a> MultiBufferBytes<'a> {
2645 fn consume(&mut self, len: usize) {
2646 self.range.start += len;
2647 self.chunk = &self.chunk[len..];
2648
2649 if !self.range.is_empty() && self.chunk.is_empty() {
2650 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
2651 self.chunk = chunk;
2652 } else {
2653 self.excerpts.next(&());
2654 if let Some(excerpt) = self.excerpts.item() {
2655 let mut excerpt_bytes =
2656 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
2657 self.chunk = excerpt_bytes.next().unwrap();
2658 self.excerpt_bytes = Some(excerpt_bytes);
2659 }
2660 }
2661 }
2662 }
2663}
2664
2665impl<'a> Iterator for MultiBufferBytes<'a> {
2666 type Item = &'a [u8];
2667
2668 fn next(&mut self) -> Option<Self::Item> {
2669 let chunk = self.chunk;
2670 if chunk.is_empty() {
2671 None
2672 } else {
2673 self.consume(chunk.len());
2674 Some(chunk)
2675 }
2676 }
2677}
2678
2679impl<'a> io::Read for MultiBufferBytes<'a> {
2680 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2681 let len = cmp::min(buf.len(), self.chunk.len());
2682 buf[..len].copy_from_slice(&self.chunk[..len]);
2683 if len > 0 {
2684 self.consume(len);
2685 }
2686 Ok(len)
2687 }
2688}
2689
2690impl<'a> Iterator for ExcerptBytes<'a> {
2691 type Item = &'a [u8];
2692
2693 fn next(&mut self) -> Option<Self::Item> {
2694 if let Some(chunk) = self.content_bytes.next() {
2695 if !chunk.is_empty() {
2696 return Some(chunk);
2697 }
2698 }
2699
2700 if self.footer_height > 0 {
2701 let result = &NEWLINES[..self.footer_height];
2702 self.footer_height = 0;
2703 return Some(result);
2704 }
2705
2706 None
2707 }
2708}
2709
2710impl<'a> Iterator for ExcerptChunks<'a> {
2711 type Item = Chunk<'a>;
2712
2713 fn next(&mut self) -> Option<Self::Item> {
2714 if let Some(chunk) = self.content_chunks.next() {
2715 return Some(chunk);
2716 }
2717
2718 if self.footer_height > 0 {
2719 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2720 self.footer_height = 0;
2721 return Some(Chunk {
2722 text,
2723 ..Default::default()
2724 });
2725 }
2726
2727 None
2728 }
2729}
2730
2731impl ToOffset for Point {
2732 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2733 snapshot.point_to_offset(*self)
2734 }
2735}
2736
2737impl ToOffset for PointUtf16 {
2738 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2739 snapshot.point_utf16_to_offset(*self)
2740 }
2741}
2742
2743impl ToOffset for usize {
2744 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2745 assert!(*self <= snapshot.len(), "offset is out of range");
2746 *self
2747 }
2748}
2749
2750impl ToPoint for usize {
2751 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2752 snapshot.offset_to_point(*self)
2753 }
2754}
2755
2756impl ToPoint for Point {
2757 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2758 *self
2759 }
2760}
2761
2762impl ToPointUtf16 for usize {
2763 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
2764 snapshot.offset_to_point_utf16(*self)
2765 }
2766}
2767
2768impl ToPointUtf16 for Point {
2769 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
2770 snapshot.point_to_point_utf16(*self)
2771 }
2772}
2773
2774impl ToPointUtf16 for PointUtf16 {
2775 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
2776 *self
2777 }
2778}
2779
2780pub fn char_kind(c: char) -> CharKind {
2781 if c == '\n' {
2782 CharKind::Newline
2783 } else if c.is_whitespace() {
2784 CharKind::Whitespace
2785 } else if c.is_alphanumeric() || c == '_' {
2786 CharKind::Word
2787 } else {
2788 CharKind::Punctuation
2789 }
2790}
2791
2792#[cfg(test)]
2793mod tests {
2794 use super::*;
2795 use gpui::MutableAppContext;
2796 use language::{Buffer, Rope};
2797 use rand::prelude::*;
2798 use std::env;
2799 use text::{Point, RandomCharIter};
2800 use util::test::sample_text;
2801
2802 #[gpui::test]
2803 fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2804 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2805 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2806
2807 let snapshot = multibuffer.read(cx).snapshot(cx);
2808 assert_eq!(snapshot.text(), buffer.read(cx).text());
2809
2810 assert_eq!(
2811 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2812 (0..buffer.read(cx).row_count())
2813 .map(Some)
2814 .collect::<Vec<_>>()
2815 );
2816
2817 buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2818 let snapshot = multibuffer.read(cx).snapshot(cx);
2819
2820 assert_eq!(snapshot.text(), buffer.read(cx).text());
2821 assert_eq!(
2822 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2823 (0..buffer.read(cx).row_count())
2824 .map(Some)
2825 .collect::<Vec<_>>()
2826 );
2827 }
2828
2829 #[gpui::test]
2830 fn test_remote_multibuffer(cx: &mut MutableAppContext) {
2831 let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
2832 let guest_buffer = cx.add_model(|cx| {
2833 let message = host_buffer.read(cx).to_proto();
2834 Buffer::from_proto(1, message, None, cx).unwrap()
2835 });
2836 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
2837 let snapshot = multibuffer.read(cx).snapshot(cx);
2838 assert_eq!(snapshot.text(), "a");
2839
2840 guest_buffer.update(cx, |buffer, cx| buffer.edit([1..1], "b", cx));
2841 let snapshot = multibuffer.read(cx).snapshot(cx);
2842 assert_eq!(snapshot.text(), "ab");
2843
2844 guest_buffer.update(cx, |buffer, cx| buffer.edit([2..2], "c", cx));
2845 let snapshot = multibuffer.read(cx).snapshot(cx);
2846 assert_eq!(snapshot.text(), "abc");
2847 }
2848
2849 #[gpui::test]
2850 fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2851 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2852 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2853 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2854
2855 let subscription = multibuffer.update(cx, |multibuffer, cx| {
2856 let subscription = multibuffer.subscribe();
2857 multibuffer.push_excerpts(buffer_1.clone(), [Point::new(1, 2)..Point::new(2, 5)], cx);
2858 assert_eq!(
2859 subscription.consume().into_inner(),
2860 [Edit {
2861 old: 0..0,
2862 new: 0..10
2863 }]
2864 );
2865
2866 multibuffer.push_excerpts(buffer_1.clone(), [Point::new(3, 3)..Point::new(4, 4)], cx);
2867 multibuffer.push_excerpts(buffer_2.clone(), [Point::new(3, 1)..Point::new(3, 3)], cx);
2868 assert_eq!(
2869 subscription.consume().into_inner(),
2870 [Edit {
2871 old: 10..10,
2872 new: 10..22
2873 }]
2874 );
2875
2876 subscription
2877 });
2878
2879 let snapshot = multibuffer.read(cx).snapshot(cx);
2880 assert_eq!(
2881 snapshot.text(),
2882 concat!(
2883 "bbbb\n", // Preserve newlines
2884 "ccccc\n", //
2885 "ddd\n", //
2886 "eeee\n", //
2887 "jj" //
2888 )
2889 );
2890 assert_eq!(
2891 snapshot.buffer_rows(0).collect::<Vec<_>>(),
2892 [Some(1), Some(2), Some(3), Some(4), Some(3)]
2893 );
2894 assert_eq!(
2895 snapshot.buffer_rows(2).collect::<Vec<_>>(),
2896 [Some(3), Some(4), Some(3)]
2897 );
2898 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2899 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2900
2901 assert_eq!(
2902 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
2903 &[
2904 (0, "bbbb\nccccc".to_string(), true),
2905 (2, "ddd\neeee".to_string(), false),
2906 (4, "jj".to_string(), true),
2907 ]
2908 );
2909 assert_eq!(
2910 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
2911 &[(0, "bbbb\nccccc".to_string(), true)]
2912 );
2913 assert_eq!(
2914 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
2915 &[]
2916 );
2917 assert_eq!(
2918 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
2919 &[]
2920 );
2921 assert_eq!(
2922 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
2923 &[(2, "ddd\neeee".to_string(), false)]
2924 );
2925 assert_eq!(
2926 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
2927 &[(2, "ddd\neeee".to_string(), false)]
2928 );
2929 assert_eq!(
2930 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
2931 &[(2, "ddd\neeee".to_string(), false)]
2932 );
2933 assert_eq!(
2934 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
2935 &[(4, "jj".to_string(), true)]
2936 );
2937 assert_eq!(
2938 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
2939 &[]
2940 );
2941
2942 buffer_1.update(cx, |buffer, cx| {
2943 buffer.edit(
2944 [
2945 Point::new(0, 0)..Point::new(0, 0),
2946 Point::new(2, 1)..Point::new(2, 3),
2947 ],
2948 "\n",
2949 cx,
2950 );
2951 });
2952
2953 let snapshot = multibuffer.read(cx).snapshot(cx);
2954 assert_eq!(
2955 snapshot.text(),
2956 concat!(
2957 "bbbb\n", // Preserve newlines
2958 "c\n", //
2959 "cc\n", //
2960 "ddd\n", //
2961 "eeee\n", //
2962 "jj" //
2963 )
2964 );
2965
2966 assert_eq!(
2967 subscription.consume().into_inner(),
2968 [Edit {
2969 old: 6..8,
2970 new: 6..7
2971 }]
2972 );
2973
2974 let snapshot = multibuffer.read(cx).snapshot(cx);
2975 assert_eq!(
2976 snapshot.clip_point(Point::new(0, 5), Bias::Left),
2977 Point::new(0, 4)
2978 );
2979 assert_eq!(
2980 snapshot.clip_point(Point::new(0, 5), Bias::Right),
2981 Point::new(0, 4)
2982 );
2983 assert_eq!(
2984 snapshot.clip_point(Point::new(5, 1), Bias::Right),
2985 Point::new(5, 1)
2986 );
2987 assert_eq!(
2988 snapshot.clip_point(Point::new(5, 2), Bias::Right),
2989 Point::new(5, 2)
2990 );
2991 assert_eq!(
2992 snapshot.clip_point(Point::new(5, 3), Bias::Right),
2993 Point::new(5, 2)
2994 );
2995
2996 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2997 let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2998 multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2999 multibuffer.snapshot(cx)
3000 });
3001
3002 assert_eq!(
3003 snapshot.text(),
3004 concat!(
3005 "bbbb\n", // Preserve newlines
3006 "c\n", //
3007 "cc\n", //
3008 "ddd\n", //
3009 "eeee", //
3010 )
3011 );
3012
3013 fn boundaries_in_range(
3014 range: Range<Point>,
3015 snapshot: &MultiBufferSnapshot,
3016 ) -> Vec<(u32, String, bool)> {
3017 snapshot
3018 .excerpt_boundaries_in_range(range)
3019 .map(|boundary| {
3020 (
3021 boundary.row,
3022 boundary
3023 .buffer
3024 .text_for_range(boundary.range)
3025 .collect::<String>(),
3026 boundary.starts_new_buffer,
3027 )
3028 })
3029 .collect::<Vec<_>>()
3030 }
3031 }
3032
3033 #[gpui::test]
3034 fn test_excerpts_with_context_lines(cx: &mut MutableAppContext) {
3035 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
3036 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3037 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
3038 multibuffer.push_excerpts_with_context_lines(
3039 buffer.clone(),
3040 vec![
3041 Point::new(3, 2)..Point::new(4, 2),
3042 Point::new(7, 1)..Point::new(7, 3),
3043 Point::new(15, 0)..Point::new(15, 0),
3044 ],
3045 2,
3046 cx,
3047 )
3048 });
3049
3050 let snapshot = multibuffer.read(cx).snapshot(cx);
3051 assert_eq!(
3052 snapshot.text(),
3053 "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
3054 );
3055
3056 assert_eq!(
3057 anchor_ranges
3058 .iter()
3059 .map(|range| range.to_point(&snapshot))
3060 .collect::<Vec<_>>(),
3061 vec![
3062 Point::new(2, 2)..Point::new(3, 2),
3063 Point::new(6, 1)..Point::new(6, 3),
3064 Point::new(12, 0)..Point::new(12, 0)
3065 ]
3066 );
3067 }
3068
3069 #[gpui::test]
3070 fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
3071 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3072
3073 let snapshot = multibuffer.read(cx).snapshot(cx);
3074 assert_eq!(snapshot.text(), "");
3075 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
3076 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
3077 }
3078
3079 #[gpui::test]
3080 fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
3081 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3082 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3083 let old_snapshot = multibuffer.read(cx).snapshot(cx);
3084 buffer.update(cx, |buffer, cx| {
3085 buffer.edit([0..0], "X", cx);
3086 buffer.edit([5..5], "Y", cx);
3087 });
3088 let new_snapshot = multibuffer.read(cx).snapshot(cx);
3089
3090 assert_eq!(old_snapshot.text(), "abcd");
3091 assert_eq!(new_snapshot.text(), "XabcdY");
3092
3093 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
3094 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
3095 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
3096 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
3097 }
3098
3099 #[gpui::test]
3100 fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
3101 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3102 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
3103 let multibuffer = cx.add_model(|cx| {
3104 let mut multibuffer = MultiBuffer::new(0);
3105 multibuffer.push_excerpts(buffer_1.clone(), [0..4], cx);
3106 multibuffer.push_excerpts(buffer_2.clone(), [0..5], cx);
3107 multibuffer
3108 });
3109 let old_snapshot = multibuffer.read(cx).snapshot(cx);
3110
3111 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
3112 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
3113 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
3114 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
3115 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
3116 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
3117
3118 buffer_1.update(cx, |buffer, cx| {
3119 buffer.edit([0..0], "W", cx);
3120 buffer.edit([5..5], "X", cx);
3121 });
3122 buffer_2.update(cx, |buffer, cx| {
3123 buffer.edit([0..0], "Y", cx);
3124 buffer.edit([6..0], "Z", cx);
3125 });
3126 let new_snapshot = multibuffer.read(cx).snapshot(cx);
3127
3128 assert_eq!(old_snapshot.text(), "abcd\nefghi");
3129 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
3130
3131 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
3132 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
3133 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
3134 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
3135 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
3136 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
3137 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
3138 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
3139 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
3140 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
3141 }
3142
3143 #[gpui::test]
3144 fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
3145 cx: &mut MutableAppContext,
3146 ) {
3147 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3148 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
3149 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3150
3151 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
3152 // Add an excerpt from buffer 1 that spans this new insertion.
3153 buffer_1.update(cx, |buffer, cx| buffer.edit([4..4], "123", cx));
3154 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
3155 multibuffer
3156 .push_excerpts(buffer_1.clone(), [0..7], cx)
3157 .pop()
3158 .unwrap()
3159 });
3160
3161 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
3162 assert_eq!(snapshot_1.text(), "abcd123");
3163
3164 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
3165 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
3166 multibuffer.remove_excerpts([&excerpt_id_1], cx);
3167 let mut ids = multibuffer
3168 .push_excerpts(buffer_2.clone(), [0..4, 6..10, 12..16], cx)
3169 .into_iter();
3170 (ids.next().unwrap(), ids.next().unwrap())
3171 });
3172 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
3173 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
3174
3175 // The old excerpt id has been reused.
3176 assert_eq!(excerpt_id_2, excerpt_id_1);
3177
3178 // Resolve some anchors from the previous snapshot in the new snapshot.
3179 // Although there is still an excerpt with the same id, it is for
3180 // a different buffer, so we don't attempt to resolve the old text
3181 // anchor in the new buffer.
3182 assert_eq!(
3183 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
3184 0
3185 );
3186 assert_eq!(
3187 snapshot_2.summaries_for_anchors::<usize, _>(&[
3188 snapshot_1.anchor_before(2),
3189 snapshot_1.anchor_after(3)
3190 ]),
3191 vec![0, 0]
3192 );
3193 let refresh =
3194 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
3195 assert_eq!(
3196 refresh,
3197 &[
3198 (0, snapshot_2.anchor_before(0), false),
3199 (1, snapshot_2.anchor_after(0), false),
3200 ]
3201 );
3202
3203 // Replace the middle excerpt with a smaller excerpt in buffer 2,
3204 // that intersects the old excerpt.
3205 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
3206 multibuffer.remove_excerpts([&excerpt_id_3], cx);
3207 multibuffer
3208 .insert_excerpts_after(&excerpt_id_3, buffer_2.clone(), [5..8], cx)
3209 .pop()
3210 .unwrap()
3211 });
3212
3213 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
3214 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
3215 assert_ne!(excerpt_id_5, excerpt_id_3);
3216
3217 // Resolve some anchors from the previous snapshot in the new snapshot.
3218 // The anchor in the middle excerpt snaps to the beginning of the
3219 // excerpt, since it is not
3220 let anchors = [
3221 snapshot_2.anchor_before(0),
3222 snapshot_2.anchor_after(2),
3223 snapshot_2.anchor_after(6),
3224 snapshot_2.anchor_after(14),
3225 ];
3226 assert_eq!(
3227 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
3228 &[0, 2, 9, 13]
3229 );
3230
3231 let new_anchors = snapshot_3.refresh_anchors(&anchors);
3232 assert_eq!(
3233 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
3234 &[(0, true), (1, true), (2, true), (3, true)]
3235 );
3236 assert_eq!(
3237 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
3238 &[0, 2, 7, 13]
3239 );
3240 }
3241
3242 #[gpui::test(iterations = 100)]
3243 fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
3244 let operations = env::var("OPERATIONS")
3245 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3246 .unwrap_or(10);
3247
3248 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
3249 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3250 let mut excerpt_ids = Vec::new();
3251 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
3252 let mut anchors = Vec::new();
3253 let mut old_versions = Vec::new();
3254
3255 for _ in 0..operations {
3256 match rng.gen_range(0..100) {
3257 0..=19 if !buffers.is_empty() => {
3258 let buffer = buffers.choose(&mut rng).unwrap();
3259 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
3260 }
3261 20..=29 if !expected_excerpts.is_empty() => {
3262 let mut ids_to_remove = vec![];
3263 for _ in 0..rng.gen_range(1..=3) {
3264 if expected_excerpts.is_empty() {
3265 break;
3266 }
3267
3268 let ix = rng.gen_range(0..expected_excerpts.len());
3269 ids_to_remove.push(excerpt_ids.remove(ix));
3270 let (buffer, range) = expected_excerpts.remove(ix);
3271 let buffer = buffer.read(cx);
3272 log::info!(
3273 "Removing excerpt {}: {:?}",
3274 ix,
3275 buffer
3276 .text_for_range(range.to_offset(&buffer))
3277 .collect::<String>(),
3278 );
3279 }
3280 ids_to_remove.sort_unstable();
3281 multibuffer.update(cx, |multibuffer, cx| {
3282 multibuffer.remove_excerpts(&ids_to_remove, cx)
3283 });
3284 }
3285 30..=39 if !expected_excerpts.is_empty() => {
3286 let multibuffer = multibuffer.read(cx).read(cx);
3287 let offset =
3288 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
3289 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
3290 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
3291 anchors.push(multibuffer.anchor_at(offset, bias));
3292 anchors.sort_by(|a, b| a.cmp(&b, &multibuffer).unwrap());
3293 }
3294 40..=44 if !anchors.is_empty() => {
3295 let multibuffer = multibuffer.read(cx).read(cx);
3296
3297 anchors = multibuffer
3298 .refresh_anchors(&anchors)
3299 .into_iter()
3300 .map(|a| a.1)
3301 .collect();
3302
3303 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
3304 // overshoot its boundaries.
3305 let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
3306 for anchor in &anchors {
3307 if anchor.excerpt_id == ExcerptId::min()
3308 || anchor.excerpt_id == ExcerptId::max()
3309 {
3310 continue;
3311 }
3312
3313 cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
3314 let excerpt = cursor.item().unwrap();
3315 assert_eq!(excerpt.id, anchor.excerpt_id);
3316 assert!(excerpt.contains(anchor));
3317 }
3318 }
3319 _ => {
3320 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
3321 let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
3322 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
3323 buffers.last().unwrap()
3324 } else {
3325 buffers.choose(&mut rng).unwrap()
3326 };
3327
3328 let buffer = buffer_handle.read(cx);
3329 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
3330 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3331 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3332 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
3333 let prev_excerpt_id = excerpt_ids
3334 .get(prev_excerpt_ix)
3335 .cloned()
3336 .unwrap_or(ExcerptId::max());
3337 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3338
3339 log::info!(
3340 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3341 excerpt_ix,
3342 expected_excerpts.len(),
3343 buffer_handle.id(),
3344 buffer.text(),
3345 start_ix..end_ix,
3346 &buffer.text()[start_ix..end_ix]
3347 );
3348
3349 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3350 multibuffer
3351 .insert_excerpts_after(
3352 &prev_excerpt_id,
3353 buffer_handle.clone(),
3354 [start_ix..end_ix],
3355 cx,
3356 )
3357 .pop()
3358 .unwrap()
3359 });
3360
3361 excerpt_ids.insert(excerpt_ix, excerpt_id);
3362 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
3363 }
3364 }
3365
3366 if rng.gen_bool(0.3) {
3367 multibuffer.update(cx, |multibuffer, cx| {
3368 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3369 })
3370 }
3371
3372 let snapshot = multibuffer.read(cx).snapshot(cx);
3373
3374 let mut excerpt_starts = Vec::new();
3375 let mut expected_text = String::new();
3376 let mut expected_buffer_rows = Vec::new();
3377 for (buffer, range) in &expected_excerpts {
3378 let buffer = buffer.read(cx);
3379 let buffer_range = range.to_offset(buffer);
3380
3381 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
3382 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
3383 expected_text.push('\n');
3384
3385 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
3386 ..=buffer.offset_to_point(buffer_range.end).row;
3387 for row in buffer_row_range {
3388 expected_buffer_rows.push(Some(row));
3389 }
3390 }
3391 // Remove final trailing newline.
3392 if !expected_excerpts.is_empty() {
3393 expected_text.pop();
3394 }
3395
3396 // Always report one buffer row
3397 if expected_buffer_rows.is_empty() {
3398 expected_buffer_rows.push(Some(0));
3399 }
3400
3401 assert_eq!(snapshot.text(), expected_text);
3402 log::info!("MultiBuffer text: {:?}", expected_text);
3403
3404 assert_eq!(
3405 snapshot.buffer_rows(0).collect::<Vec<_>>(),
3406 expected_buffer_rows,
3407 );
3408
3409 for _ in 0..5 {
3410 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
3411 assert_eq!(
3412 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
3413 &expected_buffer_rows[start_row..],
3414 "buffer_rows({})",
3415 start_row
3416 );
3417 }
3418
3419 assert_eq!(
3420 snapshot.max_buffer_row(),
3421 expected_buffer_rows
3422 .into_iter()
3423 .filter_map(|r| r)
3424 .max()
3425 .unwrap()
3426 );
3427
3428 let mut excerpt_starts = excerpt_starts.into_iter();
3429 for (buffer, range) in &expected_excerpts {
3430 let buffer_id = buffer.id();
3431 let buffer = buffer.read(cx);
3432 let buffer_range = range.to_offset(buffer);
3433 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
3434 let buffer_start_point_utf16 =
3435 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
3436
3437 let excerpt_start = excerpt_starts.next().unwrap();
3438 let mut offset = excerpt_start.bytes;
3439 let mut buffer_offset = buffer_range.start;
3440 let mut point = excerpt_start.lines;
3441 let mut buffer_point = buffer_start_point;
3442 let mut point_utf16 = excerpt_start.lines_utf16;
3443 let mut buffer_point_utf16 = buffer_start_point_utf16;
3444 for ch in buffer
3445 .snapshot()
3446 .chunks(buffer_range.clone(), false)
3447 .flat_map(|c| c.text.chars())
3448 {
3449 for _ in 0..ch.len_utf8() {
3450 let left_offset = snapshot.clip_offset(offset, Bias::Left);
3451 let right_offset = snapshot.clip_offset(offset, Bias::Right);
3452 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
3453 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
3454 assert_eq!(
3455 left_offset,
3456 excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
3457 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
3458 offset,
3459 buffer_id,
3460 buffer_offset,
3461 );
3462 assert_eq!(
3463 right_offset,
3464 excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
3465 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
3466 offset,
3467 buffer_id,
3468 buffer_offset,
3469 );
3470
3471 let left_point = snapshot.clip_point(point, Bias::Left);
3472 let right_point = snapshot.clip_point(point, Bias::Right);
3473 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
3474 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
3475 assert_eq!(
3476 left_point,
3477 excerpt_start.lines + (buffer_left_point - buffer_start_point),
3478 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
3479 point,
3480 buffer_id,
3481 buffer_point,
3482 );
3483 assert_eq!(
3484 right_point,
3485 excerpt_start.lines + (buffer_right_point - buffer_start_point),
3486 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
3487 point,
3488 buffer_id,
3489 buffer_point,
3490 );
3491
3492 assert_eq!(
3493 snapshot.point_to_offset(left_point),
3494 left_offset,
3495 "point_to_offset({:?})",
3496 left_point,
3497 );
3498 assert_eq!(
3499 snapshot.offset_to_point(left_offset),
3500 left_point,
3501 "offset_to_point({:?})",
3502 left_offset,
3503 );
3504
3505 offset += 1;
3506 buffer_offset += 1;
3507 if ch == '\n' {
3508 point += Point::new(1, 0);
3509 buffer_point += Point::new(1, 0);
3510 } else {
3511 point += Point::new(0, 1);
3512 buffer_point += Point::new(0, 1);
3513 }
3514 }
3515
3516 for _ in 0..ch.len_utf16() {
3517 let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
3518 let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
3519 let buffer_left_point_utf16 =
3520 buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
3521 let buffer_right_point_utf16 =
3522 buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
3523 assert_eq!(
3524 left_point_utf16,
3525 excerpt_start.lines_utf16
3526 + (buffer_left_point_utf16 - buffer_start_point_utf16),
3527 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
3528 point_utf16,
3529 buffer_id,
3530 buffer_point_utf16,
3531 );
3532 assert_eq!(
3533 right_point_utf16,
3534 excerpt_start.lines_utf16
3535 + (buffer_right_point_utf16 - buffer_start_point_utf16),
3536 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
3537 point_utf16,
3538 buffer_id,
3539 buffer_point_utf16,
3540 );
3541
3542 if ch == '\n' {
3543 point_utf16 += PointUtf16::new(1, 0);
3544 buffer_point_utf16 += PointUtf16::new(1, 0);
3545 } else {
3546 point_utf16 += PointUtf16::new(0, 1);
3547 buffer_point_utf16 += PointUtf16::new(0, 1);
3548 }
3549 }
3550 }
3551 }
3552
3553 for (row, line) in expected_text.split('\n').enumerate() {
3554 assert_eq!(
3555 snapshot.line_len(row as u32),
3556 line.len() as u32,
3557 "line_len({}).",
3558 row
3559 );
3560 }
3561
3562 let text_rope = Rope::from(expected_text.as_str());
3563 for _ in 0..10 {
3564 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3565 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3566
3567 let text_for_range = snapshot
3568 .text_for_range(start_ix..end_ix)
3569 .collect::<String>();
3570 assert_eq!(
3571 text_for_range,
3572 &expected_text[start_ix..end_ix],
3573 "incorrect text for range {:?}",
3574 start_ix..end_ix
3575 );
3576
3577 let excerpted_buffer_ranges = multibuffer
3578 .read(cx)
3579 .range_to_buffer_ranges(start_ix..end_ix, cx);
3580 let excerpted_buffers_text = excerpted_buffer_ranges
3581 .into_iter()
3582 .map(|(buffer, buffer_range)| {
3583 buffer
3584 .read(cx)
3585 .text_for_range(buffer_range)
3586 .collect::<String>()
3587 })
3588 .collect::<Vec<_>>()
3589 .join("\n");
3590 assert_eq!(excerpted_buffers_text, text_for_range);
3591
3592 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
3593 assert_eq!(
3594 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
3595 expected_summary,
3596 "incorrect summary for range {:?}",
3597 start_ix..end_ix
3598 );
3599 }
3600
3601 // Anchor resolution
3602 for (anchor, resolved_offset) in anchors
3603 .iter()
3604 .zip(snapshot.summaries_for_anchors::<usize, _>(&anchors))
3605 {
3606 assert!(resolved_offset <= snapshot.len());
3607 assert_eq!(
3608 snapshot.summary_for_anchor::<usize>(anchor),
3609 resolved_offset
3610 );
3611 }
3612
3613 for _ in 0..10 {
3614 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3615 assert_eq!(
3616 snapshot.reversed_chars_at(end_ix).collect::<String>(),
3617 expected_text[..end_ix].chars().rev().collect::<String>(),
3618 );
3619 }
3620
3621 for _ in 0..10 {
3622 let end_ix = rng.gen_range(0..=text_rope.len());
3623 let start_ix = rng.gen_range(0..=end_ix);
3624 assert_eq!(
3625 snapshot
3626 .bytes_in_range(start_ix..end_ix)
3627 .flatten()
3628 .copied()
3629 .collect::<Vec<_>>(),
3630 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3631 "bytes_in_range({:?})",
3632 start_ix..end_ix,
3633 );
3634 }
3635 }
3636
3637 let snapshot = multibuffer.read(cx).snapshot(cx);
3638 for (old_snapshot, subscription) in old_versions {
3639 let edits = subscription.consume().into_inner();
3640
3641 log::info!(
3642 "applying subscription edits to old text: {:?}: {:?}",
3643 old_snapshot.text(),
3644 edits,
3645 );
3646
3647 let mut text = old_snapshot.text();
3648 for edit in edits {
3649 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
3650 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
3651 }
3652 assert_eq!(text.to_string(), snapshot.text());
3653 }
3654 }
3655
3656 #[gpui::test]
3657 fn test_history(cx: &mut MutableAppContext) {
3658 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
3659 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
3660 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3661 let group_interval = multibuffer.read(cx).history.group_interval;
3662 multibuffer.update(cx, |multibuffer, cx| {
3663 multibuffer.push_excerpts(buffer_1.clone(), [0..buffer_1.read(cx).len()], cx);
3664 multibuffer.push_excerpts(buffer_2.clone(), [0..buffer_2.read(cx).len()], cx);
3665 });
3666
3667 let mut now = Instant::now();
3668
3669 multibuffer.update(cx, |multibuffer, cx| {
3670 multibuffer.start_transaction_at(now, cx);
3671 multibuffer.edit(
3672 [
3673 Point::new(0, 0)..Point::new(0, 0),
3674 Point::new(1, 0)..Point::new(1, 0),
3675 ],
3676 "A",
3677 cx,
3678 );
3679 multibuffer.edit(
3680 [
3681 Point::new(0, 1)..Point::new(0, 1),
3682 Point::new(1, 1)..Point::new(1, 1),
3683 ],
3684 "B",
3685 cx,
3686 );
3687 multibuffer.end_transaction_at(now, cx);
3688 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3689
3690 now += 2 * group_interval;
3691 multibuffer.start_transaction_at(now, cx);
3692 multibuffer.edit([2..2], "C", cx);
3693 multibuffer.end_transaction_at(now, cx);
3694 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3695
3696 multibuffer.undo(cx);
3697 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3698
3699 multibuffer.undo(cx);
3700 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3701
3702 multibuffer.redo(cx);
3703 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3704
3705 multibuffer.redo(cx);
3706 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3707
3708 buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
3709 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3710
3711 multibuffer.undo(cx);
3712 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3713
3714 multibuffer.redo(cx);
3715 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3716
3717 multibuffer.redo(cx);
3718 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3719
3720 multibuffer.undo(cx);
3721 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3722
3723 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3724 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3725
3726 multibuffer.undo(cx);
3727 assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
3728 });
3729 }
3730}