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