1mod anchor;
2
3pub use anchor::{Anchor, AnchorRangeExt};
4use anyhow::Result;
5use clock::ReplicaId;
6use collections::{BTreeMap, Bound, HashMap, HashSet};
7use git::diff::DiffHunk;
8use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task};
9pub use language::Completion;
10use language::{
11 char_kind, AutoindentMode, Buffer, BufferChunks, BufferSnapshot, CharKind, Chunk, CursorShape,
12 DiagnosticEntry, File, IndentSize, Language, OffsetRangeExt, OffsetUtf16, Outline, OutlineItem,
13 Point, PointUtf16, Selection, TextDimension, ToOffset as _, ToOffsetUtf16 as _, ToPoint as _,
14 ToPointUtf16 as _, TransactionId, Unclipped,
15};
16use smallvec::SmallVec;
17use std::{
18 borrow::Cow,
19 cell::{Ref, RefCell},
20 cmp, fmt, io,
21 iter::{self, FromIterator},
22 mem,
23 ops::{Range, RangeBounds, Sub},
24 str,
25 sync::Arc,
26 time::{Duration, Instant},
27};
28use sum_tree::{Bias, Cursor, SumTree};
29use text::{
30 locator::Locator,
31 subscription::{Subscription, Topic},
32 Edit, TextSummary,
33};
34use theme::SyntaxTheme;
35use util::post_inc;
36
37const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize];
38
39#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
40pub struct ExcerptId(usize);
41
42pub struct MultiBuffer {
43 snapshot: RefCell<MultiBufferSnapshot>,
44 buffers: RefCell<HashMap<usize, BufferState>>,
45 next_excerpt_id: usize,
46 subscriptions: Topic,
47 singleton: bool,
48 replica_id: ReplicaId,
49 history: History,
50 title: Option<String>,
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub enum Event {
55 ExcerptsAdded {
56 buffer: ModelHandle<Buffer>,
57 predecessor: ExcerptId,
58 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
59 },
60 ExcerptsRemoved {
61 ids: Vec<ExcerptId>,
62 },
63 Edited,
64 Reloaded,
65 Reparsed,
66 Saved,
67 FileHandleChanged,
68 Closed,
69 DirtyChanged,
70 DiagnosticsUpdated,
71}
72
73#[derive(Clone)]
74struct History {
75 next_transaction_id: TransactionId,
76 undo_stack: Vec<Transaction>,
77 redo_stack: Vec<Transaction>,
78 transaction_depth: usize,
79 group_interval: Duration,
80}
81
82#[derive(Clone)]
83struct Transaction {
84 id: TransactionId,
85 buffer_transactions: HashMap<usize, text::TransactionId>,
86 first_edit_at: Instant,
87 last_edit_at: Instant,
88 suppress_grouping: bool,
89}
90
91pub trait ToOffset: 'static + fmt::Debug {
92 fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
93}
94
95pub trait ToOffsetUtf16: 'static + fmt::Debug {
96 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16;
97}
98
99pub trait ToPoint: 'static + fmt::Debug {
100 fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
101}
102
103pub trait ToPointUtf16: 'static + fmt::Debug {
104 fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16;
105}
106
107struct BufferState {
108 buffer: ModelHandle<Buffer>,
109 last_version: clock::Global,
110 last_parse_count: usize,
111 last_selections_update_count: usize,
112 last_diagnostics_update_count: usize,
113 last_file_update_count: usize,
114 last_git_diff_update_count: usize,
115 excerpts: Vec<Locator>,
116 _subscriptions: [gpui::Subscription; 2],
117}
118
119#[derive(Clone, Default)]
120pub struct MultiBufferSnapshot {
121 singleton: bool,
122 excerpts: SumTree<Excerpt>,
123 excerpt_ids: SumTree<ExcerptIdMapping>,
124 parse_count: usize,
125 diagnostics_update_count: usize,
126 trailing_excerpt_update_count: usize,
127 git_diff_update_count: usize,
128 edit_count: usize,
129 is_dirty: bool,
130 has_conflict: bool,
131}
132
133pub struct ExcerptBoundary {
134 pub id: ExcerptId,
135 pub row: u32,
136 pub buffer: BufferSnapshot,
137 pub range: ExcerptRange<text::Anchor>,
138 pub starts_new_buffer: bool,
139}
140
141#[derive(Clone)]
142struct Excerpt {
143 id: ExcerptId,
144 locator: Locator,
145 buffer_id: usize,
146 buffer: BufferSnapshot,
147 range: ExcerptRange<text::Anchor>,
148 max_buffer_row: u32,
149 text_summary: TextSummary,
150 has_trailing_newline: bool,
151}
152
153#[derive(Clone, Debug)]
154struct ExcerptIdMapping {
155 id: ExcerptId,
156 locator: Locator,
157}
158
159#[derive(Clone, Debug, Eq, PartialEq)]
160pub struct ExcerptRange<T> {
161 pub context: Range<T>,
162 pub primary: Option<Range<T>>,
163}
164
165#[derive(Clone, Debug, Default)]
166struct ExcerptSummary {
167 excerpt_id: ExcerptId,
168 excerpt_locator: Locator,
169 max_buffer_row: u32,
170 text: TextSummary,
171}
172
173#[derive(Clone)]
174pub struct MultiBufferRows<'a> {
175 buffer_row_range: Range<u32>,
176 excerpts: Cursor<'a, Excerpt, Point>,
177}
178
179pub struct MultiBufferChunks<'a> {
180 range: Range<usize>,
181 excerpts: Cursor<'a, Excerpt, usize>,
182 excerpt_chunks: Option<ExcerptChunks<'a>>,
183 language_aware: bool,
184}
185
186pub struct MultiBufferBytes<'a> {
187 range: Range<usize>,
188 excerpts: Cursor<'a, Excerpt, usize>,
189 excerpt_bytes: Option<ExcerptBytes<'a>>,
190 chunk: &'a [u8],
191}
192
193struct ExcerptChunks<'a> {
194 content_chunks: BufferChunks<'a>,
195 footer_height: usize,
196}
197
198struct ExcerptBytes<'a> {
199 content_bytes: text::Bytes<'a>,
200 footer_height: usize,
201}
202
203impl MultiBuffer {
204 pub fn new(replica_id: ReplicaId) -> Self {
205 Self {
206 snapshot: Default::default(),
207 buffers: Default::default(),
208 next_excerpt_id: 1,
209 subscriptions: Default::default(),
210 singleton: false,
211 replica_id,
212 history: History {
213 next_transaction_id: Default::default(),
214 undo_stack: Default::default(),
215 redo_stack: Default::default(),
216 transaction_depth: 0,
217 group_interval: Duration::from_millis(300),
218 },
219 title: Default::default(),
220 }
221 }
222
223 pub fn clone(&self, new_cx: &mut ModelContext<Self>) -> Self {
224 let mut buffers = HashMap::default();
225 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
226 buffers.insert(
227 *buffer_id,
228 BufferState {
229 buffer: buffer_state.buffer.clone(),
230 last_version: buffer_state.last_version.clone(),
231 last_parse_count: buffer_state.last_parse_count,
232 last_selections_update_count: buffer_state.last_selections_update_count,
233 last_diagnostics_update_count: buffer_state.last_diagnostics_update_count,
234 last_file_update_count: buffer_state.last_file_update_count,
235 last_git_diff_update_count: buffer_state.last_git_diff_update_count,
236 excerpts: buffer_state.excerpts.clone(),
237 _subscriptions: [
238 new_cx.observe(&buffer_state.buffer, |_, _, cx| cx.notify()),
239 new_cx.subscribe(&buffer_state.buffer, Self::on_buffer_event),
240 ],
241 },
242 );
243 }
244 Self {
245 snapshot: RefCell::new(self.snapshot.borrow().clone()),
246 buffers: RefCell::new(buffers),
247 next_excerpt_id: 1,
248 subscriptions: Default::default(),
249 singleton: self.singleton,
250 replica_id: self.replica_id,
251 history: self.history.clone(),
252 title: self.title.clone(),
253 }
254 }
255
256 pub fn with_title(mut self, title: String) -> Self {
257 self.title = Some(title);
258 self
259 }
260
261 pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
262 let mut this = Self::new(buffer.read(cx).replica_id());
263 this.singleton = true;
264 this.push_excerpts(
265 buffer,
266 [ExcerptRange {
267 context: text::Anchor::MIN..text::Anchor::MAX,
268 primary: None,
269 }],
270 cx,
271 );
272 this.snapshot.borrow_mut().singleton = true;
273 this
274 }
275
276 pub fn replica_id(&self) -> ReplicaId {
277 self.replica_id
278 }
279
280 pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
281 self.sync(cx);
282 self.snapshot.borrow().clone()
283 }
284
285 pub(crate) fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
286 self.sync(cx);
287 self.snapshot.borrow()
288 }
289
290 pub fn as_singleton(&self) -> Option<ModelHandle<Buffer>> {
291 if self.singleton {
292 return Some(
293 self.buffers
294 .borrow()
295 .values()
296 .next()
297 .unwrap()
298 .buffer
299 .clone(),
300 );
301 } else {
302 None
303 }
304 }
305
306 pub fn is_singleton(&self) -> bool {
307 self.singleton
308 }
309
310 pub fn subscribe(&mut self) -> Subscription {
311 self.subscriptions.subscribe()
312 }
313
314 pub fn is_dirty(&self, cx: &AppContext) -> bool {
315 self.read(cx).is_dirty()
316 }
317
318 pub fn has_conflict(&self, cx: &AppContext) -> bool {
319 self.read(cx).has_conflict()
320 }
321
322 // The `is_empty` signature doesn't match what clippy expects
323 #[allow(clippy::len_without_is_empty)]
324 pub fn len(&self, cx: &AppContext) -> usize {
325 self.read(cx).len()
326 }
327
328 pub fn is_empty(&self, cx: &AppContext) -> bool {
329 self.len(cx) != 0
330 }
331
332 pub fn symbols_containing<T: ToOffset>(
333 &self,
334 offset: T,
335 theme: Option<&SyntaxTheme>,
336 cx: &AppContext,
337 ) -> Option<(usize, Vec<OutlineItem<Anchor>>)> {
338 self.read(cx).symbols_containing(offset, theme)
339 }
340
341 pub fn git_diff_recalc(&mut self, cx: &mut ModelContext<Self>) {
342 let buffers = self.buffers.borrow();
343 for buffer_state in buffers.values() {
344 if buffer_state.buffer.read(cx).needs_git_diff_recalc() {
345 buffer_state
346 .buffer
347 .update(cx, |buffer, cx| buffer.git_diff_recalc(cx))
348 }
349 }
350 }
351
352 pub fn edit<I, S, T>(
353 &mut self,
354 edits: I,
355 mut autoindent_mode: Option<AutoindentMode>,
356 cx: &mut ModelContext<Self>,
357 ) where
358 I: IntoIterator<Item = (Range<S>, T)>,
359 S: ToOffset,
360 T: Into<Arc<str>>,
361 {
362 if self.buffers.borrow().is_empty() {
363 return;
364 }
365
366 let snapshot = self.read(cx);
367 let edits = edits.into_iter().map(|(range, new_text)| {
368 let mut range = range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot);
369 if range.start > range.end {
370 mem::swap(&mut range.start, &mut range.end);
371 }
372 (range, new_text)
373 });
374
375 if let Some(buffer) = self.as_singleton() {
376 return buffer.update(cx, |buffer, cx| {
377 buffer.edit(edits, autoindent_mode, cx);
378 });
379 }
380
381 let original_indent_columns = match &mut autoindent_mode {
382 Some(AutoindentMode::Block {
383 original_indent_columns,
384 }) => mem::take(original_indent_columns),
385 _ => Default::default(),
386 };
387
388 #[allow(clippy::type_complexity)]
389 let mut buffer_edits: HashMap<usize, Vec<(Range<usize>, Arc<str>, bool, u32)>> =
390 Default::default();
391 let mut cursor = snapshot.excerpts.cursor::<usize>();
392 for (ix, (range, new_text)) in edits.enumerate() {
393 let new_text: Arc<str> = new_text.into();
394 let original_indent_column = original_indent_columns.get(ix).copied().unwrap_or(0);
395 cursor.seek(&range.start, Bias::Right, &());
396 if cursor.item().is_none() && range.start == *cursor.start() {
397 cursor.prev(&());
398 }
399 let start_excerpt = cursor.item().expect("start offset out of bounds");
400 let start_overshoot = range.start - cursor.start();
401 let buffer_start = start_excerpt
402 .range
403 .context
404 .start
405 .to_offset(&start_excerpt.buffer)
406 + start_overshoot;
407
408 cursor.seek(&range.end, Bias::Right, &());
409 if cursor.item().is_none() && range.end == *cursor.start() {
410 cursor.prev(&());
411 }
412 let end_excerpt = cursor.item().expect("end offset out of bounds");
413 let end_overshoot = range.end - cursor.start();
414 let buffer_end = end_excerpt
415 .range
416 .context
417 .start
418 .to_offset(&end_excerpt.buffer)
419 + end_overshoot;
420
421 if start_excerpt.id == end_excerpt.id {
422 buffer_edits
423 .entry(start_excerpt.buffer_id)
424 .or_insert(Vec::new())
425 .push((
426 buffer_start..buffer_end,
427 new_text,
428 true,
429 original_indent_column,
430 ));
431 } else {
432 let start_excerpt_range = buffer_start
433 ..start_excerpt
434 .range
435 .context
436 .end
437 .to_offset(&start_excerpt.buffer);
438 let end_excerpt_range = end_excerpt
439 .range
440 .context
441 .start
442 .to_offset(&end_excerpt.buffer)
443 ..buffer_end;
444 buffer_edits
445 .entry(start_excerpt.buffer_id)
446 .or_insert(Vec::new())
447 .push((
448 start_excerpt_range,
449 new_text.clone(),
450 true,
451 original_indent_column,
452 ));
453 buffer_edits
454 .entry(end_excerpt.buffer_id)
455 .or_insert(Vec::new())
456 .push((
457 end_excerpt_range,
458 new_text.clone(),
459 false,
460 original_indent_column,
461 ));
462
463 cursor.seek(&range.start, Bias::Right, &());
464 cursor.next(&());
465 while let Some(excerpt) = cursor.item() {
466 if excerpt.id == end_excerpt.id {
467 break;
468 }
469 buffer_edits
470 .entry(excerpt.buffer_id)
471 .or_insert(Vec::new())
472 .push((
473 excerpt.range.context.to_offset(&excerpt.buffer),
474 new_text.clone(),
475 false,
476 original_indent_column,
477 ));
478 cursor.next(&());
479 }
480 }
481 }
482
483 for (buffer_id, mut edits) in buffer_edits {
484 edits.sort_unstable_by_key(|(range, _, _, _)| range.start);
485 self.buffers.borrow()[&buffer_id]
486 .buffer
487 .update(cx, |buffer, cx| {
488 let mut edits = edits.into_iter().peekable();
489 let mut insertions = Vec::new();
490 let mut original_indent_columns = Vec::new();
491 let mut deletions = Vec::new();
492 let empty_str: Arc<str> = "".into();
493 while let Some((
494 mut range,
495 new_text,
496 mut is_insertion,
497 original_indent_column,
498 )) = edits.next()
499 {
500 while let Some((next_range, _, next_is_insertion, _)) = edits.peek() {
501 if range.end >= next_range.start {
502 range.end = cmp::max(next_range.end, range.end);
503 is_insertion |= *next_is_insertion;
504 edits.next();
505 } else {
506 break;
507 }
508 }
509
510 if is_insertion {
511 original_indent_columns.push(original_indent_column);
512 insertions.push((
513 buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
514 new_text.clone(),
515 ));
516 } else if !range.is_empty() {
517 deletions.push((
518 buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
519 empty_str.clone(),
520 ));
521 }
522 }
523
524 let deletion_autoindent_mode =
525 if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
526 Some(AutoindentMode::Block {
527 original_indent_columns: Default::default(),
528 })
529 } else {
530 None
531 };
532 let insertion_autoindent_mode =
533 if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
534 Some(AutoindentMode::Block {
535 original_indent_columns,
536 })
537 } else {
538 None
539 };
540
541 buffer.edit(deletions, deletion_autoindent_mode, cx);
542 buffer.edit(insertions, insertion_autoindent_mode, cx);
543 })
544 }
545 }
546
547 pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
548 self.start_transaction_at(Instant::now(), cx)
549 }
550
551 pub(crate) fn start_transaction_at(
552 &mut self,
553 now: Instant,
554 cx: &mut ModelContext<Self>,
555 ) -> Option<TransactionId> {
556 if let Some(buffer) = self.as_singleton() {
557 return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
558 }
559
560 for BufferState { buffer, .. } in self.buffers.borrow().values() {
561 buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
562 }
563 self.history.start_transaction(now)
564 }
565
566 pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
567 self.end_transaction_at(Instant::now(), cx)
568 }
569
570 pub(crate) fn end_transaction_at(
571 &mut self,
572 now: Instant,
573 cx: &mut ModelContext<Self>,
574 ) -> Option<TransactionId> {
575 if let Some(buffer) = self.as_singleton() {
576 return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
577 }
578
579 let mut buffer_transactions = HashMap::default();
580 for BufferState { buffer, .. } in self.buffers.borrow().values() {
581 if let Some(transaction_id) =
582 buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
583 {
584 buffer_transactions.insert(buffer.id(), transaction_id);
585 }
586 }
587
588 if self.history.end_transaction(now, buffer_transactions) {
589 let transaction_id = self.history.group().unwrap();
590 Some(transaction_id)
591 } else {
592 None
593 }
594 }
595
596 pub fn finalize_last_transaction(&mut self, cx: &mut ModelContext<Self>) {
597 self.history.finalize_last_transaction();
598 for BufferState { buffer, .. } in self.buffers.borrow().values() {
599 buffer.update(cx, |buffer, _| {
600 buffer.finalize_last_transaction();
601 });
602 }
603 }
604
605 pub fn push_transaction<'a, T>(&mut self, buffer_transactions: T)
606 where
607 T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
608 {
609 self.history
610 .push_transaction(buffer_transactions, Instant::now());
611 self.history.finalize_last_transaction();
612 }
613
614 pub fn group_until_transaction(
615 &mut self,
616 transaction_id: TransactionId,
617 cx: &mut ModelContext<Self>,
618 ) {
619 if let Some(buffer) = self.as_singleton() {
620 buffer.update(cx, |buffer, _| {
621 buffer.group_until_transaction(transaction_id)
622 });
623 } else {
624 self.history.group_until(transaction_id);
625 }
626 }
627
628 pub fn set_active_selections(
629 &mut self,
630 selections: &[Selection<Anchor>],
631 line_mode: bool,
632 cursor_shape: CursorShape,
633 cx: &mut ModelContext<Self>,
634 ) {
635 let mut selections_by_buffer: HashMap<usize, Vec<Selection<text::Anchor>>> =
636 Default::default();
637 let snapshot = self.read(cx);
638 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
639 for selection in selections {
640 let start_locator = snapshot.excerpt_locator_for_id(selection.start.excerpt_id);
641 let end_locator = snapshot.excerpt_locator_for_id(selection.end.excerpt_id);
642
643 cursor.seek(&Some(start_locator), Bias::Left, &());
644 while let Some(excerpt) = cursor.item() {
645 if excerpt.locator > *end_locator {
646 break;
647 }
648
649 let mut start = excerpt.range.context.start;
650 let mut end = excerpt.range.context.end;
651 if excerpt.id == selection.start.excerpt_id {
652 start = selection.start.text_anchor;
653 }
654 if excerpt.id == selection.end.excerpt_id {
655 end = selection.end.text_anchor;
656 }
657 selections_by_buffer
658 .entry(excerpt.buffer_id)
659 .or_default()
660 .push(Selection {
661 id: selection.id,
662 start,
663 end,
664 reversed: selection.reversed,
665 goal: selection.goal,
666 });
667
668 cursor.next(&());
669 }
670 }
671
672 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
673 if !selections_by_buffer.contains_key(buffer_id) {
674 buffer_state
675 .buffer
676 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
677 }
678 }
679
680 for (buffer_id, mut selections) in selections_by_buffer {
681 self.buffers.borrow()[&buffer_id]
682 .buffer
683 .update(cx, |buffer, cx| {
684 selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer));
685 let mut selections = selections.into_iter().peekable();
686 let merged_selections = Arc::from_iter(iter::from_fn(|| {
687 let mut selection = selections.next()?;
688 while let Some(next_selection) = selections.peek() {
689 if selection.end.cmp(&next_selection.start, buffer).is_ge() {
690 let next_selection = selections.next().unwrap();
691 if next_selection.end.cmp(&selection.end, buffer).is_ge() {
692 selection.end = next_selection.end;
693 }
694 } else {
695 break;
696 }
697 }
698 Some(selection)
699 }));
700 buffer.set_active_selections(merged_selections, line_mode, cursor_shape, cx);
701 });
702 }
703 }
704
705 pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
706 for buffer in self.buffers.borrow().values() {
707 buffer
708 .buffer
709 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
710 }
711 }
712
713 pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
714 if let Some(buffer) = self.as_singleton() {
715 return buffer.update(cx, |buffer, cx| buffer.undo(cx));
716 }
717
718 while let Some(transaction) = self.history.pop_undo() {
719 let mut undone = false;
720 for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
721 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
722 undone |= buffer.update(cx, |buffer, cx| {
723 let undo_to = *buffer_transaction_id;
724 if let Some(entry) = buffer.peek_undo_stack() {
725 *buffer_transaction_id = entry.transaction_id();
726 }
727 buffer.undo_to_transaction(undo_to, cx)
728 });
729 }
730 }
731
732 if undone {
733 return Some(transaction.id);
734 }
735 }
736
737 None
738 }
739
740 pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
741 if let Some(buffer) = self.as_singleton() {
742 return buffer.update(cx, |buffer, cx| buffer.redo(cx));
743 }
744
745 while let Some(transaction) = self.history.pop_redo() {
746 let mut redone = false;
747 for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
748 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
749 redone |= buffer.update(cx, |buffer, cx| {
750 let redo_to = *buffer_transaction_id;
751 if let Some(entry) = buffer.peek_redo_stack() {
752 *buffer_transaction_id = entry.transaction_id();
753 }
754 buffer.redo_to_transaction(redo_to, cx)
755 });
756 }
757 }
758
759 if redone {
760 return Some(transaction.id);
761 }
762 }
763
764 None
765 }
766
767 pub fn push_excerpts<O>(
768 &mut self,
769 buffer: ModelHandle<Buffer>,
770 ranges: impl IntoIterator<Item = ExcerptRange<O>>,
771 cx: &mut ModelContext<Self>,
772 ) -> Vec<ExcerptId>
773 where
774 O: text::ToOffset,
775 {
776 self.insert_excerpts_after(ExcerptId::max(), buffer, ranges, cx)
777 }
778
779 pub fn push_excerpts_with_context_lines<O>(
780 &mut self,
781 buffer: ModelHandle<Buffer>,
782 ranges: Vec<Range<O>>,
783 context_line_count: u32,
784 cx: &mut ModelContext<Self>,
785 ) -> Vec<Range<Anchor>>
786 where
787 O: text::ToPoint + text::ToOffset,
788 {
789 let buffer_id = buffer.id();
790 let buffer_snapshot = buffer.read(cx).snapshot();
791 let max_point = buffer_snapshot.max_point();
792
793 let mut range_counts = Vec::new();
794 let mut excerpt_ranges = Vec::new();
795 let mut range_iter = ranges
796 .iter()
797 .map(|range| {
798 range.start.to_point(&buffer_snapshot)..range.end.to_point(&buffer_snapshot)
799 })
800 .peekable();
801 while let Some(range) = range_iter.next() {
802 let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
803 let mut excerpt_end =
804 Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
805 let mut ranges_in_excerpt = 1;
806
807 while let Some(next_range) = range_iter.peek() {
808 if next_range.start.row <= excerpt_end.row + context_line_count {
809 excerpt_end =
810 Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
811 ranges_in_excerpt += 1;
812 range_iter.next();
813 } else {
814 break;
815 }
816 }
817
818 excerpt_ranges.push(ExcerptRange {
819 context: excerpt_start..excerpt_end,
820 primary: Some(range),
821 });
822 range_counts.push(ranges_in_excerpt);
823 }
824
825 let excerpt_ids = self.push_excerpts(buffer, excerpt_ranges, cx);
826
827 let mut anchor_ranges = Vec::new();
828 let mut ranges = ranges.into_iter();
829 for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(range_counts.into_iter()) {
830 anchor_ranges.extend(ranges.by_ref().take(range_count).map(|range| {
831 let start = Anchor {
832 buffer_id: Some(buffer_id),
833 excerpt_id: excerpt_id.clone(),
834 text_anchor: buffer_snapshot.anchor_after(range.start),
835 };
836 let end = Anchor {
837 buffer_id: Some(buffer_id),
838 excerpt_id: excerpt_id.clone(),
839 text_anchor: buffer_snapshot.anchor_after(range.end),
840 };
841 start..end
842 }))
843 }
844 anchor_ranges
845 }
846
847 pub fn insert_excerpts_after<O>(
848 &mut self,
849 prev_excerpt_id: ExcerptId,
850 buffer: ModelHandle<Buffer>,
851 ranges: impl IntoIterator<Item = ExcerptRange<O>>,
852 cx: &mut ModelContext<Self>,
853 ) -> Vec<ExcerptId>
854 where
855 O: text::ToOffset,
856 {
857 let mut ids = Vec::new();
858 let mut next_excerpt_id = self.next_excerpt_id;
859 self.insert_excerpts_with_ids_after(
860 prev_excerpt_id,
861 buffer,
862 ranges.into_iter().map(|range| {
863 let id = ExcerptId(post_inc(&mut next_excerpt_id));
864 ids.push(id);
865 (id, range)
866 }),
867 cx,
868 );
869 ids
870 }
871
872 pub fn insert_excerpts_with_ids_after<O>(
873 &mut self,
874 prev_excerpt_id: ExcerptId,
875 buffer: ModelHandle<Buffer>,
876 ranges: impl IntoIterator<Item = (ExcerptId, ExcerptRange<O>)>,
877 cx: &mut ModelContext<Self>,
878 ) where
879 O: text::ToOffset,
880 {
881 assert_eq!(self.history.transaction_depth, 0);
882 let mut ranges = ranges.into_iter().peekable();
883 if ranges.peek().is_none() {
884 return Default::default();
885 }
886
887 self.sync(cx);
888
889 let buffer_id = buffer.id();
890 let buffer_snapshot = buffer.read(cx).snapshot();
891
892 let mut buffers = self.buffers.borrow_mut();
893 let buffer_state = buffers.entry(buffer_id).or_insert_with(|| BufferState {
894 last_version: buffer_snapshot.version().clone(),
895 last_parse_count: buffer_snapshot.parse_count(),
896 last_selections_update_count: buffer_snapshot.selections_update_count(),
897 last_diagnostics_update_count: buffer_snapshot.diagnostics_update_count(),
898 last_file_update_count: buffer_snapshot.file_update_count(),
899 last_git_diff_update_count: buffer_snapshot.git_diff_update_count(),
900 excerpts: Default::default(),
901 _subscriptions: [
902 cx.observe(&buffer, |_, _, cx| cx.notify()),
903 cx.subscribe(&buffer, Self::on_buffer_event),
904 ],
905 buffer: buffer.clone(),
906 });
907
908 let mut snapshot = self.snapshot.borrow_mut();
909
910 let mut prev_locator = snapshot.excerpt_locator_for_id(prev_excerpt_id).clone();
911 let mut new_excerpt_ids = mem::take(&mut snapshot.excerpt_ids);
912 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
913 let mut new_excerpts = cursor.slice(&prev_locator, Bias::Right, &());
914 prev_locator = cursor.start().unwrap_or(Locator::min_ref()).clone();
915
916 let edit_start = new_excerpts.summary().text.len;
917 new_excerpts.update_last(
918 |excerpt| {
919 excerpt.has_trailing_newline = true;
920 },
921 &(),
922 );
923
924 let next_locator = if let Some(excerpt) = cursor.item() {
925 excerpt.locator.clone()
926 } else {
927 Locator::max()
928 };
929
930 let mut excerpts = Vec::new();
931 while let Some((id, range)) = ranges.next() {
932 let locator = Locator::between(&prev_locator, &next_locator);
933 if let Err(ix) = buffer_state.excerpts.binary_search(&locator) {
934 buffer_state.excerpts.insert(ix, locator.clone());
935 }
936 let range = ExcerptRange {
937 context: buffer_snapshot.anchor_before(&range.context.start)
938 ..buffer_snapshot.anchor_after(&range.context.end),
939 primary: range.primary.map(|primary| {
940 buffer_snapshot.anchor_before(&primary.start)
941 ..buffer_snapshot.anchor_after(&primary.end)
942 }),
943 };
944 if id.0 >= self.next_excerpt_id {
945 self.next_excerpt_id = id.0 + 1;
946 }
947 excerpts.push((id, range.clone()));
948 let excerpt = Excerpt::new(
949 id,
950 locator.clone(),
951 buffer_id,
952 buffer_snapshot.clone(),
953 range,
954 ranges.peek().is_some() || cursor.item().is_some(),
955 );
956 new_excerpts.push(excerpt, &());
957 prev_locator = locator.clone();
958 new_excerpt_ids.push(ExcerptIdMapping { id, locator }, &());
959 }
960
961 let edit_end = new_excerpts.summary().text.len;
962
963 let suffix = cursor.suffix(&());
964 let changed_trailing_excerpt = suffix.is_empty();
965 new_excerpts.push_tree(suffix, &());
966 drop(cursor);
967 snapshot.excerpts = new_excerpts;
968 snapshot.excerpt_ids = new_excerpt_ids;
969 if changed_trailing_excerpt {
970 snapshot.trailing_excerpt_update_count += 1;
971 }
972
973 self.subscriptions.publish_mut([Edit {
974 old: edit_start..edit_start,
975 new: edit_start..edit_end,
976 }]);
977 cx.emit(Event::Edited);
978 cx.emit(Event::ExcerptsAdded {
979 buffer,
980 predecessor: prev_excerpt_id,
981 excerpts,
982 });
983 cx.notify();
984 }
985
986 pub fn clear(&mut self, cx: &mut ModelContext<Self>) {
987 self.sync(cx);
988 let ids = self.excerpt_ids();
989 self.buffers.borrow_mut().clear();
990 let mut snapshot = self.snapshot.borrow_mut();
991 let prev_len = snapshot.len();
992 snapshot.excerpts = Default::default();
993 snapshot.trailing_excerpt_update_count += 1;
994 snapshot.is_dirty = false;
995 snapshot.has_conflict = false;
996
997 self.subscriptions.publish_mut([Edit {
998 old: 0..prev_len,
999 new: 0..0,
1000 }]);
1001 cx.emit(Event::Edited);
1002 cx.emit(Event::ExcerptsRemoved { ids });
1003 cx.notify();
1004 }
1005
1006 pub fn excerpts_for_buffer(
1007 &self,
1008 buffer: &ModelHandle<Buffer>,
1009 cx: &AppContext,
1010 ) -> Vec<(ExcerptId, ExcerptRange<text::Anchor>)> {
1011 let mut excerpts = Vec::new();
1012 let snapshot = self.read(cx);
1013 let buffers = self.buffers.borrow();
1014 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
1015 for locator in buffers
1016 .get(&buffer.id())
1017 .map(|state| &state.excerpts)
1018 .into_iter()
1019 .flatten()
1020 {
1021 cursor.seek_forward(&Some(locator), Bias::Left, &());
1022 if let Some(excerpt) = cursor.item() {
1023 if excerpt.locator == *locator {
1024 excerpts.push((excerpt.id.clone(), excerpt.range.clone()));
1025 }
1026 }
1027 }
1028
1029 excerpts
1030 }
1031
1032 pub fn excerpt_ids(&self) -> Vec<ExcerptId> {
1033 self.snapshot
1034 .borrow()
1035 .excerpts
1036 .iter()
1037 .map(|entry| entry.id)
1038 .collect()
1039 }
1040
1041 pub fn excerpt_containing(
1042 &self,
1043 position: impl ToOffset,
1044 cx: &AppContext,
1045 ) -> Option<(ExcerptId, ModelHandle<Buffer>, Range<text::Anchor>)> {
1046 let snapshot = self.read(cx);
1047 let position = position.to_offset(&snapshot);
1048
1049 let mut cursor = snapshot.excerpts.cursor::<usize>();
1050 cursor.seek(&position, Bias::Right, &());
1051 cursor.item().map(|excerpt| {
1052 (
1053 excerpt.id.clone(),
1054 self.buffers
1055 .borrow()
1056 .get(&excerpt.buffer_id)
1057 .unwrap()
1058 .buffer
1059 .clone(),
1060 excerpt.range.context.clone(),
1061 )
1062 })
1063 }
1064
1065 // If point is at the end of the buffer, the last excerpt is returned
1066 pub fn point_to_buffer_offset<T: ToOffset>(
1067 &self,
1068 point: T,
1069 cx: &AppContext,
1070 ) -> Option<(ModelHandle<Buffer>, usize)> {
1071 let snapshot = self.read(cx);
1072 let offset = point.to_offset(&snapshot);
1073 let mut cursor = snapshot.excerpts.cursor::<usize>();
1074 cursor.seek(&offset, Bias::Right, &());
1075 if cursor.item().is_none() {
1076 cursor.prev(&());
1077 }
1078
1079 cursor.item().map(|excerpt| {
1080 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1081 let buffer_point = excerpt_start + offset - *cursor.start();
1082 let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1083
1084 (buffer, buffer_point)
1085 })
1086 }
1087
1088 pub fn range_to_buffer_ranges<T: ToOffset>(
1089 &self,
1090 range: Range<T>,
1091 cx: &AppContext,
1092 ) -> Vec<(ModelHandle<Buffer>, Range<usize>)> {
1093 let snapshot = self.read(cx);
1094 let start = range.start.to_offset(&snapshot);
1095 let end = range.end.to_offset(&snapshot);
1096
1097 let mut result = Vec::new();
1098 let mut cursor = snapshot.excerpts.cursor::<usize>();
1099 cursor.seek(&start, Bias::Right, &());
1100 while let Some(excerpt) = cursor.item() {
1101 if *cursor.start() > end {
1102 break;
1103 }
1104
1105 let mut end_before_newline = cursor.end(&());
1106 if excerpt.has_trailing_newline {
1107 end_before_newline -= 1;
1108 }
1109 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1110 let start = excerpt_start + (cmp::max(start, *cursor.start()) - *cursor.start());
1111 let end = excerpt_start + (cmp::min(end, end_before_newline) - *cursor.start());
1112 let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1113 result.push((buffer, start..end));
1114 cursor.next(&());
1115 }
1116
1117 result
1118 }
1119
1120 pub fn remove_excerpts(
1121 &mut self,
1122 excerpt_ids: impl IntoIterator<Item = ExcerptId>,
1123 cx: &mut ModelContext<Self>,
1124 ) {
1125 self.sync(cx);
1126 let ids = excerpt_ids.into_iter().collect::<Vec<_>>();
1127
1128 let mut buffers = self.buffers.borrow_mut();
1129 let mut snapshot = self.snapshot.borrow_mut();
1130 let mut new_excerpts = SumTree::new();
1131 let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1132 let mut edits = Vec::new();
1133 let mut excerpt_ids = ids.iter().copied().peekable();
1134
1135 while let Some(excerpt_id) = excerpt_ids.next() {
1136 // Seek to the next excerpt to remove, preserving any preceding excerpts.
1137 let locator = snapshot.excerpt_locator_for_id(excerpt_id);
1138 new_excerpts.push_tree(cursor.slice(&Some(locator), Bias::Left, &()), &());
1139
1140 if let Some(mut excerpt) = cursor.item() {
1141 if excerpt.id != excerpt_id {
1142 continue;
1143 }
1144 let mut old_start = cursor.start().1;
1145
1146 // Skip over the removed excerpt.
1147 'remove_excerpts: loop {
1148 if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
1149 buffer_state.excerpts.retain(|l| l != &excerpt.locator);
1150 if buffer_state.excerpts.is_empty() {
1151 buffers.remove(&excerpt.buffer_id);
1152 }
1153 }
1154 cursor.next(&());
1155
1156 // Skip over any subsequent excerpts that are also removed.
1157 while let Some(&next_excerpt_id) = excerpt_ids.peek() {
1158 let next_locator = snapshot.excerpt_locator_for_id(next_excerpt_id);
1159 if let Some(next_excerpt) = cursor.item() {
1160 if next_excerpt.locator == *next_locator {
1161 excerpt_ids.next();
1162 excerpt = next_excerpt;
1163 continue 'remove_excerpts;
1164 }
1165 }
1166 break;
1167 }
1168
1169 break;
1170 }
1171
1172 // When removing the last excerpt, remove the trailing newline from
1173 // the previous excerpt.
1174 if cursor.item().is_none() && old_start > 0 {
1175 old_start -= 1;
1176 new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
1177 }
1178
1179 // Push an edit for the removal of this run of excerpts.
1180 let old_end = cursor.start().1;
1181 let new_start = new_excerpts.summary().text.len;
1182 edits.push(Edit {
1183 old: old_start..old_end,
1184 new: new_start..new_start,
1185 });
1186 }
1187 }
1188 let suffix = cursor.suffix(&());
1189 let changed_trailing_excerpt = suffix.is_empty();
1190 new_excerpts.push_tree(suffix, &());
1191 drop(cursor);
1192 snapshot.excerpts = new_excerpts;
1193
1194 if changed_trailing_excerpt {
1195 snapshot.trailing_excerpt_update_count += 1;
1196 }
1197
1198 self.subscriptions.publish_mut(edits);
1199 cx.emit(Event::Edited);
1200 cx.emit(Event::ExcerptsRemoved { ids });
1201 cx.notify();
1202 }
1203
1204 pub fn text_anchor_for_position<T: ToOffset>(
1205 &self,
1206 position: T,
1207 cx: &AppContext,
1208 ) -> Option<(ModelHandle<Buffer>, language::Anchor)> {
1209 let snapshot = self.read(cx);
1210 let anchor = snapshot.anchor_before(position);
1211 let buffer = self
1212 .buffers
1213 .borrow()
1214 .get(&anchor.buffer_id?)?
1215 .buffer
1216 .clone();
1217 Some((buffer, anchor.text_anchor))
1218 }
1219
1220 fn on_buffer_event(
1221 &mut self,
1222 _: ModelHandle<Buffer>,
1223 event: &language::Event,
1224 cx: &mut ModelContext<Self>,
1225 ) {
1226 cx.emit(match event {
1227 language::Event::Edited => Event::Edited,
1228 language::Event::DirtyChanged => Event::DirtyChanged,
1229 language::Event::Saved => Event::Saved,
1230 language::Event::FileHandleChanged => Event::FileHandleChanged,
1231 language::Event::Reloaded => Event::Reloaded,
1232 language::Event::Reparsed => Event::Reparsed,
1233 language::Event::DiagnosticsUpdated => Event::DiagnosticsUpdated,
1234 language::Event::Closed => Event::Closed,
1235
1236 //
1237 language::Event::Operation(_) => return,
1238 });
1239 }
1240
1241 pub fn all_buffers(&self) -> HashSet<ModelHandle<Buffer>> {
1242 self.buffers
1243 .borrow()
1244 .values()
1245 .map(|state| state.buffer.clone())
1246 .collect()
1247 }
1248
1249 pub fn buffer(&self, buffer_id: usize) -> Option<ModelHandle<Buffer>> {
1250 self.buffers
1251 .borrow()
1252 .get(&buffer_id)
1253 .map(|state| state.buffer.clone())
1254 }
1255
1256 pub fn save(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
1257 let mut save_tasks = Vec::new();
1258 for BufferState { buffer, .. } in self.buffers.borrow().values() {
1259 save_tasks.push(buffer.update(cx, |buffer, cx| buffer.save(cx)));
1260 }
1261
1262 cx.spawn(|_, _| async move {
1263 for save in save_tasks {
1264 save.await?;
1265 }
1266 Ok(())
1267 })
1268 }
1269
1270 pub fn is_completion_trigger<T>(&self, position: T, text: &str, cx: &AppContext) -> bool
1271 where
1272 T: ToOffset,
1273 {
1274 let mut chars = text.chars();
1275 let char = if let Some(char) = chars.next() {
1276 char
1277 } else {
1278 return false;
1279 };
1280 if chars.next().is_some() {
1281 return false;
1282 }
1283
1284 if char.is_alphanumeric() || char == '_' {
1285 return true;
1286 }
1287
1288 let snapshot = self.snapshot(cx);
1289 let anchor = snapshot.anchor_before(position);
1290 anchor
1291 .buffer_id
1292 .and_then(|buffer_id| {
1293 let buffer = self.buffers.borrow().get(&buffer_id)?.buffer.clone();
1294 Some(
1295 buffer
1296 .read(cx)
1297 .completion_triggers()
1298 .iter()
1299 .any(|string| string == text),
1300 )
1301 })
1302 .unwrap_or(false)
1303 }
1304
1305 pub fn language_at<'a, T: ToOffset>(
1306 &self,
1307 point: T,
1308 cx: &'a AppContext,
1309 ) -> Option<Arc<Language>> {
1310 self.point_to_buffer_offset(point, cx)
1311 .and_then(|(buffer, offset)| buffer.read(cx).language_at(offset))
1312 }
1313
1314 pub fn files<'a>(&'a self, cx: &'a AppContext) -> SmallVec<[&'a Arc<dyn File>; 2]> {
1315 let buffers = self.buffers.borrow();
1316 buffers
1317 .values()
1318 .filter_map(|buffer| buffer.buffer.read(cx).file())
1319 .collect()
1320 }
1321
1322 pub fn title<'a>(&'a self, cx: &'a AppContext) -> Cow<'a, str> {
1323 if let Some(title) = self.title.as_ref() {
1324 return title.into();
1325 }
1326
1327 if let Some(buffer) = self.as_singleton() {
1328 if let Some(file) = buffer.read(cx).file() {
1329 return file.file_name(cx).to_string_lossy();
1330 }
1331 }
1332
1333 "untitled".into()
1334 }
1335
1336 #[cfg(test)]
1337 pub fn is_parsing(&self, cx: &AppContext) -> bool {
1338 self.as_singleton().unwrap().read(cx).is_parsing()
1339 }
1340
1341 fn sync(&self, cx: &AppContext) {
1342 let mut snapshot = self.snapshot.borrow_mut();
1343 let mut excerpts_to_edit = Vec::new();
1344 let mut reparsed = false;
1345 let mut diagnostics_updated = false;
1346 let mut git_diff_updated = false;
1347 let mut is_dirty = false;
1348 let mut has_conflict = false;
1349 let mut edited = false;
1350 let mut buffers = self.buffers.borrow_mut();
1351 for buffer_state in buffers.values_mut() {
1352 let buffer = buffer_state.buffer.read(cx);
1353 let version = buffer.version();
1354 let parse_count = buffer.parse_count();
1355 let selections_update_count = buffer.selections_update_count();
1356 let diagnostics_update_count = buffer.diagnostics_update_count();
1357 let file_update_count = buffer.file_update_count();
1358 let git_diff_update_count = buffer.git_diff_update_count();
1359
1360 let buffer_edited = version.changed_since(&buffer_state.last_version);
1361 let buffer_reparsed = parse_count > buffer_state.last_parse_count;
1362 let buffer_selections_updated =
1363 selections_update_count > buffer_state.last_selections_update_count;
1364 let buffer_diagnostics_updated =
1365 diagnostics_update_count > buffer_state.last_diagnostics_update_count;
1366 let buffer_file_updated = file_update_count > buffer_state.last_file_update_count;
1367 let buffer_git_diff_updated =
1368 git_diff_update_count > buffer_state.last_git_diff_update_count;
1369 if buffer_edited
1370 || buffer_reparsed
1371 || buffer_selections_updated
1372 || buffer_diagnostics_updated
1373 || buffer_file_updated
1374 || buffer_git_diff_updated
1375 {
1376 buffer_state.last_version = version;
1377 buffer_state.last_parse_count = parse_count;
1378 buffer_state.last_selections_update_count = selections_update_count;
1379 buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1380 buffer_state.last_file_update_count = file_update_count;
1381 buffer_state.last_git_diff_update_count = git_diff_update_count;
1382 excerpts_to_edit.extend(
1383 buffer_state
1384 .excerpts
1385 .iter()
1386 .map(|locator| (locator, buffer_state.buffer.clone(), buffer_edited)),
1387 );
1388 }
1389
1390 edited |= buffer_edited;
1391 reparsed |= buffer_reparsed;
1392 diagnostics_updated |= buffer_diagnostics_updated;
1393 git_diff_updated |= buffer_git_diff_updated;
1394 is_dirty |= buffer.is_dirty();
1395 has_conflict |= buffer.has_conflict();
1396 }
1397 if edited {
1398 snapshot.edit_count += 1;
1399 }
1400 if reparsed {
1401 snapshot.parse_count += 1;
1402 }
1403 if diagnostics_updated {
1404 snapshot.diagnostics_update_count += 1;
1405 }
1406 if git_diff_updated {
1407 snapshot.git_diff_update_count += 1;
1408 }
1409 snapshot.is_dirty = is_dirty;
1410 snapshot.has_conflict = has_conflict;
1411
1412 excerpts_to_edit.sort_unstable_by_key(|(locator, _, _)| *locator);
1413
1414 let mut edits = Vec::new();
1415 let mut new_excerpts = SumTree::new();
1416 let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1417
1418 for (locator, buffer, buffer_edited) in excerpts_to_edit {
1419 new_excerpts.push_tree(cursor.slice(&Some(locator), Bias::Left, &()), &());
1420 let old_excerpt = cursor.item().unwrap();
1421 let buffer_id = buffer.id();
1422 let buffer = buffer.read(cx);
1423
1424 let mut new_excerpt;
1425 if buffer_edited {
1426 edits.extend(
1427 buffer
1428 .edits_since_in_range::<usize>(
1429 old_excerpt.buffer.version(),
1430 old_excerpt.range.context.clone(),
1431 )
1432 .map(|mut edit| {
1433 let excerpt_old_start = cursor.start().1;
1434 let excerpt_new_start = new_excerpts.summary().text.len;
1435 edit.old.start += excerpt_old_start;
1436 edit.old.end += excerpt_old_start;
1437 edit.new.start += excerpt_new_start;
1438 edit.new.end += excerpt_new_start;
1439 edit
1440 }),
1441 );
1442
1443 new_excerpt = Excerpt::new(
1444 old_excerpt.id,
1445 locator.clone(),
1446 buffer_id,
1447 buffer.snapshot(),
1448 old_excerpt.range.clone(),
1449 old_excerpt.has_trailing_newline,
1450 );
1451 } else {
1452 new_excerpt = old_excerpt.clone();
1453 new_excerpt.buffer = buffer.snapshot();
1454 }
1455
1456 new_excerpts.push(new_excerpt, &());
1457 cursor.next(&());
1458 }
1459 new_excerpts.push_tree(cursor.suffix(&()), &());
1460
1461 drop(cursor);
1462 snapshot.excerpts = new_excerpts;
1463
1464 self.subscriptions.publish(edits);
1465 }
1466}
1467
1468#[cfg(any(test, feature = "test-support"))]
1469impl MultiBuffer {
1470 pub fn build_simple(text: &str, cx: &mut gpui::MutableAppContext) -> ModelHandle<Self> {
1471 let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
1472 cx.add_model(|cx| Self::singleton(buffer, cx))
1473 }
1474
1475 pub fn build_random(
1476 rng: &mut impl rand::Rng,
1477 cx: &mut gpui::MutableAppContext,
1478 ) -> ModelHandle<Self> {
1479 cx.add_model(|cx| {
1480 let mut multibuffer = MultiBuffer::new(0);
1481 let mutation_count = rng.gen_range(1..=5);
1482 multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1483 multibuffer
1484 })
1485 }
1486
1487 pub fn randomly_edit(
1488 &mut self,
1489 rng: &mut impl rand::Rng,
1490 edit_count: usize,
1491 cx: &mut ModelContext<Self>,
1492 ) {
1493 use util::RandomCharIter;
1494
1495 let snapshot = self.read(cx);
1496 let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1497 let mut last_end = None;
1498 for _ in 0..edit_count {
1499 if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1500 break;
1501 }
1502
1503 let new_start = last_end.map_or(0, |last_end| last_end + 1);
1504 let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1505 let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1506 last_end = Some(end);
1507
1508 let mut range = start..end;
1509 if rng.gen_bool(0.2) {
1510 mem::swap(&mut range.start, &mut range.end);
1511 }
1512
1513 let new_text_len = rng.gen_range(0..10);
1514 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1515
1516 edits.push((range, new_text.into()));
1517 }
1518 log::info!("mutating multi-buffer with {:?}", edits);
1519 drop(snapshot);
1520
1521 self.edit(edits, None, cx);
1522 }
1523
1524 pub fn randomly_edit_excerpts(
1525 &mut self,
1526 rng: &mut impl rand::Rng,
1527 mutation_count: usize,
1528 cx: &mut ModelContext<Self>,
1529 ) {
1530 use rand::prelude::*;
1531 use std::env;
1532 use util::RandomCharIter;
1533
1534 let max_excerpts = env::var("MAX_EXCERPTS")
1535 .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1536 .unwrap_or(5);
1537
1538 let mut buffers = Vec::new();
1539 for _ in 0..mutation_count {
1540 if rng.gen_bool(0.05) {
1541 log::info!("Clearing multi-buffer");
1542 self.clear(cx);
1543 continue;
1544 }
1545
1546 let excerpt_ids = self.excerpt_ids();
1547 if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1548 let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1549 let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1550 buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
1551 let buffer = buffers.last().unwrap();
1552 log::info!(
1553 "Creating new buffer {} with text: {:?}",
1554 buffer.id(),
1555 buffer.read(cx).text()
1556 );
1557 buffers.last().unwrap().clone()
1558 } else {
1559 self.buffers
1560 .borrow()
1561 .values()
1562 .choose(rng)
1563 .unwrap()
1564 .buffer
1565 .clone()
1566 };
1567
1568 let buffer = buffer_handle.read(cx);
1569 let buffer_text = buffer.text();
1570 let ranges = (0..rng.gen_range(0..5))
1571 .map(|_| {
1572 let end_ix =
1573 buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1574 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1575 ExcerptRange {
1576 context: start_ix..end_ix,
1577 primary: None,
1578 }
1579 })
1580 .collect::<Vec<_>>();
1581 log::info!(
1582 "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
1583 buffer_handle.id(),
1584 ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
1585 ranges
1586 .iter()
1587 .map(|r| &buffer_text[r.context.clone()])
1588 .collect::<Vec<_>>()
1589 );
1590
1591 let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
1592 log::info!("Inserted with ids: {:?}", excerpt_id);
1593 } else {
1594 let remove_count = rng.gen_range(1..=excerpt_ids.len());
1595 let mut excerpts_to_remove = excerpt_ids
1596 .choose_multiple(rng, remove_count)
1597 .cloned()
1598 .collect::<Vec<_>>();
1599 let snapshot = self.snapshot.borrow();
1600 excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &*snapshot));
1601 drop(snapshot);
1602 log::info!("Removing excerpts {:?}", excerpts_to_remove);
1603 self.remove_excerpts(excerpts_to_remove, cx);
1604 }
1605 }
1606 }
1607
1608 pub fn randomly_mutate(
1609 &mut self,
1610 rng: &mut impl rand::Rng,
1611 mutation_count: usize,
1612 cx: &mut ModelContext<Self>,
1613 ) {
1614 use rand::prelude::*;
1615
1616 if rng.gen_bool(0.7) || self.singleton {
1617 let buffer = self
1618 .buffers
1619 .borrow()
1620 .values()
1621 .choose(rng)
1622 .map(|state| state.buffer.clone());
1623
1624 if let Some(buffer) = buffer {
1625 buffer.update(cx, |buffer, cx| {
1626 if rng.gen() {
1627 buffer.randomly_edit(rng, mutation_count, cx);
1628 } else {
1629 buffer.randomly_undo_redo(rng, cx);
1630 }
1631 });
1632 } else {
1633 self.randomly_edit(rng, mutation_count, cx);
1634 }
1635 } else {
1636 self.randomly_edit_excerpts(rng, mutation_count, cx);
1637 }
1638
1639 self.check_invariants(cx);
1640 }
1641
1642 fn check_invariants(&self, cx: &mut ModelContext<Self>) {
1643 let snapshot = self.read(cx);
1644 let excerpts = snapshot.excerpts.items(&());
1645 let excerpt_ids = snapshot.excerpt_ids.items(&());
1646
1647 for (ix, excerpt) in excerpts.iter().enumerate() {
1648 if ix == 0 {
1649 if excerpt.locator <= Locator::min() {
1650 panic!("invalid first excerpt locator {:?}", excerpt.locator);
1651 }
1652 } else {
1653 if excerpt.locator <= excerpts[ix - 1].locator {
1654 panic!("excerpts are out-of-order: {:?}", excerpts);
1655 }
1656 }
1657 }
1658
1659 for (ix, entry) in excerpt_ids.iter().enumerate() {
1660 if ix == 0 {
1661 if entry.id.cmp(&ExcerptId::min(), &*snapshot).is_le() {
1662 panic!("invalid first excerpt id {:?}", entry.id);
1663 }
1664 } else {
1665 if entry.id <= excerpt_ids[ix - 1].id {
1666 panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
1667 }
1668 }
1669 }
1670 }
1671}
1672
1673impl Entity for MultiBuffer {
1674 type Event = Event;
1675}
1676
1677impl MultiBufferSnapshot {
1678 pub fn text(&self) -> String {
1679 self.chunks(0..self.len(), false)
1680 .map(|chunk| chunk.text)
1681 .collect()
1682 }
1683
1684 pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1685 let mut offset = position.to_offset(self);
1686 let mut cursor = self.excerpts.cursor::<usize>();
1687 cursor.seek(&offset, Bias::Left, &());
1688 let mut excerpt_chunks = cursor.item().map(|excerpt| {
1689 let end_before_footer = cursor.start() + excerpt.text_summary.len;
1690 let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1691 let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1692 excerpt.buffer.reversed_chunks_in_range(start..end)
1693 });
1694 iter::from_fn(move || {
1695 if offset == *cursor.start() {
1696 cursor.prev(&());
1697 let excerpt = cursor.item()?;
1698 excerpt_chunks = Some(
1699 excerpt
1700 .buffer
1701 .reversed_chunks_in_range(excerpt.range.context.clone()),
1702 );
1703 }
1704
1705 let excerpt = cursor.item().unwrap();
1706 if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1707 offset -= 1;
1708 Some("\n")
1709 } else {
1710 let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1711 offset -= chunk.len();
1712 Some(chunk)
1713 }
1714 })
1715 .flat_map(|c| c.chars().rev())
1716 }
1717
1718 pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1719 let offset = position.to_offset(self);
1720 self.text_for_range(offset..self.len())
1721 .flat_map(|chunk| chunk.chars())
1722 }
1723
1724 pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
1725 self.chunks(range, false).map(|chunk| chunk.text)
1726 }
1727
1728 pub fn is_line_blank(&self, row: u32) -> bool {
1729 self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1730 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1731 }
1732
1733 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1734 where
1735 T: ToOffset,
1736 {
1737 let position = position.to_offset(self);
1738 position == self.clip_offset(position, Bias::Left)
1739 && self
1740 .bytes_in_range(position..self.len())
1741 .flatten()
1742 .copied()
1743 .take(needle.len())
1744 .eq(needle.bytes())
1745 }
1746
1747 pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1748 let mut start = start.to_offset(self);
1749 let mut end = start;
1750 let mut next_chars = self.chars_at(start).peekable();
1751 let mut prev_chars = self.reversed_chars_at(start).peekable();
1752 let word_kind = cmp::max(
1753 prev_chars.peek().copied().map(char_kind),
1754 next_chars.peek().copied().map(char_kind),
1755 );
1756
1757 for ch in prev_chars {
1758 if Some(char_kind(ch)) == word_kind && ch != '\n' {
1759 start -= ch.len_utf8();
1760 } else {
1761 break;
1762 }
1763 }
1764
1765 for ch in next_chars {
1766 if Some(char_kind(ch)) == word_kind && ch != '\n' {
1767 end += ch.len_utf8();
1768 } else {
1769 break;
1770 }
1771 }
1772
1773 (start..end, word_kind)
1774 }
1775
1776 pub fn as_singleton(&self) -> Option<(&ExcerptId, usize, &BufferSnapshot)> {
1777 if self.singleton {
1778 self.excerpts
1779 .iter()
1780 .next()
1781 .map(|e| (&e.id, e.buffer_id, &e.buffer))
1782 } else {
1783 None
1784 }
1785 }
1786
1787 pub fn len(&self) -> usize {
1788 self.excerpts.summary().text.len
1789 }
1790
1791 pub fn is_empty(&self) -> bool {
1792 self.excerpts.summary().text.len == 0
1793 }
1794
1795 pub fn max_buffer_row(&self) -> u32 {
1796 self.excerpts.summary().max_buffer_row
1797 }
1798
1799 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1800 if let Some((_, _, buffer)) = self.as_singleton() {
1801 return buffer.clip_offset(offset, bias);
1802 }
1803
1804 let mut cursor = self.excerpts.cursor::<usize>();
1805 cursor.seek(&offset, Bias::Right, &());
1806 let overshoot = if let Some(excerpt) = cursor.item() {
1807 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1808 let buffer_offset = excerpt
1809 .buffer
1810 .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1811 buffer_offset.saturating_sub(excerpt_start)
1812 } else {
1813 0
1814 };
1815 cursor.start() + overshoot
1816 }
1817
1818 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1819 if let Some((_, _, buffer)) = self.as_singleton() {
1820 return buffer.clip_point(point, bias);
1821 }
1822
1823 let mut cursor = self.excerpts.cursor::<Point>();
1824 cursor.seek(&point, Bias::Right, &());
1825 let overshoot = if let Some(excerpt) = cursor.item() {
1826 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
1827 let buffer_point = excerpt
1828 .buffer
1829 .clip_point(excerpt_start + (point - cursor.start()), bias);
1830 buffer_point.saturating_sub(excerpt_start)
1831 } else {
1832 Point::zero()
1833 };
1834 *cursor.start() + overshoot
1835 }
1836
1837 pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
1838 if let Some((_, _, buffer)) = self.as_singleton() {
1839 return buffer.clip_offset_utf16(offset, bias);
1840 }
1841
1842 let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
1843 cursor.seek(&offset, Bias::Right, &());
1844 let overshoot = if let Some(excerpt) = cursor.item() {
1845 let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
1846 let buffer_offset = excerpt
1847 .buffer
1848 .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
1849 OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
1850 } else {
1851 OffsetUtf16(0)
1852 };
1853 *cursor.start() + overshoot
1854 }
1855
1856 pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
1857 if let Some((_, _, buffer)) = self.as_singleton() {
1858 return buffer.clip_point_utf16(point, bias);
1859 }
1860
1861 let mut cursor = self.excerpts.cursor::<PointUtf16>();
1862 cursor.seek(&point.0, Bias::Right, &());
1863 let overshoot = if let Some(excerpt) = cursor.item() {
1864 let excerpt_start = excerpt
1865 .buffer
1866 .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
1867 let buffer_point = excerpt
1868 .buffer
1869 .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
1870 buffer_point.saturating_sub(excerpt_start)
1871 } else {
1872 PointUtf16::zero()
1873 };
1874 *cursor.start() + overshoot
1875 }
1876
1877 pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
1878 let range = range.start.to_offset(self)..range.end.to_offset(self);
1879 let mut excerpts = self.excerpts.cursor::<usize>();
1880 excerpts.seek(&range.start, Bias::Right, &());
1881
1882 let mut chunk = &[][..];
1883 let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1884 let mut excerpt_bytes = excerpt
1885 .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1886 chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1887 Some(excerpt_bytes)
1888 } else {
1889 None
1890 };
1891
1892 MultiBufferBytes {
1893 range,
1894 excerpts,
1895 excerpt_bytes,
1896 chunk,
1897 }
1898 }
1899
1900 pub fn buffer_rows(&self, start_row: u32) -> MultiBufferRows {
1901 let mut result = MultiBufferRows {
1902 buffer_row_range: 0..0,
1903 excerpts: self.excerpts.cursor(),
1904 };
1905 result.seek(start_row);
1906 result
1907 }
1908
1909 pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
1910 let range = range.start.to_offset(self)..range.end.to_offset(self);
1911 let mut chunks = MultiBufferChunks {
1912 range: range.clone(),
1913 excerpts: self.excerpts.cursor(),
1914 excerpt_chunks: None,
1915 language_aware,
1916 };
1917 chunks.seek(range.start);
1918 chunks
1919 }
1920
1921 pub fn offset_to_point(&self, offset: usize) -> Point {
1922 if let Some((_, _, buffer)) = self.as_singleton() {
1923 return buffer.offset_to_point(offset);
1924 }
1925
1926 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1927 cursor.seek(&offset, Bias::Right, &());
1928 if let Some(excerpt) = cursor.item() {
1929 let (start_offset, start_point) = cursor.start();
1930 let overshoot = offset - start_offset;
1931 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1932 let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1933 let buffer_point = excerpt
1934 .buffer
1935 .offset_to_point(excerpt_start_offset + overshoot);
1936 *start_point + (buffer_point - excerpt_start_point)
1937 } else {
1938 self.excerpts.summary().text.lines
1939 }
1940 }
1941
1942 pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1943 if let Some((_, _, buffer)) = self.as_singleton() {
1944 return buffer.offset_to_point_utf16(offset);
1945 }
1946
1947 let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
1948 cursor.seek(&offset, Bias::Right, &());
1949 if let Some(excerpt) = cursor.item() {
1950 let (start_offset, start_point) = cursor.start();
1951 let overshoot = offset - start_offset;
1952 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1953 let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
1954 let buffer_point = excerpt
1955 .buffer
1956 .offset_to_point_utf16(excerpt_start_offset + overshoot);
1957 *start_point + (buffer_point - excerpt_start_point)
1958 } else {
1959 self.excerpts.summary().text.lines_utf16()
1960 }
1961 }
1962
1963 pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1964 if let Some((_, _, buffer)) = self.as_singleton() {
1965 return buffer.point_to_point_utf16(point);
1966 }
1967
1968 let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
1969 cursor.seek(&point, Bias::Right, &());
1970 if let Some(excerpt) = cursor.item() {
1971 let (start_offset, start_point) = cursor.start();
1972 let overshoot = point - start_offset;
1973 let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1974 let excerpt_start_point_utf16 =
1975 excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
1976 let buffer_point = excerpt
1977 .buffer
1978 .point_to_point_utf16(excerpt_start_point + overshoot);
1979 *start_point + (buffer_point - excerpt_start_point_utf16)
1980 } else {
1981 self.excerpts.summary().text.lines_utf16()
1982 }
1983 }
1984
1985 pub fn point_to_offset(&self, point: Point) -> usize {
1986 if let Some((_, _, buffer)) = self.as_singleton() {
1987 return buffer.point_to_offset(point);
1988 }
1989
1990 let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1991 cursor.seek(&point, Bias::Right, &());
1992 if let Some(excerpt) = cursor.item() {
1993 let (start_point, start_offset) = cursor.start();
1994 let overshoot = point - start_point;
1995 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1996 let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1997 let buffer_offset = excerpt
1998 .buffer
1999 .point_to_offset(excerpt_start_point + overshoot);
2000 *start_offset + buffer_offset - excerpt_start_offset
2001 } else {
2002 self.excerpts.summary().text.len
2003 }
2004 }
2005
2006 pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2007 if let Some((_, _, buffer)) = self.as_singleton() {
2008 return buffer.offset_utf16_to_offset(offset_utf16);
2009 }
2010
2011 let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2012 cursor.seek(&offset_utf16, Bias::Right, &());
2013 if let Some(excerpt) = cursor.item() {
2014 let (start_offset_utf16, start_offset) = cursor.start();
2015 let overshoot = offset_utf16 - start_offset_utf16;
2016 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2017 let excerpt_start_offset_utf16 =
2018 excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2019 let buffer_offset = excerpt
2020 .buffer
2021 .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2022 *start_offset + (buffer_offset - excerpt_start_offset)
2023 } else {
2024 self.excerpts.summary().text.len
2025 }
2026 }
2027
2028 pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2029 if let Some((_, _, buffer)) = self.as_singleton() {
2030 return buffer.offset_to_offset_utf16(offset);
2031 }
2032
2033 let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2034 cursor.seek(&offset, Bias::Right, &());
2035 if let Some(excerpt) = cursor.item() {
2036 let (start_offset, start_offset_utf16) = cursor.start();
2037 let overshoot = offset - start_offset;
2038 let excerpt_start_offset_utf16 =
2039 excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2040 let excerpt_start_offset = excerpt
2041 .buffer
2042 .offset_utf16_to_offset(excerpt_start_offset_utf16);
2043 let buffer_offset_utf16 = excerpt
2044 .buffer
2045 .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2046 *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2047 } else {
2048 self.excerpts.summary().text.len_utf16
2049 }
2050 }
2051
2052 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2053 if let Some((_, _, buffer)) = self.as_singleton() {
2054 return buffer.point_utf16_to_offset(point);
2055 }
2056
2057 let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2058 cursor.seek(&point, Bias::Right, &());
2059 if let Some(excerpt) = cursor.item() {
2060 let (start_point, start_offset) = cursor.start();
2061 let overshoot = point - start_point;
2062 let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2063 let excerpt_start_point = excerpt
2064 .buffer
2065 .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2066 let buffer_offset = excerpt
2067 .buffer
2068 .point_utf16_to_offset(excerpt_start_point + overshoot);
2069 *start_offset + (buffer_offset - excerpt_start_offset)
2070 } else {
2071 self.excerpts.summary().text.len
2072 }
2073 }
2074
2075 pub fn point_to_buffer_offset<T: ToOffset>(
2076 &self,
2077 point: T,
2078 ) -> Option<(&BufferSnapshot, usize)> {
2079 let offset = point.to_offset(&self);
2080 let mut cursor = self.excerpts.cursor::<usize>();
2081 cursor.seek(&offset, Bias::Right, &());
2082 if cursor.item().is_none() {
2083 cursor.prev(&());
2084 }
2085
2086 cursor.item().map(|excerpt| {
2087 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2088 let buffer_point = excerpt_start + offset - *cursor.start();
2089 (&excerpt.buffer, buffer_point)
2090 })
2091 }
2092
2093 pub fn suggested_indents(
2094 &self,
2095 rows: impl IntoIterator<Item = u32>,
2096 cx: &AppContext,
2097 ) -> BTreeMap<u32, IndentSize> {
2098 let mut result = BTreeMap::new();
2099
2100 let mut rows_for_excerpt = Vec::new();
2101 let mut cursor = self.excerpts.cursor::<Point>();
2102 let mut rows = rows.into_iter().peekable();
2103 let mut prev_row = u32::MAX;
2104 let mut prev_language_indent_size = IndentSize::default();
2105
2106 while let Some(row) = rows.next() {
2107 cursor.seek(&Point::new(row, 0), Bias::Right, &());
2108 let excerpt = match cursor.item() {
2109 Some(excerpt) => excerpt,
2110 _ => continue,
2111 };
2112
2113 // Retrieve the language and indent size once for each disjoint region being indented.
2114 let single_indent_size = if row.saturating_sub(1) == prev_row {
2115 prev_language_indent_size
2116 } else {
2117 excerpt
2118 .buffer
2119 .language_indent_size_at(Point::new(row, 0), cx)
2120 };
2121 prev_language_indent_size = single_indent_size;
2122 prev_row = row;
2123
2124 let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2125 let start_multibuffer_row = cursor.start().row;
2126
2127 rows_for_excerpt.push(row);
2128 while let Some(next_row) = rows.peek().copied() {
2129 if cursor.end(&()).row > next_row {
2130 rows_for_excerpt.push(next_row);
2131 rows.next();
2132 } else {
2133 break;
2134 }
2135 }
2136
2137 let buffer_rows = rows_for_excerpt
2138 .drain(..)
2139 .map(|row| start_buffer_row + row - start_multibuffer_row);
2140 let buffer_indents = excerpt
2141 .buffer
2142 .suggested_indents(buffer_rows, single_indent_size);
2143 let multibuffer_indents = buffer_indents
2144 .into_iter()
2145 .map(|(row, indent)| (start_multibuffer_row + row - start_buffer_row, indent));
2146 result.extend(multibuffer_indents);
2147 }
2148
2149 result
2150 }
2151
2152 pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2153 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2154 let mut size = buffer.indent_size_for_line(range.start.row);
2155 size.len = size
2156 .len
2157 .min(range.end.column)
2158 .saturating_sub(range.start.column);
2159 size
2160 } else {
2161 IndentSize::spaces(0)
2162 }
2163 }
2164
2165 pub fn line_len(&self, row: u32) -> u32 {
2166 if let Some((_, range)) = self.buffer_line_for_row(row) {
2167 range.end.column - range.start.column
2168 } else {
2169 0
2170 }
2171 }
2172
2173 pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
2174 let mut cursor = self.excerpts.cursor::<Point>();
2175 cursor.seek(&Point::new(row, 0), Bias::Right, &());
2176 if let Some(excerpt) = cursor.item() {
2177 let overshoot = row - cursor.start().row;
2178 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2179 let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2180 let buffer_row = excerpt_start.row + overshoot;
2181 let line_start = Point::new(buffer_row, 0);
2182 let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2183 return Some((
2184 &excerpt.buffer,
2185 line_start.max(excerpt_start)..line_end.min(excerpt_end),
2186 ));
2187 }
2188 None
2189 }
2190
2191 pub fn max_point(&self) -> Point {
2192 self.text_summary().lines
2193 }
2194
2195 pub fn text_summary(&self) -> TextSummary {
2196 self.excerpts.summary().text.clone()
2197 }
2198
2199 pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2200 where
2201 D: TextDimension,
2202 O: ToOffset,
2203 {
2204 let mut summary = D::default();
2205 let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2206 let mut cursor = self.excerpts.cursor::<usize>();
2207 cursor.seek(&range.start, Bias::Right, &());
2208 if let Some(excerpt) = cursor.item() {
2209 let mut end_before_newline = cursor.end(&());
2210 if excerpt.has_trailing_newline {
2211 end_before_newline -= 1;
2212 }
2213
2214 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2215 let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2216 let end_in_excerpt =
2217 excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2218 summary.add_assign(
2219 &excerpt
2220 .buffer
2221 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2222 );
2223
2224 if range.end > end_before_newline {
2225 summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2226 }
2227
2228 cursor.next(&());
2229 }
2230
2231 if range.end > *cursor.start() {
2232 summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2233 &range.end,
2234 Bias::Right,
2235 &(),
2236 )));
2237 if let Some(excerpt) = cursor.item() {
2238 range.end = cmp::max(*cursor.start(), range.end);
2239
2240 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2241 let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2242 summary.add_assign(
2243 &excerpt
2244 .buffer
2245 .text_summary_for_range(excerpt_start..end_in_excerpt),
2246 );
2247 }
2248 }
2249
2250 summary
2251 }
2252
2253 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2254 where
2255 D: TextDimension + Ord + Sub<D, Output = D>,
2256 {
2257 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2258 let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2259
2260 cursor.seek(locator, Bias::Left, &());
2261 if cursor.item().is_none() {
2262 cursor.next(&());
2263 }
2264
2265 let mut position = D::from_text_summary(&cursor.start().text);
2266 if let Some(excerpt) = cursor.item() {
2267 if excerpt.id == anchor.excerpt_id {
2268 let excerpt_buffer_start =
2269 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2270 let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2271 let buffer_position = cmp::min(
2272 excerpt_buffer_end,
2273 anchor.text_anchor.summary::<D>(&excerpt.buffer),
2274 );
2275 if buffer_position > excerpt_buffer_start {
2276 position.add_assign(&(buffer_position - excerpt_buffer_start));
2277 }
2278 }
2279 }
2280 position
2281 }
2282
2283 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2284 where
2285 D: TextDimension + Ord + Sub<D, Output = D>,
2286 I: 'a + IntoIterator<Item = &'a Anchor>,
2287 {
2288 if let Some((_, _, buffer)) = self.as_singleton() {
2289 return buffer
2290 .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2291 .collect();
2292 }
2293
2294 let mut anchors = anchors.into_iter().peekable();
2295 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2296 let mut summaries = Vec::new();
2297 while let Some(anchor) = anchors.peek() {
2298 let excerpt_id = anchor.excerpt_id;
2299 let excerpt_anchors = iter::from_fn(|| {
2300 let anchor = anchors.peek()?;
2301 if anchor.excerpt_id == excerpt_id {
2302 Some(&anchors.next().unwrap().text_anchor)
2303 } else {
2304 None
2305 }
2306 });
2307
2308 let locator = self.excerpt_locator_for_id(excerpt_id);
2309 cursor.seek_forward(locator, Bias::Left, &());
2310 if cursor.item().is_none() {
2311 cursor.next(&());
2312 }
2313
2314 let position = D::from_text_summary(&cursor.start().text);
2315 if let Some(excerpt) = cursor.item() {
2316 if excerpt.id == excerpt_id {
2317 let excerpt_buffer_start =
2318 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2319 let excerpt_buffer_end =
2320 excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2321 summaries.extend(
2322 excerpt
2323 .buffer
2324 .summaries_for_anchors::<D, _>(excerpt_anchors)
2325 .map(move |summary| {
2326 let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2327 let mut position = position.clone();
2328 let excerpt_buffer_start = excerpt_buffer_start.clone();
2329 if summary > excerpt_buffer_start {
2330 position.add_assign(&(summary - excerpt_buffer_start));
2331 }
2332 position
2333 }),
2334 );
2335 continue;
2336 }
2337 }
2338
2339 summaries.extend(excerpt_anchors.map(|_| position.clone()));
2340 }
2341
2342 summaries
2343 }
2344
2345 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2346 where
2347 I: 'a + IntoIterator<Item = &'a Anchor>,
2348 {
2349 let mut anchors = anchors.into_iter().enumerate().peekable();
2350 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2351 cursor.next(&());
2352
2353 let mut result = Vec::new();
2354
2355 while let Some((_, anchor)) = anchors.peek() {
2356 let old_excerpt_id = anchor.excerpt_id;
2357
2358 // Find the location where this anchor's excerpt should be.
2359 let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2360 cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2361
2362 if cursor.item().is_none() {
2363 cursor.next(&());
2364 }
2365
2366 let next_excerpt = cursor.item();
2367 let prev_excerpt = cursor.prev_item();
2368
2369 // Process all of the anchors for this excerpt.
2370 while let Some((_, anchor)) = anchors.peek() {
2371 if anchor.excerpt_id != old_excerpt_id {
2372 break;
2373 }
2374 let (anchor_ix, anchor) = anchors.next().unwrap();
2375 let mut anchor = *anchor;
2376
2377 // Leave min and max anchors unchanged if invalid or
2378 // if the old excerpt still exists at this location
2379 let mut kept_position = next_excerpt
2380 .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2381 || old_excerpt_id == ExcerptId::max()
2382 || old_excerpt_id == ExcerptId::min();
2383
2384 // If the old excerpt no longer exists at this location, then attempt to
2385 // find an equivalent position for this anchor in an adjacent excerpt.
2386 if !kept_position {
2387 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2388 if excerpt.contains(&anchor) {
2389 anchor.excerpt_id = excerpt.id.clone();
2390 kept_position = true;
2391 break;
2392 }
2393 }
2394 }
2395
2396 // If there's no adjacent excerpt that contains the anchor's position,
2397 // then report that the anchor has lost its position.
2398 if !kept_position {
2399 anchor = if let Some(excerpt) = next_excerpt {
2400 let mut text_anchor = excerpt
2401 .range
2402 .context
2403 .start
2404 .bias(anchor.text_anchor.bias, &excerpt.buffer);
2405 if text_anchor
2406 .cmp(&excerpt.range.context.end, &excerpt.buffer)
2407 .is_gt()
2408 {
2409 text_anchor = excerpt.range.context.end;
2410 }
2411 Anchor {
2412 buffer_id: Some(excerpt.buffer_id),
2413 excerpt_id: excerpt.id.clone(),
2414 text_anchor,
2415 }
2416 } else if let Some(excerpt) = prev_excerpt {
2417 let mut text_anchor = excerpt
2418 .range
2419 .context
2420 .end
2421 .bias(anchor.text_anchor.bias, &excerpt.buffer);
2422 if text_anchor
2423 .cmp(&excerpt.range.context.start, &excerpt.buffer)
2424 .is_lt()
2425 {
2426 text_anchor = excerpt.range.context.start;
2427 }
2428 Anchor {
2429 buffer_id: Some(excerpt.buffer_id),
2430 excerpt_id: excerpt.id.clone(),
2431 text_anchor,
2432 }
2433 } else if anchor.text_anchor.bias == Bias::Left {
2434 Anchor::min()
2435 } else {
2436 Anchor::max()
2437 };
2438 }
2439
2440 result.push((anchor_ix, anchor, kept_position));
2441 }
2442 }
2443 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2444 result
2445 }
2446
2447 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2448 self.anchor_at(position, Bias::Left)
2449 }
2450
2451 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2452 self.anchor_at(position, Bias::Right)
2453 }
2454
2455 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2456 let offset = position.to_offset(self);
2457 if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2458 return Anchor {
2459 buffer_id: Some(buffer_id),
2460 excerpt_id: excerpt_id.clone(),
2461 text_anchor: buffer.anchor_at(offset, bias),
2462 };
2463 }
2464
2465 let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2466 cursor.seek(&offset, Bias::Right, &());
2467 if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2468 cursor.prev(&());
2469 }
2470 if let Some(excerpt) = cursor.item() {
2471 let mut overshoot = offset.saturating_sub(cursor.start().0);
2472 if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2473 overshoot -= 1;
2474 bias = Bias::Right;
2475 }
2476
2477 let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2478 let text_anchor =
2479 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2480 Anchor {
2481 buffer_id: Some(excerpt.buffer_id),
2482 excerpt_id: excerpt.id.clone(),
2483 text_anchor,
2484 }
2485 } else if offset == 0 && bias == Bias::Left {
2486 Anchor::min()
2487 } else {
2488 Anchor::max()
2489 }
2490 }
2491
2492 pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
2493 let locator = self.excerpt_locator_for_id(excerpt_id);
2494 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2495 cursor.seek(locator, Bias::Left, &());
2496 if let Some(excerpt) = cursor.item() {
2497 if excerpt.id == excerpt_id {
2498 let text_anchor = excerpt.clip_anchor(text_anchor);
2499 drop(cursor);
2500 return Anchor {
2501 buffer_id: Some(excerpt.buffer_id),
2502 excerpt_id,
2503 text_anchor,
2504 };
2505 }
2506 }
2507 panic!("excerpt not found");
2508 }
2509
2510 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2511 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2512 true
2513 } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
2514 excerpt.buffer.can_resolve(&anchor.text_anchor)
2515 } else {
2516 false
2517 }
2518 }
2519
2520 pub fn excerpts(
2521 &self,
2522 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
2523 self.excerpts
2524 .iter()
2525 .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
2526 }
2527
2528 pub fn excerpt_boundaries_in_range<R, T>(
2529 &self,
2530 range: R,
2531 ) -> impl Iterator<Item = ExcerptBoundary> + '_
2532 where
2533 R: RangeBounds<T>,
2534 T: ToOffset,
2535 {
2536 let start_offset;
2537 let start = match range.start_bound() {
2538 Bound::Included(start) => {
2539 start_offset = start.to_offset(self);
2540 Bound::Included(start_offset)
2541 }
2542 Bound::Excluded(start) => {
2543 start_offset = start.to_offset(self);
2544 Bound::Excluded(start_offset)
2545 }
2546 Bound::Unbounded => {
2547 start_offset = 0;
2548 Bound::Unbounded
2549 }
2550 };
2551 let end = match range.end_bound() {
2552 Bound::Included(end) => Bound::Included(end.to_offset(self)),
2553 Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2554 Bound::Unbounded => Bound::Unbounded,
2555 };
2556 let bounds = (start, end);
2557
2558 let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2559 cursor.seek(&start_offset, Bias::Right, &());
2560 if cursor.item().is_none() {
2561 cursor.prev(&());
2562 }
2563 if !bounds.contains(&cursor.start().0) {
2564 cursor.next(&());
2565 }
2566
2567 let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2568 std::iter::from_fn(move || {
2569 if self.singleton {
2570 None
2571 } else if bounds.contains(&cursor.start().0) {
2572 let excerpt = cursor.item()?;
2573 let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2574 let boundary = ExcerptBoundary {
2575 id: excerpt.id.clone(),
2576 row: cursor.start().1.row,
2577 buffer: excerpt.buffer.clone(),
2578 range: excerpt.range.clone(),
2579 starts_new_buffer,
2580 };
2581
2582 prev_buffer_id = Some(excerpt.buffer_id);
2583 cursor.next(&());
2584 Some(boundary)
2585 } else {
2586 None
2587 }
2588 })
2589 }
2590
2591 pub fn edit_count(&self) -> usize {
2592 self.edit_count
2593 }
2594
2595 pub fn parse_count(&self) -> usize {
2596 self.parse_count
2597 }
2598
2599 pub fn enclosing_bracket_ranges<T: ToOffset>(
2600 &self,
2601 range: Range<T>,
2602 ) -> Option<(Range<usize>, Range<usize>)> {
2603 let range = range.start.to_offset(self)..range.end.to_offset(self);
2604
2605 let mut cursor = self.excerpts.cursor::<usize>();
2606 cursor.seek(&range.start, Bias::Right, &());
2607 let start_excerpt = cursor.item();
2608
2609 cursor.seek(&range.end, Bias::Right, &());
2610 let end_excerpt = cursor.item();
2611
2612 start_excerpt
2613 .zip(end_excerpt)
2614 .and_then(|(start_excerpt, end_excerpt)| {
2615 if start_excerpt.id != end_excerpt.id {
2616 return None;
2617 }
2618
2619 let excerpt_buffer_start = start_excerpt
2620 .range
2621 .context
2622 .start
2623 .to_offset(&start_excerpt.buffer);
2624 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.len;
2625
2626 let start_in_buffer =
2627 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2628 let end_in_buffer =
2629 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2630 let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
2631 .buffer
2632 .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
2633
2634 if start_bracket_range.start >= excerpt_buffer_start
2635 && end_bracket_range.end <= excerpt_buffer_end
2636 {
2637 start_bracket_range.start =
2638 cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
2639 start_bracket_range.end =
2640 cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
2641 end_bracket_range.start =
2642 cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
2643 end_bracket_range.end =
2644 cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
2645 Some((start_bracket_range, end_bracket_range))
2646 } else {
2647 None
2648 }
2649 })
2650 }
2651
2652 pub fn diagnostics_update_count(&self) -> usize {
2653 self.diagnostics_update_count
2654 }
2655
2656 pub fn git_diff_update_count(&self) -> usize {
2657 self.git_diff_update_count
2658 }
2659
2660 pub fn trailing_excerpt_update_count(&self) -> usize {
2661 self.trailing_excerpt_update_count
2662 }
2663
2664 pub fn language_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<Language>> {
2665 self.point_to_buffer_offset(point)
2666 .and_then(|(buffer, offset)| buffer.language_at(offset))
2667 }
2668
2669 pub fn is_dirty(&self) -> bool {
2670 self.is_dirty
2671 }
2672
2673 pub fn has_conflict(&self) -> bool {
2674 self.has_conflict
2675 }
2676
2677 pub fn diagnostic_group<'a, O>(
2678 &'a self,
2679 group_id: usize,
2680 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2681 where
2682 O: text::FromAnchor + 'a,
2683 {
2684 self.as_singleton()
2685 .into_iter()
2686 .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2687 }
2688
2689 pub fn diagnostics_in_range<'a, T, O>(
2690 &'a self,
2691 range: Range<T>,
2692 reversed: bool,
2693 ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2694 where
2695 T: 'a + ToOffset,
2696 O: 'a + text::FromAnchor,
2697 {
2698 self.as_singleton()
2699 .into_iter()
2700 .flat_map(move |(_, _, buffer)| {
2701 buffer.diagnostics_in_range(
2702 range.start.to_offset(self)..range.end.to_offset(self),
2703 reversed,
2704 )
2705 })
2706 }
2707
2708 pub fn git_diff_hunks_in_range<'a>(
2709 &'a self,
2710 row_range: Range<u32>,
2711 reversed: bool,
2712 ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2713 let mut cursor = self.excerpts.cursor::<Point>();
2714
2715 if reversed {
2716 cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
2717 if cursor.item().is_none() {
2718 cursor.prev(&());
2719 }
2720 } else {
2721 cursor.seek(&Point::new(row_range.start, 0), Bias::Right, &());
2722 }
2723
2724 std::iter::from_fn(move || {
2725 let excerpt = cursor.item()?;
2726 let multibuffer_start = *cursor.start();
2727 let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2728 if multibuffer_start.row >= row_range.end {
2729 return None;
2730 }
2731
2732 let mut buffer_start = excerpt.range.context.start;
2733 let mut buffer_end = excerpt.range.context.end;
2734 let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
2735 let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
2736
2737 if row_range.start > multibuffer_start.row {
2738 let buffer_start_point =
2739 excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
2740 buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
2741 }
2742
2743 if row_range.end < multibuffer_end.row {
2744 let buffer_end_point =
2745 excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
2746 buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
2747 }
2748
2749 let buffer_hunks = excerpt
2750 .buffer
2751 .git_diff_hunks_intersecting_range(buffer_start..buffer_end, reversed)
2752 .filter_map(move |hunk| {
2753 let start = multibuffer_start.row
2754 + hunk
2755 .buffer_range
2756 .start
2757 .saturating_sub(excerpt_start_point.row);
2758 let end = multibuffer_start.row
2759 + hunk
2760 .buffer_range
2761 .end
2762 .min(excerpt_end_point.row + 1)
2763 .saturating_sub(excerpt_start_point.row);
2764
2765 Some(DiffHunk {
2766 buffer_range: start..end,
2767 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
2768 })
2769 });
2770
2771 if reversed {
2772 cursor.prev(&());
2773 } else {
2774 cursor.next(&());
2775 }
2776
2777 Some(buffer_hunks)
2778 })
2779 .flatten()
2780 }
2781
2782 pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2783 let range = range.start.to_offset(self)..range.end.to_offset(self);
2784
2785 let mut cursor = self.excerpts.cursor::<usize>();
2786 cursor.seek(&range.start, Bias::Right, &());
2787 let start_excerpt = cursor.item();
2788
2789 cursor.seek(&range.end, Bias::Right, &());
2790 let end_excerpt = cursor.item();
2791
2792 start_excerpt
2793 .zip(end_excerpt)
2794 .and_then(|(start_excerpt, end_excerpt)| {
2795 if start_excerpt.id != end_excerpt.id {
2796 return None;
2797 }
2798
2799 let excerpt_buffer_start = start_excerpt
2800 .range
2801 .context
2802 .start
2803 .to_offset(&start_excerpt.buffer);
2804 let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.len;
2805
2806 let start_in_buffer =
2807 excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2808 let end_in_buffer =
2809 excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2810 let mut ancestor_buffer_range = start_excerpt
2811 .buffer
2812 .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2813 ancestor_buffer_range.start =
2814 cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2815 ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2816
2817 let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
2818 let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
2819 Some(start..end)
2820 })
2821 }
2822
2823 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2824 let (excerpt_id, _, buffer) = self.as_singleton()?;
2825 let outline = buffer.outline(theme)?;
2826 Some(Outline::new(
2827 outline
2828 .items
2829 .into_iter()
2830 .map(|item| OutlineItem {
2831 depth: item.depth,
2832 range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2833 ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2834 text: item.text,
2835 highlight_ranges: item.highlight_ranges,
2836 name_ranges: item.name_ranges,
2837 })
2838 .collect(),
2839 ))
2840 }
2841
2842 pub fn symbols_containing<T: ToOffset>(
2843 &self,
2844 offset: T,
2845 theme: Option<&SyntaxTheme>,
2846 ) -> Option<(usize, Vec<OutlineItem<Anchor>>)> {
2847 let anchor = self.anchor_before(offset);
2848 let excerpt_id = anchor.excerpt_id();
2849 let excerpt = self.excerpt(excerpt_id)?;
2850 Some((
2851 excerpt.buffer_id,
2852 excerpt
2853 .buffer
2854 .symbols_containing(anchor.text_anchor, theme)
2855 .into_iter()
2856 .flatten()
2857 .map(|item| OutlineItem {
2858 depth: item.depth,
2859 range: self.anchor_in_excerpt(excerpt_id, item.range.start)
2860 ..self.anchor_in_excerpt(excerpt_id, item.range.end),
2861 text: item.text,
2862 highlight_ranges: item.highlight_ranges,
2863 name_ranges: item.name_ranges,
2864 })
2865 .collect(),
2866 ))
2867 }
2868
2869 fn excerpt_locator_for_id<'a>(&'a self, id: ExcerptId) -> &'a Locator {
2870 if id == ExcerptId::min() {
2871 Locator::min_ref()
2872 } else if id == ExcerptId::max() {
2873 Locator::max_ref()
2874 } else {
2875 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
2876 cursor.seek(&id, Bias::Left, &());
2877 if let Some(entry) = cursor.item() {
2878 if entry.id == id {
2879 return &entry.locator;
2880 }
2881 }
2882 panic!("invalid excerpt id {:?}", id)
2883 }
2884 }
2885
2886 pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<usize> {
2887 Some(self.excerpt(excerpt_id)?.buffer_id)
2888 }
2889
2890 fn excerpt<'a>(&'a self, excerpt_id: ExcerptId) -> Option<&'a Excerpt> {
2891 let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2892 let locator = self.excerpt_locator_for_id(excerpt_id);
2893 cursor.seek(&Some(locator), Bias::Left, &());
2894 if let Some(excerpt) = cursor.item() {
2895 if excerpt.id == excerpt_id {
2896 return Some(excerpt);
2897 }
2898 }
2899 None
2900 }
2901
2902 pub fn remote_selections_in_range<'a>(
2903 &'a self,
2904 range: &'a Range<Anchor>,
2905 ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
2906 let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2907 let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
2908 let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
2909 cursor.seek(start_locator, Bias::Left, &());
2910 cursor
2911 .take_while(move |excerpt| excerpt.locator <= *end_locator)
2912 .flat_map(move |excerpt| {
2913 let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
2914 if excerpt.id == range.start.excerpt_id {
2915 query_range.start = range.start.text_anchor;
2916 }
2917 if excerpt.id == range.end.excerpt_id {
2918 query_range.end = range.end.text_anchor;
2919 }
2920
2921 excerpt
2922 .buffer
2923 .remote_selections_in_range(query_range)
2924 .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
2925 selections.map(move |selection| {
2926 let mut start = Anchor {
2927 buffer_id: Some(excerpt.buffer_id),
2928 excerpt_id: excerpt.id.clone(),
2929 text_anchor: selection.start,
2930 };
2931 let mut end = Anchor {
2932 buffer_id: Some(excerpt.buffer_id),
2933 excerpt_id: excerpt.id.clone(),
2934 text_anchor: selection.end,
2935 };
2936 if range.start.cmp(&start, self).is_gt() {
2937 start = range.start.clone();
2938 }
2939 if range.end.cmp(&end, self).is_lt() {
2940 end = range.end.clone();
2941 }
2942
2943 (
2944 replica_id,
2945 line_mode,
2946 cursor_shape,
2947 Selection {
2948 id: selection.id,
2949 start,
2950 end,
2951 reversed: selection.reversed,
2952 goal: selection.goal,
2953 },
2954 )
2955 })
2956 })
2957 })
2958 }
2959}
2960
2961#[cfg(any(test, feature = "test-support"))]
2962impl MultiBufferSnapshot {
2963 pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
2964 let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
2965 let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
2966 start..end
2967 }
2968}
2969
2970impl History {
2971 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2972 self.transaction_depth += 1;
2973 if self.transaction_depth == 1 {
2974 let id = self.next_transaction_id.tick();
2975 self.undo_stack.push(Transaction {
2976 id,
2977 buffer_transactions: Default::default(),
2978 first_edit_at: now,
2979 last_edit_at: now,
2980 suppress_grouping: false,
2981 });
2982 Some(id)
2983 } else {
2984 None
2985 }
2986 }
2987
2988 fn end_transaction(
2989 &mut self,
2990 now: Instant,
2991 buffer_transactions: HashMap<usize, TransactionId>,
2992 ) -> bool {
2993 assert_ne!(self.transaction_depth, 0);
2994 self.transaction_depth -= 1;
2995 if self.transaction_depth == 0 {
2996 if buffer_transactions.is_empty() {
2997 self.undo_stack.pop();
2998 false
2999 } else {
3000 self.redo_stack.clear();
3001 let transaction = self.undo_stack.last_mut().unwrap();
3002 transaction.last_edit_at = now;
3003 for (buffer_id, transaction_id) in buffer_transactions {
3004 transaction
3005 .buffer_transactions
3006 .entry(buffer_id)
3007 .or_insert(transaction_id);
3008 }
3009 true
3010 }
3011 } else {
3012 false
3013 }
3014 }
3015
3016 fn push_transaction<'a, T>(&mut self, buffer_transactions: T, now: Instant)
3017 where
3018 T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
3019 {
3020 assert_eq!(self.transaction_depth, 0);
3021 let transaction = Transaction {
3022 id: self.next_transaction_id.tick(),
3023 buffer_transactions: buffer_transactions
3024 .into_iter()
3025 .map(|(buffer, transaction)| (buffer.id(), transaction.id))
3026 .collect(),
3027 first_edit_at: now,
3028 last_edit_at: now,
3029 suppress_grouping: false,
3030 };
3031 if !transaction.buffer_transactions.is_empty() {
3032 self.undo_stack.push(transaction);
3033 self.redo_stack.clear();
3034 }
3035 }
3036
3037 fn finalize_last_transaction(&mut self) {
3038 if let Some(transaction) = self.undo_stack.last_mut() {
3039 transaction.suppress_grouping = true;
3040 }
3041 }
3042
3043 fn pop_undo(&mut self) -> Option<&mut Transaction> {
3044 assert_eq!(self.transaction_depth, 0);
3045 if let Some(transaction) = self.undo_stack.pop() {
3046 self.redo_stack.push(transaction);
3047 self.redo_stack.last_mut()
3048 } else {
3049 None
3050 }
3051 }
3052
3053 fn pop_redo(&mut self) -> Option<&mut Transaction> {
3054 assert_eq!(self.transaction_depth, 0);
3055 if let Some(transaction) = self.redo_stack.pop() {
3056 self.undo_stack.push(transaction);
3057 self.undo_stack.last_mut()
3058 } else {
3059 None
3060 }
3061 }
3062
3063 fn group(&mut self) -> Option<TransactionId> {
3064 let mut count = 0;
3065 let mut transactions = self.undo_stack.iter();
3066 if let Some(mut transaction) = transactions.next_back() {
3067 while let Some(prev_transaction) = transactions.next_back() {
3068 if !prev_transaction.suppress_grouping
3069 && transaction.first_edit_at - prev_transaction.last_edit_at
3070 <= self.group_interval
3071 {
3072 transaction = prev_transaction;
3073 count += 1;
3074 } else {
3075 break;
3076 }
3077 }
3078 }
3079 self.group_trailing(count)
3080 }
3081
3082 fn group_until(&mut self, transaction_id: TransactionId) {
3083 let mut count = 0;
3084 for transaction in self.undo_stack.iter().rev() {
3085 if transaction.id == transaction_id {
3086 self.group_trailing(count);
3087 break;
3088 } else if transaction.suppress_grouping {
3089 break;
3090 } else {
3091 count += 1;
3092 }
3093 }
3094 }
3095
3096 fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3097 let new_len = self.undo_stack.len() - n;
3098 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3099 if let Some(last_transaction) = transactions_to_keep.last_mut() {
3100 if let Some(transaction) = transactions_to_merge.last() {
3101 last_transaction.last_edit_at = transaction.last_edit_at;
3102 }
3103 for to_merge in transactions_to_merge {
3104 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3105 last_transaction
3106 .buffer_transactions
3107 .entry(*buffer_id)
3108 .or_insert(*transaction_id);
3109 }
3110 }
3111 }
3112
3113 self.undo_stack.truncate(new_len);
3114 self.undo_stack.last().map(|t| t.id)
3115 }
3116}
3117
3118impl Excerpt {
3119 fn new(
3120 id: ExcerptId,
3121 locator: Locator,
3122 buffer_id: usize,
3123 buffer: BufferSnapshot,
3124 range: ExcerptRange<text::Anchor>,
3125 has_trailing_newline: bool,
3126 ) -> Self {
3127 Excerpt {
3128 id,
3129 locator,
3130 max_buffer_row: range.context.end.to_point(&buffer).row,
3131 text_summary: buffer
3132 .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3133 buffer_id,
3134 buffer,
3135 range,
3136 has_trailing_newline,
3137 }
3138 }
3139
3140 fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3141 let content_start = self.range.context.start.to_offset(&self.buffer);
3142 let chunks_start = content_start + range.start;
3143 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3144
3145 let footer_height = if self.has_trailing_newline
3146 && range.start <= self.text_summary.len
3147 && range.end > self.text_summary.len
3148 {
3149 1
3150 } else {
3151 0
3152 };
3153
3154 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3155
3156 ExcerptChunks {
3157 content_chunks,
3158 footer_height,
3159 }
3160 }
3161
3162 fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3163 let content_start = self.range.context.start.to_offset(&self.buffer);
3164 let bytes_start = content_start + range.start;
3165 let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3166 let footer_height = if self.has_trailing_newline
3167 && range.start <= self.text_summary.len
3168 && range.end > self.text_summary.len
3169 {
3170 1
3171 } else {
3172 0
3173 };
3174 let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3175
3176 ExcerptBytes {
3177 content_bytes,
3178 footer_height,
3179 }
3180 }
3181
3182 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3183 if text_anchor
3184 .cmp(&self.range.context.start, &self.buffer)
3185 .is_lt()
3186 {
3187 self.range.context.start
3188 } else if text_anchor
3189 .cmp(&self.range.context.end, &self.buffer)
3190 .is_gt()
3191 {
3192 self.range.context.end
3193 } else {
3194 text_anchor
3195 }
3196 }
3197
3198 fn contains(&self, anchor: &Anchor) -> bool {
3199 Some(self.buffer_id) == anchor.buffer_id
3200 && self
3201 .range
3202 .context
3203 .start
3204 .cmp(&anchor.text_anchor, &self.buffer)
3205 .is_le()
3206 && self
3207 .range
3208 .context
3209 .end
3210 .cmp(&anchor.text_anchor, &self.buffer)
3211 .is_ge()
3212 }
3213}
3214
3215impl ExcerptId {
3216 pub fn min() -> Self {
3217 Self(0)
3218 }
3219
3220 pub fn max() -> Self {
3221 Self(usize::MAX)
3222 }
3223
3224 pub fn to_proto(&self) -> u64 {
3225 self.0 as _
3226 }
3227
3228 pub fn from_proto(proto: u64) -> Self {
3229 Self(proto as _)
3230 }
3231
3232 pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3233 let a = snapshot.excerpt_locator_for_id(*self);
3234 let b = snapshot.excerpt_locator_for_id(*other);
3235 a.cmp(&b).then_with(|| self.0.cmp(&other.0))
3236 }
3237}
3238
3239impl Into<usize> for ExcerptId {
3240 fn into(self) -> usize {
3241 self.0
3242 }
3243}
3244
3245impl fmt::Debug for Excerpt {
3246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3247 f.debug_struct("Excerpt")
3248 .field("id", &self.id)
3249 .field("locator", &self.locator)
3250 .field("buffer_id", &self.buffer_id)
3251 .field("range", &self.range)
3252 .field("text_summary", &self.text_summary)
3253 .field("has_trailing_newline", &self.has_trailing_newline)
3254 .finish()
3255 }
3256}
3257
3258impl sum_tree::Item for Excerpt {
3259 type Summary = ExcerptSummary;
3260
3261 fn summary(&self) -> Self::Summary {
3262 let mut text = self.text_summary.clone();
3263 if self.has_trailing_newline {
3264 text += TextSummary::from("\n");
3265 }
3266 ExcerptSummary {
3267 excerpt_id: self.id,
3268 excerpt_locator: self.locator.clone(),
3269 max_buffer_row: self.max_buffer_row,
3270 text,
3271 }
3272 }
3273}
3274
3275impl sum_tree::Item for ExcerptIdMapping {
3276 type Summary = ExcerptId;
3277
3278 fn summary(&self) -> Self::Summary {
3279 self.id
3280 }
3281}
3282
3283impl sum_tree::KeyedItem for ExcerptIdMapping {
3284 type Key = ExcerptId;
3285
3286 fn key(&self) -> Self::Key {
3287 self.id
3288 }
3289}
3290
3291impl sum_tree::Summary for ExcerptId {
3292 type Context = ();
3293
3294 fn add_summary(&mut self, other: &Self, _: &()) {
3295 *self = *other;
3296 }
3297}
3298
3299impl sum_tree::Summary for ExcerptSummary {
3300 type Context = ();
3301
3302 fn add_summary(&mut self, summary: &Self, _: &()) {
3303 debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3304 self.excerpt_locator = summary.excerpt_locator.clone();
3305 self.text.add_summary(&summary.text, &());
3306 self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3307 }
3308}
3309
3310impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3311 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3312 *self += &summary.text;
3313 }
3314}
3315
3316impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3317 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3318 *self += summary.text.len;
3319 }
3320}
3321
3322impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3323 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3324 Ord::cmp(self, &cursor_location.text.len)
3325 }
3326}
3327
3328impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3329 fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3330 Ord::cmp(&Some(self), cursor_location)
3331 }
3332}
3333
3334impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3335 fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3336 Ord::cmp(self, &cursor_location.excerpt_locator)
3337 }
3338}
3339
3340impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3341 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3342 *self += summary.text.len_utf16;
3343 }
3344}
3345
3346impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3347 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3348 *self += summary.text.lines;
3349 }
3350}
3351
3352impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3353 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3354 *self += summary.text.lines_utf16()
3355 }
3356}
3357
3358impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3359 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3360 *self = Some(&summary.excerpt_locator);
3361 }
3362}
3363
3364impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3365 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3366 *self = Some(summary.excerpt_id);
3367 }
3368}
3369
3370impl<'a> MultiBufferRows<'a> {
3371 pub fn seek(&mut self, row: u32) {
3372 self.buffer_row_range = 0..0;
3373
3374 self.excerpts
3375 .seek_forward(&Point::new(row, 0), Bias::Right, &());
3376 if self.excerpts.item().is_none() {
3377 self.excerpts.prev(&());
3378
3379 if self.excerpts.item().is_none() && row == 0 {
3380 self.buffer_row_range = 0..1;
3381 return;
3382 }
3383 }
3384
3385 if let Some(excerpt) = self.excerpts.item() {
3386 let overshoot = row - self.excerpts.start().row;
3387 let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3388 self.buffer_row_range.start = excerpt_start + overshoot;
3389 self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3390 }
3391 }
3392}
3393
3394impl<'a> Iterator for MultiBufferRows<'a> {
3395 type Item = Option<u32>;
3396
3397 fn next(&mut self) -> Option<Self::Item> {
3398 loop {
3399 if !self.buffer_row_range.is_empty() {
3400 let row = Some(self.buffer_row_range.start);
3401 self.buffer_row_range.start += 1;
3402 return Some(row);
3403 }
3404 self.excerpts.item()?;
3405 self.excerpts.next(&());
3406 let excerpt = self.excerpts.item()?;
3407 self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3408 self.buffer_row_range.end =
3409 self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3410 }
3411 }
3412}
3413
3414impl<'a> MultiBufferChunks<'a> {
3415 pub fn offset(&self) -> usize {
3416 self.range.start
3417 }
3418
3419 pub fn seek(&mut self, offset: usize) {
3420 self.range.start = offset;
3421 self.excerpts.seek(&offset, Bias::Right, &());
3422 if let Some(excerpt) = self.excerpts.item() {
3423 self.excerpt_chunks = Some(excerpt.chunks_in_range(
3424 self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3425 self.language_aware,
3426 ));
3427 } else {
3428 self.excerpt_chunks = None;
3429 }
3430 }
3431}
3432
3433impl<'a> Iterator for MultiBufferChunks<'a> {
3434 type Item = Chunk<'a>;
3435
3436 fn next(&mut self) -> Option<Self::Item> {
3437 if self.range.is_empty() {
3438 None
3439 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3440 self.range.start += chunk.text.len();
3441 Some(chunk)
3442 } else {
3443 self.excerpts.next(&());
3444 let excerpt = self.excerpts.item()?;
3445 self.excerpt_chunks = Some(excerpt.chunks_in_range(
3446 0..self.range.end - self.excerpts.start(),
3447 self.language_aware,
3448 ));
3449 self.next()
3450 }
3451 }
3452}
3453
3454impl<'a> MultiBufferBytes<'a> {
3455 fn consume(&mut self, len: usize) {
3456 self.range.start += len;
3457 self.chunk = &self.chunk[len..];
3458
3459 if !self.range.is_empty() && self.chunk.is_empty() {
3460 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3461 self.chunk = chunk;
3462 } else {
3463 self.excerpts.next(&());
3464 if let Some(excerpt) = self.excerpts.item() {
3465 let mut excerpt_bytes =
3466 excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3467 self.chunk = excerpt_bytes.next().unwrap();
3468 self.excerpt_bytes = Some(excerpt_bytes);
3469 }
3470 }
3471 }
3472 }
3473}
3474
3475impl<'a> Iterator for MultiBufferBytes<'a> {
3476 type Item = &'a [u8];
3477
3478 fn next(&mut self) -> Option<Self::Item> {
3479 let chunk = self.chunk;
3480 if chunk.is_empty() {
3481 None
3482 } else {
3483 self.consume(chunk.len());
3484 Some(chunk)
3485 }
3486 }
3487}
3488
3489impl<'a> io::Read for MultiBufferBytes<'a> {
3490 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3491 let len = cmp::min(buf.len(), self.chunk.len());
3492 buf[..len].copy_from_slice(&self.chunk[..len]);
3493 if len > 0 {
3494 self.consume(len);
3495 }
3496 Ok(len)
3497 }
3498}
3499
3500impl<'a> Iterator for ExcerptBytes<'a> {
3501 type Item = &'a [u8];
3502
3503 fn next(&mut self) -> Option<Self::Item> {
3504 if let Some(chunk) = self.content_bytes.next() {
3505 if !chunk.is_empty() {
3506 return Some(chunk);
3507 }
3508 }
3509
3510 if self.footer_height > 0 {
3511 let result = &NEWLINES[..self.footer_height];
3512 self.footer_height = 0;
3513 return Some(result);
3514 }
3515
3516 None
3517 }
3518}
3519
3520impl<'a> Iterator for ExcerptChunks<'a> {
3521 type Item = Chunk<'a>;
3522
3523 fn next(&mut self) -> Option<Self::Item> {
3524 if let Some(chunk) = self.content_chunks.next() {
3525 return Some(chunk);
3526 }
3527
3528 if self.footer_height > 0 {
3529 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3530 self.footer_height = 0;
3531 return Some(Chunk {
3532 text,
3533 ..Default::default()
3534 });
3535 }
3536
3537 None
3538 }
3539}
3540
3541impl ToOffset for Point {
3542 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3543 snapshot.point_to_offset(*self)
3544 }
3545}
3546
3547impl ToOffset for usize {
3548 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3549 assert!(*self <= snapshot.len(), "offset is out of range");
3550 *self
3551 }
3552}
3553
3554impl ToOffset for OffsetUtf16 {
3555 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3556 snapshot.offset_utf16_to_offset(*self)
3557 }
3558}
3559
3560impl ToOffset for PointUtf16 {
3561 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3562 snapshot.point_utf16_to_offset(*self)
3563 }
3564}
3565
3566impl ToOffsetUtf16 for OffsetUtf16 {
3567 fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3568 *self
3569 }
3570}
3571
3572impl ToOffsetUtf16 for usize {
3573 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3574 snapshot.offset_to_offset_utf16(*self)
3575 }
3576}
3577
3578impl ToPoint for usize {
3579 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3580 snapshot.offset_to_point(*self)
3581 }
3582}
3583
3584impl ToPoint for Point {
3585 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3586 *self
3587 }
3588}
3589
3590impl ToPointUtf16 for usize {
3591 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3592 snapshot.offset_to_point_utf16(*self)
3593 }
3594}
3595
3596impl ToPointUtf16 for Point {
3597 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3598 snapshot.point_to_point_utf16(*self)
3599 }
3600}
3601
3602impl ToPointUtf16 for PointUtf16 {
3603 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3604 *self
3605 }
3606}
3607
3608#[cfg(test)]
3609mod tests {
3610 use super::*;
3611 use gpui::{MutableAppContext, TestAppContext};
3612 use language::{Buffer, Rope};
3613 use rand::prelude::*;
3614 use settings::Settings;
3615 use std::{env, rc::Rc};
3616 use unindent::Unindent;
3617
3618 use util::test::sample_text;
3619
3620 #[gpui::test]
3621 fn test_singleton(cx: &mut MutableAppContext) {
3622 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3623 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3624
3625 let snapshot = multibuffer.read(cx).snapshot(cx);
3626 assert_eq!(snapshot.text(), buffer.read(cx).text());
3627
3628 assert_eq!(
3629 snapshot.buffer_rows(0).collect::<Vec<_>>(),
3630 (0..buffer.read(cx).row_count())
3631 .map(Some)
3632 .collect::<Vec<_>>()
3633 );
3634
3635 buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
3636 let snapshot = multibuffer.read(cx).snapshot(cx);
3637
3638 assert_eq!(snapshot.text(), buffer.read(cx).text());
3639 assert_eq!(
3640 snapshot.buffer_rows(0).collect::<Vec<_>>(),
3641 (0..buffer.read(cx).row_count())
3642 .map(Some)
3643 .collect::<Vec<_>>()
3644 );
3645 }
3646
3647 #[gpui::test]
3648 fn test_remote(cx: &mut MutableAppContext) {
3649 let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
3650 let guest_buffer = cx.add_model(|cx| {
3651 let state = host_buffer.read(cx).to_proto();
3652 let ops = cx
3653 .background()
3654 .block(host_buffer.read(cx).serialize_ops(None, cx));
3655 let mut buffer = Buffer::from_proto(1, state, None).unwrap();
3656 buffer
3657 .apply_ops(
3658 ops.into_iter()
3659 .map(|op| language::proto::deserialize_operation(op).unwrap()),
3660 cx,
3661 )
3662 .unwrap();
3663 buffer
3664 });
3665 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
3666 let snapshot = multibuffer.read(cx).snapshot(cx);
3667 assert_eq!(snapshot.text(), "a");
3668
3669 guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
3670 let snapshot = multibuffer.read(cx).snapshot(cx);
3671 assert_eq!(snapshot.text(), "ab");
3672
3673 guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
3674 let snapshot = multibuffer.read(cx).snapshot(cx);
3675 assert_eq!(snapshot.text(), "abc");
3676 }
3677
3678 #[gpui::test]
3679 fn test_excerpt_boundaries_and_clipping(cx: &mut MutableAppContext) {
3680 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3681 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
3682 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3683
3684 let events = Rc::new(RefCell::new(Vec::<Event>::new()));
3685 multibuffer.update(cx, |_, cx| {
3686 let events = events.clone();
3687 cx.subscribe(&multibuffer, move |_, _, event, _| {
3688 if let Event::Edited = event {
3689 events.borrow_mut().push(event.clone())
3690 }
3691 })
3692 .detach();
3693 });
3694
3695 let subscription = multibuffer.update(cx, |multibuffer, cx| {
3696 let subscription = multibuffer.subscribe();
3697 multibuffer.push_excerpts(
3698 buffer_1.clone(),
3699 [ExcerptRange {
3700 context: Point::new(1, 2)..Point::new(2, 5),
3701 primary: None,
3702 }],
3703 cx,
3704 );
3705 assert_eq!(
3706 subscription.consume().into_inner(),
3707 [Edit {
3708 old: 0..0,
3709 new: 0..10
3710 }]
3711 );
3712
3713 multibuffer.push_excerpts(
3714 buffer_1.clone(),
3715 [ExcerptRange {
3716 context: Point::new(3, 3)..Point::new(4, 4),
3717 primary: None,
3718 }],
3719 cx,
3720 );
3721 multibuffer.push_excerpts(
3722 buffer_2.clone(),
3723 [ExcerptRange {
3724 context: Point::new(3, 1)..Point::new(3, 3),
3725 primary: None,
3726 }],
3727 cx,
3728 );
3729 assert_eq!(
3730 subscription.consume().into_inner(),
3731 [Edit {
3732 old: 10..10,
3733 new: 10..22
3734 }]
3735 );
3736
3737 subscription
3738 });
3739
3740 // Adding excerpts emits an edited event.
3741 assert_eq!(
3742 events.borrow().as_slice(),
3743 &[Event::Edited, Event::Edited, Event::Edited]
3744 );
3745
3746 let snapshot = multibuffer.read(cx).snapshot(cx);
3747 assert_eq!(
3748 snapshot.text(),
3749 concat!(
3750 "bbbb\n", // Preserve newlines
3751 "ccccc\n", //
3752 "ddd\n", //
3753 "eeee\n", //
3754 "jj" //
3755 )
3756 );
3757 assert_eq!(
3758 snapshot.buffer_rows(0).collect::<Vec<_>>(),
3759 [Some(1), Some(2), Some(3), Some(4), Some(3)]
3760 );
3761 assert_eq!(
3762 snapshot.buffer_rows(2).collect::<Vec<_>>(),
3763 [Some(3), Some(4), Some(3)]
3764 );
3765 assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
3766 assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
3767
3768 assert_eq!(
3769 boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
3770 &[
3771 (0, "bbbb\nccccc".to_string(), true),
3772 (2, "ddd\neeee".to_string(), false),
3773 (4, "jj".to_string(), true),
3774 ]
3775 );
3776 assert_eq!(
3777 boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
3778 &[(0, "bbbb\nccccc".to_string(), true)]
3779 );
3780 assert_eq!(
3781 boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
3782 &[]
3783 );
3784 assert_eq!(
3785 boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
3786 &[]
3787 );
3788 assert_eq!(
3789 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3790 &[(2, "ddd\neeee".to_string(), false)]
3791 );
3792 assert_eq!(
3793 boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3794 &[(2, "ddd\neeee".to_string(), false)]
3795 );
3796 assert_eq!(
3797 boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
3798 &[(2, "ddd\neeee".to_string(), false)]
3799 );
3800 assert_eq!(
3801 boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
3802 &[(4, "jj".to_string(), true)]
3803 );
3804 assert_eq!(
3805 boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
3806 &[]
3807 );
3808
3809 buffer_1.update(cx, |buffer, cx| {
3810 let text = "\n";
3811 buffer.edit(
3812 [
3813 (Point::new(0, 0)..Point::new(0, 0), text),
3814 (Point::new(2, 1)..Point::new(2, 3), text),
3815 ],
3816 None,
3817 cx,
3818 );
3819 });
3820
3821 let snapshot = multibuffer.read(cx).snapshot(cx);
3822 assert_eq!(
3823 snapshot.text(),
3824 concat!(
3825 "bbbb\n", // Preserve newlines
3826 "c\n", //
3827 "cc\n", //
3828 "ddd\n", //
3829 "eeee\n", //
3830 "jj" //
3831 )
3832 );
3833
3834 assert_eq!(
3835 subscription.consume().into_inner(),
3836 [Edit {
3837 old: 6..8,
3838 new: 6..7
3839 }]
3840 );
3841
3842 let snapshot = multibuffer.read(cx).snapshot(cx);
3843 assert_eq!(
3844 snapshot.clip_point(Point::new(0, 5), Bias::Left),
3845 Point::new(0, 4)
3846 );
3847 assert_eq!(
3848 snapshot.clip_point(Point::new(0, 5), Bias::Right),
3849 Point::new(0, 4)
3850 );
3851 assert_eq!(
3852 snapshot.clip_point(Point::new(5, 1), Bias::Right),
3853 Point::new(5, 1)
3854 );
3855 assert_eq!(
3856 snapshot.clip_point(Point::new(5, 2), Bias::Right),
3857 Point::new(5, 2)
3858 );
3859 assert_eq!(
3860 snapshot.clip_point(Point::new(5, 3), Bias::Right),
3861 Point::new(5, 2)
3862 );
3863
3864 let snapshot = multibuffer.update(cx, |multibuffer, cx| {
3865 let (buffer_2_excerpt_id, _) =
3866 multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
3867 multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
3868 multibuffer.snapshot(cx)
3869 });
3870
3871 assert_eq!(
3872 snapshot.text(),
3873 concat!(
3874 "bbbb\n", // Preserve newlines
3875 "c\n", //
3876 "cc\n", //
3877 "ddd\n", //
3878 "eeee", //
3879 )
3880 );
3881
3882 fn boundaries_in_range(
3883 range: Range<Point>,
3884 snapshot: &MultiBufferSnapshot,
3885 ) -> Vec<(u32, String, bool)> {
3886 snapshot
3887 .excerpt_boundaries_in_range(range)
3888 .map(|boundary| {
3889 (
3890 boundary.row,
3891 boundary
3892 .buffer
3893 .text_for_range(boundary.range.context)
3894 .collect::<String>(),
3895 boundary.starts_new_buffer,
3896 )
3897 })
3898 .collect::<Vec<_>>()
3899 }
3900 }
3901
3902 #[gpui::test]
3903 fn test_excerpt_events(cx: &mut MutableAppContext) {
3904 let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'a'), cx));
3905 let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'm'), cx));
3906
3907 let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3908 let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3909
3910 follower_multibuffer.update(cx, |_, cx| {
3911 cx.subscribe(&leader_multibuffer, |follower, _, event, cx| {
3912 match event.clone() {
3913 Event::ExcerptsAdded {
3914 buffer,
3915 predecessor,
3916 excerpts,
3917 } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
3918 Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
3919 _ => {}
3920 }
3921 })
3922 .detach();
3923 });
3924
3925 leader_multibuffer.update(cx, |leader, cx| {
3926 leader.push_excerpts(
3927 buffer_1.clone(),
3928 [
3929 ExcerptRange {
3930 context: 0..8,
3931 primary: None,
3932 },
3933 ExcerptRange {
3934 context: 12..16,
3935 primary: None,
3936 },
3937 ],
3938 cx,
3939 );
3940 leader.insert_excerpts_after(
3941 leader.excerpt_ids()[0],
3942 buffer_2.clone(),
3943 [
3944 ExcerptRange {
3945 context: 0..5,
3946 primary: None,
3947 },
3948 ExcerptRange {
3949 context: 10..15,
3950 primary: None,
3951 },
3952 ],
3953 cx,
3954 )
3955 });
3956 assert_eq!(
3957 leader_multibuffer.read(cx).snapshot(cx).text(),
3958 follower_multibuffer.read(cx).snapshot(cx).text(),
3959 );
3960
3961 leader_multibuffer.update(cx, |leader, cx| {
3962 let excerpt_ids = leader.excerpt_ids();
3963 leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
3964 });
3965 assert_eq!(
3966 leader_multibuffer.read(cx).snapshot(cx).text(),
3967 follower_multibuffer.read(cx).snapshot(cx).text(),
3968 );
3969
3970 leader_multibuffer.update(cx, |leader, cx| {
3971 leader.clear(cx);
3972 });
3973 assert_eq!(
3974 leader_multibuffer.read(cx).snapshot(cx).text(),
3975 follower_multibuffer.read(cx).snapshot(cx).text(),
3976 );
3977 }
3978
3979 #[gpui::test]
3980 fn test_push_excerpts_with_context_lines(cx: &mut MutableAppContext) {
3981 let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
3982 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3983 let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
3984 multibuffer.push_excerpts_with_context_lines(
3985 buffer.clone(),
3986 vec![
3987 Point::new(3, 2)..Point::new(4, 2),
3988 Point::new(7, 1)..Point::new(7, 3),
3989 Point::new(15, 0)..Point::new(15, 0),
3990 ],
3991 2,
3992 cx,
3993 )
3994 });
3995
3996 let snapshot = multibuffer.read(cx).snapshot(cx);
3997 assert_eq!(
3998 snapshot.text(),
3999 "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4000 );
4001
4002 assert_eq!(
4003 anchor_ranges
4004 .iter()
4005 .map(|range| range.to_point(&snapshot))
4006 .collect::<Vec<_>>(),
4007 vec![
4008 Point::new(2, 2)..Point::new(3, 2),
4009 Point::new(6, 1)..Point::new(6, 3),
4010 Point::new(12, 0)..Point::new(12, 0)
4011 ]
4012 );
4013 }
4014
4015 #[gpui::test]
4016 fn test_empty_multibuffer(cx: &mut MutableAppContext) {
4017 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4018
4019 let snapshot = multibuffer.read(cx).snapshot(cx);
4020 assert_eq!(snapshot.text(), "");
4021 assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
4022 assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
4023 }
4024
4025 #[gpui::test]
4026 fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
4027 let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4028 let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4029 let old_snapshot = multibuffer.read(cx).snapshot(cx);
4030 buffer.update(cx, |buffer, cx| {
4031 buffer.edit([(0..0, "X")], None, cx);
4032 buffer.edit([(5..5, "Y")], None, cx);
4033 });
4034 let new_snapshot = multibuffer.read(cx).snapshot(cx);
4035
4036 assert_eq!(old_snapshot.text(), "abcd");
4037 assert_eq!(new_snapshot.text(), "XabcdY");
4038
4039 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4040 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4041 assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
4042 assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
4043 }
4044
4045 #[gpui::test]
4046 fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
4047 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4048 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
4049 let multibuffer = cx.add_model(|cx| {
4050 let mut multibuffer = MultiBuffer::new(0);
4051 multibuffer.push_excerpts(
4052 buffer_1.clone(),
4053 [ExcerptRange {
4054 context: 0..4,
4055 primary: None,
4056 }],
4057 cx,
4058 );
4059 multibuffer.push_excerpts(
4060 buffer_2.clone(),
4061 [ExcerptRange {
4062 context: 0..5,
4063 primary: None,
4064 }],
4065 cx,
4066 );
4067 multibuffer
4068 });
4069 let old_snapshot = multibuffer.read(cx).snapshot(cx);
4070
4071 assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
4072 assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
4073 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4074 assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4075 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4076 assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4077
4078 buffer_1.update(cx, |buffer, cx| {
4079 buffer.edit([(0..0, "W")], None, cx);
4080 buffer.edit([(5..5, "X")], None, cx);
4081 });
4082 buffer_2.update(cx, |buffer, cx| {
4083 buffer.edit([(0..0, "Y")], None, cx);
4084 buffer.edit([(6..6, "Z")], None, cx);
4085 });
4086 let new_snapshot = multibuffer.read(cx).snapshot(cx);
4087
4088 assert_eq!(old_snapshot.text(), "abcd\nefghi");
4089 assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
4090
4091 assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4092 assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4093 assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
4094 assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
4095 assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
4096 assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
4097 assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
4098 assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
4099 assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
4100 assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
4101 }
4102
4103 #[gpui::test]
4104 fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut MutableAppContext) {
4105 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4106 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
4107 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4108
4109 // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
4110 // Add an excerpt from buffer 1 that spans this new insertion.
4111 buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
4112 let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
4113 multibuffer
4114 .push_excerpts(
4115 buffer_1.clone(),
4116 [ExcerptRange {
4117 context: 0..7,
4118 primary: None,
4119 }],
4120 cx,
4121 )
4122 .pop()
4123 .unwrap()
4124 });
4125
4126 let snapshot_1 = multibuffer.read(cx).snapshot(cx);
4127 assert_eq!(snapshot_1.text(), "abcd123");
4128
4129 // Replace the buffer 1 excerpt with new excerpts from buffer 2.
4130 let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
4131 multibuffer.remove_excerpts([excerpt_id_1], cx);
4132 let mut ids = multibuffer
4133 .push_excerpts(
4134 buffer_2.clone(),
4135 [
4136 ExcerptRange {
4137 context: 0..4,
4138 primary: None,
4139 },
4140 ExcerptRange {
4141 context: 6..10,
4142 primary: None,
4143 },
4144 ExcerptRange {
4145 context: 12..16,
4146 primary: None,
4147 },
4148 ],
4149 cx,
4150 )
4151 .into_iter();
4152 (ids.next().unwrap(), ids.next().unwrap())
4153 });
4154 let snapshot_2 = multibuffer.read(cx).snapshot(cx);
4155 assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
4156
4157 // The old excerpt id doesn't get reused.
4158 assert_ne!(excerpt_id_2, excerpt_id_1);
4159
4160 // Resolve some anchors from the previous snapshot in the new snapshot.
4161 // The current excerpts are from a different buffer, so we don't attempt to
4162 // resolve the old text anchor in the new buffer.
4163 assert_eq!(
4164 snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
4165 0
4166 );
4167 assert_eq!(
4168 snapshot_2.summaries_for_anchors::<usize, _>(&[
4169 snapshot_1.anchor_before(2),
4170 snapshot_1.anchor_after(3)
4171 ]),
4172 vec![0, 0]
4173 );
4174
4175 // Refresh anchors from the old snapshot. The return value indicates that both
4176 // anchors lost their original excerpt.
4177 let refresh =
4178 snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
4179 assert_eq!(
4180 refresh,
4181 &[
4182 (0, snapshot_2.anchor_before(0), false),
4183 (1, snapshot_2.anchor_after(0), false),
4184 ]
4185 );
4186
4187 // Replace the middle excerpt with a smaller excerpt in buffer 2,
4188 // that intersects the old excerpt.
4189 let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
4190 multibuffer.remove_excerpts([excerpt_id_3], cx);
4191 multibuffer
4192 .insert_excerpts_after(
4193 excerpt_id_2,
4194 buffer_2.clone(),
4195 [ExcerptRange {
4196 context: 5..8,
4197 primary: None,
4198 }],
4199 cx,
4200 )
4201 .pop()
4202 .unwrap()
4203 });
4204
4205 let snapshot_3 = multibuffer.read(cx).snapshot(cx);
4206 assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
4207 assert_ne!(excerpt_id_5, excerpt_id_3);
4208
4209 // Resolve some anchors from the previous snapshot in the new snapshot.
4210 // The third anchor can't be resolved, since its excerpt has been removed,
4211 // so it resolves to the same position as its predecessor.
4212 let anchors = [
4213 snapshot_2.anchor_before(0),
4214 snapshot_2.anchor_after(2),
4215 snapshot_2.anchor_after(6),
4216 snapshot_2.anchor_after(14),
4217 ];
4218 assert_eq!(
4219 snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
4220 &[0, 2, 9, 13]
4221 );
4222
4223 let new_anchors = snapshot_3.refresh_anchors(&anchors);
4224 assert_eq!(
4225 new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
4226 &[(0, true), (1, true), (2, true), (3, true)]
4227 );
4228 assert_eq!(
4229 snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
4230 &[0, 2, 7, 13]
4231 );
4232 }
4233
4234 #[gpui::test]
4235 async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
4236 use git::diff::DiffHunkStatus;
4237
4238 // buffer has two modified hunks with two rows each
4239 let buffer_1 = cx.add_model(|cx| {
4240 let mut buffer = Buffer::new(
4241 0,
4242 "
4243 1.zero
4244 1.ONE
4245 1.TWO
4246 1.three
4247 1.FOUR
4248 1.FIVE
4249 1.six
4250 "
4251 .unindent(),
4252 cx,
4253 );
4254 buffer.set_diff_base(
4255 Some(
4256 "
4257 1.zero
4258 1.one
4259 1.two
4260 1.three
4261 1.four
4262 1.five
4263 1.six
4264 "
4265 .unindent(),
4266 ),
4267 cx,
4268 );
4269 buffer
4270 });
4271
4272 // buffer has a deletion hunk and an insertion hunk
4273 let buffer_2 = cx.add_model(|cx| {
4274 let mut buffer = Buffer::new(
4275 0,
4276 "
4277 2.zero
4278 2.one
4279 2.two
4280 2.three
4281 2.four
4282 2.five
4283 2.six
4284 "
4285 .unindent(),
4286 cx,
4287 );
4288 buffer.set_diff_base(
4289 Some(
4290 "
4291 2.zero
4292 2.one
4293 2.one-and-a-half
4294 2.two
4295 2.three
4296 2.four
4297 2.six
4298 "
4299 .unindent(),
4300 ),
4301 cx,
4302 );
4303 buffer
4304 });
4305
4306 cx.foreground().run_until_parked();
4307
4308 let multibuffer = cx.add_model(|cx| {
4309 let mut multibuffer = MultiBuffer::new(0);
4310 multibuffer.push_excerpts(
4311 buffer_1.clone(),
4312 [
4313 // excerpt ends in the middle of a modified hunk
4314 ExcerptRange {
4315 context: Point::new(0, 0)..Point::new(1, 5),
4316 primary: Default::default(),
4317 },
4318 // excerpt begins in the middle of a modified hunk
4319 ExcerptRange {
4320 context: Point::new(5, 0)..Point::new(6, 5),
4321 primary: Default::default(),
4322 },
4323 ],
4324 cx,
4325 );
4326 multibuffer.push_excerpts(
4327 buffer_2.clone(),
4328 [
4329 // excerpt ends at a deletion
4330 ExcerptRange {
4331 context: Point::new(0, 0)..Point::new(1, 5),
4332 primary: Default::default(),
4333 },
4334 // excerpt starts at a deletion
4335 ExcerptRange {
4336 context: Point::new(2, 0)..Point::new(2, 5),
4337 primary: Default::default(),
4338 },
4339 // excerpt fully contains a deletion hunk
4340 ExcerptRange {
4341 context: Point::new(1, 0)..Point::new(2, 5),
4342 primary: Default::default(),
4343 },
4344 // excerpt fully contains an insertion hunk
4345 ExcerptRange {
4346 context: Point::new(4, 0)..Point::new(6, 5),
4347 primary: Default::default(),
4348 },
4349 ],
4350 cx,
4351 );
4352 multibuffer
4353 });
4354
4355 let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
4356
4357 assert_eq!(
4358 snapshot.text(),
4359 "
4360 1.zero
4361 1.ONE
4362 1.FIVE
4363 1.six
4364 2.zero
4365 2.one
4366 2.two
4367 2.one
4368 2.two
4369 2.four
4370 2.five
4371 2.six"
4372 .unindent()
4373 );
4374
4375 let expected = [
4376 (DiffHunkStatus::Modified, 1..2),
4377 (DiffHunkStatus::Modified, 2..3),
4378 //TODO: Define better when and where removed hunks show up at range extremities
4379 (DiffHunkStatus::Removed, 6..6),
4380 (DiffHunkStatus::Removed, 8..8),
4381 (DiffHunkStatus::Added, 10..11),
4382 ];
4383
4384 assert_eq!(
4385 snapshot
4386 .git_diff_hunks_in_range(0..12, false)
4387 .map(|hunk| (hunk.status(), hunk.buffer_range))
4388 .collect::<Vec<_>>(),
4389 &expected,
4390 );
4391
4392 assert_eq!(
4393 snapshot
4394 .git_diff_hunks_in_range(0..12, true)
4395 .map(|hunk| (hunk.status(), hunk.buffer_range))
4396 .collect::<Vec<_>>(),
4397 expected
4398 .iter()
4399 .rev()
4400 .cloned()
4401 .collect::<Vec<_>>()
4402 .as_slice(),
4403 );
4404 }
4405
4406 #[gpui::test(iterations = 100)]
4407 fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
4408 let operations = env::var("OPERATIONS")
4409 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4410 .unwrap_or(10);
4411
4412 let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
4413 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4414 let mut excerpt_ids = Vec::<ExcerptId>::new();
4415 let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
4416 let mut anchors = Vec::new();
4417 let mut old_versions = Vec::new();
4418
4419 for _ in 0..operations {
4420 match rng.gen_range(0..100) {
4421 0..=19 if !buffers.is_empty() => {
4422 let buffer = buffers.choose(&mut rng).unwrap();
4423 buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
4424 }
4425 20..=29 if !expected_excerpts.is_empty() => {
4426 let mut ids_to_remove = vec![];
4427 for _ in 0..rng.gen_range(1..=3) {
4428 if expected_excerpts.is_empty() {
4429 break;
4430 }
4431
4432 let ix = rng.gen_range(0..expected_excerpts.len());
4433 ids_to_remove.push(excerpt_ids.remove(ix));
4434 let (buffer, range) = expected_excerpts.remove(ix);
4435 let buffer = buffer.read(cx);
4436 log::info!(
4437 "Removing excerpt {}: {:?}",
4438 ix,
4439 buffer
4440 .text_for_range(range.to_offset(buffer))
4441 .collect::<String>(),
4442 );
4443 }
4444 let snapshot = multibuffer.read(cx).read(cx);
4445 ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
4446 drop(snapshot);
4447 multibuffer.update(cx, |multibuffer, cx| {
4448 multibuffer.remove_excerpts(ids_to_remove, cx)
4449 });
4450 }
4451 30..=39 if !expected_excerpts.is_empty() => {
4452 let multibuffer = multibuffer.read(cx).read(cx);
4453 let offset =
4454 multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
4455 let bias = if rng.gen() { Bias::Left } else { Bias::Right };
4456 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
4457 anchors.push(multibuffer.anchor_at(offset, bias));
4458 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
4459 }
4460 40..=44 if !anchors.is_empty() => {
4461 let multibuffer = multibuffer.read(cx).read(cx);
4462 let prev_len = anchors.len();
4463 anchors = multibuffer
4464 .refresh_anchors(&anchors)
4465 .into_iter()
4466 .map(|a| a.1)
4467 .collect();
4468
4469 // Ensure the newly-refreshed anchors point to a valid excerpt and don't
4470 // overshoot its boundaries.
4471 assert_eq!(anchors.len(), prev_len);
4472 for anchor in &anchors {
4473 if anchor.excerpt_id == ExcerptId::min()
4474 || anchor.excerpt_id == ExcerptId::max()
4475 {
4476 continue;
4477 }
4478
4479 let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
4480 assert_eq!(excerpt.id, anchor.excerpt_id);
4481 assert!(excerpt.contains(anchor));
4482 }
4483 }
4484 _ => {
4485 let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
4486 let base_text = util::RandomCharIter::new(&mut rng)
4487 .take(10)
4488 .collect::<String>();
4489 buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
4490 buffers.last().unwrap()
4491 } else {
4492 buffers.choose(&mut rng).unwrap()
4493 };
4494
4495 let buffer = buffer_handle.read(cx);
4496 let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
4497 let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4498 let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
4499 let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
4500 let prev_excerpt_id = excerpt_ids
4501 .get(prev_excerpt_ix)
4502 .cloned()
4503 .unwrap_or_else(ExcerptId::max);
4504 let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
4505
4506 log::info!(
4507 "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
4508 excerpt_ix,
4509 expected_excerpts.len(),
4510 buffer_handle.id(),
4511 buffer.text(),
4512 start_ix..end_ix,
4513 &buffer.text()[start_ix..end_ix]
4514 );
4515
4516 let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
4517 multibuffer
4518 .insert_excerpts_after(
4519 prev_excerpt_id,
4520 buffer_handle.clone(),
4521 [ExcerptRange {
4522 context: start_ix..end_ix,
4523 primary: None,
4524 }],
4525 cx,
4526 )
4527 .pop()
4528 .unwrap()
4529 });
4530
4531 excerpt_ids.insert(excerpt_ix, excerpt_id);
4532 expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
4533 }
4534 }
4535
4536 if rng.gen_bool(0.3) {
4537 multibuffer.update(cx, |multibuffer, cx| {
4538 old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
4539 })
4540 }
4541
4542 let snapshot = multibuffer.read(cx).snapshot(cx);
4543
4544 let mut excerpt_starts = Vec::new();
4545 let mut expected_text = String::new();
4546 let mut expected_buffer_rows = Vec::new();
4547 for (buffer, range) in &expected_excerpts {
4548 let buffer = buffer.read(cx);
4549 let buffer_range = range.to_offset(buffer);
4550
4551 excerpt_starts.push(TextSummary::from(expected_text.as_str()));
4552 expected_text.extend(buffer.text_for_range(buffer_range.clone()));
4553 expected_text.push('\n');
4554
4555 let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
4556 ..=buffer.offset_to_point(buffer_range.end).row;
4557 for row in buffer_row_range {
4558 expected_buffer_rows.push(Some(row));
4559 }
4560 }
4561 // Remove final trailing newline.
4562 if !expected_excerpts.is_empty() {
4563 expected_text.pop();
4564 }
4565
4566 // Always report one buffer row
4567 if expected_buffer_rows.is_empty() {
4568 expected_buffer_rows.push(Some(0));
4569 }
4570
4571 assert_eq!(snapshot.text(), expected_text);
4572 log::info!("MultiBuffer text: {:?}", expected_text);
4573
4574 assert_eq!(
4575 snapshot.buffer_rows(0).collect::<Vec<_>>(),
4576 expected_buffer_rows,
4577 );
4578
4579 for _ in 0..5 {
4580 let start_row = rng.gen_range(0..=expected_buffer_rows.len());
4581 assert_eq!(
4582 snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
4583 &expected_buffer_rows[start_row..],
4584 "buffer_rows({})",
4585 start_row
4586 );
4587 }
4588
4589 assert_eq!(
4590 snapshot.max_buffer_row(),
4591 expected_buffer_rows.into_iter().flatten().max().unwrap()
4592 );
4593
4594 let mut excerpt_starts = excerpt_starts.into_iter();
4595 for (buffer, range) in &expected_excerpts {
4596 let buffer_id = buffer.id();
4597 let buffer = buffer.read(cx);
4598 let buffer_range = range.to_offset(buffer);
4599 let buffer_start_point = buffer.offset_to_point(buffer_range.start);
4600 let buffer_start_point_utf16 =
4601 buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
4602
4603 let excerpt_start = excerpt_starts.next().unwrap();
4604 let mut offset = excerpt_start.len;
4605 let mut buffer_offset = buffer_range.start;
4606 let mut point = excerpt_start.lines;
4607 let mut buffer_point = buffer_start_point;
4608 let mut point_utf16 = excerpt_start.lines_utf16();
4609 let mut buffer_point_utf16 = buffer_start_point_utf16;
4610 for ch in buffer
4611 .snapshot()
4612 .chunks(buffer_range.clone(), false)
4613 .flat_map(|c| c.text.chars())
4614 {
4615 for _ in 0..ch.len_utf8() {
4616 let left_offset = snapshot.clip_offset(offset, Bias::Left);
4617 let right_offset = snapshot.clip_offset(offset, Bias::Right);
4618 let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
4619 let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
4620 assert_eq!(
4621 left_offset,
4622 excerpt_start.len + (buffer_left_offset - buffer_range.start),
4623 "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
4624 offset,
4625 buffer_id,
4626 buffer_offset,
4627 );
4628 assert_eq!(
4629 right_offset,
4630 excerpt_start.len + (buffer_right_offset - buffer_range.start),
4631 "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
4632 offset,
4633 buffer_id,
4634 buffer_offset,
4635 );
4636
4637 let left_point = snapshot.clip_point(point, Bias::Left);
4638 let right_point = snapshot.clip_point(point, Bias::Right);
4639 let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
4640 let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
4641 assert_eq!(
4642 left_point,
4643 excerpt_start.lines + (buffer_left_point - buffer_start_point),
4644 "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
4645 point,
4646 buffer_id,
4647 buffer_point,
4648 );
4649 assert_eq!(
4650 right_point,
4651 excerpt_start.lines + (buffer_right_point - buffer_start_point),
4652 "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
4653 point,
4654 buffer_id,
4655 buffer_point,
4656 );
4657
4658 assert_eq!(
4659 snapshot.point_to_offset(left_point),
4660 left_offset,
4661 "point_to_offset({:?})",
4662 left_point,
4663 );
4664 assert_eq!(
4665 snapshot.offset_to_point(left_offset),
4666 left_point,
4667 "offset_to_point({:?})",
4668 left_offset,
4669 );
4670
4671 offset += 1;
4672 buffer_offset += 1;
4673 if ch == '\n' {
4674 point += Point::new(1, 0);
4675 buffer_point += Point::new(1, 0);
4676 } else {
4677 point += Point::new(0, 1);
4678 buffer_point += Point::new(0, 1);
4679 }
4680 }
4681
4682 for _ in 0..ch.len_utf16() {
4683 let left_point_utf16 =
4684 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
4685 let right_point_utf16 =
4686 snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
4687 let buffer_left_point_utf16 =
4688 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
4689 let buffer_right_point_utf16 =
4690 buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
4691 assert_eq!(
4692 left_point_utf16,
4693 excerpt_start.lines_utf16()
4694 + (buffer_left_point_utf16 - buffer_start_point_utf16),
4695 "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
4696 point_utf16,
4697 buffer_id,
4698 buffer_point_utf16,
4699 );
4700 assert_eq!(
4701 right_point_utf16,
4702 excerpt_start.lines_utf16()
4703 + (buffer_right_point_utf16 - buffer_start_point_utf16),
4704 "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
4705 point_utf16,
4706 buffer_id,
4707 buffer_point_utf16,
4708 );
4709
4710 if ch == '\n' {
4711 point_utf16 += PointUtf16::new(1, 0);
4712 buffer_point_utf16 += PointUtf16::new(1, 0);
4713 } else {
4714 point_utf16 += PointUtf16::new(0, 1);
4715 buffer_point_utf16 += PointUtf16::new(0, 1);
4716 }
4717 }
4718 }
4719 }
4720
4721 for (row, line) in expected_text.split('\n').enumerate() {
4722 assert_eq!(
4723 snapshot.line_len(row as u32),
4724 line.len() as u32,
4725 "line_len({}).",
4726 row
4727 );
4728 }
4729
4730 let text_rope = Rope::from(expected_text.as_str());
4731 for _ in 0..10 {
4732 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4733 let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4734
4735 let text_for_range = snapshot
4736 .text_for_range(start_ix..end_ix)
4737 .collect::<String>();
4738 assert_eq!(
4739 text_for_range,
4740 &expected_text[start_ix..end_ix],
4741 "incorrect text for range {:?}",
4742 start_ix..end_ix
4743 );
4744
4745 let excerpted_buffer_ranges = multibuffer
4746 .read(cx)
4747 .range_to_buffer_ranges(start_ix..end_ix, cx);
4748 let excerpted_buffers_text = excerpted_buffer_ranges
4749 .into_iter()
4750 .map(|(buffer, buffer_range)| {
4751 buffer
4752 .read(cx)
4753 .text_for_range(buffer_range)
4754 .collect::<String>()
4755 })
4756 .collect::<Vec<_>>()
4757 .join("\n");
4758 assert_eq!(excerpted_buffers_text, text_for_range);
4759
4760 let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
4761 assert_eq!(
4762 snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
4763 expected_summary,
4764 "incorrect summary for range {:?}",
4765 start_ix..end_ix
4766 );
4767 }
4768
4769 // Anchor resolution
4770 let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
4771 assert_eq!(anchors.len(), summaries.len());
4772 for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
4773 assert!(resolved_offset <= snapshot.len());
4774 assert_eq!(
4775 snapshot.summary_for_anchor::<usize>(anchor),
4776 resolved_offset
4777 );
4778 }
4779
4780 for _ in 0..10 {
4781 let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4782 assert_eq!(
4783 snapshot.reversed_chars_at(end_ix).collect::<String>(),
4784 expected_text[..end_ix].chars().rev().collect::<String>(),
4785 );
4786 }
4787
4788 for _ in 0..10 {
4789 let end_ix = rng.gen_range(0..=text_rope.len());
4790 let start_ix = rng.gen_range(0..=end_ix);
4791 assert_eq!(
4792 snapshot
4793 .bytes_in_range(start_ix..end_ix)
4794 .flatten()
4795 .copied()
4796 .collect::<Vec<_>>(),
4797 expected_text.as_bytes()[start_ix..end_ix].to_vec(),
4798 "bytes_in_range({:?})",
4799 start_ix..end_ix,
4800 );
4801 }
4802 }
4803
4804 let snapshot = multibuffer.read(cx).snapshot(cx);
4805 for (old_snapshot, subscription) in old_versions {
4806 let edits = subscription.consume().into_inner();
4807
4808 log::info!(
4809 "applying subscription edits to old text: {:?}: {:?}",
4810 old_snapshot.text(),
4811 edits,
4812 );
4813
4814 let mut text = old_snapshot.text();
4815 for edit in edits {
4816 let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
4817 text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
4818 }
4819 assert_eq!(text.to_string(), snapshot.text());
4820 }
4821 }
4822
4823 #[gpui::test]
4824 fn test_history(cx: &mut MutableAppContext) {
4825 cx.set_global(Settings::test(cx));
4826 let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
4827 let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
4828 let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4829 let group_interval = multibuffer.read(cx).history.group_interval;
4830 multibuffer.update(cx, |multibuffer, cx| {
4831 multibuffer.push_excerpts(
4832 buffer_1.clone(),
4833 [ExcerptRange {
4834 context: 0..buffer_1.read(cx).len(),
4835 primary: None,
4836 }],
4837 cx,
4838 );
4839 multibuffer.push_excerpts(
4840 buffer_2.clone(),
4841 [ExcerptRange {
4842 context: 0..buffer_2.read(cx).len(),
4843 primary: None,
4844 }],
4845 cx,
4846 );
4847 });
4848
4849 let mut now = Instant::now();
4850
4851 multibuffer.update(cx, |multibuffer, cx| {
4852 let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
4853 multibuffer.edit(
4854 [
4855 (Point::new(0, 0)..Point::new(0, 0), "A"),
4856 (Point::new(1, 0)..Point::new(1, 0), "A"),
4857 ],
4858 None,
4859 cx,
4860 );
4861 multibuffer.edit(
4862 [
4863 (Point::new(0, 1)..Point::new(0, 1), "B"),
4864 (Point::new(1, 1)..Point::new(1, 1), "B"),
4865 ],
4866 None,
4867 cx,
4868 );
4869 multibuffer.end_transaction_at(now, cx);
4870 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4871
4872 // Edit buffer 1 through the multibuffer
4873 now += 2 * group_interval;
4874 multibuffer.start_transaction_at(now, cx);
4875 multibuffer.edit([(2..2, "C")], None, cx);
4876 multibuffer.end_transaction_at(now, cx);
4877 assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
4878
4879 // Edit buffer 1 independently
4880 buffer_1.update(cx, |buffer_1, cx| {
4881 buffer_1.start_transaction_at(now);
4882 buffer_1.edit([(3..3, "D")], None, cx);
4883 buffer_1.end_transaction_at(now, cx);
4884
4885 now += 2 * group_interval;
4886 buffer_1.start_transaction_at(now);
4887 buffer_1.edit([(4..4, "E")], None, cx);
4888 buffer_1.end_transaction_at(now, cx);
4889 });
4890 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
4891
4892 // An undo in the multibuffer undoes the multibuffer transaction
4893 // and also any individual buffer edits that have occured since
4894 // that transaction.
4895 multibuffer.undo(cx);
4896 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4897
4898 multibuffer.undo(cx);
4899 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4900
4901 multibuffer.redo(cx);
4902 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4903
4904 multibuffer.redo(cx);
4905 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
4906
4907 // Undo buffer 2 independently.
4908 buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
4909 assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
4910
4911 // An undo in the multibuffer undoes the components of the
4912 // the last multibuffer transaction that are not already undone.
4913 multibuffer.undo(cx);
4914 assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
4915
4916 multibuffer.undo(cx);
4917 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4918
4919 multibuffer.redo(cx);
4920 assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4921
4922 buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
4923 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
4924
4925 // Redo stack gets cleared after an edit.
4926 now += 2 * group_interval;
4927 multibuffer.start_transaction_at(now, cx);
4928 multibuffer.edit([(0..0, "X")], None, cx);
4929 multibuffer.end_transaction_at(now, cx);
4930 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4931 multibuffer.redo(cx);
4932 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4933 multibuffer.undo(cx);
4934 assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
4935 multibuffer.undo(cx);
4936 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4937
4938 // Transactions can be grouped manually.
4939 multibuffer.redo(cx);
4940 multibuffer.redo(cx);
4941 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4942 multibuffer.group_until_transaction(transaction_1, cx);
4943 multibuffer.undo(cx);
4944 assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4945 multibuffer.redo(cx);
4946 assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4947 });
4948 }
4949}