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