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