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