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