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