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