1mod anchor;
2#[cfg(test)]
3mod multi_buffer_tests;
4mod position;
5
6pub use anchor::{Anchor, AnchorRangeExt, Offset};
7pub use position::{TypedOffset, TypedPoint, TypedRow};
8
9use anyhow::{Result, anyhow};
10use buffer_diff::{
11 BufferDiff, BufferDiffEvent, BufferDiffSnapshot, DiffHunkSecondaryStatus, DiffHunkStatus,
12 DiffHunkStatusKind,
13};
14use clock::ReplicaId;
15use collections::{BTreeMap, Bound, HashMap, HashSet};
16use gpui::{App, AppContext as _, Context, Entity, EntityId, EventEmitter, Task};
17use itertools::Itertools;
18use language::{
19 AutoindentMode, Buffer, BufferChunks, BufferRow, BufferSnapshot, Capability, CharClassifier,
20 CharKind, CharScopeContext, Chunk, CursorShape, DiagnosticEntryRef, DiskState, File,
21 IndentGuideSettings, IndentSize, Language, LanguageScope, OffsetRangeExt, OffsetUtf16, Outline,
22 OutlineItem, Point, PointUtf16, Selection, TextDimension, TextObject, ToOffset as _,
23 ToPoint as _, TransactionId, TreeSitterOptions, Unclipped,
24 language_settings::{LanguageSettings, language_settings},
25};
26
27use rope::DimensionPair;
28use smallvec::SmallVec;
29use smol::future::yield_now;
30use std::{
31 any::type_name,
32 borrow::Cow,
33 cell::{Cell, Ref, RefCell},
34 cmp, fmt,
35 future::Future,
36 io,
37 iter::{self, FromIterator},
38 mem,
39 ops::{Range, RangeBounds, Sub},
40 rc::Rc,
41 str,
42 sync::Arc,
43 time::{Duration, Instant},
44};
45use sum_tree::{Bias, Cursor, Dimension, Dimensions, SumTree, Summary, TreeMap};
46use text::{
47 BufferId, Edit, LineIndent, TextSummary,
48 locator::Locator,
49 subscription::{Subscription, Topic},
50};
51use theme::SyntaxTheme;
52use util::post_inc;
53
54const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize];
55
56#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
57pub struct ExcerptId(u32);
58
59/// One or more [`Buffers`](Buffer) being edited in a single view.
60///
61/// See <https://zed.dev/features#multi-buffers>
62pub struct MultiBuffer {
63 /// A snapshot of the [`Excerpt`]s in the MultiBuffer.
64 /// Use [`MultiBuffer::snapshot`] to get a up-to-date snapshot.
65 snapshot: RefCell<MultiBufferSnapshot>,
66 /// Contains the state of the buffers being edited
67 buffers: RefCell<HashMap<BufferId, BufferState>>,
68 // only used by consumers using `set_excerpts_for_buffer`
69 excerpts_by_path: BTreeMap<PathKey, Vec<ExcerptId>>,
70 paths_by_excerpt: HashMap<ExcerptId, PathKey>,
71 diffs: HashMap<BufferId, DiffState>,
72 // all_diff_hunks_expanded: bool,
73 subscriptions: Topic,
74 /// If true, the multi-buffer only contains a single [`Buffer`] and a single [`Excerpt`]
75 singleton: bool,
76 history: History,
77 title: Option<String>,
78 capability: Capability,
79 buffer_changed_since_sync: Rc<Cell<bool>>,
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub enum Event {
84 ExcerptsAdded {
85 buffer: Entity<Buffer>,
86 predecessor: ExcerptId,
87 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
88 },
89 ExcerptsRemoved {
90 ids: Vec<ExcerptId>,
91 removed_buffer_ids: Vec<BufferId>,
92 },
93 ExcerptsExpanded {
94 ids: Vec<ExcerptId>,
95 },
96 ExcerptsEdited {
97 excerpt_ids: Vec<ExcerptId>,
98 buffer_ids: Vec<BufferId>,
99 },
100 DiffHunksToggled,
101 Edited {
102 singleton_buffer_edited: bool,
103 edited_buffer: Option<Entity<Buffer>>,
104 },
105 TransactionUndone {
106 transaction_id: TransactionId,
107 },
108 Reloaded,
109 LanguageChanged(BufferId),
110 Reparsed(BufferId),
111 Saved,
112 FileHandleChanged,
113 DirtyChanged,
114 DiagnosticsUpdated,
115 BufferDiffChanged,
116}
117
118/// A diff hunk, representing a range of consequent lines in a multibuffer.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct MultiBufferDiffHunk {
121 /// The row range in the multibuffer where this diff hunk appears.
122 pub row_range: Range<MultiBufferRow>,
123 /// The buffer ID that this hunk belongs to.
124 pub buffer_id: BufferId,
125 /// The range of the underlying buffer that this hunk corresponds to.
126 pub buffer_range: Range<text::Anchor>,
127 /// The excerpt that contains the diff hunk.
128 pub excerpt_id: ExcerptId,
129 /// The range within the buffer's diff base that this hunk corresponds to.
130 pub diff_base_byte_range: Range<usize>,
131 /// Whether or not this hunk also appears in the 'secondary diff'.
132 pub secondary_status: DiffHunkSecondaryStatus,
133}
134
135impl MultiBufferDiffHunk {
136 pub fn status(&self) -> DiffHunkStatus {
137 let kind = if self.buffer_range.start == self.buffer_range.end {
138 DiffHunkStatusKind::Deleted
139 } else if self.diff_base_byte_range.is_empty() {
140 DiffHunkStatusKind::Added
141 } else {
142 DiffHunkStatusKind::Modified
143 };
144 DiffHunkStatus {
145 kind,
146 secondary: self.secondary_status,
147 }
148 }
149
150 pub fn is_created_file(&self) -> bool {
151 self.diff_base_byte_range == (0..0)
152 && self.buffer_range == (text::Anchor::MIN..text::Anchor::MAX)
153 }
154
155 pub fn multi_buffer_range(&self) -> Range<Anchor> {
156 let start = Anchor::in_buffer(self.excerpt_id, self.buffer_id, self.buffer_range.start);
157 let end = Anchor::in_buffer(self.excerpt_id, self.buffer_id, self.buffer_range.end);
158 start..end
159 }
160}
161
162#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Hash, Debug)]
163pub struct PathKey {
164 namespace: u32,
165 path: Arc<str>,
166}
167
168impl PathKey {
169 pub fn namespaced(namespace: u32, path: Arc<str>) -> Self {
170 Self { namespace, path }
171 }
172
173 pub fn for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Self {
174 if let Some(file) = buffer.read(cx).file() {
175 Self::namespaced(1, file.full_path(cx).to_string_lossy().into_owned().into())
176 } else {
177 Self::namespaced(0, buffer.entity_id().to_string().into())
178 }
179 }
180
181 pub fn path(&self) -> &Arc<str> {
182 &self.path
183 }
184}
185
186pub type MultiBufferPoint = Point;
187type ExcerptOffset = TypedOffset<Excerpt>;
188type ExcerptPoint = TypedPoint<Excerpt>;
189
190#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq, Hash, serde::Deserialize)]
191#[serde(transparent)]
192pub struct MultiBufferRow(pub u32);
193
194impl MultiBufferRow {
195 pub const MIN: Self = Self(0);
196 pub const MAX: Self = Self(u32::MAX);
197}
198
199impl std::ops::Add<usize> for MultiBufferRow {
200 type Output = Self;
201
202 fn add(self, rhs: usize) -> Self::Output {
203 MultiBufferRow(self.0 + rhs as u32)
204 }
205}
206
207#[derive(Clone)]
208struct History {
209 next_transaction_id: TransactionId,
210 undo_stack: Vec<Transaction>,
211 redo_stack: Vec<Transaction>,
212 transaction_depth: usize,
213 group_interval: Duration,
214}
215
216#[derive(Clone)]
217struct Transaction {
218 id: TransactionId,
219 buffer_transactions: HashMap<BufferId, text::TransactionId>,
220 first_edit_at: Instant,
221 last_edit_at: Instant,
222 suppress_grouping: bool,
223}
224
225pub trait ToOffset: 'static + fmt::Debug {
226 fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
227}
228
229pub trait ToOffsetUtf16: 'static + fmt::Debug {
230 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16;
231}
232
233pub trait ToPoint: 'static + fmt::Debug {
234 fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
235}
236
237pub trait ToPointUtf16: 'static + fmt::Debug {
238 fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16;
239}
240
241struct BufferState {
242 buffer: Entity<Buffer>,
243 last_version: clock::Global,
244 last_non_text_state_update_count: usize,
245 excerpts: Vec<Locator>,
246 _subscriptions: [gpui::Subscription; 2],
247}
248
249struct DiffState {
250 diff: Entity<BufferDiff>,
251 _subscription: gpui::Subscription,
252}
253
254impl DiffState {
255 fn new(diff: Entity<BufferDiff>, cx: &mut Context<MultiBuffer>) -> Self {
256 DiffState {
257 _subscription: cx.subscribe(&diff, |this, diff, event, cx| match event {
258 BufferDiffEvent::DiffChanged { changed_range } => {
259 if let Some(changed_range) = changed_range.clone() {
260 this.buffer_diff_changed(diff, changed_range, cx)
261 }
262 cx.emit(Event::BufferDiffChanged);
263 }
264 BufferDiffEvent::LanguageChanged => this.buffer_diff_language_changed(diff, cx),
265 _ => {}
266 }),
267 diff,
268 }
269 }
270}
271
272/// The contents of a [`MultiBuffer`] at a single point in time.
273#[derive(Clone, Default)]
274pub struct MultiBufferSnapshot {
275 singleton: bool,
276 excerpts: SumTree<Excerpt>,
277 excerpt_ids: SumTree<ExcerptIdMapping>,
278 diffs: TreeMap<BufferId, BufferDiffSnapshot>,
279 diff_transforms: SumTree<DiffTransform>,
280 replaced_excerpts: TreeMap<ExcerptId, ExcerptId>,
281 trailing_excerpt_update_count: usize,
282 all_diff_hunks_expanded: bool,
283 non_text_state_update_count: usize,
284 edit_count: usize,
285 is_dirty: bool,
286 has_deleted_file: bool,
287 has_conflict: bool,
288 show_headers: bool,
289}
290
291#[derive(Debug, Clone)]
292enum DiffTransform {
293 BufferContent {
294 summary: TextSummary,
295 inserted_hunk_info: Option<DiffTransformHunkInfo>,
296 },
297 DeletedHunk {
298 summary: TextSummary,
299 buffer_id: BufferId,
300 hunk_info: DiffTransformHunkInfo,
301 base_text_byte_range: Range<usize>,
302 has_trailing_newline: bool,
303 },
304}
305
306#[derive(Clone, Copy, Debug)]
307struct DiffTransformHunkInfo {
308 excerpt_id: ExcerptId,
309 hunk_start_anchor: text::Anchor,
310 hunk_secondary_status: DiffHunkSecondaryStatus,
311}
312
313impl Eq for DiffTransformHunkInfo {}
314
315impl PartialEq for DiffTransformHunkInfo {
316 fn eq(&self, other: &DiffTransformHunkInfo) -> bool {
317 self.excerpt_id == other.excerpt_id && self.hunk_start_anchor == other.hunk_start_anchor
318 }
319}
320
321impl std::hash::Hash for DiffTransformHunkInfo {
322 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
323 self.excerpt_id.hash(state);
324 self.hunk_start_anchor.hash(state);
325 }
326}
327
328#[derive(Clone)]
329pub struct ExcerptInfo {
330 pub id: ExcerptId,
331 pub buffer: BufferSnapshot,
332 pub buffer_id: BufferId,
333 pub range: ExcerptRange<text::Anchor>,
334 pub end_row: MultiBufferRow,
335}
336
337impl std::fmt::Debug for ExcerptInfo {
338 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339 f.debug_struct(type_name::<Self>())
340 .field("id", &self.id)
341 .field("buffer_id", &self.buffer_id)
342 .field("path", &self.buffer.file().map(|f| f.path()))
343 .field("range", &self.range)
344 .finish()
345 }
346}
347
348/// A boundary between `Excerpt`s in a [`MultiBuffer`]
349#[derive(Debug)]
350pub struct ExcerptBoundary {
351 pub prev: Option<ExcerptInfo>,
352 pub next: ExcerptInfo,
353 /// The row in the `MultiBuffer` where the boundary is located
354 pub row: MultiBufferRow,
355}
356
357impl ExcerptBoundary {
358 pub fn starts_new_buffer(&self) -> bool {
359 match (self.prev.as_ref(), &self.next) {
360 (None, _) => true,
361 (Some(prev), next) => prev.buffer_id != next.buffer_id,
362 }
363 }
364}
365
366#[derive(Copy, Clone, Debug, PartialEq, Eq)]
367pub struct ExpandInfo {
368 pub direction: ExpandExcerptDirection,
369 pub excerpt_id: ExcerptId,
370}
371
372#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
373pub struct RowInfo {
374 pub buffer_id: Option<BufferId>,
375 pub buffer_row: Option<u32>,
376 pub multibuffer_row: Option<MultiBufferRow>,
377 pub diff_status: Option<buffer_diff::DiffHunkStatus>,
378 pub expand_info: Option<ExpandInfo>,
379}
380
381/// A slice into a [`Buffer`] that is being edited in a [`MultiBuffer`].
382#[derive(Clone)]
383struct Excerpt {
384 /// The unique identifier for this excerpt
385 id: ExcerptId,
386 /// The location of the excerpt in the [`MultiBuffer`]
387 locator: Locator,
388 /// The buffer being excerpted
389 buffer_id: BufferId,
390 /// A snapshot of the buffer being excerpted
391 buffer: BufferSnapshot,
392 /// The range of the buffer to be shown in the excerpt
393 range: ExcerptRange<text::Anchor>,
394 /// The last row in the excerpted slice of the buffer
395 max_buffer_row: BufferRow,
396 /// A summary of the text in the excerpt
397 text_summary: TextSummary,
398 has_trailing_newline: bool,
399}
400
401/// A public view into an `Excerpt` in a [`MultiBuffer`].
402///
403/// Contains methods for getting the [`Buffer`] of the excerpt,
404/// as well as mapping offsets to/from buffer and multibuffer coordinates.
405#[derive(Clone)]
406pub struct MultiBufferExcerpt<'a> {
407 excerpt: &'a Excerpt,
408 diff_transforms: sum_tree::Cursor<'a, 'static, DiffTransform, DiffTransforms<usize>>,
409 offset: usize,
410 excerpt_offset: ExcerptDimension<usize>,
411 buffer_offset: usize,
412}
413
414#[derive(Clone, Debug)]
415struct ExcerptIdMapping {
416 id: ExcerptId,
417 locator: Locator,
418}
419
420/// A range of text from a single [`Buffer`], to be shown as an `Excerpt`.
421/// These ranges are relative to the buffer itself
422#[derive(Clone, Debug, Eq, PartialEq, Hash)]
423pub struct ExcerptRange<T> {
424 /// The full range of text to be shown in the excerpt.
425 pub context: Range<T>,
426 /// The primary range of text to be highlighted in the excerpt.
427 /// In a multi-buffer search, this would be the text that matched the search
428 pub primary: Range<T>,
429}
430
431impl<T: Clone> ExcerptRange<T> {
432 pub fn new(context: Range<T>) -> Self {
433 Self {
434 context: context.clone(),
435 primary: context,
436 }
437 }
438}
439
440#[derive(Clone, Debug, Default)]
441pub struct ExcerptSummary {
442 excerpt_id: ExcerptId,
443 /// The location of the last [`Excerpt`] being summarized
444 excerpt_locator: Locator,
445 widest_line_number: u32,
446 text: TextSummary,
447}
448
449#[derive(Debug, Clone)]
450pub struct DiffTransformSummary {
451 input: TextSummary,
452 output: TextSummary,
453}
454
455#[derive(Clone)]
456pub struct MultiBufferRows<'a> {
457 point: Point,
458 is_empty: bool,
459 is_singleton: bool,
460 cursor: MultiBufferCursor<'a, Point>,
461}
462
463pub struct MultiBufferChunks<'a> {
464 excerpts: Cursor<'a, 'static, Excerpt, ExcerptOffset>,
465 diff_transforms: Cursor<'a, 'static, DiffTransform, Dimensions<usize, ExcerptOffset>>,
466 diffs: &'a TreeMap<BufferId, BufferDiffSnapshot>,
467 diff_base_chunks: Option<(BufferId, BufferChunks<'a>)>,
468 buffer_chunk: Option<Chunk<'a>>,
469 range: Range<usize>,
470 excerpt_offset_range: Range<ExcerptOffset>,
471 excerpt_chunks: Option<ExcerptChunks<'a>>,
472 language_aware: bool,
473}
474
475pub struct ReversedMultiBufferChunks<'a> {
476 cursor: MultiBufferCursor<'a, usize>,
477 current_chunks: Option<rope::Chunks<'a>>,
478 start: usize,
479 offset: usize,
480}
481
482pub struct MultiBufferBytes<'a> {
483 range: Range<usize>,
484 cursor: MultiBufferCursor<'a, usize>,
485 excerpt_bytes: Option<text::Bytes<'a>>,
486 has_trailing_newline: bool,
487 chunk: &'a [u8],
488}
489
490pub struct ReversedMultiBufferBytes<'a> {
491 range: Range<usize>,
492 chunks: ReversedMultiBufferChunks<'a>,
493 chunk: &'a [u8],
494}
495
496#[derive(Clone)]
497struct DiffTransforms<D> {
498 output_dimension: OutputDimension<D>,
499 excerpt_dimension: ExcerptDimension<D>,
500}
501
502impl<'a, D: TextDimension> Dimension<'a, DiffTransformSummary> for DiffTransforms<D> {
503 fn zero(cx: <DiffTransformSummary as sum_tree::Summary>::Context<'_>) -> Self {
504 Self {
505 output_dimension: OutputDimension::zero(cx),
506 excerpt_dimension: <ExcerptDimension<D> as Dimension<'a, DiffTransformSummary>>::zero(
507 cx,
508 ),
509 }
510 }
511
512 fn add_summary(
513 &mut self,
514 summary: &'a DiffTransformSummary,
515 cx: <DiffTransformSummary as sum_tree::Summary>::Context<'_>,
516 ) {
517 self.output_dimension.add_summary(summary, cx);
518 self.excerpt_dimension.add_summary(summary, cx);
519 }
520}
521
522#[derive(Clone)]
523struct MultiBufferCursor<'a, D: TextDimension> {
524 excerpts: Cursor<'a, 'static, Excerpt, ExcerptDimension<D>>,
525 diff_transforms: Cursor<'a, 'static, DiffTransform, DiffTransforms<D>>,
526 diffs: &'a TreeMap<BufferId, BufferDiffSnapshot>,
527 cached_region: Option<MultiBufferRegion<'a, D>>,
528}
529
530#[derive(Clone)]
531struct MultiBufferRegion<'a, D: TextDimension> {
532 buffer: &'a BufferSnapshot,
533 is_main_buffer: bool,
534 diff_hunk_status: Option<DiffHunkStatus>,
535 excerpt: &'a Excerpt,
536 buffer_range: Range<D>,
537 range: Range<D>,
538 has_trailing_newline: bool,
539}
540
541struct ExcerptChunks<'a> {
542 excerpt_id: ExcerptId,
543 content_chunks: BufferChunks<'a>,
544 footer_height: usize,
545}
546
547#[derive(Debug)]
548struct BufferEdit {
549 range: Range<usize>,
550 new_text: Arc<str>,
551 is_insertion: bool,
552 original_indent_column: Option<u32>,
553 excerpt_id: ExcerptId,
554}
555
556#[derive(Clone, Copy, Debug, PartialEq)]
557enum DiffChangeKind {
558 BufferEdited,
559 DiffUpdated { base_changed: bool },
560 ExpandOrCollapseHunks { expand: bool },
561}
562
563#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
564pub enum ExpandExcerptDirection {
565 Up,
566 Down,
567 UpAndDown,
568}
569
570impl ExpandExcerptDirection {
571 pub fn should_expand_up(&self) -> bool {
572 match self {
573 ExpandExcerptDirection::Up => true,
574 ExpandExcerptDirection::Down => false,
575 ExpandExcerptDirection::UpAndDown => true,
576 }
577 }
578
579 pub fn should_expand_down(&self) -> bool {
580 match self {
581 ExpandExcerptDirection::Up => false,
582 ExpandExcerptDirection::Down => true,
583 ExpandExcerptDirection::UpAndDown => true,
584 }
585 }
586}
587
588#[derive(Clone, Debug, PartialEq)]
589pub struct IndentGuide {
590 pub buffer_id: BufferId,
591 pub start_row: MultiBufferRow,
592 pub end_row: MultiBufferRow,
593 pub depth: u32,
594 pub tab_size: u32,
595 pub settings: IndentGuideSettings,
596}
597
598impl IndentGuide {
599 pub fn indent_level(&self) -> u32 {
600 self.depth * self.tab_size
601 }
602}
603
604impl MultiBuffer {
605 pub fn new(capability: Capability) -> Self {
606 Self {
607 snapshot: RefCell::new(MultiBufferSnapshot {
608 show_headers: true,
609 ..MultiBufferSnapshot::default()
610 }),
611 buffers: RefCell::default(),
612 diffs: HashMap::default(),
613 subscriptions: Topic::default(),
614 singleton: false,
615 capability,
616 title: None,
617 excerpts_by_path: Default::default(),
618 paths_by_excerpt: Default::default(),
619 buffer_changed_since_sync: Default::default(),
620 history: History {
621 next_transaction_id: clock::Lamport::default(),
622 undo_stack: Vec::new(),
623 redo_stack: Vec::new(),
624 transaction_depth: 0,
625 group_interval: Duration::from_millis(300),
626 },
627 }
628 }
629
630 pub fn without_headers(capability: Capability) -> Self {
631 Self {
632 snapshot: Default::default(),
633 buffers: Default::default(),
634 excerpts_by_path: Default::default(),
635 paths_by_excerpt: Default::default(),
636 diffs: HashMap::default(),
637 subscriptions: Default::default(),
638 singleton: false,
639 capability,
640 buffer_changed_since_sync: Default::default(),
641 history: History {
642 next_transaction_id: Default::default(),
643 undo_stack: Default::default(),
644 redo_stack: Default::default(),
645 transaction_depth: 0,
646 group_interval: Duration::from_millis(300),
647 },
648 title: Default::default(),
649 }
650 }
651
652 pub fn clone(&self, new_cx: &mut Context<Self>) -> Self {
653 let mut buffers = HashMap::default();
654 let buffer_changed_since_sync = Rc::new(Cell::new(false));
655 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
656 buffer_state.buffer.update(new_cx, |buffer, _| {
657 buffer.record_changes(Rc::downgrade(&buffer_changed_since_sync));
658 });
659 buffers.insert(
660 *buffer_id,
661 BufferState {
662 buffer: buffer_state.buffer.clone(),
663 last_version: buffer_state.last_version.clone(),
664 last_non_text_state_update_count: buffer_state.last_non_text_state_update_count,
665 excerpts: buffer_state.excerpts.clone(),
666 _subscriptions: [
667 new_cx.observe(&buffer_state.buffer, |_, _, cx| cx.notify()),
668 new_cx.subscribe(&buffer_state.buffer, Self::on_buffer_event),
669 ],
670 },
671 );
672 }
673 let mut diff_bases = HashMap::default();
674 for (buffer_id, diff) in self.diffs.iter() {
675 diff_bases.insert(*buffer_id, DiffState::new(diff.diff.clone(), new_cx));
676 }
677 Self {
678 snapshot: RefCell::new(self.snapshot.borrow().clone()),
679 buffers: RefCell::new(buffers),
680 excerpts_by_path: Default::default(),
681 paths_by_excerpt: Default::default(),
682 diffs: diff_bases,
683 subscriptions: Default::default(),
684 singleton: self.singleton,
685 capability: self.capability,
686 history: self.history.clone(),
687 title: self.title.clone(),
688 buffer_changed_since_sync,
689 }
690 }
691
692 pub fn with_title(mut self, title: String) -> Self {
693 self.title = Some(title);
694 self
695 }
696
697 pub fn read_only(&self) -> bool {
698 self.capability == Capability::ReadOnly
699 }
700
701 pub fn singleton(buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Self {
702 let mut this = Self::new(buffer.read(cx).capability());
703 this.singleton = true;
704 this.push_excerpts(
705 buffer,
706 [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
707 cx,
708 );
709 this.snapshot.borrow_mut().singleton = true;
710 this
711 }
712
713 /// Returns an up-to-date snapshot of the MultiBuffer.
714 pub fn snapshot(&self, cx: &App) -> MultiBufferSnapshot {
715 self.sync(cx);
716 self.snapshot.borrow().clone()
717 }
718
719 pub fn read(&self, cx: &App) -> Ref<'_, MultiBufferSnapshot> {
720 self.sync(cx);
721 self.snapshot.borrow()
722 }
723
724 pub fn as_singleton(&self) -> Option<Entity<Buffer>> {
725 if self.singleton {
726 Some(
727 self.buffers
728 .borrow()
729 .values()
730 .next()
731 .unwrap()
732 .buffer
733 .clone(),
734 )
735 } else {
736 None
737 }
738 }
739
740 pub fn is_singleton(&self) -> bool {
741 self.singleton
742 }
743
744 pub fn subscribe(&mut self) -> Subscription {
745 self.subscriptions.subscribe()
746 }
747
748 pub fn is_dirty(&self, cx: &App) -> bool {
749 self.read(cx).is_dirty()
750 }
751
752 pub fn has_deleted_file(&self, cx: &App) -> bool {
753 self.read(cx).has_deleted_file()
754 }
755
756 pub fn has_conflict(&self, cx: &App) -> bool {
757 self.read(cx).has_conflict()
758 }
759
760 // The `is_empty` signature doesn't match what clippy expects
761 #[allow(clippy::len_without_is_empty)]
762 pub fn len(&self, cx: &App) -> usize {
763 self.read(cx).len()
764 }
765
766 pub fn is_empty(&self) -> bool {
767 self.buffers.borrow().is_empty()
768 }
769
770 pub fn symbols_containing<T: ToOffset>(
771 &self,
772 offset: T,
773 theme: Option<&SyntaxTheme>,
774 cx: &App,
775 ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
776 self.read(cx).symbols_containing(offset, theme)
777 }
778
779 pub fn edit<I, S, T>(
780 &self,
781 edits: I,
782 autoindent_mode: Option<AutoindentMode>,
783 cx: &mut Context<Self>,
784 ) where
785 I: IntoIterator<Item = (Range<S>, T)>,
786 S: ToOffset,
787 T: Into<Arc<str>>,
788 {
789 let snapshot = self.read(cx);
790 let edits = edits
791 .into_iter()
792 .map(|(range, new_text)| {
793 let mut range = range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot);
794 if range.start > range.end {
795 mem::swap(&mut range.start, &mut range.end);
796 }
797 (range, new_text.into())
798 })
799 .collect::<Vec<_>>();
800
801 return edit_internal(self, snapshot, edits, autoindent_mode, cx);
802
803 // Non-generic part of edit, hoisted out to avoid blowing up LLVM IR.
804 fn edit_internal(
805 this: &MultiBuffer,
806 snapshot: Ref<MultiBufferSnapshot>,
807 edits: Vec<(Range<usize>, Arc<str>)>,
808 mut autoindent_mode: Option<AutoindentMode>,
809 cx: &mut Context<MultiBuffer>,
810 ) {
811 if this.read_only() || this.buffers.borrow().is_empty() {
812 return;
813 }
814
815 let original_indent_columns = match &mut autoindent_mode {
816 Some(AutoindentMode::Block {
817 original_indent_columns,
818 }) => mem::take(original_indent_columns),
819 _ => Default::default(),
820 };
821
822 let (buffer_edits, edited_excerpt_ids) =
823 this.convert_edits_to_buffer_edits(edits, &snapshot, &original_indent_columns);
824 drop(snapshot);
825
826 let mut buffer_ids = Vec::with_capacity(buffer_edits.len());
827 for (buffer_id, mut edits) in buffer_edits {
828 buffer_ids.push(buffer_id);
829 edits.sort_by_key(|edit| edit.range.start);
830 this.buffers.borrow()[&buffer_id]
831 .buffer
832 .update(cx, |buffer, cx| {
833 let mut edits = edits.into_iter().peekable();
834 let mut insertions = Vec::new();
835 let mut original_indent_columns = Vec::new();
836 let mut deletions = Vec::new();
837 let empty_str: Arc<str> = Arc::default();
838 while let Some(BufferEdit {
839 mut range,
840 mut new_text,
841 mut is_insertion,
842 original_indent_column,
843 excerpt_id,
844 }) = edits.next()
845 {
846 while let Some(BufferEdit {
847 range: next_range,
848 is_insertion: next_is_insertion,
849 new_text: next_new_text,
850 excerpt_id: next_excerpt_id,
851 ..
852 }) = edits.peek()
853 {
854 if range.end >= next_range.start {
855 range.end = cmp::max(next_range.end, range.end);
856 is_insertion |= *next_is_insertion;
857 if excerpt_id == *next_excerpt_id {
858 new_text = format!("{new_text}{next_new_text}").into();
859 }
860 edits.next();
861 } else {
862 break;
863 }
864 }
865
866 if is_insertion {
867 original_indent_columns.push(original_indent_column);
868 insertions.push((
869 buffer.anchor_before(range.start)
870 ..buffer.anchor_before(range.end),
871 new_text.clone(),
872 ));
873 } else if !range.is_empty() {
874 deletions.push((
875 buffer.anchor_before(range.start)
876 ..buffer.anchor_before(range.end),
877 empty_str.clone(),
878 ));
879 }
880 }
881
882 let deletion_autoindent_mode =
883 if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
884 Some(AutoindentMode::Block {
885 original_indent_columns: Default::default(),
886 })
887 } else {
888 autoindent_mode.clone()
889 };
890 let insertion_autoindent_mode =
891 if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
892 Some(AutoindentMode::Block {
893 original_indent_columns,
894 })
895 } else {
896 autoindent_mode.clone()
897 };
898
899 buffer.edit(deletions, deletion_autoindent_mode, cx);
900 buffer.edit(insertions, insertion_autoindent_mode, cx);
901 })
902 }
903
904 cx.emit(Event::ExcerptsEdited {
905 excerpt_ids: edited_excerpt_ids,
906 buffer_ids,
907 });
908 }
909 }
910
911 fn convert_edits_to_buffer_edits(
912 &self,
913 edits: Vec<(Range<usize>, Arc<str>)>,
914 snapshot: &MultiBufferSnapshot,
915 original_indent_columns: &[Option<u32>],
916 ) -> (HashMap<BufferId, Vec<BufferEdit>>, Vec<ExcerptId>) {
917 let mut buffer_edits: HashMap<BufferId, Vec<BufferEdit>> = Default::default();
918 let mut edited_excerpt_ids = Vec::new();
919 let mut cursor = snapshot.cursor::<usize>();
920 for (ix, (range, new_text)) in edits.into_iter().enumerate() {
921 let original_indent_column = original_indent_columns.get(ix).copied().flatten();
922
923 cursor.seek(&range.start);
924 let mut start_region = cursor.region().expect("start offset out of bounds");
925 if !start_region.is_main_buffer {
926 cursor.next();
927 if let Some(region) = cursor.region() {
928 start_region = region;
929 } else {
930 continue;
931 }
932 }
933
934 if range.end < start_region.range.start {
935 continue;
936 }
937
938 if range.end > start_region.range.end {
939 cursor.seek_forward(&range.end);
940 }
941 let mut end_region = cursor.region().expect("end offset out of bounds");
942 if !end_region.is_main_buffer {
943 cursor.prev();
944 if let Some(region) = cursor.region() {
945 end_region = region;
946 } else {
947 continue;
948 }
949 }
950
951 if range.start > end_region.range.end {
952 continue;
953 }
954
955 let start_overshoot = range.start.saturating_sub(start_region.range.start);
956 let end_overshoot = range.end.saturating_sub(end_region.range.start);
957 let buffer_start = (start_region.buffer_range.start + start_overshoot)
958 .min(start_region.buffer_range.end);
959 let buffer_end =
960 (end_region.buffer_range.start + end_overshoot).min(end_region.buffer_range.end);
961
962 if start_region.excerpt.id == end_region.excerpt.id {
963 if start_region.is_main_buffer {
964 edited_excerpt_ids.push(start_region.excerpt.id);
965 buffer_edits
966 .entry(start_region.buffer.remote_id())
967 .or_default()
968 .push(BufferEdit {
969 range: buffer_start..buffer_end,
970 new_text,
971 is_insertion: true,
972 original_indent_column,
973 excerpt_id: start_region.excerpt.id,
974 });
975 }
976 } else {
977 let start_excerpt_range = buffer_start..start_region.buffer_range.end;
978 let end_excerpt_range = end_region.buffer_range.start..buffer_end;
979 if start_region.is_main_buffer {
980 edited_excerpt_ids.push(start_region.excerpt.id);
981 buffer_edits
982 .entry(start_region.buffer.remote_id())
983 .or_default()
984 .push(BufferEdit {
985 range: start_excerpt_range,
986 new_text: new_text.clone(),
987 is_insertion: true,
988 original_indent_column,
989 excerpt_id: start_region.excerpt.id,
990 });
991 }
992 if end_region.is_main_buffer {
993 edited_excerpt_ids.push(end_region.excerpt.id);
994 buffer_edits
995 .entry(end_region.buffer.remote_id())
996 .or_default()
997 .push(BufferEdit {
998 range: end_excerpt_range,
999 new_text: new_text.clone(),
1000 is_insertion: false,
1001 original_indent_column,
1002 excerpt_id: end_region.excerpt.id,
1003 });
1004 }
1005
1006 cursor.seek(&range.start);
1007 cursor.next_excerpt();
1008 while let Some(region) = cursor.region() {
1009 if region.excerpt.id == end_region.excerpt.id {
1010 break;
1011 }
1012 if region.is_main_buffer {
1013 edited_excerpt_ids.push(region.excerpt.id);
1014 buffer_edits
1015 .entry(region.buffer.remote_id())
1016 .or_default()
1017 .push(BufferEdit {
1018 range: region.buffer_range,
1019 new_text: new_text.clone(),
1020 is_insertion: false,
1021 original_indent_column,
1022 excerpt_id: region.excerpt.id,
1023 });
1024 }
1025 cursor.next_excerpt();
1026 }
1027 }
1028 }
1029 (buffer_edits, edited_excerpt_ids)
1030 }
1031
1032 pub fn autoindent_ranges<I, S>(&self, ranges: I, cx: &mut Context<Self>)
1033 where
1034 I: IntoIterator<Item = Range<S>>,
1035 S: ToOffset,
1036 {
1037 let snapshot = self.read(cx);
1038 let empty = Arc::<str>::from("");
1039 let edits = ranges
1040 .into_iter()
1041 .map(|range| {
1042 let mut range = range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot);
1043 if range.start > range.end {
1044 mem::swap(&mut range.start, &mut range.end);
1045 }
1046 (range, empty.clone())
1047 })
1048 .collect::<Vec<_>>();
1049
1050 return autoindent_ranges_internal(self, snapshot, edits, cx);
1051
1052 fn autoindent_ranges_internal(
1053 this: &MultiBuffer,
1054 snapshot: Ref<MultiBufferSnapshot>,
1055 edits: Vec<(Range<usize>, Arc<str>)>,
1056 cx: &mut Context<MultiBuffer>,
1057 ) {
1058 if this.read_only() || this.buffers.borrow().is_empty() {
1059 return;
1060 }
1061
1062 let (buffer_edits, edited_excerpt_ids) =
1063 this.convert_edits_to_buffer_edits(edits, &snapshot, &[]);
1064 drop(snapshot);
1065
1066 let mut buffer_ids = Vec::new();
1067 for (buffer_id, mut edits) in buffer_edits {
1068 buffer_ids.push(buffer_id);
1069 edits.sort_unstable_by_key(|edit| edit.range.start);
1070
1071 let mut ranges: Vec<Range<usize>> = Vec::new();
1072 for edit in edits {
1073 if let Some(last_range) = ranges.last_mut()
1074 && edit.range.start <= last_range.end
1075 {
1076 last_range.end = last_range.end.max(edit.range.end);
1077 continue;
1078 }
1079 ranges.push(edit.range);
1080 }
1081
1082 this.buffers.borrow()[&buffer_id]
1083 .buffer
1084 .update(cx, |buffer, cx| {
1085 buffer.autoindent_ranges(ranges, cx);
1086 })
1087 }
1088
1089 cx.emit(Event::ExcerptsEdited {
1090 excerpt_ids: edited_excerpt_ids,
1091 buffer_ids,
1092 });
1093 }
1094 }
1095
1096 // Inserts newlines at the given position to create an empty line, returning the start of the new line.
1097 // You can also request the insertion of empty lines above and below the line starting at the returned point.
1098 // Panics if the given position is invalid.
1099 pub fn insert_empty_line(
1100 &mut self,
1101 position: impl ToPoint,
1102 space_above: bool,
1103 space_below: bool,
1104 cx: &mut Context<Self>,
1105 ) -> Point {
1106 let multibuffer_point = position.to_point(&self.read(cx));
1107 let (buffer, buffer_point, _) = self.point_to_buffer_point(multibuffer_point, cx).unwrap();
1108 self.start_transaction(cx);
1109 let empty_line_start = buffer.update(cx, |buffer, cx| {
1110 buffer.insert_empty_line(buffer_point, space_above, space_below, cx)
1111 });
1112 self.end_transaction(cx);
1113 multibuffer_point + (empty_line_start - buffer_point)
1114 }
1115
1116 pub fn start_transaction(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
1117 self.start_transaction_at(Instant::now(), cx)
1118 }
1119
1120 pub fn start_transaction_at(
1121 &mut self,
1122 now: Instant,
1123 cx: &mut Context<Self>,
1124 ) -> Option<TransactionId> {
1125 if let Some(buffer) = self.as_singleton() {
1126 return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
1127 }
1128
1129 for BufferState { buffer, .. } in self.buffers.borrow().values() {
1130 buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
1131 }
1132 self.history.start_transaction(now)
1133 }
1134
1135 pub fn last_transaction_id(&self, cx: &App) -> Option<TransactionId> {
1136 if let Some(buffer) = self.as_singleton() {
1137 buffer
1138 .read(cx)
1139 .peek_undo_stack()
1140 .map(|history_entry| history_entry.transaction_id())
1141 } else {
1142 let last_transaction = self.history.undo_stack.last()?;
1143 Some(last_transaction.id)
1144 }
1145 }
1146
1147 pub fn end_transaction(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
1148 self.end_transaction_at(Instant::now(), cx)
1149 }
1150
1151 pub fn end_transaction_at(
1152 &mut self,
1153 now: Instant,
1154 cx: &mut Context<Self>,
1155 ) -> Option<TransactionId> {
1156 if let Some(buffer) = self.as_singleton() {
1157 return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
1158 }
1159
1160 let mut buffer_transactions = HashMap::default();
1161 for BufferState { buffer, .. } in self.buffers.borrow().values() {
1162 if let Some(transaction_id) =
1163 buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
1164 {
1165 buffer_transactions.insert(buffer.read(cx).remote_id(), transaction_id);
1166 }
1167 }
1168
1169 if self.history.end_transaction(now, buffer_transactions) {
1170 let transaction_id = self.history.group().unwrap();
1171 Some(transaction_id)
1172 } else {
1173 None
1174 }
1175 }
1176
1177 pub fn edited_ranges_for_transaction<D>(
1178 &self,
1179 transaction_id: TransactionId,
1180 cx: &App,
1181 ) -> Vec<Range<D>>
1182 where
1183 D: TextDimension + Ord + Sub<D, Output = D>,
1184 {
1185 let Some(transaction) = self.history.transaction(transaction_id) else {
1186 return Vec::new();
1187 };
1188
1189 let mut ranges = Vec::new();
1190 let snapshot = self.read(cx);
1191 let buffers = self.buffers.borrow();
1192 let mut cursor = snapshot.excerpts.cursor::<ExcerptSummary>(());
1193
1194 for (buffer_id, buffer_transaction) in &transaction.buffer_transactions {
1195 let Some(buffer_state) = buffers.get(buffer_id) else {
1196 continue;
1197 };
1198
1199 let buffer = buffer_state.buffer.read(cx);
1200 for range in buffer.edited_ranges_for_transaction_id::<D>(*buffer_transaction) {
1201 for excerpt_id in &buffer_state.excerpts {
1202 cursor.seek(excerpt_id, Bias::Left);
1203 if let Some(excerpt) = cursor.item()
1204 && excerpt.locator == *excerpt_id
1205 {
1206 let excerpt_buffer_start = excerpt.range.context.start.summary::<D>(buffer);
1207 let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(buffer);
1208 let excerpt_range = excerpt_buffer_start..excerpt_buffer_end;
1209 if excerpt_range.contains(&range.start)
1210 && excerpt_range.contains(&range.end)
1211 {
1212 let excerpt_start = D::from_text_summary(&cursor.start().text);
1213
1214 let mut start = excerpt_start;
1215 start.add_assign(&(range.start - excerpt_buffer_start));
1216 let mut end = excerpt_start;
1217 end.add_assign(&(range.end - excerpt_buffer_start));
1218
1219 ranges.push(start..end);
1220 break;
1221 }
1222 }
1223 }
1224 }
1225 }
1226
1227 ranges.sort_by_key(|range| range.start);
1228 ranges
1229 }
1230
1231 pub fn merge_transactions(
1232 &mut self,
1233 transaction: TransactionId,
1234 destination: TransactionId,
1235 cx: &mut Context<Self>,
1236 ) {
1237 if let Some(buffer) = self.as_singleton() {
1238 buffer.update(cx, |buffer, _| {
1239 buffer.merge_transactions(transaction, destination)
1240 });
1241 } else if let Some(transaction) = self.history.forget(transaction)
1242 && let Some(destination) = self.history.transaction_mut(destination)
1243 {
1244 for (buffer_id, buffer_transaction_id) in transaction.buffer_transactions {
1245 if let Some(destination_buffer_transaction_id) =
1246 destination.buffer_transactions.get(&buffer_id)
1247 {
1248 if let Some(state) = self.buffers.borrow().get(&buffer_id) {
1249 state.buffer.update(cx, |buffer, _| {
1250 buffer.merge_transactions(
1251 buffer_transaction_id,
1252 *destination_buffer_transaction_id,
1253 )
1254 });
1255 }
1256 } else {
1257 destination
1258 .buffer_transactions
1259 .insert(buffer_id, buffer_transaction_id);
1260 }
1261 }
1262 }
1263 }
1264
1265 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
1266 self.history.finalize_last_transaction();
1267 for BufferState { buffer, .. } in self.buffers.borrow().values() {
1268 buffer.update(cx, |buffer, _| {
1269 buffer.finalize_last_transaction();
1270 });
1271 }
1272 }
1273
1274 pub fn push_transaction<'a, T>(&mut self, buffer_transactions: T, cx: &Context<Self>)
1275 where
1276 T: IntoIterator<Item = (&'a Entity<Buffer>, &'a language::Transaction)>,
1277 {
1278 self.history
1279 .push_transaction(buffer_transactions, Instant::now(), cx);
1280 self.history.finalize_last_transaction();
1281 }
1282
1283 pub fn group_until_transaction(
1284 &mut self,
1285 transaction_id: TransactionId,
1286 cx: &mut Context<Self>,
1287 ) {
1288 if let Some(buffer) = self.as_singleton() {
1289 buffer.update(cx, |buffer, _| {
1290 buffer.group_until_transaction(transaction_id)
1291 });
1292 } else {
1293 self.history.group_until(transaction_id);
1294 }
1295 }
1296
1297 pub fn set_active_selections(
1298 &self,
1299 selections: &[Selection<Anchor>],
1300 line_mode: bool,
1301 cursor_shape: CursorShape,
1302 cx: &mut Context<Self>,
1303 ) {
1304 let mut selections_by_buffer: HashMap<BufferId, Vec<Selection<text::Anchor>>> =
1305 Default::default();
1306 let snapshot = self.read(cx);
1307 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>(());
1308 for selection in selections {
1309 let start_id = snapshot.clip_excerpt_id(selection.start.excerpt_id);
1310 let start_locator = snapshot.excerpt_locator_for_id(start_id);
1311 let end_id = snapshot.clip_excerpt_id(selection.end.excerpt_id);
1312 let end_locator = snapshot.excerpt_locator_for_id(end_id);
1313
1314 cursor.seek(&Some(start_locator), Bias::Left);
1315 while let Some(excerpt) = cursor.item()
1316 && excerpt.locator <= *end_locator
1317 {
1318 let mut start = excerpt.range.context.start;
1319 let mut end = excerpt.range.context.end;
1320 if excerpt.id == start_id {
1321 start = selection.start.text_anchor;
1322 }
1323 if excerpt.id == end_id {
1324 end = selection.end.text_anchor;
1325 }
1326 selections_by_buffer
1327 .entry(excerpt.buffer_id)
1328 .or_default()
1329 .push(Selection {
1330 id: selection.id,
1331 start,
1332 end,
1333 reversed: selection.reversed,
1334 goal: selection.goal,
1335 });
1336
1337 cursor.next();
1338 }
1339 }
1340
1341 for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
1342 if !selections_by_buffer.contains_key(buffer_id) {
1343 buffer_state
1344 .buffer
1345 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
1346 }
1347 }
1348
1349 for (buffer_id, mut selections) in selections_by_buffer {
1350 self.buffers.borrow()[&buffer_id]
1351 .buffer
1352 .update(cx, |buffer, cx| {
1353 selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer));
1354 let mut selections = selections.into_iter().peekable();
1355 let merged_selections = Arc::from_iter(iter::from_fn(|| {
1356 let mut selection = selections.next()?;
1357 while let Some(next_selection) = selections.peek() {
1358 if selection.end.cmp(&next_selection.start, buffer).is_ge() {
1359 let next_selection = selections.next().unwrap();
1360 if next_selection.end.cmp(&selection.end, buffer).is_ge() {
1361 selection.end = next_selection.end;
1362 }
1363 } else {
1364 break;
1365 }
1366 }
1367 Some(selection)
1368 }));
1369 buffer.set_active_selections(merged_selections, line_mode, cursor_shape, cx);
1370 });
1371 }
1372 }
1373
1374 pub fn remove_active_selections(&self, cx: &mut Context<Self>) {
1375 for buffer in self.buffers.borrow().values() {
1376 buffer
1377 .buffer
1378 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
1379 }
1380 }
1381
1382 pub fn undo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
1383 let mut transaction_id = None;
1384 if let Some(buffer) = self.as_singleton() {
1385 transaction_id = buffer.update(cx, |buffer, cx| buffer.undo(cx));
1386 } else {
1387 while let Some(transaction) = self.history.pop_undo() {
1388 let mut undone = false;
1389 for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
1390 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
1391 undone |= buffer.update(cx, |buffer, cx| {
1392 let undo_to = *buffer_transaction_id;
1393 if let Some(entry) = buffer.peek_undo_stack() {
1394 *buffer_transaction_id = entry.transaction_id();
1395 }
1396 buffer.undo_to_transaction(undo_to, cx)
1397 });
1398 }
1399 }
1400
1401 if undone {
1402 transaction_id = Some(transaction.id);
1403 break;
1404 }
1405 }
1406 }
1407
1408 if let Some(transaction_id) = transaction_id {
1409 cx.emit(Event::TransactionUndone { transaction_id });
1410 }
1411
1412 transaction_id
1413 }
1414
1415 pub fn redo(&mut self, cx: &mut Context<Self>) -> Option<TransactionId> {
1416 if let Some(buffer) = self.as_singleton() {
1417 return buffer.update(cx, |buffer, cx| buffer.redo(cx));
1418 }
1419
1420 while let Some(transaction) = self.history.pop_redo() {
1421 let mut redone = false;
1422 for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
1423 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
1424 redone |= buffer.update(cx, |buffer, cx| {
1425 let redo_to = *buffer_transaction_id;
1426 if let Some(entry) = buffer.peek_redo_stack() {
1427 *buffer_transaction_id = entry.transaction_id();
1428 }
1429 buffer.redo_to_transaction(redo_to, cx)
1430 });
1431 }
1432 }
1433
1434 if redone {
1435 return Some(transaction.id);
1436 }
1437 }
1438
1439 None
1440 }
1441
1442 pub fn undo_transaction(&mut self, transaction_id: TransactionId, cx: &mut Context<Self>) {
1443 if let Some(buffer) = self.as_singleton() {
1444 buffer.update(cx, |buffer, cx| buffer.undo_transaction(transaction_id, cx));
1445 } else if let Some(transaction) = self.history.remove_from_undo(transaction_id) {
1446 for (buffer_id, transaction_id) in &transaction.buffer_transactions {
1447 if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
1448 buffer.update(cx, |buffer, cx| {
1449 buffer.undo_transaction(*transaction_id, cx)
1450 });
1451 }
1452 }
1453 }
1454 }
1455
1456 pub fn forget_transaction(&mut self, transaction_id: TransactionId, cx: &mut Context<Self>) {
1457 if let Some(buffer) = self.as_singleton() {
1458 buffer.update(cx, |buffer, _| {
1459 buffer.forget_transaction(transaction_id);
1460 });
1461 } else if let Some(transaction) = self.history.forget(transaction_id) {
1462 for (buffer_id, buffer_transaction_id) in transaction.buffer_transactions {
1463 if let Some(state) = self.buffers.borrow_mut().get_mut(&buffer_id) {
1464 state.buffer.update(cx, |buffer, _| {
1465 buffer.forget_transaction(buffer_transaction_id);
1466 });
1467 }
1468 }
1469 }
1470 }
1471
1472 pub fn push_excerpts<O>(
1473 &mut self,
1474 buffer: Entity<Buffer>,
1475 ranges: impl IntoIterator<Item = ExcerptRange<O>>,
1476 cx: &mut Context<Self>,
1477 ) -> Vec<ExcerptId>
1478 where
1479 O: text::ToOffset,
1480 {
1481 self.insert_excerpts_after(ExcerptId::max(), buffer, ranges, cx)
1482 }
1483
1484 pub fn location_for_path(&self, path: &PathKey, cx: &App) -> Option<Anchor> {
1485 let excerpt_id = self.excerpts_by_path.get(path)?.first()?;
1486 let snapshot = self.snapshot(cx);
1487 let excerpt = snapshot.excerpt(*excerpt_id)?;
1488 Some(Anchor::in_buffer(
1489 *excerpt_id,
1490 excerpt.buffer_id,
1491 excerpt.range.context.start,
1492 ))
1493 }
1494
1495 pub fn excerpt_paths(&self) -> impl Iterator<Item = &PathKey> {
1496 self.excerpts_by_path.keys()
1497 }
1498
1499 fn expand_excerpts_with_paths(
1500 &mut self,
1501 ids: impl IntoIterator<Item = ExcerptId>,
1502 line_count: u32,
1503 direction: ExpandExcerptDirection,
1504 cx: &mut Context<Self>,
1505 ) {
1506 let snapshot = self.snapshot(cx);
1507 let grouped = ids
1508 .into_iter()
1509 .map(|id| snapshot.clip_excerpt_id(id))
1510 .chunk_by(|id| self.paths_by_excerpt.get(id).cloned())
1511 .into_iter()
1512 .flat_map(|(k, v)| Some((k?, v.into_iter().collect::<Vec<_>>())))
1513 .collect::<Vec<_>>();
1514
1515 for (path, ids) in grouped.into_iter() {
1516 let Some(excerpt_ids) = self.excerpts_by_path.get(&path) else {
1517 continue;
1518 };
1519
1520 let ids_to_expand = HashSet::from_iter(ids);
1521 let expanded_ranges = excerpt_ids.iter().filter_map(|excerpt_id| {
1522 let excerpt = snapshot.excerpt(*excerpt_id)?;
1523
1524 let mut context = excerpt.range.context.to_point(&excerpt.buffer);
1525 if ids_to_expand.contains(excerpt_id) {
1526 match direction {
1527 ExpandExcerptDirection::Up => {
1528 context.start.row = context.start.row.saturating_sub(line_count);
1529 context.start.column = 0;
1530 }
1531 ExpandExcerptDirection::Down => {
1532 context.end.row =
1533 (context.end.row + line_count).min(excerpt.buffer.max_point().row);
1534 context.end.column = excerpt.buffer.line_len(context.end.row);
1535 }
1536 ExpandExcerptDirection::UpAndDown => {
1537 context.start.row = context.start.row.saturating_sub(line_count);
1538 context.start.column = 0;
1539 context.end.row =
1540 (context.end.row + line_count).min(excerpt.buffer.max_point().row);
1541 context.end.column = excerpt.buffer.line_len(context.end.row);
1542 }
1543 }
1544 }
1545
1546 Some(ExcerptRange {
1547 context,
1548 primary: excerpt.range.primary.to_point(&excerpt.buffer),
1549 })
1550 });
1551 let mut merged_ranges: Vec<ExcerptRange<Point>> = Vec::new();
1552 for range in expanded_ranges {
1553 if let Some(last_range) = merged_ranges.last_mut()
1554 && last_range.context.end >= range.context.start
1555 {
1556 last_range.context.end = range.context.end;
1557 continue;
1558 }
1559 merged_ranges.push(range)
1560 }
1561 let Some(excerpt_id) = excerpt_ids.first() else {
1562 continue;
1563 };
1564 let Some(buffer_id) = &snapshot.buffer_id_for_excerpt(*excerpt_id) else {
1565 continue;
1566 };
1567
1568 let Some(buffer) = self
1569 .buffers
1570 .borrow()
1571 .get(buffer_id)
1572 .map(|b| b.buffer.clone())
1573 else {
1574 continue;
1575 };
1576
1577 let buffer_snapshot = buffer.read(cx).snapshot();
1578 self.update_path_excerpts(path.clone(), buffer, &buffer_snapshot, merged_ranges, cx);
1579 }
1580 }
1581
1582 /// Sets excerpts, returns `true` if at least one new excerpt was added.
1583 pub fn set_excerpts_for_path(
1584 &mut self,
1585 path: PathKey,
1586 buffer: Entity<Buffer>,
1587 ranges: impl IntoIterator<Item = Range<Point>>,
1588 context_line_count: u32,
1589 cx: &mut Context<Self>,
1590 ) -> (Vec<Range<Anchor>>, bool) {
1591 let buffer_snapshot = buffer.read(cx).snapshot();
1592 let excerpt_ranges = build_excerpt_ranges(ranges, context_line_count, &buffer_snapshot);
1593
1594 let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
1595 self.set_merged_excerpt_ranges_for_path(
1596 path,
1597 buffer,
1598 excerpt_ranges,
1599 &buffer_snapshot,
1600 new,
1601 counts,
1602 cx,
1603 )
1604 }
1605
1606 pub fn set_excerpt_ranges_for_path(
1607 &mut self,
1608 path: PathKey,
1609 buffer: Entity<Buffer>,
1610 buffer_snapshot: &BufferSnapshot,
1611 excerpt_ranges: Vec<ExcerptRange<Point>>,
1612 cx: &mut Context<Self>,
1613 ) -> (Vec<Range<Anchor>>, bool) {
1614 let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
1615 self.set_merged_excerpt_ranges_for_path(
1616 path,
1617 buffer,
1618 excerpt_ranges,
1619 buffer_snapshot,
1620 new,
1621 counts,
1622 cx,
1623 )
1624 }
1625
1626 pub fn set_anchored_excerpts_for_path(
1627 &self,
1628 buffer: Entity<Buffer>,
1629 ranges: Vec<Range<text::Anchor>>,
1630 context_line_count: u32,
1631 cx: &mut Context<Self>,
1632 ) -> Task<Vec<Range<Anchor>>> {
1633 let buffer_snapshot = buffer.read(cx).snapshot();
1634 let path_key = PathKey::for_buffer(&buffer, cx);
1635 cx.spawn(async move |multi_buffer, cx| {
1636 let snapshot = buffer_snapshot.clone();
1637 let (excerpt_ranges, new, counts) = cx
1638 .background_spawn(async move {
1639 let ranges = ranges.into_iter().map(|range| range.to_point(&snapshot));
1640 let excerpt_ranges =
1641 build_excerpt_ranges(ranges, context_line_count, &snapshot);
1642 let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
1643 (excerpt_ranges, new, counts)
1644 })
1645 .await;
1646
1647 multi_buffer
1648 .update(cx, move |multi_buffer, cx| {
1649 let (ranges, _) = multi_buffer.set_merged_excerpt_ranges_for_path(
1650 path_key,
1651 buffer,
1652 excerpt_ranges,
1653 &buffer_snapshot,
1654 new,
1655 counts,
1656 cx,
1657 );
1658 ranges
1659 })
1660 .ok()
1661 .unwrap_or_default()
1662 })
1663 }
1664
1665 /// Sets excerpts, returns `true` if at least one new excerpt was added.
1666 fn set_merged_excerpt_ranges_for_path(
1667 &mut self,
1668 path: PathKey,
1669 buffer: Entity<Buffer>,
1670 ranges: Vec<ExcerptRange<Point>>,
1671 buffer_snapshot: &BufferSnapshot,
1672 new: Vec<ExcerptRange<Point>>,
1673 counts: Vec<usize>,
1674 cx: &mut Context<Self>,
1675 ) -> (Vec<Range<Anchor>>, bool) {
1676 let (excerpt_ids, added_a_new_excerpt) =
1677 self.update_path_excerpts(path, buffer, buffer_snapshot, new, cx);
1678
1679 let mut result = Vec::new();
1680 let mut ranges = ranges.into_iter();
1681 for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(counts.into_iter()) {
1682 for range in ranges.by_ref().take(range_count) {
1683 let range = Anchor::range_in_buffer(
1684 excerpt_id,
1685 buffer_snapshot.remote_id(),
1686 buffer_snapshot.anchor_before(&range.primary.start)
1687 ..buffer_snapshot.anchor_after(&range.primary.end),
1688 );
1689 result.push(range)
1690 }
1691 }
1692 (result, added_a_new_excerpt)
1693 }
1694
1695 fn merge_excerpt_ranges<'a>(
1696 expanded_ranges: impl IntoIterator<Item = &'a ExcerptRange<Point>> + 'a,
1697 ) -> (Vec<ExcerptRange<Point>>, Vec<usize>) {
1698 let mut merged_ranges: Vec<ExcerptRange<Point>> = Vec::new();
1699 let mut counts: Vec<usize> = Vec::new();
1700 for range in expanded_ranges {
1701 if let Some(last_range) = merged_ranges.last_mut() {
1702 debug_assert!(
1703 last_range.context.start <= range.context.start,
1704 "Last range: {last_range:?} Range: {range:?}"
1705 );
1706 if last_range.context.end >= range.context.start
1707 || last_range.context.end.row + 1 == range.context.start.row
1708 {
1709 last_range.context.end = range.context.end.max(last_range.context.end);
1710 *counts.last_mut().unwrap() += 1;
1711 continue;
1712 }
1713 }
1714 merged_ranges.push(range.clone());
1715 counts.push(1);
1716 }
1717 (merged_ranges, counts)
1718 }
1719
1720 fn update_path_excerpts(
1721 &mut self,
1722 path: PathKey,
1723 buffer: Entity<Buffer>,
1724 buffer_snapshot: &BufferSnapshot,
1725 new: Vec<ExcerptRange<Point>>,
1726 cx: &mut Context<Self>,
1727 ) -> (Vec<ExcerptId>, bool) {
1728 let mut insert_after = self
1729 .excerpts_by_path
1730 .range(..path.clone())
1731 .next_back()
1732 .map(|(_, value)| *value.last().unwrap())
1733 .unwrap_or(ExcerptId::min());
1734
1735 let existing = self
1736 .excerpts_by_path
1737 .get(&path)
1738 .cloned()
1739 .unwrap_or_default();
1740
1741 let mut new_iter = new.into_iter().peekable();
1742 let mut existing_iter = existing.into_iter().peekable();
1743
1744 let mut excerpt_ids = Vec::new();
1745 let mut to_remove = Vec::new();
1746 let mut to_insert: Vec<(ExcerptId, ExcerptRange<Point>)> = Vec::new();
1747 let mut added_a_new_excerpt = false;
1748 let snapshot = self.snapshot(cx);
1749
1750 let mut next_excerpt_id =
1751 if let Some(last_entry) = self.snapshot.borrow().excerpt_ids.last() {
1752 last_entry.id.0 + 1
1753 } else {
1754 1
1755 };
1756
1757 let mut next_excerpt_id = move || ExcerptId(post_inc(&mut next_excerpt_id));
1758
1759 let mut excerpts_cursor = snapshot.excerpts.cursor::<Option<&Locator>>(());
1760 excerpts_cursor.next();
1761
1762 loop {
1763 let new = new_iter.peek();
1764 let existing = if let Some(existing_id) = existing_iter.peek() {
1765 let locator = snapshot.excerpt_locator_for_id(*existing_id);
1766 excerpts_cursor.seek_forward(&Some(locator), Bias::Left);
1767 if let Some(excerpt) = excerpts_cursor.item() {
1768 if excerpt.buffer_id != buffer_snapshot.remote_id() {
1769 to_remove.push(*existing_id);
1770 existing_iter.next();
1771 continue;
1772 }
1773 Some((
1774 *existing_id,
1775 excerpt.range.context.to_point(buffer_snapshot),
1776 ))
1777 } else {
1778 None
1779 }
1780 } else {
1781 None
1782 };
1783
1784 if let Some((last_id, last)) = to_insert.last_mut() {
1785 if let Some(new) = new
1786 && last.context.end >= new.context.start
1787 {
1788 last.context.end = last.context.end.max(new.context.end);
1789 excerpt_ids.push(*last_id);
1790 new_iter.next();
1791 continue;
1792 }
1793 if let Some((existing_id, existing_range)) = &existing
1794 && last.context.end >= existing_range.start
1795 {
1796 last.context.end = last.context.end.max(existing_range.end);
1797 to_remove.push(*existing_id);
1798 self.snapshot
1799 .borrow_mut()
1800 .replaced_excerpts
1801 .insert(*existing_id, *last_id);
1802 existing_iter.next();
1803 continue;
1804 }
1805 }
1806
1807 match (new, existing) {
1808 (None, None) => break,
1809 (None, Some((existing_id, _))) => {
1810 existing_iter.next();
1811 to_remove.push(existing_id);
1812 continue;
1813 }
1814 (Some(_), None) => {
1815 added_a_new_excerpt = true;
1816 let new_id = next_excerpt_id();
1817 excerpt_ids.push(new_id);
1818 to_insert.push((new_id, new_iter.next().unwrap()));
1819 continue;
1820 }
1821 (Some(new), Some((_, existing_range))) => {
1822 if existing_range.end < new.context.start {
1823 let existing_id = existing_iter.next().unwrap();
1824 to_remove.push(existing_id);
1825 continue;
1826 } else if existing_range.start > new.context.end {
1827 let new_id = next_excerpt_id();
1828 excerpt_ids.push(new_id);
1829 to_insert.push((new_id, new_iter.next().unwrap()));
1830 continue;
1831 }
1832
1833 if existing_range.start == new.context.start
1834 && existing_range.end == new.context.end
1835 {
1836 self.insert_excerpts_with_ids_after(
1837 insert_after,
1838 buffer.clone(),
1839 mem::take(&mut to_insert),
1840 cx,
1841 );
1842 insert_after = existing_iter.next().unwrap();
1843 excerpt_ids.push(insert_after);
1844 new_iter.next();
1845 } else {
1846 let existing_id = existing_iter.next().unwrap();
1847 let new_id = next_excerpt_id();
1848 self.snapshot
1849 .borrow_mut()
1850 .replaced_excerpts
1851 .insert(existing_id, new_id);
1852 to_remove.push(existing_id);
1853 let mut range = new_iter.next().unwrap();
1854 range.context.start = range.context.start.min(existing_range.start);
1855 range.context.end = range.context.end.max(existing_range.end);
1856 excerpt_ids.push(new_id);
1857 to_insert.push((new_id, range));
1858 }
1859 }
1860 };
1861 }
1862
1863 self.insert_excerpts_with_ids_after(insert_after, buffer, to_insert, cx);
1864 self.remove_excerpts(to_remove, cx);
1865 if excerpt_ids.is_empty() {
1866 self.excerpts_by_path.remove(&path);
1867 } else {
1868 for excerpt_id in &excerpt_ids {
1869 self.paths_by_excerpt.insert(*excerpt_id, path.clone());
1870 }
1871 self.excerpts_by_path
1872 .insert(path, excerpt_ids.iter().dedup().cloned().collect());
1873 }
1874
1875 (excerpt_ids, added_a_new_excerpt)
1876 }
1877
1878 pub fn paths(&self) -> impl Iterator<Item = PathKey> + '_ {
1879 self.excerpts_by_path.keys().cloned()
1880 }
1881
1882 pub fn remove_excerpts_for_path(&mut self, path: PathKey, cx: &mut Context<Self>) {
1883 if let Some(to_remove) = self.excerpts_by_path.remove(&path) {
1884 self.remove_excerpts(to_remove, cx)
1885 }
1886 }
1887
1888 pub fn insert_excerpts_after<O>(
1889 &mut self,
1890 prev_excerpt_id: ExcerptId,
1891 buffer: Entity<Buffer>,
1892 ranges: impl IntoIterator<Item = ExcerptRange<O>>,
1893 cx: &mut Context<Self>,
1894 ) -> Vec<ExcerptId>
1895 where
1896 O: text::ToOffset,
1897 {
1898 let mut ids = Vec::new();
1899 let mut next_excerpt_id =
1900 if let Some(last_entry) = self.snapshot.borrow().excerpt_ids.last() {
1901 last_entry.id.0 + 1
1902 } else {
1903 1
1904 };
1905 self.insert_excerpts_with_ids_after(
1906 prev_excerpt_id,
1907 buffer,
1908 ranges.into_iter().map(|range| {
1909 let id = ExcerptId(post_inc(&mut next_excerpt_id));
1910 ids.push(id);
1911 (id, range)
1912 }),
1913 cx,
1914 );
1915 ids
1916 }
1917
1918 pub fn insert_excerpts_with_ids_after<O>(
1919 &mut self,
1920 prev_excerpt_id: ExcerptId,
1921 buffer: Entity<Buffer>,
1922 ranges: impl IntoIterator<Item = (ExcerptId, ExcerptRange<O>)>,
1923 cx: &mut Context<Self>,
1924 ) where
1925 O: text::ToOffset,
1926 {
1927 assert_eq!(self.history.transaction_depth, 0);
1928 let mut ranges = ranges.into_iter().peekable();
1929 if ranges.peek().is_none() {
1930 return Default::default();
1931 }
1932
1933 self.sync(cx);
1934
1935 let buffer_snapshot = buffer.read(cx).snapshot();
1936 let buffer_id = buffer_snapshot.remote_id();
1937
1938 let mut buffers = self.buffers.borrow_mut();
1939 let buffer_state = buffers.entry(buffer_id).or_insert_with(|| {
1940 self.buffer_changed_since_sync.replace(true);
1941 buffer.update(cx, |buffer, _| {
1942 buffer.record_changes(Rc::downgrade(&self.buffer_changed_since_sync));
1943 });
1944 BufferState {
1945 last_version: buffer_snapshot.version().clone(),
1946 last_non_text_state_update_count: buffer_snapshot.non_text_state_update_count(),
1947 excerpts: Default::default(),
1948 _subscriptions: [
1949 cx.observe(&buffer, |_, _, cx| cx.notify()),
1950 cx.subscribe(&buffer, Self::on_buffer_event),
1951 ],
1952 buffer: buffer.clone(),
1953 }
1954 });
1955
1956 let mut snapshot = self.snapshot.borrow_mut();
1957 let prev_excerpt_id = snapshot.clip_excerpt_id(prev_excerpt_id);
1958 let mut prev_locator = snapshot.excerpt_locator_for_id(prev_excerpt_id).clone();
1959 let mut new_excerpt_ids = mem::take(&mut snapshot.excerpt_ids);
1960 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>(());
1961 let mut new_excerpts = cursor.slice(&prev_locator, Bias::Right);
1962 prev_locator = cursor.start().unwrap_or(Locator::min_ref()).clone();
1963
1964 let edit_start = ExcerptOffset::new(new_excerpts.summary().text.len);
1965 new_excerpts.update_last(
1966 |excerpt| {
1967 excerpt.has_trailing_newline = true;
1968 },
1969 (),
1970 );
1971
1972 let next_locator = if let Some(excerpt) = cursor.item() {
1973 excerpt.locator.clone()
1974 } else {
1975 Locator::max()
1976 };
1977
1978 let mut excerpts = Vec::new();
1979 while let Some((id, range)) = ranges.next() {
1980 let locator = Locator::between(&prev_locator, &next_locator);
1981 if let Err(ix) = buffer_state.excerpts.binary_search(&locator) {
1982 buffer_state.excerpts.insert(ix, locator.clone());
1983 }
1984 let range = ExcerptRange {
1985 context: buffer_snapshot.anchor_before(&range.context.start)
1986 ..buffer_snapshot.anchor_after(&range.context.end),
1987 primary: buffer_snapshot.anchor_before(&range.primary.start)
1988 ..buffer_snapshot.anchor_after(&range.primary.end),
1989 };
1990 excerpts.push((id, range.clone()));
1991 let excerpt = Excerpt::new(
1992 id,
1993 locator.clone(),
1994 buffer_id,
1995 buffer_snapshot.clone(),
1996 range,
1997 ranges.peek().is_some() || cursor.item().is_some(),
1998 );
1999 new_excerpts.push(excerpt, ());
2000 prev_locator = locator.clone();
2001
2002 if let Some(last_mapping_entry) = new_excerpt_ids.last() {
2003 assert!(id > last_mapping_entry.id, "excerpt ids must be increasing");
2004 }
2005 new_excerpt_ids.push(ExcerptIdMapping { id, locator }, ());
2006 }
2007
2008 let edit_end = ExcerptOffset::new(new_excerpts.summary().text.len);
2009
2010 let suffix = cursor.suffix();
2011 let changed_trailing_excerpt = suffix.is_empty();
2012 new_excerpts.append(suffix, ());
2013 drop(cursor);
2014 snapshot.excerpts = new_excerpts;
2015 snapshot.excerpt_ids = new_excerpt_ids;
2016 if changed_trailing_excerpt {
2017 snapshot.trailing_excerpt_update_count += 1;
2018 }
2019
2020 self.sync_diff_transforms(
2021 &mut snapshot,
2022 vec![Edit {
2023 old: edit_start..edit_start,
2024 new: edit_start..edit_end,
2025 }],
2026 DiffChangeKind::BufferEdited,
2027 );
2028 cx.emit(Event::Edited {
2029 singleton_buffer_edited: false,
2030 edited_buffer: None,
2031 });
2032 cx.emit(Event::ExcerptsAdded {
2033 buffer,
2034 predecessor: prev_excerpt_id,
2035 excerpts,
2036 });
2037 cx.notify();
2038 }
2039
2040 pub fn clear(&mut self, cx: &mut Context<Self>) {
2041 self.sync(cx);
2042 let ids = self.excerpt_ids();
2043 let removed_buffer_ids = self
2044 .buffers
2045 .borrow_mut()
2046 .drain()
2047 .map(|(id, _)| id)
2048 .collect();
2049 self.excerpts_by_path.clear();
2050 self.paths_by_excerpt.clear();
2051 let mut snapshot = self.snapshot.borrow_mut();
2052 let start = ExcerptOffset::new(0);
2053 let prev_len = ExcerptOffset::new(snapshot.excerpts.summary().text.len);
2054 snapshot.excerpts = Default::default();
2055 snapshot.trailing_excerpt_update_count += 1;
2056 snapshot.is_dirty = false;
2057 snapshot.has_deleted_file = false;
2058 snapshot.has_conflict = false;
2059 snapshot.replaced_excerpts.clear();
2060
2061 self.sync_diff_transforms(
2062 &mut snapshot,
2063 vec![Edit {
2064 old: start..prev_len,
2065 new: start..start,
2066 }],
2067 DiffChangeKind::BufferEdited,
2068 );
2069 cx.emit(Event::Edited {
2070 singleton_buffer_edited: false,
2071 edited_buffer: None,
2072 });
2073 cx.emit(Event::ExcerptsRemoved {
2074 ids,
2075 removed_buffer_ids,
2076 });
2077 cx.notify();
2078 }
2079
2080 pub fn excerpts_for_buffer(
2081 &self,
2082 buffer_id: BufferId,
2083 cx: &App,
2084 ) -> Vec<(ExcerptId, ExcerptRange<text::Anchor>)> {
2085 let mut excerpts = Vec::new();
2086 let snapshot = self.read(cx);
2087 let buffers = self.buffers.borrow();
2088 let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>(());
2089 if let Some(locators) = buffers.get(&buffer_id).map(|state| &state.excerpts) {
2090 for locator in locators {
2091 cursor.seek_forward(&Some(locator), Bias::Left);
2092 if let Some(excerpt) = cursor.item()
2093 && excerpt.locator == *locator
2094 {
2095 excerpts.push((excerpt.id, excerpt.range.clone()));
2096 }
2097 }
2098 }
2099
2100 excerpts
2101 }
2102
2103 pub fn excerpt_ranges_for_buffer(&self, buffer_id: BufferId, cx: &App) -> Vec<Range<Point>> {
2104 let snapshot = self.read(cx);
2105 let buffers = self.buffers.borrow();
2106 let mut excerpts = snapshot
2107 .excerpts
2108 .cursor::<Dimensions<Option<&Locator>, ExcerptDimension<Point>>>(());
2109 let mut diff_transforms = snapshot
2110 .diff_transforms
2111 .cursor::<Dimensions<ExcerptDimension<Point>, OutputDimension<Point>>>(());
2112 diff_transforms.next();
2113 let locators = buffers
2114 .get(&buffer_id)
2115 .into_iter()
2116 .flat_map(|state| &state.excerpts);
2117 let mut result = Vec::new();
2118 for locator in locators {
2119 excerpts.seek_forward(&Some(locator), Bias::Left);
2120 if let Some(excerpt) = excerpts.item()
2121 && excerpt.locator == *locator
2122 {
2123 let excerpt_start = excerpts.start().1.clone();
2124 let excerpt_end = ExcerptDimension(excerpt_start.0 + excerpt.text_summary.lines);
2125
2126 diff_transforms.seek_forward(&excerpt_start, Bias::Left);
2127 let overshoot = excerpt_start.0 - diff_transforms.start().0.0;
2128 let start = diff_transforms.start().1.0 + overshoot;
2129
2130 diff_transforms.seek_forward(&excerpt_end, Bias::Right);
2131 let overshoot = excerpt_end.0 - diff_transforms.start().0.0;
2132 let end = diff_transforms.start().1.0 + overshoot;
2133
2134 result.push(start..end)
2135 }
2136 }
2137 result
2138 }
2139
2140 pub fn excerpt_buffer_ids(&self) -> Vec<BufferId> {
2141 self.snapshot
2142 .borrow()
2143 .excerpts
2144 .iter()
2145 .map(|entry| entry.buffer_id)
2146 .collect()
2147 }
2148
2149 pub fn excerpt_ids(&self) -> Vec<ExcerptId> {
2150 self.snapshot
2151 .borrow()
2152 .excerpts
2153 .iter()
2154 .map(|entry| entry.id)
2155 .collect()
2156 }
2157
2158 pub fn excerpt_containing(
2159 &self,
2160 position: impl ToOffset,
2161 cx: &App,
2162 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2163 let snapshot = self.read(cx);
2164 let offset = position.to_offset(&snapshot);
2165
2166 let mut cursor = snapshot.cursor::<usize>();
2167 cursor.seek(&offset);
2168 cursor
2169 .excerpt()
2170 .or_else(|| snapshot.excerpts.last())
2171 .map(|excerpt| {
2172 (
2173 excerpt.id,
2174 self.buffers
2175 .borrow()
2176 .get(&excerpt.buffer_id)
2177 .unwrap()
2178 .buffer
2179 .clone(),
2180 excerpt.range.context.clone(),
2181 )
2182 })
2183 }
2184
2185 pub fn buffer_for_anchor(&self, anchor: Anchor, cx: &App) -> Option<Entity<Buffer>> {
2186 if let Some(buffer_id) = anchor.buffer_id {
2187 self.buffer(buffer_id)
2188 } else {
2189 let (_, buffer, _) = self.excerpt_containing(anchor, cx)?;
2190 Some(buffer)
2191 }
2192 }
2193
2194 // If point is at the end of the buffer, the last excerpt is returned
2195 pub fn point_to_buffer_offset<T: ToOffset>(
2196 &self,
2197 point: T,
2198 cx: &App,
2199 ) -> Option<(Entity<Buffer>, usize)> {
2200 let snapshot = self.read(cx);
2201 let (buffer, offset) = snapshot.point_to_buffer_offset(point)?;
2202 Some((
2203 self.buffers
2204 .borrow()
2205 .get(&buffer.remote_id())?
2206 .buffer
2207 .clone(),
2208 offset,
2209 ))
2210 }
2211
2212 // If point is at the end of the buffer, the last excerpt is returned
2213 pub fn point_to_buffer_point<T: ToPoint>(
2214 &self,
2215 point: T,
2216 cx: &App,
2217 ) -> Option<(Entity<Buffer>, Point, ExcerptId)> {
2218 let snapshot = self.read(cx);
2219 let (buffer, point, is_main_buffer) =
2220 snapshot.point_to_buffer_point(point.to_point(&snapshot))?;
2221 Some((
2222 self.buffers
2223 .borrow()
2224 .get(&buffer.remote_id())?
2225 .buffer
2226 .clone(),
2227 point,
2228 is_main_buffer,
2229 ))
2230 }
2231
2232 pub fn buffer_point_to_anchor(
2233 &self,
2234 buffer: &Entity<Buffer>,
2235 point: Point,
2236 cx: &App,
2237 ) -> Option<Anchor> {
2238 let mut found = None;
2239 let snapshot = buffer.read(cx).snapshot();
2240 for (excerpt_id, range) in self.excerpts_for_buffer(snapshot.remote_id(), cx) {
2241 let start = range.context.start.to_point(&snapshot);
2242 let end = range.context.end.to_point(&snapshot);
2243 if start <= point && point < end {
2244 found = Some((snapshot.clip_point(point, Bias::Left), excerpt_id));
2245 break;
2246 }
2247 if point < start {
2248 found = Some((start, excerpt_id));
2249 }
2250 if point > end {
2251 found = Some((end, excerpt_id));
2252 }
2253 }
2254
2255 found.map(|(point, excerpt_id)| {
2256 let text_anchor = snapshot.anchor_after(point);
2257 Anchor::in_buffer(excerpt_id, snapshot.remote_id(), text_anchor)
2258 })
2259 }
2260
2261 pub fn remove_excerpts(
2262 &mut self,
2263 excerpt_ids: impl IntoIterator<Item = ExcerptId>,
2264 cx: &mut Context<Self>,
2265 ) {
2266 self.sync(cx);
2267 let ids = excerpt_ids.into_iter().collect::<Vec<_>>();
2268 if ids.is_empty() {
2269 return;
2270 }
2271
2272 let mut buffers = self.buffers.borrow_mut();
2273 let mut snapshot = self.snapshot.borrow_mut();
2274 let mut new_excerpts = SumTree::default();
2275 let mut cursor = snapshot
2276 .excerpts
2277 .cursor::<Dimensions<Option<&Locator>, ExcerptOffset>>(());
2278 let mut edits = Vec::new();
2279 let mut excerpt_ids = ids.iter().copied().peekable();
2280 let mut removed_buffer_ids = Vec::new();
2281
2282 while let Some(excerpt_id) = excerpt_ids.next() {
2283 self.paths_by_excerpt.remove(&excerpt_id);
2284 // Seek to the next excerpt to remove, preserving any preceding excerpts.
2285 let locator = snapshot.excerpt_locator_for_id(excerpt_id);
2286 new_excerpts.append(cursor.slice(&Some(locator), Bias::Left), ());
2287
2288 if let Some(mut excerpt) = cursor.item() {
2289 if excerpt.id != excerpt_id {
2290 continue;
2291 }
2292 let mut old_start = cursor.start().1;
2293
2294 // Skip over the removed excerpt.
2295 'remove_excerpts: loop {
2296 if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
2297 buffer_state.excerpts.retain(|l| l != &excerpt.locator);
2298 if buffer_state.excerpts.is_empty() {
2299 log::debug!(
2300 "removing buffer and diff for buffer {}",
2301 excerpt.buffer_id
2302 );
2303 buffers.remove(&excerpt.buffer_id);
2304 removed_buffer_ids.push(excerpt.buffer_id);
2305 }
2306 }
2307 cursor.next();
2308
2309 // Skip over any subsequent excerpts that are also removed.
2310 if let Some(&next_excerpt_id) = excerpt_ids.peek() {
2311 let next_locator = snapshot.excerpt_locator_for_id(next_excerpt_id);
2312 if let Some(next_excerpt) = cursor.item()
2313 && next_excerpt.locator == *next_locator
2314 {
2315 excerpt_ids.next();
2316 excerpt = next_excerpt;
2317 continue 'remove_excerpts;
2318 }
2319 }
2320
2321 break;
2322 }
2323
2324 // When removing the last excerpt, remove the trailing newline from
2325 // the previous excerpt.
2326 if cursor.item().is_none() && old_start.value > 0 {
2327 old_start.value -= 1;
2328 new_excerpts.update_last(|e| e.has_trailing_newline = false, ());
2329 }
2330
2331 // Push an edit for the removal of this run of excerpts.
2332 let old_end = cursor.start().1;
2333 let new_start = ExcerptOffset::new(new_excerpts.summary().text.len);
2334 edits.push(Edit {
2335 old: old_start..old_end,
2336 new: new_start..new_start,
2337 });
2338 }
2339 }
2340 let suffix = cursor.suffix();
2341 let changed_trailing_excerpt = suffix.is_empty();
2342 new_excerpts.append(suffix, ());
2343 drop(cursor);
2344 snapshot.excerpts = new_excerpts;
2345 for buffer_id in &removed_buffer_ids {
2346 self.diffs.remove(buffer_id);
2347 snapshot.diffs.remove(buffer_id);
2348 }
2349
2350 if changed_trailing_excerpt {
2351 snapshot.trailing_excerpt_update_count += 1;
2352 }
2353
2354 self.sync_diff_transforms(&mut snapshot, edits, DiffChangeKind::BufferEdited);
2355 self.buffer_changed_since_sync.replace(true);
2356 cx.emit(Event::Edited {
2357 singleton_buffer_edited: false,
2358 edited_buffer: None,
2359 });
2360 cx.emit(Event::ExcerptsRemoved {
2361 ids,
2362 removed_buffer_ids,
2363 });
2364 cx.notify();
2365 }
2366
2367 pub fn wait_for_anchors<'a, Anchors: 'a + Iterator<Item = Anchor>>(
2368 &self,
2369 anchors: Anchors,
2370 cx: &mut Context<Self>,
2371 ) -> impl 'static + Future<Output = Result<()>> + use<Anchors> {
2372 let borrow = self.buffers.borrow();
2373 let mut error = None;
2374 let mut futures = Vec::new();
2375 for anchor in anchors {
2376 if let Some(buffer_id) = anchor.buffer_id {
2377 if let Some(buffer) = borrow.get(&buffer_id) {
2378 buffer.buffer.update(cx, |buffer, _| {
2379 futures.push(buffer.wait_for_anchors([anchor.text_anchor]))
2380 });
2381 } else {
2382 error = Some(anyhow!(
2383 "buffer {buffer_id} is not part of this multi-buffer"
2384 ));
2385 break;
2386 }
2387 }
2388 }
2389 async move {
2390 if let Some(error) = error {
2391 Err(error)?;
2392 }
2393 for future in futures {
2394 future.await?;
2395 }
2396 Ok(())
2397 }
2398 }
2399
2400 pub fn text_anchor_for_position<T: ToOffset>(
2401 &self,
2402 position: T,
2403 cx: &App,
2404 ) -> Option<(Entity<Buffer>, language::Anchor)> {
2405 let snapshot = self.read(cx);
2406 let anchor = snapshot.anchor_before(position);
2407 let buffer = self
2408 .buffers
2409 .borrow()
2410 .get(&anchor.buffer_id?)?
2411 .buffer
2412 .clone();
2413 Some((buffer, anchor.text_anchor))
2414 }
2415
2416 fn on_buffer_event(
2417 &mut self,
2418 buffer: Entity<Buffer>,
2419 event: &language::BufferEvent,
2420 cx: &mut Context<Self>,
2421 ) {
2422 use language::BufferEvent;
2423 cx.emit(match event {
2424 BufferEvent::Edited => Event::Edited {
2425 singleton_buffer_edited: true,
2426 edited_buffer: Some(buffer),
2427 },
2428 BufferEvent::DirtyChanged => Event::DirtyChanged,
2429 BufferEvent::Saved => Event::Saved,
2430 BufferEvent::FileHandleChanged => Event::FileHandleChanged,
2431 BufferEvent::Reloaded => Event::Reloaded,
2432 BufferEvent::LanguageChanged => Event::LanguageChanged(buffer.read(cx).remote_id()),
2433 BufferEvent::Reparsed => Event::Reparsed(buffer.read(cx).remote_id()),
2434 BufferEvent::DiagnosticsUpdated => Event::DiagnosticsUpdated,
2435 BufferEvent::CapabilityChanged => {
2436 self.capability = buffer.read(cx).capability();
2437 return;
2438 }
2439 BufferEvent::Operation { .. } | BufferEvent::ReloadNeeded => return,
2440 });
2441 }
2442
2443 fn buffer_diff_language_changed(&mut self, diff: Entity<BufferDiff>, cx: &mut Context<Self>) {
2444 self.sync(cx);
2445 let mut snapshot = self.snapshot.borrow_mut();
2446 let diff = diff.read(cx);
2447 let buffer_id = diff.buffer_id;
2448 let diff = diff.snapshot(cx);
2449 snapshot.diffs.insert(buffer_id, diff);
2450 }
2451
2452 fn buffer_diff_changed(
2453 &mut self,
2454 diff: Entity<BufferDiff>,
2455 range: Range<text::Anchor>,
2456 cx: &mut Context<Self>,
2457 ) {
2458 self.sync(cx);
2459 self.buffer_changed_since_sync.replace(true);
2460
2461 let diff = diff.read(cx);
2462 let buffer_id = diff.buffer_id;
2463 let buffers = self.buffers.borrow();
2464 let Some(buffer_state) = buffers.get(&buffer_id) else {
2465 return;
2466 };
2467
2468 let buffer = buffer_state.buffer.read(cx);
2469 let diff_change_range = range.to_offset(buffer);
2470
2471 let new_diff = diff.snapshot(cx);
2472 let mut snapshot = self.snapshot.borrow_mut();
2473 let base_text_changed = snapshot
2474 .diffs
2475 .get(&buffer_id)
2476 .is_none_or(|old_diff| !new_diff.base_texts_eq(old_diff));
2477
2478 snapshot.diffs.insert(buffer_id, new_diff);
2479
2480 let mut excerpt_edits = Vec::new();
2481 for locator in &buffer_state.excerpts {
2482 let mut cursor = snapshot
2483 .excerpts
2484 .cursor::<Dimensions<Option<&Locator>, ExcerptOffset>>(());
2485 cursor.seek_forward(&Some(locator), Bias::Left);
2486 if let Some(excerpt) = cursor.item()
2487 && excerpt.locator == *locator
2488 {
2489 let excerpt_buffer_range = excerpt.range.context.to_offset(&excerpt.buffer);
2490 if diff_change_range.end < excerpt_buffer_range.start
2491 || diff_change_range.start > excerpt_buffer_range.end
2492 {
2493 continue;
2494 }
2495 let excerpt_start = cursor.start().1;
2496 let excerpt_len = ExcerptOffset::new(excerpt.text_summary.len);
2497 let diff_change_start_in_excerpt = ExcerptOffset::new(
2498 diff_change_range
2499 .start
2500 .saturating_sub(excerpt_buffer_range.start),
2501 );
2502 let diff_change_end_in_excerpt = ExcerptOffset::new(
2503 diff_change_range
2504 .end
2505 .saturating_sub(excerpt_buffer_range.start),
2506 );
2507 let edit_start = excerpt_start + diff_change_start_in_excerpt.min(excerpt_len);
2508 let edit_end = excerpt_start + diff_change_end_in_excerpt.min(excerpt_len);
2509 excerpt_edits.push(Edit {
2510 old: edit_start..edit_end,
2511 new: edit_start..edit_end,
2512 });
2513 }
2514 }
2515
2516 self.sync_diff_transforms(
2517 &mut snapshot,
2518 excerpt_edits,
2519 DiffChangeKind::DiffUpdated {
2520 base_changed: base_text_changed,
2521 },
2522 );
2523 cx.emit(Event::Edited {
2524 singleton_buffer_edited: false,
2525 edited_buffer: None,
2526 });
2527 }
2528
2529 pub fn all_buffers(&self) -> HashSet<Entity<Buffer>> {
2530 self.buffers
2531 .borrow()
2532 .values()
2533 .map(|state| state.buffer.clone())
2534 .collect()
2535 }
2536
2537 pub fn all_buffer_ids(&self) -> Vec<BufferId> {
2538 self.buffers.borrow().keys().copied().collect()
2539 }
2540
2541 pub fn buffer(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
2542 self.buffers
2543 .borrow()
2544 .get(&buffer_id)
2545 .map(|state| state.buffer.clone())
2546 }
2547
2548 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2549 self.point_to_buffer_offset(point, cx)
2550 .and_then(|(buffer, offset)| buffer.read(cx).language_at(offset))
2551 }
2552
2553 pub fn language_settings<'a>(&'a self, cx: &'a App) -> Cow<'a, LanguageSettings> {
2554 let buffer_id = self
2555 .snapshot
2556 .borrow()
2557 .excerpts
2558 .first()
2559 .map(|excerpt| excerpt.buffer.remote_id());
2560 buffer_id
2561 .and_then(|buffer_id| self.buffer(buffer_id))
2562 .map(|buffer| {
2563 let buffer = buffer.read(cx);
2564 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
2565 })
2566 .unwrap_or_else(move || self.language_settings_at(0, cx))
2567 }
2568
2569 pub fn language_settings_at<'a, T: ToOffset>(
2570 &'a self,
2571 point: T,
2572 cx: &'a App,
2573 ) -> Cow<'a, LanguageSettings> {
2574 let mut language = None;
2575 let mut file = None;
2576 if let Some((buffer, offset)) = self.point_to_buffer_offset(point, cx) {
2577 let buffer = buffer.read(cx);
2578 language = buffer.language_at(offset);
2579 file = buffer.file();
2580 }
2581 language_settings(language.map(|l| l.name()), file, cx)
2582 }
2583
2584 pub fn for_each_buffer(&self, mut f: impl FnMut(&Entity<Buffer>)) {
2585 self.buffers
2586 .borrow()
2587 .values()
2588 .for_each(|state| f(&state.buffer))
2589 }
2590
2591 pub fn title<'a>(&'a self, cx: &'a App) -> Cow<'a, str> {
2592 if let Some(title) = self.title.as_ref() {
2593 return title.into();
2594 }
2595
2596 if let Some(buffer) = self.as_singleton() {
2597 let buffer = buffer.read(cx);
2598
2599 if let Some(file) = buffer.file() {
2600 return file.file_name(cx).into();
2601 }
2602
2603 if let Some(title) = self.buffer_content_title(buffer) {
2604 return title;
2605 }
2606 };
2607
2608 "untitled".into()
2609 }
2610
2611 fn buffer_content_title(&self, buffer: &Buffer) -> Option<Cow<'_, str>> {
2612 let mut is_leading_whitespace = true;
2613 let mut count = 0;
2614 let mut prev_was_space = false;
2615 let mut title = String::new();
2616
2617 for ch in buffer.snapshot().chars() {
2618 if is_leading_whitespace && ch.is_whitespace() {
2619 continue;
2620 }
2621
2622 is_leading_whitespace = false;
2623
2624 if ch == '\n' || count >= 40 {
2625 break;
2626 }
2627
2628 if ch.is_whitespace() {
2629 if !prev_was_space {
2630 title.push(' ');
2631 count += 1;
2632 prev_was_space = true;
2633 }
2634 } else {
2635 title.push(ch);
2636 count += 1;
2637 prev_was_space = false;
2638 }
2639 }
2640
2641 let title = title.trim_end().to_string();
2642
2643 if title.is_empty() {
2644 return None;
2645 }
2646
2647 Some(title.into())
2648 }
2649
2650 pub fn set_title(&mut self, title: String, cx: &mut Context<Self>) {
2651 self.title = Some(title);
2652 cx.notify();
2653 }
2654
2655 /// Preserve preview tabs containing this multibuffer until additional edits occur.
2656 pub fn refresh_preview(&self, cx: &mut Context<Self>) {
2657 for buffer_state in self.buffers.borrow().values() {
2658 buffer_state
2659 .buffer
2660 .update(cx, |buffer, _cx| buffer.refresh_preview());
2661 }
2662 }
2663
2664 /// Whether we should preserve the preview status of a tab containing this multi-buffer.
2665 pub fn preserve_preview(&self, cx: &App) -> bool {
2666 self.buffers
2667 .borrow()
2668 .values()
2669 .all(|state| state.buffer.read(cx).preserve_preview())
2670 }
2671
2672 #[cfg(any(test, feature = "test-support"))]
2673 pub fn is_parsing(&self, cx: &App) -> bool {
2674 self.as_singleton().unwrap().read(cx).is_parsing()
2675 }
2676
2677 pub fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut Context<Self>) {
2678 let buffer_id = diff.read(cx).buffer_id;
2679 self.buffer_diff_changed(diff.clone(), text::Anchor::MIN..text::Anchor::MAX, cx);
2680 self.diffs.insert(buffer_id, DiffState::new(diff, cx));
2681 }
2682
2683 pub fn diff_for(&self, buffer_id: BufferId) -> Option<Entity<BufferDiff>> {
2684 self.diffs.get(&buffer_id).map(|state| state.diff.clone())
2685 }
2686
2687 pub fn expand_diff_hunks(&mut self, ranges: Vec<Range<Anchor>>, cx: &mut Context<Self>) {
2688 self.expand_or_collapse_diff_hunks(ranges, true, cx);
2689 }
2690
2691 pub fn collapse_diff_hunks(&mut self, ranges: Vec<Range<Anchor>>, cx: &mut Context<Self>) {
2692 self.expand_or_collapse_diff_hunks(ranges, false, cx);
2693 }
2694
2695 pub fn set_all_diff_hunks_expanded(&mut self, cx: &mut Context<Self>) {
2696 self.snapshot.borrow_mut().all_diff_hunks_expanded = true;
2697 self.expand_or_collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], true, cx);
2698 }
2699
2700 pub fn all_diff_hunks_expanded(&self) -> bool {
2701 self.snapshot.borrow().all_diff_hunks_expanded
2702 }
2703
2704 pub fn set_all_diff_hunks_collapsed(&mut self, cx: &mut Context<Self>) {
2705 self.snapshot.borrow_mut().all_diff_hunks_expanded = false;
2706 self.expand_or_collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], false, cx);
2707 }
2708
2709 pub fn has_multiple_hunks(&self, cx: &App) -> bool {
2710 self.read(cx)
2711 .diff_hunks_in_range(Anchor::min()..Anchor::max())
2712 .nth(1)
2713 .is_some()
2714 }
2715
2716 pub fn single_hunk_is_expanded(&self, range: Range<Anchor>, cx: &App) -> bool {
2717 let snapshot = self.read(cx);
2718 let mut cursor = snapshot.diff_transforms.cursor::<usize>(());
2719 let offset_range = range.to_offset(&snapshot);
2720 cursor.seek(&offset_range.start, Bias::Left);
2721 while let Some(item) = cursor.item() {
2722 if *cursor.start() >= offset_range.end && *cursor.start() > offset_range.start {
2723 break;
2724 }
2725 if item.hunk_info().is_some() {
2726 return true;
2727 }
2728 cursor.next();
2729 }
2730 false
2731 }
2732
2733 pub fn has_expanded_diff_hunks_in_ranges(&self, ranges: &[Range<Anchor>], cx: &App) -> bool {
2734 let snapshot = self.read(cx);
2735 let mut cursor = snapshot.diff_transforms.cursor::<usize>(());
2736 for range in ranges {
2737 let range = range.to_point(&snapshot);
2738 let start = snapshot.point_to_offset(Point::new(range.start.row, 0));
2739 let end = snapshot.point_to_offset(Point::new(range.end.row + 1, 0));
2740 let start = start.saturating_sub(1);
2741 let end = snapshot.len().min(end + 1);
2742 cursor.seek(&start, Bias::Right);
2743 while let Some(item) = cursor.item() {
2744 if *cursor.start() >= end {
2745 break;
2746 }
2747 if item.hunk_info().is_some() {
2748 return true;
2749 }
2750 cursor.next();
2751 }
2752 }
2753 false
2754 }
2755
2756 pub fn expand_or_collapse_diff_hunks_inner(
2757 &mut self,
2758 ranges: impl IntoIterator<Item = (Range<Point>, ExcerptId)>,
2759 expand: bool,
2760 cx: &mut Context<Self>,
2761 ) {
2762 if self.snapshot.borrow().all_diff_hunks_expanded && !expand {
2763 return;
2764 }
2765 self.sync(cx);
2766 let mut snapshot = self.snapshot.borrow_mut();
2767 let mut excerpt_edits = Vec::new();
2768 let mut last_hunk_row = None;
2769 for (range, end_excerpt_id) in ranges {
2770 for diff_hunk in snapshot.diff_hunks_in_range(range) {
2771 if diff_hunk.excerpt_id.cmp(&end_excerpt_id, &snapshot).is_gt() {
2772 continue;
2773 }
2774 if last_hunk_row.is_some_and(|row| row >= diff_hunk.row_range.start) {
2775 continue;
2776 }
2777 let start = Anchor::in_buffer(
2778 diff_hunk.excerpt_id,
2779 diff_hunk.buffer_id,
2780 diff_hunk.buffer_range.start,
2781 );
2782 let end = Anchor::in_buffer(
2783 diff_hunk.excerpt_id,
2784 diff_hunk.buffer_id,
2785 diff_hunk.buffer_range.end,
2786 );
2787 let start = snapshot.excerpt_offset_for_anchor(&start);
2788 let end = snapshot.excerpt_offset_for_anchor(&end);
2789 last_hunk_row = Some(diff_hunk.row_range.start);
2790 excerpt_edits.push(text::Edit {
2791 old: start..end,
2792 new: start..end,
2793 });
2794 }
2795 }
2796
2797 self.sync_diff_transforms(
2798 &mut snapshot,
2799 excerpt_edits,
2800 DiffChangeKind::ExpandOrCollapseHunks { expand },
2801 );
2802 cx.emit(Event::DiffHunksToggled);
2803 cx.emit(Event::Edited {
2804 singleton_buffer_edited: false,
2805 edited_buffer: None,
2806 });
2807 }
2808
2809 pub fn expand_or_collapse_diff_hunks(
2810 &mut self,
2811 ranges: Vec<Range<Anchor>>,
2812 expand: bool,
2813 cx: &mut Context<Self>,
2814 ) {
2815 let snapshot = self.snapshot.borrow().clone();
2816 let ranges = ranges.iter().map(move |range| {
2817 let end_excerpt_id = range.end.excerpt_id;
2818 let range = range.to_point(&snapshot);
2819 let mut peek_end = range.end;
2820 if range.end.row < snapshot.max_row().0 {
2821 peek_end = Point::new(range.end.row + 1, 0);
2822 };
2823 (range.start..peek_end, end_excerpt_id)
2824 });
2825 self.expand_or_collapse_diff_hunks_inner(ranges, expand, cx);
2826 }
2827
2828 pub fn resize_excerpt(
2829 &mut self,
2830 id: ExcerptId,
2831 range: Range<text::Anchor>,
2832 cx: &mut Context<Self>,
2833 ) {
2834 self.sync(cx);
2835
2836 let mut snapshot = self.snapshot.borrow_mut();
2837 let locator = snapshot.excerpt_locator_for_id(id);
2838 let mut new_excerpts = SumTree::default();
2839 let mut cursor = snapshot
2840 .excerpts
2841 .cursor::<Dimensions<Option<&Locator>, ExcerptOffset>>(());
2842 let mut edits = Vec::<Edit<ExcerptOffset>>::new();
2843
2844 let prefix = cursor.slice(&Some(locator), Bias::Left);
2845 new_excerpts.append(prefix, ());
2846
2847 let mut excerpt = cursor.item().unwrap().clone();
2848 let old_text_len = ExcerptOffset::new(excerpt.text_summary.len);
2849
2850 excerpt.range.context.start = range.start;
2851 excerpt.range.context.end = range.end;
2852 excerpt.max_buffer_row = range.end.to_point(&excerpt.buffer).row;
2853
2854 excerpt.text_summary = excerpt
2855 .buffer
2856 .text_summary_for_range(excerpt.range.context.clone());
2857
2858 let new_start_offset = ExcerptOffset::new(new_excerpts.summary().text.len);
2859 let old_start_offset = cursor.start().1;
2860 let new_text_len = ExcerptOffset::new(excerpt.text_summary.len);
2861 let edit = Edit {
2862 old: old_start_offset..old_start_offset + old_text_len,
2863 new: new_start_offset..new_start_offset + new_text_len,
2864 };
2865
2866 if let Some(last_edit) = edits.last_mut() {
2867 if last_edit.old.end == edit.old.start {
2868 last_edit.old.end = edit.old.end;
2869 last_edit.new.end = edit.new.end;
2870 } else {
2871 edits.push(edit);
2872 }
2873 } else {
2874 edits.push(edit);
2875 }
2876
2877 new_excerpts.push(excerpt, ());
2878
2879 cursor.next();
2880
2881 new_excerpts.append(cursor.suffix(), ());
2882
2883 drop(cursor);
2884 snapshot.excerpts = new_excerpts;
2885
2886 self.sync_diff_transforms(&mut snapshot, edits, DiffChangeKind::BufferEdited);
2887 cx.emit(Event::Edited {
2888 singleton_buffer_edited: false,
2889 edited_buffer: None,
2890 });
2891 cx.emit(Event::ExcerptsExpanded { ids: vec![id] });
2892 cx.notify();
2893 }
2894
2895 pub fn expand_excerpts(
2896 &mut self,
2897 ids: impl IntoIterator<Item = ExcerptId>,
2898 line_count: u32,
2899 direction: ExpandExcerptDirection,
2900 cx: &mut Context<Self>,
2901 ) {
2902 if line_count == 0 {
2903 return;
2904 }
2905 self.sync(cx);
2906 if !self.excerpts_by_path.is_empty() {
2907 self.expand_excerpts_with_paths(ids, line_count, direction, cx);
2908 return;
2909 }
2910 let mut snapshot = self.snapshot.borrow_mut();
2911
2912 let ids = ids.into_iter().collect::<Vec<_>>();
2913 let locators = snapshot.excerpt_locators_for_ids(ids.iter().copied());
2914 let mut new_excerpts = SumTree::default();
2915 let mut cursor = snapshot
2916 .excerpts
2917 .cursor::<Dimensions<Option<&Locator>, ExcerptOffset>>(());
2918 let mut edits = Vec::<Edit<ExcerptOffset>>::new();
2919
2920 for locator in &locators {
2921 let prefix = cursor.slice(&Some(locator), Bias::Left);
2922 new_excerpts.append(prefix, ());
2923
2924 let mut excerpt = cursor.item().unwrap().clone();
2925 let old_text_len = ExcerptOffset::new(excerpt.text_summary.len);
2926
2927 let up_line_count = if direction.should_expand_up() {
2928 line_count
2929 } else {
2930 0
2931 };
2932
2933 let start_row = excerpt
2934 .range
2935 .context
2936 .start
2937 .to_point(&excerpt.buffer)
2938 .row
2939 .saturating_sub(up_line_count);
2940 let start_point = Point::new(start_row, 0);
2941 excerpt.range.context.start = excerpt.buffer.anchor_before(start_point);
2942
2943 let down_line_count = if direction.should_expand_down() {
2944 line_count
2945 } else {
2946 0
2947 };
2948
2949 let mut end_point = excerpt.buffer.clip_point(
2950 excerpt.range.context.end.to_point(&excerpt.buffer)
2951 + Point::new(down_line_count, 0),
2952 Bias::Left,
2953 );
2954 end_point.column = excerpt.buffer.line_len(end_point.row);
2955 excerpt.range.context.end = excerpt.buffer.anchor_after(end_point);
2956 excerpt.max_buffer_row = end_point.row;
2957
2958 excerpt.text_summary = excerpt
2959 .buffer
2960 .text_summary_for_range(excerpt.range.context.clone());
2961
2962 let new_start_offset = ExcerptOffset::new(new_excerpts.summary().text.len);
2963 let old_start_offset = cursor.start().1;
2964 let new_text_len = ExcerptOffset::new(excerpt.text_summary.len);
2965 let edit = Edit {
2966 old: old_start_offset..old_start_offset + old_text_len,
2967 new: new_start_offset..new_start_offset + new_text_len,
2968 };
2969
2970 if let Some(last_edit) = edits.last_mut() {
2971 if last_edit.old.end == edit.old.start {
2972 last_edit.old.end = edit.old.end;
2973 last_edit.new.end = edit.new.end;
2974 } else {
2975 edits.push(edit);
2976 }
2977 } else {
2978 edits.push(edit);
2979 }
2980
2981 new_excerpts.push(excerpt, ());
2982
2983 cursor.next();
2984 }
2985
2986 new_excerpts.append(cursor.suffix(), ());
2987
2988 drop(cursor);
2989 snapshot.excerpts = new_excerpts;
2990
2991 self.sync_diff_transforms(&mut snapshot, edits, DiffChangeKind::BufferEdited);
2992 cx.emit(Event::Edited {
2993 singleton_buffer_edited: false,
2994 edited_buffer: None,
2995 });
2996 cx.emit(Event::ExcerptsExpanded { ids });
2997 cx.notify();
2998 }
2999
3000 fn sync(&self, cx: &App) {
3001 let changed = self.buffer_changed_since_sync.replace(false);
3002 if !changed {
3003 return;
3004 }
3005
3006 let mut snapshot = self.snapshot.borrow_mut();
3007 let mut excerpts_to_edit = Vec::new();
3008 let mut non_text_state_updated = false;
3009 let mut is_dirty = false;
3010 let mut has_deleted_file = false;
3011 let mut has_conflict = false;
3012 let mut edited = false;
3013 let mut buffers = self.buffers.borrow_mut();
3014 for buffer_state in buffers.values_mut() {
3015 let buffer = buffer_state.buffer.read(cx);
3016 let version = buffer.version();
3017 let non_text_state_update_count = buffer.non_text_state_update_count();
3018
3019 let buffer_edited = version.changed_since(&buffer_state.last_version);
3020 let buffer_non_text_state_updated =
3021 non_text_state_update_count > buffer_state.last_non_text_state_update_count;
3022 if buffer_edited || buffer_non_text_state_updated {
3023 buffer_state.last_version = version;
3024 buffer_state.last_non_text_state_update_count = non_text_state_update_count;
3025 excerpts_to_edit.extend(
3026 buffer_state
3027 .excerpts
3028 .iter()
3029 .map(|locator| (locator, buffer_state.buffer.clone(), buffer_edited)),
3030 );
3031 }
3032
3033 edited |= buffer_edited;
3034 non_text_state_updated |= buffer_non_text_state_updated;
3035 is_dirty |= buffer.is_dirty();
3036 has_deleted_file |= buffer
3037 .file()
3038 .is_some_and(|file| file.disk_state() == DiskState::Deleted);
3039 has_conflict |= buffer.has_conflict();
3040 }
3041 if edited {
3042 snapshot.edit_count += 1;
3043 }
3044 if non_text_state_updated {
3045 snapshot.non_text_state_update_count += 1;
3046 }
3047 snapshot.is_dirty = is_dirty;
3048 snapshot.has_deleted_file = has_deleted_file;
3049 snapshot.has_conflict = has_conflict;
3050
3051 for (id, diff) in self.diffs.iter() {
3052 if snapshot.diffs.get(id).is_none() {
3053 snapshot.diffs.insert(*id, diff.diff.read(cx).snapshot(cx));
3054 }
3055 }
3056
3057 excerpts_to_edit.sort_unstable_by_key(|(locator, _, _)| *locator);
3058
3059 let mut edits = Vec::new();
3060 let mut new_excerpts = SumTree::default();
3061 let mut cursor = snapshot
3062 .excerpts
3063 .cursor::<Dimensions<Option<&Locator>, ExcerptOffset>>(());
3064
3065 for (locator, buffer, buffer_edited) in excerpts_to_edit {
3066 new_excerpts.append(cursor.slice(&Some(locator), Bias::Left), ());
3067 let old_excerpt = cursor.item().unwrap();
3068 let buffer = buffer.read(cx);
3069 let buffer_id = buffer.remote_id();
3070
3071 let mut new_excerpt;
3072 if buffer_edited {
3073 edits.extend(
3074 buffer
3075 .edits_since_in_range::<usize>(
3076 old_excerpt.buffer.version(),
3077 old_excerpt.range.context.clone(),
3078 )
3079 .map(|edit| {
3080 let excerpt_old_start = cursor.start().1;
3081 let excerpt_new_start =
3082 ExcerptOffset::new(new_excerpts.summary().text.len);
3083 let old_start = excerpt_old_start + ExcerptOffset::new(edit.old.start);
3084 let old_end = excerpt_old_start + ExcerptOffset::new(edit.old.end);
3085 let new_start = excerpt_new_start + ExcerptOffset::new(edit.new.start);
3086 let new_end = excerpt_new_start + ExcerptOffset::new(edit.new.end);
3087 Edit {
3088 old: old_start..old_end,
3089 new: new_start..new_end,
3090 }
3091 }),
3092 );
3093
3094 new_excerpt = Excerpt::new(
3095 old_excerpt.id,
3096 locator.clone(),
3097 buffer_id,
3098 buffer.snapshot(),
3099 old_excerpt.range.clone(),
3100 old_excerpt.has_trailing_newline,
3101 );
3102 } else {
3103 new_excerpt = old_excerpt.clone();
3104 new_excerpt.buffer = buffer.snapshot();
3105 }
3106
3107 new_excerpts.push(new_excerpt, ());
3108 cursor.next();
3109 }
3110 new_excerpts.append(cursor.suffix(), ());
3111
3112 drop(cursor);
3113 snapshot.excerpts = new_excerpts;
3114
3115 self.sync_diff_transforms(&mut snapshot, edits, DiffChangeKind::BufferEdited);
3116 }
3117
3118 fn sync_diff_transforms(
3119 &self,
3120 snapshot: &mut MultiBufferSnapshot,
3121 excerpt_edits: Vec<text::Edit<ExcerptOffset>>,
3122 change_kind: DiffChangeKind,
3123 ) {
3124 if excerpt_edits.is_empty() {
3125 return;
3126 }
3127
3128 let mut excerpts = snapshot.excerpts.cursor::<ExcerptOffset>(());
3129 let mut old_diff_transforms = snapshot
3130 .diff_transforms
3131 .cursor::<Dimensions<ExcerptOffset, usize>>(());
3132 let mut new_diff_transforms = SumTree::default();
3133 let mut old_expanded_hunks = HashSet::default();
3134 let mut output_edits = Vec::new();
3135 let mut output_delta = 0_isize;
3136 let mut at_transform_boundary = true;
3137 let mut end_of_current_insert = None;
3138
3139 let mut excerpt_edits = excerpt_edits.into_iter().peekable();
3140 while let Some(edit) = excerpt_edits.next() {
3141 excerpts.seek_forward(&edit.new.start, Bias::Right);
3142 if excerpts.item().is_none() && *excerpts.start() == edit.new.start {
3143 excerpts.prev();
3144 }
3145
3146 // Keep any transforms that are before the edit.
3147 if at_transform_boundary {
3148 at_transform_boundary = false;
3149 let transforms_before_edit = old_diff_transforms.slice(&edit.old.start, Bias::Left);
3150 self.append_diff_transforms(&mut new_diff_transforms, transforms_before_edit);
3151 if let Some(transform) = old_diff_transforms.item()
3152 && old_diff_transforms.end().0 == edit.old.start
3153 && old_diff_transforms.start().0 < edit.old.start
3154 {
3155 self.push_diff_transform(&mut new_diff_transforms, transform.clone());
3156 old_diff_transforms.next();
3157 }
3158 }
3159
3160 // Compute the start of the edit in output coordinates.
3161 let edit_start_overshoot = (edit.old.start - old_diff_transforms.start().0).value;
3162 let edit_old_start = old_diff_transforms.start().1 + edit_start_overshoot;
3163 let edit_new_start = (edit_old_start as isize + output_delta) as usize;
3164
3165 let changed_diff_hunks = self.recompute_diff_transforms_for_edit(
3166 &edit,
3167 &mut excerpts,
3168 &mut old_diff_transforms,
3169 &mut new_diff_transforms,
3170 &mut end_of_current_insert,
3171 &mut old_expanded_hunks,
3172 snapshot,
3173 change_kind,
3174 );
3175
3176 // Compute the end of the edit in output coordinates.
3177 let edit_old_end_overshoot = edit.old.end - old_diff_transforms.start().0;
3178 let edit_new_end_overshoot = edit.new.end - new_diff_transforms.summary().excerpt_len();
3179 let edit_old_end = old_diff_transforms.start().1 + edit_old_end_overshoot.value;
3180 let edit_new_end =
3181 new_diff_transforms.summary().output.len + edit_new_end_overshoot.value;
3182 let output_edit = Edit {
3183 old: edit_old_start..edit_old_end,
3184 new: edit_new_start..edit_new_end,
3185 };
3186
3187 output_delta += (output_edit.new.end - output_edit.new.start) as isize;
3188 output_delta -= (output_edit.old.end - output_edit.old.start) as isize;
3189 if changed_diff_hunks || matches!(change_kind, DiffChangeKind::BufferEdited) {
3190 output_edits.push(output_edit);
3191 }
3192
3193 // If this is the last edit that intersects the current diff transform,
3194 // then recreate the content up to the end of this transform, to prepare
3195 // for reusing additional slices of the old transforms.
3196 if excerpt_edits
3197 .peek()
3198 .is_none_or(|next_edit| next_edit.old.start >= old_diff_transforms.end().0)
3199 {
3200 let keep_next_old_transform = (old_diff_transforms.start().0 >= edit.old.end)
3201 && match old_diff_transforms.item() {
3202 Some(DiffTransform::BufferContent {
3203 inserted_hunk_info: Some(hunk),
3204 ..
3205 }) => excerpts.item().is_some_and(|excerpt| {
3206 hunk.hunk_start_anchor.is_valid(&excerpt.buffer)
3207 }),
3208 _ => true,
3209 };
3210
3211 let mut excerpt_offset = edit.new.end;
3212 if !keep_next_old_transform {
3213 excerpt_offset += old_diff_transforms.end().0 - edit.old.end;
3214 old_diff_transforms.next();
3215 }
3216
3217 old_expanded_hunks.clear();
3218 self.push_buffer_content_transform(
3219 snapshot,
3220 &mut new_diff_transforms,
3221 excerpt_offset,
3222 end_of_current_insert,
3223 );
3224 at_transform_boundary = true;
3225 }
3226 }
3227
3228 // Keep any transforms that are after the last edit.
3229 self.append_diff_transforms(&mut new_diff_transforms, old_diff_transforms.suffix());
3230
3231 // Ensure there's always at least one buffer content transform.
3232 if new_diff_transforms.is_empty() {
3233 new_diff_transforms.push(
3234 DiffTransform::BufferContent {
3235 summary: Default::default(),
3236 inserted_hunk_info: None,
3237 },
3238 (),
3239 );
3240 }
3241
3242 self.subscriptions.publish(output_edits);
3243 drop(old_diff_transforms);
3244 drop(excerpts);
3245 snapshot.diff_transforms = new_diff_transforms;
3246 snapshot.edit_count += 1;
3247
3248 #[cfg(any(test, feature = "test-support"))]
3249 snapshot.check_invariants();
3250 }
3251
3252 fn recompute_diff_transforms_for_edit(
3253 &self,
3254 edit: &Edit<TypedOffset<Excerpt>>,
3255 excerpts: &mut Cursor<Excerpt, TypedOffset<Excerpt>>,
3256 old_diff_transforms: &mut Cursor<DiffTransform, Dimensions<TypedOffset<Excerpt>, usize>>,
3257 new_diff_transforms: &mut SumTree<DiffTransform>,
3258 end_of_current_insert: &mut Option<(TypedOffset<Excerpt>, DiffTransformHunkInfo)>,
3259 old_expanded_hunks: &mut HashSet<DiffTransformHunkInfo>,
3260 snapshot: &MultiBufferSnapshot,
3261 change_kind: DiffChangeKind,
3262 ) -> bool {
3263 log::trace!(
3264 "recomputing diff transform for edit {:?} => {:?}",
3265 edit.old.start.value..edit.old.end.value,
3266 edit.new.start.value..edit.new.end.value
3267 );
3268
3269 // Record which hunks were previously expanded.
3270 while let Some(item) = old_diff_transforms.item() {
3271 if let Some(hunk_info) = item.hunk_info() {
3272 log::trace!(
3273 "previously expanded hunk at {}",
3274 old_diff_transforms.start().0
3275 );
3276 old_expanded_hunks.insert(hunk_info);
3277 }
3278 if old_diff_transforms.end().0 > edit.old.end {
3279 break;
3280 }
3281 old_diff_transforms.next();
3282 }
3283
3284 // Avoid querying diff hunks if there's no possibility of hunks being expanded.
3285 let all_diff_hunks_expanded = snapshot.all_diff_hunks_expanded;
3286 if old_expanded_hunks.is_empty()
3287 && change_kind == DiffChangeKind::BufferEdited
3288 && !all_diff_hunks_expanded
3289 {
3290 return false;
3291 }
3292
3293 // Visit each excerpt that intersects the edit.
3294 let mut did_expand_hunks = false;
3295 while let Some(excerpt) = excerpts.item() {
3296 // Recompute the expanded hunks in the portion of the excerpt that
3297 // intersects the edit.
3298 if let Some(diff) = snapshot.diffs.get(&excerpt.buffer_id) {
3299 let buffer = &excerpt.buffer;
3300 let excerpt_start = *excerpts.start();
3301 let excerpt_end = excerpt_start + ExcerptOffset::new(excerpt.text_summary.len);
3302 let excerpt_buffer_start = excerpt.range.context.start.to_offset(buffer);
3303 let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
3304 let edit_buffer_start =
3305 excerpt_buffer_start + edit.new.start.value.saturating_sub(excerpt_start.value);
3306 let edit_buffer_end =
3307 excerpt_buffer_start + edit.new.end.value.saturating_sub(excerpt_start.value);
3308 let edit_buffer_end = edit_buffer_end.min(excerpt_buffer_end);
3309 let edit_anchor_range =
3310 buffer.anchor_before(edit_buffer_start)..buffer.anchor_after(edit_buffer_end);
3311
3312 for hunk in diff.hunks_intersecting_range(edit_anchor_range, buffer) {
3313 if hunk.is_created_file() && !all_diff_hunks_expanded {
3314 continue;
3315 }
3316
3317 let hunk_buffer_range = hunk.buffer_range.to_offset(buffer);
3318 if hunk_buffer_range.start < excerpt_buffer_start {
3319 log::trace!("skipping hunk that starts before excerpt");
3320 continue;
3321 }
3322
3323 let hunk_info = DiffTransformHunkInfo {
3324 excerpt_id: excerpt.id,
3325 hunk_start_anchor: hunk.buffer_range.start,
3326 hunk_secondary_status: hunk.secondary_status,
3327 };
3328
3329 let hunk_excerpt_start = excerpt_start
3330 + ExcerptOffset::new(
3331 hunk_buffer_range.start.saturating_sub(excerpt_buffer_start),
3332 );
3333 let hunk_excerpt_end = excerpt_end.min(
3334 excerpt_start
3335 + ExcerptOffset::new(hunk_buffer_range.end - excerpt_buffer_start),
3336 );
3337
3338 self.push_buffer_content_transform(
3339 snapshot,
3340 new_diff_transforms,
3341 hunk_excerpt_start,
3342 *end_of_current_insert,
3343 );
3344
3345 // For every existing hunk, determine if it was previously expanded
3346 // and if it should currently be expanded.
3347 let was_previously_expanded = old_expanded_hunks.contains(&hunk_info);
3348 let should_expand_hunk = match &change_kind {
3349 DiffChangeKind::DiffUpdated { base_changed: true } => {
3350 was_previously_expanded || all_diff_hunks_expanded
3351 }
3352 DiffChangeKind::ExpandOrCollapseHunks { expand } => {
3353 let intersects = hunk_buffer_range.is_empty()
3354 || hunk_buffer_range.end > edit_buffer_start;
3355 if *expand {
3356 intersects || was_previously_expanded || all_diff_hunks_expanded
3357 } else {
3358 !intersects && (was_previously_expanded || all_diff_hunks_expanded)
3359 }
3360 }
3361 _ => was_previously_expanded || all_diff_hunks_expanded,
3362 };
3363
3364 if should_expand_hunk {
3365 did_expand_hunks = true;
3366 log::trace!(
3367 "expanding hunk {:?}, excerpt:{:?}",
3368 hunk_excerpt_start.value..hunk_excerpt_end.value,
3369 excerpt.id
3370 );
3371
3372 if !hunk.diff_base_byte_range.is_empty()
3373 && hunk_buffer_range.start >= edit_buffer_start
3374 && hunk_buffer_range.start <= excerpt_buffer_end
3375 {
3376 let base_text = diff.base_text();
3377 let mut text_cursor =
3378 base_text.as_rope().cursor(hunk.diff_base_byte_range.start);
3379 let mut base_text_summary =
3380 text_cursor.summary::<TextSummary>(hunk.diff_base_byte_range.end);
3381
3382 let mut has_trailing_newline = false;
3383 if base_text_summary.last_line_chars > 0 {
3384 base_text_summary += TextSummary::newline();
3385 has_trailing_newline = true;
3386 }
3387
3388 new_diff_transforms.push(
3389 DiffTransform::DeletedHunk {
3390 base_text_byte_range: hunk.diff_base_byte_range.clone(),
3391 summary: base_text_summary,
3392 buffer_id: excerpt.buffer_id,
3393 hunk_info,
3394 has_trailing_newline,
3395 },
3396 (),
3397 );
3398 }
3399
3400 if !hunk_buffer_range.is_empty() {
3401 *end_of_current_insert =
3402 Some((hunk_excerpt_end.min(excerpt_end), hunk_info));
3403 }
3404 }
3405 }
3406 }
3407
3408 if excerpts.end() <= edit.new.end {
3409 excerpts.next();
3410 } else {
3411 break;
3412 }
3413 }
3414
3415 did_expand_hunks || !old_expanded_hunks.is_empty()
3416 }
3417
3418 fn append_diff_transforms(
3419 &self,
3420 new_transforms: &mut SumTree<DiffTransform>,
3421 subtree: SumTree<DiffTransform>,
3422 ) {
3423 if let Some(DiffTransform::BufferContent {
3424 inserted_hunk_info,
3425 summary,
3426 }) = subtree.first()
3427 && self.extend_last_buffer_content_transform(
3428 new_transforms,
3429 *inserted_hunk_info,
3430 *summary,
3431 )
3432 {
3433 let mut cursor = subtree.cursor::<()>(());
3434 cursor.next();
3435 cursor.next();
3436 new_transforms.append(cursor.suffix(), ());
3437 return;
3438 }
3439 new_transforms.append(subtree, ());
3440 }
3441
3442 fn push_diff_transform(
3443 &self,
3444 new_transforms: &mut SumTree<DiffTransform>,
3445 transform: DiffTransform,
3446 ) {
3447 if let DiffTransform::BufferContent {
3448 inserted_hunk_info: inserted_hunk_anchor,
3449 summary,
3450 } = transform
3451 && self.extend_last_buffer_content_transform(
3452 new_transforms,
3453 inserted_hunk_anchor,
3454 summary,
3455 )
3456 {
3457 return;
3458 }
3459 new_transforms.push(transform, ());
3460 }
3461
3462 fn push_buffer_content_transform(
3463 &self,
3464 old_snapshot: &MultiBufferSnapshot,
3465 new_transforms: &mut SumTree<DiffTransform>,
3466 end_offset: ExcerptOffset,
3467 current_inserted_hunk: Option<(ExcerptOffset, DiffTransformHunkInfo)>,
3468 ) {
3469 let inserted_region = current_inserted_hunk.map(|(insertion_end_offset, hunk_info)| {
3470 (end_offset.min(insertion_end_offset), Some(hunk_info))
3471 });
3472 let unchanged_region = [(end_offset, None)];
3473
3474 for (end_offset, inserted_hunk_info) in inserted_region.into_iter().chain(unchanged_region)
3475 {
3476 let start_offset = new_transforms.summary().excerpt_len();
3477 if end_offset <= start_offset {
3478 continue;
3479 }
3480 let summary_to_add = old_snapshot
3481 .text_summary_for_excerpt_offset_range::<TextSummary>(start_offset..end_offset);
3482
3483 if !self.extend_last_buffer_content_transform(
3484 new_transforms,
3485 inserted_hunk_info,
3486 summary_to_add,
3487 ) {
3488 new_transforms.push(
3489 DiffTransform::BufferContent {
3490 summary: summary_to_add,
3491 inserted_hunk_info,
3492 },
3493 (),
3494 )
3495 }
3496 }
3497 }
3498
3499 fn extend_last_buffer_content_transform(
3500 &self,
3501 new_transforms: &mut SumTree<DiffTransform>,
3502 new_inserted_hunk_info: Option<DiffTransformHunkInfo>,
3503 summary_to_add: TextSummary,
3504 ) -> bool {
3505 let mut did_extend = false;
3506 new_transforms.update_last(
3507 |last_transform| {
3508 if let DiffTransform::BufferContent {
3509 summary,
3510 inserted_hunk_info: inserted_hunk_anchor,
3511 } = last_transform
3512 && *inserted_hunk_anchor == new_inserted_hunk_info
3513 {
3514 *summary += summary_to_add;
3515 did_extend = true;
3516 }
3517 },
3518 (),
3519 );
3520 did_extend
3521 }
3522}
3523
3524fn build_excerpt_ranges(
3525 ranges: impl IntoIterator<Item = Range<Point>>,
3526 context_line_count: u32,
3527 buffer_snapshot: &BufferSnapshot,
3528) -> Vec<ExcerptRange<Point>> {
3529 ranges
3530 .into_iter()
3531 .map(|range| {
3532 let start_row = range.start.row.saturating_sub(context_line_count);
3533 let start = Point::new(start_row, 0);
3534 let end_row = (range.end.row + context_line_count).min(buffer_snapshot.max_point().row);
3535 let end = Point::new(end_row, buffer_snapshot.line_len(end_row));
3536 ExcerptRange {
3537 context: start..end,
3538 primary: range,
3539 }
3540 })
3541 .collect()
3542}
3543
3544#[cfg(any(test, feature = "test-support"))]
3545impl MultiBuffer {
3546 pub fn build_simple(text: &str, cx: &mut gpui::App) -> Entity<Self> {
3547 let buffer = cx.new(|cx| Buffer::local(text, cx));
3548 cx.new(|cx| Self::singleton(buffer, cx))
3549 }
3550
3551 pub fn build_multi<const COUNT: usize>(
3552 excerpts: [(&str, Vec<Range<Point>>); COUNT],
3553 cx: &mut gpui::App,
3554 ) -> Entity<Self> {
3555 let multi = cx.new(|_| Self::new(Capability::ReadWrite));
3556 for (text, ranges) in excerpts {
3557 let buffer = cx.new(|cx| Buffer::local(text, cx));
3558 let excerpt_ranges = ranges.into_iter().map(ExcerptRange::new);
3559 multi.update(cx, |multi, cx| {
3560 multi.push_excerpts(buffer, excerpt_ranges, cx)
3561 });
3562 }
3563
3564 multi
3565 }
3566
3567 pub fn build_from_buffer(buffer: Entity<Buffer>, cx: &mut gpui::App) -> Entity<Self> {
3568 cx.new(|cx| Self::singleton(buffer, cx))
3569 }
3570
3571 pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::App) -> Entity<Self> {
3572 cx.new(|cx| {
3573 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3574 let mutation_count = rng.random_range(1..=5);
3575 multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
3576 multibuffer
3577 })
3578 }
3579
3580 pub fn randomly_edit(
3581 &mut self,
3582 rng: &mut impl rand::Rng,
3583 edit_count: usize,
3584 cx: &mut Context<Self>,
3585 ) {
3586 use util::RandomCharIter;
3587
3588 let snapshot = self.read(cx);
3589 let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
3590 let mut last_end = None;
3591 for _ in 0..edit_count {
3592 if last_end.is_some_and(|last_end| last_end >= snapshot.len()) {
3593 break;
3594 }
3595
3596 let new_start = last_end.map_or(0, |last_end| last_end + 1);
3597 let end =
3598 snapshot.clip_offset(rng.random_range(new_start..=snapshot.len()), Bias::Right);
3599 let start = snapshot.clip_offset(rng.random_range(new_start..=end), Bias::Right);
3600 last_end = Some(end);
3601
3602 let mut range = start..end;
3603 if rng.random_bool(0.2) {
3604 mem::swap(&mut range.start, &mut range.end);
3605 }
3606
3607 let new_text_len = rng.random_range(0..10);
3608 let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
3609
3610 edits.push((range, new_text.into()));
3611 }
3612 log::info!("mutating multi-buffer with {:?}", edits);
3613 drop(snapshot);
3614
3615 self.edit(edits, None, cx);
3616 }
3617
3618 pub fn randomly_edit_excerpts(
3619 &mut self,
3620 rng: &mut impl rand::Rng,
3621 mutation_count: usize,
3622 cx: &mut Context<Self>,
3623 ) {
3624 use rand::prelude::*;
3625 use std::env;
3626 use util::RandomCharIter;
3627
3628 let max_excerpts = env::var("MAX_EXCERPTS")
3629 .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
3630 .unwrap_or(5);
3631
3632 let mut buffers = Vec::new();
3633 for _ in 0..mutation_count {
3634 if rng.random_bool(0.05) {
3635 log::info!("Clearing multi-buffer");
3636 self.clear(cx);
3637 continue;
3638 } else if rng.random_bool(0.1) && !self.excerpt_ids().is_empty() {
3639 let ids = self.excerpt_ids();
3640 let mut excerpts = HashSet::default();
3641 for _ in 0..rng.random_range(0..ids.len()) {
3642 excerpts.extend(ids.choose(rng).copied());
3643 }
3644
3645 let line_count = rng.random_range(0..5);
3646
3647 log::info!("Expanding excerpts {excerpts:?} by {line_count} lines");
3648
3649 self.expand_excerpts(
3650 excerpts.iter().cloned(),
3651 line_count,
3652 ExpandExcerptDirection::UpAndDown,
3653 cx,
3654 );
3655 continue;
3656 }
3657
3658 let excerpt_ids = self.excerpt_ids();
3659 if excerpt_ids.is_empty() || (rng.random() && excerpt_ids.len() < max_excerpts) {
3660 let buffer_handle = if rng.random() || self.buffers.borrow().is_empty() {
3661 let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
3662 buffers.push(cx.new(|cx| Buffer::local(text, cx)));
3663 let buffer = buffers.last().unwrap().read(cx);
3664 log::info!(
3665 "Creating new buffer {} with text: {:?}",
3666 buffer.remote_id(),
3667 buffer.text()
3668 );
3669 buffers.last().unwrap().clone()
3670 } else {
3671 self.buffers
3672 .borrow()
3673 .values()
3674 .choose(rng)
3675 .unwrap()
3676 .buffer
3677 .clone()
3678 };
3679
3680 let buffer = buffer_handle.read(cx);
3681 let buffer_text = buffer.text();
3682 let ranges = (0..rng.random_range(0..5))
3683 .map(|_| {
3684 let end_ix =
3685 buffer.clip_offset(rng.random_range(0..=buffer.len()), Bias::Right);
3686 let start_ix = buffer.clip_offset(rng.random_range(0..=end_ix), Bias::Left);
3687 ExcerptRange::new(start_ix..end_ix)
3688 })
3689 .collect::<Vec<_>>();
3690 log::info!(
3691 "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
3692 buffer_handle.read(cx).remote_id(),
3693 ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
3694 ranges
3695 .iter()
3696 .map(|r| &buffer_text[r.context.clone()])
3697 .collect::<Vec<_>>()
3698 );
3699
3700 let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
3701 log::info!("Inserted with ids: {:?}", excerpt_id);
3702 } else {
3703 let remove_count = rng.random_range(1..=excerpt_ids.len());
3704 let mut excerpts_to_remove = excerpt_ids
3705 .choose_multiple(rng, remove_count)
3706 .cloned()
3707 .collect::<Vec<_>>();
3708 let snapshot = self.snapshot.borrow();
3709 excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
3710 drop(snapshot);
3711 log::info!("Removing excerpts {:?}", excerpts_to_remove);
3712 self.remove_excerpts(excerpts_to_remove, cx);
3713 }
3714 }
3715 }
3716
3717 pub fn randomly_mutate(
3718 &mut self,
3719 rng: &mut impl rand::Rng,
3720 mutation_count: usize,
3721 cx: &mut Context<Self>,
3722 ) {
3723 use rand::prelude::*;
3724
3725 if rng.random_bool(0.7) || self.singleton {
3726 let buffer = self
3727 .buffers
3728 .borrow()
3729 .values()
3730 .choose(rng)
3731 .map(|state| state.buffer.clone());
3732
3733 if let Some(buffer) = buffer {
3734 buffer.update(cx, |buffer, cx| {
3735 if rng.random() {
3736 buffer.randomly_edit(rng, mutation_count, cx);
3737 } else {
3738 buffer.randomly_undo_redo(rng, cx);
3739 }
3740 });
3741 } else {
3742 self.randomly_edit(rng, mutation_count, cx);
3743 }
3744 } else {
3745 self.randomly_edit_excerpts(rng, mutation_count, cx);
3746 }
3747
3748 self.check_invariants(cx);
3749 }
3750
3751 fn check_invariants(&self, cx: &App) {
3752 self.read(cx).check_invariants();
3753 }
3754}
3755
3756impl EventEmitter<Event> for MultiBuffer {}
3757
3758impl MultiBufferSnapshot {
3759 pub fn text(&self) -> String {
3760 self.chunks(0..self.len(), false)
3761 .map(|chunk| chunk.text)
3762 .collect()
3763 }
3764
3765 pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
3766 self.reversed_chunks_in_range(0..position.to_offset(self))
3767 .flat_map(|c| c.chars().rev())
3768 }
3769
3770 fn reversed_chunks_in_range(&self, range: Range<usize>) -> ReversedMultiBufferChunks<'_> {
3771 let mut cursor = self.cursor::<usize>();
3772 cursor.seek(&range.end);
3773 let current_chunks = cursor.region().as_ref().map(|region| {
3774 let start_overshoot = range.start.saturating_sub(region.range.start);
3775 let end_overshoot = range.end - region.range.start;
3776 let end = (region.buffer_range.start + end_overshoot).min(region.buffer_range.end);
3777 let start = region.buffer_range.start + start_overshoot;
3778 region.buffer.reversed_chunks_in_range(start..end)
3779 });
3780 ReversedMultiBufferChunks {
3781 cursor,
3782 current_chunks,
3783 start: range.start,
3784 offset: range.end,
3785 }
3786 }
3787
3788 pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
3789 let offset = position.to_offset(self);
3790 self.text_for_range(offset..self.len())
3791 .flat_map(|chunk| chunk.chars())
3792 }
3793
3794 pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
3795 self.chunks(range, false).map(|chunk| chunk.text)
3796 }
3797
3798 pub fn is_line_blank(&self, row: MultiBufferRow) -> bool {
3799 self.text_for_range(Point::new(row.0, 0)..Point::new(row.0, self.line_len(row)))
3800 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
3801 }
3802
3803 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
3804 where
3805 T: ToOffset,
3806 {
3807 let position = position.to_offset(self);
3808 position == self.clip_offset(position, Bias::Left)
3809 && self
3810 .bytes_in_range(position..self.len())
3811 .flatten()
3812 .copied()
3813 .take(needle.len())
3814 .eq(needle.bytes())
3815 }
3816
3817 pub fn diff_hunks(&self) -> impl Iterator<Item = MultiBufferDiffHunk> + '_ {
3818 self.diff_hunks_in_range(Anchor::min()..Anchor::max())
3819 }
3820
3821 pub fn diff_hunks_in_range<T: ToPoint>(
3822 &self,
3823 range: Range<T>,
3824 ) -> impl Iterator<Item = MultiBufferDiffHunk> + '_ {
3825 let query_range = range.start.to_point(self)..range.end.to_point(self);
3826 self.lift_buffer_metadata(query_range.clone(), move |buffer, buffer_range| {
3827 let diff = self.diffs.get(&buffer.remote_id())?;
3828 let buffer_start = buffer.anchor_before(buffer_range.start);
3829 let buffer_end = buffer.anchor_after(buffer_range.end);
3830 Some(
3831 diff.hunks_intersecting_range(buffer_start..buffer_end, buffer)
3832 .filter_map(|hunk| {
3833 if hunk.is_created_file() && !self.all_diff_hunks_expanded {
3834 return None;
3835 }
3836 Some((hunk.range.clone(), hunk))
3837 }),
3838 )
3839 })
3840 .filter_map(move |(range, hunk, excerpt)| {
3841 if range.start != range.end && range.end == query_range.start && !hunk.range.is_empty()
3842 {
3843 return None;
3844 }
3845 let end_row = if range.end.column == 0 {
3846 range.end.row
3847 } else {
3848 range.end.row + 1
3849 };
3850 Some(MultiBufferDiffHunk {
3851 row_range: MultiBufferRow(range.start.row)..MultiBufferRow(end_row),
3852 buffer_id: excerpt.buffer_id,
3853 excerpt_id: excerpt.id,
3854 buffer_range: hunk.buffer_range.clone(),
3855 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3856 secondary_status: hunk.secondary_status,
3857 })
3858 })
3859 }
3860
3861 pub fn excerpt_ids_for_range<T: ToOffset>(
3862 &self,
3863 range: Range<T>,
3864 ) -> impl Iterator<Item = ExcerptId> + '_ {
3865 let range = range.start.to_offset(self)..range.end.to_offset(self);
3866 let mut cursor = self.cursor::<usize>();
3867 cursor.seek(&range.start);
3868 std::iter::from_fn(move || {
3869 let region = cursor.region()?;
3870 if region.range.start >= range.end {
3871 return None;
3872 }
3873 cursor.next_excerpt();
3874 Some(region.excerpt.id)
3875 })
3876 }
3877
3878 pub fn buffer_ids_for_range<T: ToOffset>(
3879 &self,
3880 range: Range<T>,
3881 ) -> impl Iterator<Item = BufferId> + '_ {
3882 let range = range.start.to_offset(self)..range.end.to_offset(self);
3883 let mut cursor = self.cursor::<usize>();
3884 cursor.seek(&range.start);
3885 std::iter::from_fn(move || {
3886 let region = cursor.region()?;
3887 if region.range.start > range.end
3888 || region.range.start == range.end && region.range.start > range.start
3889 {
3890 return None;
3891 }
3892 cursor.next_excerpt();
3893 Some(region.excerpt.buffer_id)
3894 })
3895 }
3896
3897 pub fn ranges_to_buffer_ranges<T: ToOffset>(
3898 &self,
3899 ranges: impl Iterator<Item = Range<T>>,
3900 ) -> impl Iterator<Item = (&BufferSnapshot, Range<usize>, ExcerptId)> {
3901 ranges.flat_map(|range| self.range_to_buffer_ranges(range).into_iter())
3902 }
3903
3904 pub fn range_to_buffer_ranges<T: ToOffset>(
3905 &self,
3906 range: Range<T>,
3907 ) -> Vec<(&BufferSnapshot, Range<usize>, ExcerptId)> {
3908 let start = range.start.to_offset(self);
3909 let end = range.end.to_offset(self);
3910
3911 let mut cursor = self.cursor::<usize>();
3912 cursor.seek(&start);
3913
3914 let mut result: Vec<(&BufferSnapshot, Range<usize>, ExcerptId)> = Vec::new();
3915 while let Some(region) = cursor.region() {
3916 if region.range.start > end {
3917 break;
3918 }
3919 if region.is_main_buffer {
3920 let start_overshoot = start.saturating_sub(region.range.start);
3921 let end_overshoot = end.saturating_sub(region.range.start);
3922 let start = region
3923 .buffer_range
3924 .end
3925 .min(region.buffer_range.start + start_overshoot);
3926 let end = region
3927 .buffer_range
3928 .end
3929 .min(region.buffer_range.start + end_overshoot);
3930 if let Some(prev) = result.last_mut().filter(|(_, prev_range, excerpt_id)| {
3931 *excerpt_id == region.excerpt.id && prev_range.end == start
3932 }) {
3933 prev.1.end = end;
3934 } else {
3935 result.push((region.buffer, start..end, region.excerpt.id));
3936 }
3937 }
3938 cursor.next();
3939 }
3940 result
3941 }
3942
3943 pub fn range_to_buffer_ranges_with_deleted_hunks<T: ToOffset>(
3944 &self,
3945 range: Range<T>,
3946 ) -> impl Iterator<Item = (&BufferSnapshot, Range<usize>, ExcerptId, Option<Anchor>)> + '_ {
3947 let start = range.start.to_offset(self);
3948 let end = range.end.to_offset(self);
3949
3950 let mut cursor = self.cursor::<usize>();
3951 cursor.seek(&start);
3952
3953 std::iter::from_fn(move || {
3954 let region = cursor.region()?;
3955 if region.range.start > end {
3956 return None;
3957 }
3958 let start_overshoot = start.saturating_sub(region.range.start);
3959 let end_overshoot = end.saturating_sub(region.range.start);
3960 let start = region
3961 .buffer_range
3962 .end
3963 .min(region.buffer_range.start + start_overshoot);
3964 let end = region
3965 .buffer_range
3966 .end
3967 .min(region.buffer_range.start + end_overshoot);
3968
3969 let region_excerpt_id = region.excerpt.id;
3970 let deleted_hunk_anchor = if region.is_main_buffer {
3971 None
3972 } else {
3973 Some(self.anchor_before(region.range.start))
3974 };
3975 let result = (
3976 region.buffer,
3977 start..end,
3978 region_excerpt_id,
3979 deleted_hunk_anchor,
3980 );
3981 cursor.next();
3982 Some(result)
3983 })
3984 }
3985
3986 /// Retrieves buffer metadata for the given range, and converts it into multi-buffer
3987 /// coordinates.
3988 ///
3989 /// The given callback will be called for every excerpt intersecting the given range. It will
3990 /// be passed the excerpt's buffer and the buffer range that the input range intersects.
3991 /// The callback should return an iterator of metadata items from that buffer, each paired
3992 /// with a buffer range.
3993 ///
3994 /// The returned iterator yields each of these metadata items, paired with its range in
3995 /// multi-buffer coordinates.
3996 fn lift_buffer_metadata<'a, D, M, I>(
3997 &'a self,
3998 query_range: Range<D>,
3999 get_buffer_metadata: impl 'a + Fn(&'a BufferSnapshot, Range<D>) -> Option<I>,
4000 ) -> impl Iterator<Item = (Range<D>, M, &'a Excerpt)> + 'a
4001 where
4002 I: Iterator<Item = (Range<D>, M)> + 'a,
4003 D: TextDimension + Ord + Sub<D, Output = D>,
4004 {
4005 let max_position = D::from_text_summary(&self.text_summary());
4006 let mut current_excerpt_metadata: Option<(ExcerptId, I)> = None;
4007 let mut cursor = self.cursor::<D>();
4008
4009 // Find the excerpt and buffer offset where the given range ends.
4010 cursor.seek(&query_range.end);
4011 let mut range_end = None;
4012 while let Some(region) = cursor.region() {
4013 if region.is_main_buffer {
4014 let mut buffer_end = region.buffer_range.start;
4015 let overshoot = if query_range.end > region.range.start {
4016 query_range.end - region.range.start
4017 } else {
4018 D::default()
4019 };
4020 buffer_end.add_assign(&overshoot);
4021 range_end = Some((region.excerpt.id, buffer_end));
4022 break;
4023 }
4024 cursor.next();
4025 }
4026
4027 cursor.seek(&query_range.start);
4028
4029 if let Some(region) = cursor.region().filter(|region| !region.is_main_buffer)
4030 && region.range.start > D::zero(())
4031 {
4032 cursor.prev()
4033 }
4034
4035 iter::from_fn(move || {
4036 loop {
4037 let excerpt = cursor.excerpt()?;
4038
4039 // If we have already retrieved metadata for this excerpt, continue to use it.
4040 let metadata_iter = if let Some((_, metadata)) = current_excerpt_metadata
4041 .as_mut()
4042 .filter(|(excerpt_id, _)| *excerpt_id == excerpt.id)
4043 {
4044 Some(metadata)
4045 }
4046 // Otherwise, compute the intersection of the input range with the excerpt's range,
4047 // and retrieve the metadata for the resulting range.
4048 else {
4049 let region = cursor.region()?;
4050 let mut buffer_start;
4051 if region.is_main_buffer {
4052 buffer_start = region.buffer_range.start;
4053 if query_range.start > region.range.start {
4054 let overshoot = query_range.start - region.range.start;
4055 buffer_start.add_assign(&overshoot);
4056 }
4057 buffer_start = buffer_start.min(region.buffer_range.end);
4058 } else {
4059 buffer_start = cursor.main_buffer_position()?;
4060 };
4061 let mut buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
4062 if let Some((end_excerpt_id, end_buffer_offset)) = range_end
4063 && excerpt.id == end_excerpt_id
4064 {
4065 buffer_end = buffer_end.min(end_buffer_offset);
4066 }
4067
4068 get_buffer_metadata(&excerpt.buffer, buffer_start..buffer_end).map(|iterator| {
4069 &mut current_excerpt_metadata.insert((excerpt.id, iterator)).1
4070 })
4071 };
4072
4073 // Visit each metadata item.
4074 if let Some((metadata_buffer_range, metadata)) =
4075 metadata_iter.and_then(Iterator::next)
4076 {
4077 // Find the multibuffer regions that contain the start and end of
4078 // the metadata item's range.
4079 if metadata_buffer_range.start > D::default() {
4080 while let Some(region) = cursor.region() {
4081 if region.is_main_buffer
4082 && (region.buffer_range.end >= metadata_buffer_range.start
4083 || cursor.is_at_end_of_excerpt())
4084 {
4085 break;
4086 }
4087 cursor.next();
4088 }
4089 }
4090 let start_region = cursor.region()?;
4091 while let Some(region) = cursor.region() {
4092 if region.is_main_buffer
4093 && (region.buffer_range.end > metadata_buffer_range.end
4094 || cursor.is_at_end_of_excerpt())
4095 {
4096 break;
4097 }
4098 cursor.next();
4099 }
4100 let end_region = cursor.region();
4101
4102 // Convert the metadata item's range into multibuffer coordinates.
4103 let mut start_position = start_region.range.start;
4104 let region_buffer_start = start_region.buffer_range.start;
4105 if start_region.is_main_buffer
4106 && metadata_buffer_range.start > region_buffer_start
4107 {
4108 start_position
4109 .add_assign(&(metadata_buffer_range.start - region_buffer_start));
4110 start_position = start_position.min(start_region.range.end);
4111 }
4112
4113 let mut end_position = max_position;
4114 if let Some(end_region) = &end_region {
4115 end_position = end_region.range.start;
4116 debug_assert!(end_region.is_main_buffer);
4117 let region_buffer_start = end_region.buffer_range.start;
4118 if metadata_buffer_range.end > region_buffer_start {
4119 end_position
4120 .add_assign(&(metadata_buffer_range.end - region_buffer_start));
4121 }
4122 end_position = end_position.min(end_region.range.end);
4123 }
4124
4125 if start_position <= query_range.end && end_position >= query_range.start {
4126 return Some((start_position..end_position, metadata, excerpt));
4127 }
4128 }
4129 // When there are no more metadata items for this excerpt, move to the next excerpt.
4130 else {
4131 current_excerpt_metadata.take();
4132 if let Some((end_excerpt_id, _)) = range_end
4133 && excerpt.id == end_excerpt_id
4134 {
4135 return None;
4136 }
4137 cursor.next_excerpt();
4138 }
4139 }
4140 })
4141 }
4142
4143 pub fn diff_hunk_before<T: ToOffset>(&self, position: T) -> Option<MultiBufferRow> {
4144 let offset = position.to_offset(self);
4145
4146 let mut cursor = self.cursor::<DimensionPair<usize, Point>>();
4147 cursor.seek(&DimensionPair {
4148 key: offset,
4149 value: None,
4150 });
4151 cursor.seek_to_start_of_current_excerpt();
4152 let excerpt = cursor.excerpt()?;
4153
4154 let excerpt_end = excerpt.range.context.end.to_offset(&excerpt.buffer);
4155 let current_position = self
4156 .anchor_before(offset)
4157 .text_anchor
4158 .to_offset(&excerpt.buffer);
4159 let excerpt_end = excerpt
4160 .buffer
4161 .anchor_before(excerpt_end.min(current_position));
4162
4163 if let Some(diff) = self.diffs.get(&excerpt.buffer_id) {
4164 for hunk in diff.hunks_intersecting_range_rev(
4165 excerpt.range.context.start..excerpt_end,
4166 &excerpt.buffer,
4167 ) {
4168 let hunk_end = hunk.buffer_range.end.to_offset(&excerpt.buffer);
4169 if hunk_end >= current_position {
4170 continue;
4171 }
4172 let start =
4173 Anchor::in_buffer(excerpt.id, excerpt.buffer_id, hunk.buffer_range.start)
4174 .to_point(self);
4175 return Some(MultiBufferRow(start.row));
4176 }
4177 }
4178
4179 loop {
4180 cursor.prev_excerpt();
4181 let excerpt = cursor.excerpt()?;
4182
4183 let Some(diff) = self.diffs.get(&excerpt.buffer_id) else {
4184 continue;
4185 };
4186 let mut hunks =
4187 diff.hunks_intersecting_range_rev(excerpt.range.context.clone(), &excerpt.buffer);
4188 let Some(hunk) = hunks.next() else {
4189 continue;
4190 };
4191 let start = Anchor::in_buffer(excerpt.id, excerpt.buffer_id, hunk.buffer_range.start)
4192 .to_point(self);
4193 return Some(MultiBufferRow(start.row));
4194 }
4195 }
4196
4197 pub fn has_diff_hunks(&self) -> bool {
4198 self.diffs.values().any(|diff| !diff.is_empty())
4199 }
4200
4201 pub fn is_inside_word<T: ToOffset>(
4202 &self,
4203 position: T,
4204 scope_context: Option<CharScopeContext>,
4205 ) -> bool {
4206 let position = position.to_offset(self);
4207 let classifier = self
4208 .char_classifier_at(position)
4209 .scope_context(scope_context);
4210 let next_char_kind = self.chars_at(position).next().map(|c| classifier.kind(c));
4211 let prev_char_kind = self
4212 .reversed_chars_at(position)
4213 .next()
4214 .map(|c| classifier.kind(c));
4215 prev_char_kind.zip(next_char_kind) == Some((CharKind::Word, CharKind::Word))
4216 }
4217
4218 pub fn surrounding_word<T: ToOffset>(
4219 &self,
4220 start: T,
4221 scope_context: Option<CharScopeContext>,
4222 ) -> (Range<usize>, Option<CharKind>) {
4223 let mut start = start.to_offset(self);
4224 let mut end = start;
4225 let mut next_chars = self.chars_at(start).peekable();
4226 let mut prev_chars = self.reversed_chars_at(start).peekable();
4227
4228 let classifier = self.char_classifier_at(start).scope_context(scope_context);
4229
4230 let word_kind = cmp::max(
4231 prev_chars.peek().copied().map(|c| classifier.kind(c)),
4232 next_chars.peek().copied().map(|c| classifier.kind(c)),
4233 );
4234
4235 for ch in prev_chars {
4236 if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
4237 start -= ch.len_utf8();
4238 } else {
4239 break;
4240 }
4241 }
4242
4243 for ch in next_chars {
4244 if Some(classifier.kind(ch)) == word_kind && ch != '\n' {
4245 end += ch.len_utf8();
4246 } else {
4247 break;
4248 }
4249 }
4250
4251 (start..end, word_kind)
4252 }
4253
4254 pub fn char_kind_before<T: ToOffset>(
4255 &self,
4256 start: T,
4257 scope_context: Option<CharScopeContext>,
4258 ) -> Option<CharKind> {
4259 let start = start.to_offset(self);
4260 let classifier = self.char_classifier_at(start).scope_context(scope_context);
4261 self.reversed_chars_at(start)
4262 .next()
4263 .map(|ch| classifier.kind(ch))
4264 }
4265
4266 pub fn is_singleton(&self) -> bool {
4267 self.singleton
4268 }
4269
4270 pub fn as_singleton(&self) -> Option<(&ExcerptId, BufferId, &BufferSnapshot)> {
4271 if self.singleton {
4272 self.excerpts
4273 .iter()
4274 .next()
4275 .map(|e| (&e.id, e.buffer_id, &e.buffer))
4276 } else {
4277 None
4278 }
4279 }
4280
4281 pub fn len(&self) -> usize {
4282 self.diff_transforms.summary().output.len
4283 }
4284
4285 pub fn is_empty(&self) -> bool {
4286 self.excerpts.summary().text.len == 0
4287 }
4288
4289 pub fn widest_line_number(&self) -> u32 {
4290 // widest_line_number is 0-based, so 1 is added to get the displayed line number.
4291 self.excerpts.summary().widest_line_number + 1
4292 }
4293
4294 pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes<'_> {
4295 let range = range.start.to_offset(self)..range.end.to_offset(self);
4296 let mut excerpts = self.cursor::<usize>();
4297 excerpts.seek(&range.start);
4298
4299 let mut chunk;
4300 let mut has_trailing_newline;
4301 let excerpt_bytes;
4302 if let Some(region) = excerpts.region() {
4303 let mut bytes = region.buffer.bytes_in_range(
4304 region.buffer_range.start + range.start - region.range.start
4305 ..(region.buffer_range.start + range.end - region.range.start)
4306 .min(region.buffer_range.end),
4307 );
4308 chunk = bytes.next().unwrap_or(&[][..]);
4309 excerpt_bytes = Some(bytes);
4310 has_trailing_newline = region.has_trailing_newline && range.end >= region.range.end;
4311 if chunk.is_empty() && has_trailing_newline {
4312 chunk = b"\n";
4313 has_trailing_newline = false;
4314 }
4315 } else {
4316 chunk = &[][..];
4317 excerpt_bytes = None;
4318 has_trailing_newline = false;
4319 };
4320
4321 MultiBufferBytes {
4322 range,
4323 cursor: excerpts,
4324 excerpt_bytes,
4325 has_trailing_newline,
4326 chunk,
4327 }
4328 }
4329
4330 pub fn reversed_bytes_in_range<T: ToOffset>(
4331 &self,
4332 range: Range<T>,
4333 ) -> ReversedMultiBufferBytes<'_> {
4334 let range = range.start.to_offset(self)..range.end.to_offset(self);
4335 let mut chunks = self.reversed_chunks_in_range(range.clone());
4336 let chunk = chunks.next().map_or(&[][..], |c| c.as_bytes());
4337 ReversedMultiBufferBytes {
4338 range,
4339 chunks,
4340 chunk,
4341 }
4342 }
4343
4344 pub fn row_infos(&self, start_row: MultiBufferRow) -> MultiBufferRows<'_> {
4345 let mut cursor = self.cursor::<Point>();
4346 cursor.seek(&Point::new(start_row.0, 0));
4347 let mut result = MultiBufferRows {
4348 point: Point::new(0, 0),
4349 is_empty: self.excerpts.is_empty(),
4350 is_singleton: self.is_singleton(),
4351 cursor,
4352 };
4353 result.seek(start_row);
4354 result
4355 }
4356
4357 pub fn chunks<T: ToOffset>(
4358 &self,
4359 range: Range<T>,
4360 language_aware: bool,
4361 ) -> MultiBufferChunks<'_> {
4362 let mut chunks = MultiBufferChunks {
4363 excerpt_offset_range: ExcerptOffset::new(0)..ExcerptOffset::new(0),
4364 range: 0..0,
4365 excerpts: self.excerpts.cursor(()),
4366 diff_transforms: self.diff_transforms.cursor(()),
4367 diffs: &self.diffs,
4368 diff_base_chunks: None,
4369 excerpt_chunks: None,
4370 buffer_chunk: None,
4371 language_aware,
4372 };
4373 let range = range.start.to_offset(self)..range.end.to_offset(self);
4374 chunks.seek(range);
4375 chunks
4376 }
4377
4378 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
4379 self.clip_dimension(offset, bias, text::BufferSnapshot::clip_offset)
4380 }
4381
4382 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
4383 self.clip_dimension(point, bias, text::BufferSnapshot::clip_point)
4384 }
4385
4386 pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
4387 self.clip_dimension(offset, bias, text::BufferSnapshot::clip_offset_utf16)
4388 }
4389
4390 pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
4391 self.clip_dimension(point.0, bias, |buffer, point, bias| {
4392 buffer.clip_point_utf16(Unclipped(point), bias)
4393 })
4394 }
4395
4396 pub fn offset_to_point(&self, offset: usize) -> Point {
4397 self.convert_dimension(offset, text::BufferSnapshot::offset_to_point)
4398 }
4399
4400 pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
4401 self.convert_dimension(offset, text::BufferSnapshot::offset_to_point_utf16)
4402 }
4403
4404 pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
4405 self.convert_dimension(point, text::BufferSnapshot::point_to_point_utf16)
4406 }
4407
4408 pub fn point_to_offset(&self, point: Point) -> usize {
4409 self.convert_dimension(point, text::BufferSnapshot::point_to_offset)
4410 }
4411
4412 pub fn offset_utf16_to_offset(&self, offset: OffsetUtf16) -> usize {
4413 self.convert_dimension(offset, text::BufferSnapshot::offset_utf16_to_offset)
4414 }
4415
4416 pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
4417 self.convert_dimension(offset, text::BufferSnapshot::offset_to_offset_utf16)
4418 }
4419
4420 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
4421 self.convert_dimension(point, text::BufferSnapshot::point_utf16_to_offset)
4422 }
4423
4424 fn clip_dimension<D>(
4425 &self,
4426 position: D,
4427 bias: Bias,
4428 clip_buffer_position: fn(&text::BufferSnapshot, D, Bias) -> D,
4429 ) -> D
4430 where
4431 D: TextDimension + Ord + Sub<D, Output = D>,
4432 {
4433 let mut cursor = self.cursor();
4434 cursor.seek(&position);
4435 if let Some(region) = cursor.region() {
4436 if position >= region.range.end {
4437 return region.range.end;
4438 }
4439 let overshoot = position - region.range.start;
4440 let mut buffer_position = region.buffer_range.start;
4441 buffer_position.add_assign(&overshoot);
4442 let clipped_buffer_position =
4443 clip_buffer_position(region.buffer, buffer_position, bias);
4444 let mut position = region.range.start;
4445 position.add_assign(&(clipped_buffer_position - region.buffer_range.start));
4446 position
4447 } else {
4448 D::from_text_summary(&self.text_summary())
4449 }
4450 }
4451
4452 fn convert_dimension<D1, D2>(
4453 &self,
4454 key: D1,
4455 convert_buffer_dimension: fn(&text::BufferSnapshot, D1) -> D2,
4456 ) -> D2
4457 where
4458 D1: TextDimension + Ord + Sub<D1, Output = D1>,
4459 D2: TextDimension + Ord + Sub<D2, Output = D2>,
4460 {
4461 let mut cursor = self.cursor::<DimensionPair<D1, D2>>();
4462 cursor.seek(&DimensionPair { key, value: None });
4463 if let Some(region) = cursor.region() {
4464 if key >= region.range.end.key {
4465 return region.range.end.value.unwrap();
4466 }
4467 let start_key = region.range.start.key;
4468 let start_value = region.range.start.value.unwrap();
4469 let buffer_start_key = region.buffer_range.start.key;
4470 let buffer_start_value = region.buffer_range.start.value.unwrap();
4471 let mut buffer_key = buffer_start_key;
4472 buffer_key.add_assign(&(key - start_key));
4473 let buffer_value = convert_buffer_dimension(region.buffer, buffer_key);
4474 let mut result = start_value;
4475 result.add_assign(&(buffer_value - buffer_start_value));
4476 result
4477 } else {
4478 D2::from_text_summary(&self.text_summary())
4479 }
4480 }
4481
4482 pub fn point_to_buffer_offset<T: ToOffset>(
4483 &self,
4484 point: T,
4485 ) -> Option<(&BufferSnapshot, usize)> {
4486 let offset = point.to_offset(self);
4487 let mut cursor = self.cursor::<usize>();
4488 cursor.seek(&offset);
4489 let region = cursor.region()?;
4490 let overshoot = offset - region.range.start;
4491 let buffer_offset = region.buffer_range.start + overshoot;
4492 if buffer_offset == region.buffer.len() + 1
4493 && region.has_trailing_newline
4494 && !region.is_main_buffer
4495 {
4496 return Some((&cursor.excerpt()?.buffer, cursor.main_buffer_position()?));
4497 } else if buffer_offset > region.buffer.len() {
4498 return None;
4499 }
4500 Some((region.buffer, buffer_offset))
4501 }
4502
4503 pub fn point_to_buffer_point(
4504 &self,
4505 point: Point,
4506 ) -> Option<(&BufferSnapshot, Point, ExcerptId)> {
4507 let mut cursor = self.cursor::<Point>();
4508 cursor.seek(&point);
4509 let region = cursor.region()?;
4510 let overshoot = point - region.range.start;
4511 let buffer_point = region.buffer_range.start + overshoot;
4512 let excerpt = cursor.excerpt()?;
4513 if buffer_point == region.buffer.max_point() + Point::new(1, 0)
4514 && region.has_trailing_newline
4515 && !region.is_main_buffer
4516 {
4517 return Some((&excerpt.buffer, cursor.main_buffer_position()?, excerpt.id));
4518 } else if buffer_point > region.buffer.max_point() {
4519 return None;
4520 }
4521 Some((region.buffer, buffer_point, excerpt.id))
4522 }
4523
4524 pub fn suggested_indents(
4525 &self,
4526 rows: impl IntoIterator<Item = u32>,
4527 cx: &App,
4528 ) -> BTreeMap<MultiBufferRow, IndentSize> {
4529 let mut result = BTreeMap::new();
4530
4531 let mut rows_for_excerpt = Vec::new();
4532 let mut cursor = self.cursor::<Point>();
4533 let mut rows = rows.into_iter().peekable();
4534 let mut prev_row = u32::MAX;
4535 let mut prev_language_indent_size = IndentSize::default();
4536
4537 while let Some(row) = rows.next() {
4538 cursor.seek(&Point::new(row, 0));
4539 let Some(region) = cursor.region() else {
4540 continue;
4541 };
4542
4543 // Retrieve the language and indent size once for each disjoint region being indented.
4544 let single_indent_size = if row.saturating_sub(1) == prev_row {
4545 prev_language_indent_size
4546 } else {
4547 region
4548 .buffer
4549 .language_indent_size_at(Point::new(row, 0), cx)
4550 };
4551 prev_language_indent_size = single_indent_size;
4552 prev_row = row;
4553
4554 let start_buffer_row = region.buffer_range.start.row;
4555 let start_multibuffer_row = region.range.start.row;
4556 let end_multibuffer_row = region.range.end.row;
4557
4558 rows_for_excerpt.push(row);
4559 while let Some(next_row) = rows.peek().copied() {
4560 if end_multibuffer_row > next_row {
4561 rows_for_excerpt.push(next_row);
4562 rows.next();
4563 } else {
4564 break;
4565 }
4566 }
4567
4568 let buffer_rows = rows_for_excerpt
4569 .drain(..)
4570 .map(|row| start_buffer_row + row - start_multibuffer_row);
4571 let buffer_indents = region
4572 .buffer
4573 .suggested_indents(buffer_rows, single_indent_size);
4574 let multibuffer_indents = buffer_indents.into_iter().map(|(row, indent)| {
4575 (
4576 MultiBufferRow(start_multibuffer_row + row - start_buffer_row),
4577 indent,
4578 )
4579 });
4580 result.extend(multibuffer_indents);
4581 }
4582
4583 result
4584 }
4585
4586 pub fn indent_size_for_line(&self, row: MultiBufferRow) -> IndentSize {
4587 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
4588 let mut size = buffer.indent_size_for_line(range.start.row);
4589 size.len = size
4590 .len
4591 .min(range.end.column)
4592 .saturating_sub(range.start.column);
4593 size
4594 } else {
4595 IndentSize::spaces(0)
4596 }
4597 }
4598
4599 pub fn line_indent_for_row(&self, row: MultiBufferRow) -> LineIndent {
4600 if let Some((buffer, range)) = self.buffer_line_for_row(row) {
4601 LineIndent::from_iter(buffer.text_for_range(range).flat_map(|s| s.chars()))
4602 } else {
4603 LineIndent::spaces(0)
4604 }
4605 }
4606
4607 pub fn indent_and_comment_for_line(&self, row: MultiBufferRow, cx: &App) -> String {
4608 let mut indent = self.indent_size_for_line(row).chars().collect::<String>();
4609
4610 if self.language_settings(cx).extend_comment_on_newline
4611 && let Some(language_scope) = self.language_scope_at(Point::new(row.0, 0))
4612 {
4613 let delimiters = language_scope.line_comment_prefixes();
4614 for delimiter in delimiters {
4615 if *self
4616 .chars_at(Point::new(row.0, indent.len() as u32))
4617 .take(delimiter.chars().count())
4618 .collect::<String>()
4619 .as_str()
4620 == **delimiter
4621 {
4622 indent.push_str(delimiter);
4623 break;
4624 }
4625 }
4626 }
4627
4628 indent
4629 }
4630
4631 pub fn is_line_whitespace_upto<T>(&self, position: T) -> bool
4632 where
4633 T: ToOffset,
4634 {
4635 for char in self.reversed_chars_at(position) {
4636 if !char.is_whitespace() {
4637 return false;
4638 }
4639 if char == '\n' {
4640 return true;
4641 }
4642 }
4643 true
4644 }
4645
4646 pub fn prev_non_blank_row(&self, mut row: MultiBufferRow) -> Option<MultiBufferRow> {
4647 while row.0 > 0 {
4648 row.0 -= 1;
4649 if !self.is_line_blank(row) {
4650 return Some(row);
4651 }
4652 }
4653 None
4654 }
4655
4656 pub fn line_len(&self, row: MultiBufferRow) -> u32 {
4657 if let Some((_, range)) = self.buffer_line_for_row(row) {
4658 range.end.column - range.start.column
4659 } else {
4660 0
4661 }
4662 }
4663
4664 pub fn buffer_line_for_row(
4665 &self,
4666 row: MultiBufferRow,
4667 ) -> Option<(&BufferSnapshot, Range<Point>)> {
4668 let mut cursor = self.cursor::<Point>();
4669 let point = Point::new(row.0, 0);
4670 cursor.seek(&point);
4671 let region = cursor.region()?;
4672 let overshoot = point.min(region.range.end) - region.range.start;
4673 let buffer_point = region.buffer_range.start + overshoot;
4674 if buffer_point.row > region.buffer_range.end.row {
4675 return None;
4676 }
4677 let line_start = Point::new(buffer_point.row, 0).max(region.buffer_range.start);
4678 let line_end = Point::new(buffer_point.row, region.buffer.line_len(buffer_point.row))
4679 .min(region.buffer_range.end);
4680 Some((region.buffer, line_start..line_end))
4681 }
4682
4683 pub fn max_point(&self) -> Point {
4684 self.text_summary().lines
4685 }
4686
4687 pub fn max_row(&self) -> MultiBufferRow {
4688 MultiBufferRow(self.text_summary().lines.row)
4689 }
4690
4691 pub fn text_summary(&self) -> TextSummary {
4692 self.diff_transforms.summary().output
4693 }
4694
4695 pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
4696 where
4697 D: TextDimension,
4698 O: ToOffset,
4699 {
4700 let range = range.start.to_offset(self)..range.end.to_offset(self);
4701 let mut cursor = self
4702 .diff_transforms
4703 .cursor::<Dimensions<usize, ExcerptOffset>>(());
4704 cursor.seek(&range.start, Bias::Right);
4705
4706 let Some(first_transform) = cursor.item() else {
4707 return D::from_text_summary(&TextSummary::default());
4708 };
4709
4710 let diff_transform_start = cursor.start().0;
4711 let diff_transform_end = cursor.end().0;
4712 let diff_start = range.start;
4713 let start_overshoot = diff_start - diff_transform_start;
4714 let end_overshoot = std::cmp::min(range.end, diff_transform_end) - diff_transform_start;
4715
4716 let mut result = match first_transform {
4717 DiffTransform::BufferContent { .. } => {
4718 let excerpt_start = cursor.start().1 + ExcerptOffset::new(start_overshoot);
4719 let excerpt_end = cursor.start().1 + ExcerptOffset::new(end_overshoot);
4720 self.text_summary_for_excerpt_offset_range(excerpt_start..excerpt_end)
4721 }
4722 DiffTransform::DeletedHunk {
4723 buffer_id,
4724 base_text_byte_range,
4725 has_trailing_newline,
4726 ..
4727 } => {
4728 let buffer_start = base_text_byte_range.start + start_overshoot;
4729 let mut buffer_end = base_text_byte_range.start + end_overshoot;
4730 let Some(base_text) = self.diffs.get(buffer_id).map(|diff| diff.base_text()) else {
4731 panic!("{:?} is in non-existent deleted hunk", range.start)
4732 };
4733
4734 let include_trailing_newline =
4735 *has_trailing_newline && range.end >= diff_transform_end;
4736 if include_trailing_newline {
4737 buffer_end -= 1;
4738 }
4739
4740 let mut summary =
4741 base_text.text_summary_for_range::<D, _>(buffer_start..buffer_end);
4742
4743 if include_trailing_newline {
4744 summary.add_assign(&D::from_text_summary(&TextSummary::newline()))
4745 }
4746
4747 summary
4748 }
4749 };
4750 if range.end < diff_transform_end {
4751 return result;
4752 }
4753
4754 cursor.next();
4755 result.add_assign(&D::from_text_summary(
4756 &cursor.summary(&range.end, Bias::Right),
4757 ));
4758
4759 let Some(last_transform) = cursor.item() else {
4760 return result;
4761 };
4762
4763 let overshoot = range.end - cursor.start().0;
4764 let suffix = match last_transform {
4765 DiffTransform::BufferContent { .. } => {
4766 let end = cursor.start().1 + ExcerptOffset::new(overshoot);
4767 self.text_summary_for_excerpt_offset_range::<D>(cursor.start().1..end)
4768 }
4769 DiffTransform::DeletedHunk {
4770 base_text_byte_range,
4771 buffer_id,
4772 has_trailing_newline,
4773 ..
4774 } => {
4775 let buffer_end = base_text_byte_range.start + overshoot;
4776 let Some(base_text) = self.diffs.get(buffer_id).map(|diff| diff.base_text()) else {
4777 panic!("{:?} is in non-existent deleted hunk", range.end)
4778 };
4779
4780 let mut suffix = base_text
4781 .text_summary_for_range::<D, _>(base_text_byte_range.start..buffer_end);
4782 if *has_trailing_newline && buffer_end == base_text_byte_range.end + 1 {
4783 suffix.add_assign(&D::from_text_summary(&TextSummary::newline()))
4784 }
4785 suffix
4786 }
4787 };
4788
4789 result.add_assign(&suffix);
4790 result
4791 }
4792
4793 fn text_summary_for_excerpt_offset_range<D>(&self, mut range: Range<ExcerptOffset>) -> D
4794 where
4795 D: TextDimension,
4796 {
4797 let mut summary = D::zero(());
4798 let mut cursor = self.excerpts.cursor::<ExcerptOffset>(());
4799 cursor.seek(&range.start, Bias::Right);
4800 if let Some(excerpt) = cursor.item() {
4801 let mut end_before_newline = cursor.end();
4802 if excerpt.has_trailing_newline {
4803 end_before_newline -= ExcerptOffset::new(1);
4804 }
4805
4806 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
4807 let start_in_excerpt = excerpt_start + (range.start - *cursor.start()).value;
4808 let end_in_excerpt =
4809 excerpt_start + (cmp::min(end_before_newline, range.end) - *cursor.start()).value;
4810 summary.add_assign(
4811 &excerpt
4812 .buffer
4813 .text_summary_for_range(start_in_excerpt..end_in_excerpt),
4814 );
4815
4816 if range.end > end_before_newline {
4817 summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
4818 }
4819
4820 cursor.next();
4821 }
4822
4823 if range.end > *cursor.start() {
4824 summary.add_assign(
4825 &cursor
4826 .summary::<_, ExcerptDimension<D>>(&range.end, Bias::Right)
4827 .0,
4828 );
4829 if let Some(excerpt) = cursor.item() {
4830 range.end = cmp::max(*cursor.start(), range.end);
4831
4832 let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
4833 let end_in_excerpt = excerpt_start + (range.end - *cursor.start()).value;
4834 summary.add_assign(
4835 &excerpt
4836 .buffer
4837 .text_summary_for_range(excerpt_start..end_in_excerpt),
4838 );
4839 }
4840 }
4841
4842 summary
4843 }
4844
4845 pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
4846 where
4847 D: TextDimension + Ord + Sub<D, Output = D>,
4848 {
4849 self.summaries_for_anchors([anchor])[0]
4850 }
4851
4852 fn resolve_summary_for_anchor<D>(
4853 &self,
4854 anchor: &Anchor,
4855 excerpt_position: D,
4856 diff_transforms: &mut Cursor<
4857 DiffTransform,
4858 Dimensions<ExcerptDimension<D>, OutputDimension<D>>,
4859 >,
4860 ) -> D
4861 where
4862 D: TextDimension + Ord + Sub<D, Output = D>,
4863 {
4864 loop {
4865 let transform_end_position = diff_transforms.end().0.0;
4866 let at_transform_end =
4867 excerpt_position == transform_end_position && diff_transforms.item().is_some();
4868 if at_transform_end && anchor.text_anchor.bias == Bias::Right {
4869 diff_transforms.next();
4870 continue;
4871 }
4872
4873 let mut position = diff_transforms.start().1.0;
4874 match diff_transforms.item() {
4875 Some(DiffTransform::DeletedHunk {
4876 buffer_id,
4877 base_text_byte_range,
4878 ..
4879 }) => {
4880 if let Some(diff_base_anchor) = &anchor.diff_base_anchor
4881 && let Some(base_text) =
4882 self.diffs.get(buffer_id).map(|diff| diff.base_text())
4883 && base_text.can_resolve(diff_base_anchor)
4884 {
4885 let base_text_offset = diff_base_anchor.to_offset(base_text);
4886 if base_text_offset >= base_text_byte_range.start
4887 && base_text_offset <= base_text_byte_range.end
4888 {
4889 let position_in_hunk = base_text.text_summary_for_range::<D, _>(
4890 base_text_byte_range.start..base_text_offset,
4891 );
4892 position.add_assign(&position_in_hunk);
4893 } else if at_transform_end {
4894 diff_transforms.next();
4895 continue;
4896 }
4897 }
4898 }
4899 _ => {
4900 if at_transform_end && anchor.diff_base_anchor.is_some() {
4901 diff_transforms.next();
4902 continue;
4903 }
4904 let overshoot = excerpt_position - diff_transforms.start().0.0;
4905 position.add_assign(&overshoot);
4906 }
4907 }
4908
4909 return position;
4910 }
4911 }
4912
4913 fn excerpt_offset_for_anchor(&self, anchor: &Anchor) -> ExcerptOffset {
4914 let mut cursor = self
4915 .excerpts
4916 .cursor::<Dimensions<Option<&Locator>, ExcerptOffset>>(());
4917 let excerpt_id = self.clip_excerpt_id(anchor.excerpt_id);
4918 let locator = self.excerpt_locator_for_id(excerpt_id);
4919
4920 cursor.seek(&Some(locator), Bias::Left);
4921
4922 let mut position = cursor.start().1;
4923 if let Some(excerpt) = cursor.item()
4924 && excerpt.id == excerpt_id
4925 {
4926 let excerpt_buffer_start = excerpt
4927 .buffer
4928 .offset_for_anchor(&excerpt.range.context.start);
4929 let excerpt_buffer_end = excerpt.buffer.offset_for_anchor(&excerpt.range.context.end);
4930 let buffer_position = cmp::min(
4931 excerpt_buffer_end,
4932 excerpt.buffer.offset_for_anchor(&anchor.text_anchor),
4933 );
4934 if buffer_position > excerpt_buffer_start {
4935 position.value += buffer_position - excerpt_buffer_start;
4936 }
4937 }
4938 position
4939 }
4940
4941 pub fn latest_excerpt_id(&self, mut excerpt_id: ExcerptId) -> ExcerptId {
4942 while let Some(replacement) = self.replaced_excerpts.get(&excerpt_id) {
4943 excerpt_id = *replacement;
4944 }
4945 excerpt_id
4946 }
4947
4948 pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
4949 where
4950 D: TextDimension + Ord + Sub<D, Output = D>,
4951 I: 'a + IntoIterator<Item = &'a Anchor>,
4952 {
4953 let mut anchors = anchors.into_iter().peekable();
4954 let mut cursor = self.excerpts.cursor::<ExcerptSummary>(());
4955 let mut diff_transforms_cursor = self
4956 .diff_transforms
4957 .cursor::<Dimensions<ExcerptDimension<D>, OutputDimension<D>>>(());
4958 diff_transforms_cursor.next();
4959
4960 let mut summaries = Vec::new();
4961 while let Some(anchor) = anchors.peek() {
4962 let excerpt_id = self.clip_excerpt_id(anchor.excerpt_id);
4963 let excerpt_id = self.latest_excerpt_id(excerpt_id);
4964
4965 let excerpt_anchors = anchors.peeking_take_while(|anchor| {
4966 self.latest_excerpt_id(self.clip_excerpt_id(anchor.excerpt_id)) == excerpt_id
4967 });
4968
4969 let locator = self.excerpt_locator_for_id(excerpt_id);
4970 cursor.seek_forward(locator, Bias::Left);
4971
4972 let excerpt_start_position = D::from_text_summary(&cursor.start().text);
4973 if let Some(excerpt) = cursor.item() {
4974 if excerpt.id != excerpt_id {
4975 let position = self.resolve_summary_for_anchor(
4976 &Anchor::min(),
4977 excerpt_start_position,
4978 &mut diff_transforms_cursor,
4979 );
4980 summaries.extend(excerpt_anchors.map(|_| position));
4981 continue;
4982 }
4983 let excerpt_buffer_start =
4984 excerpt.range.context.start.summary::<D>(&excerpt.buffer);
4985 let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
4986 for (buffer_summary, anchor) in excerpt
4987 .buffer
4988 .summaries_for_anchors_with_payload::<D, _, _>(
4989 excerpt_anchors.map(|a| (&a.text_anchor, a)),
4990 )
4991 {
4992 let summary = cmp::min(excerpt_buffer_end, buffer_summary);
4993 let mut position = excerpt_start_position;
4994 if summary > excerpt_buffer_start {
4995 position.add_assign(&(summary - excerpt_buffer_start));
4996 }
4997
4998 if position > diff_transforms_cursor.start().0.0 {
4999 diff_transforms_cursor
5000 .seek_forward(&ExcerptDimension(position), Bias::Left);
5001 }
5002
5003 summaries.push(self.resolve_summary_for_anchor(
5004 anchor,
5005 position,
5006 &mut diff_transforms_cursor,
5007 ));
5008 }
5009 } else {
5010 diff_transforms_cursor
5011 .seek_forward(&ExcerptDimension(excerpt_start_position), Bias::Left);
5012 let position = self.resolve_summary_for_anchor(
5013 &Anchor::max(),
5014 excerpt_start_position,
5015 &mut diff_transforms_cursor,
5016 );
5017 summaries.extend(excerpt_anchors.map(|_| position));
5018 }
5019 }
5020
5021 summaries
5022 }
5023
5024 pub fn dimensions_from_points<'a, D>(
5025 &'a self,
5026 points: impl 'a + IntoIterator<Item = Point>,
5027 ) -> impl 'a + Iterator<Item = D>
5028 where
5029 D: TextDimension + Sub<D, Output = D>,
5030 {
5031 let mut cursor = self.cursor::<DimensionPair<Point, D>>();
5032 cursor.seek(&DimensionPair {
5033 key: Point::default(),
5034 value: None,
5035 });
5036 let mut points = points.into_iter();
5037 iter::from_fn(move || {
5038 let point = points.next()?;
5039
5040 cursor.seek_forward(&DimensionPair {
5041 key: point,
5042 value: None,
5043 });
5044
5045 if let Some(region) = cursor.region() {
5046 let overshoot = point - region.range.start.key;
5047 let buffer_point = region.buffer_range.start.key + overshoot;
5048 let mut position = region.range.start.value.unwrap();
5049 position.add_assign(
5050 ®ion
5051 .buffer
5052 .text_summary_for_range(region.buffer_range.start.key..buffer_point),
5053 );
5054 if point == region.range.end.key && region.has_trailing_newline {
5055 position.add_assign(&D::from_text_summary(&TextSummary::newline()));
5056 }
5057 Some(position)
5058 } else {
5059 Some(D::from_text_summary(&self.text_summary()))
5060 }
5061 })
5062 }
5063
5064 pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
5065 where
5066 I: 'a + IntoIterator<Item = &'a Anchor>,
5067 {
5068 let mut anchors = anchors.into_iter().enumerate().peekable();
5069 let mut cursor = self.excerpts.cursor::<Option<&Locator>>(());
5070 cursor.next();
5071
5072 let mut result = Vec::new();
5073
5074 while let Some((_, anchor)) = anchors.peek() {
5075 let old_excerpt_id = anchor.excerpt_id;
5076
5077 // Find the location where this anchor's excerpt should be.
5078 let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
5079 cursor.seek_forward(&Some(old_locator), Bias::Left);
5080
5081 let next_excerpt = cursor.item();
5082 let prev_excerpt = cursor.prev_item();
5083
5084 // Process all of the anchors for this excerpt.
5085 while let Some((anchor_ix, &anchor)) =
5086 anchors.next_if(|(_, anchor)| anchor.excerpt_id == old_excerpt_id)
5087 {
5088 let mut anchor = anchor;
5089
5090 // Leave min and max anchors unchanged if invalid or
5091 // if the old excerpt still exists at this location
5092 let mut kept_position = next_excerpt
5093 .is_some_and(|e| e.id == old_excerpt_id && e.contains(&anchor))
5094 || old_excerpt_id == ExcerptId::max()
5095 || old_excerpt_id == ExcerptId::min();
5096
5097 // If the old excerpt no longer exists at this location, then attempt to
5098 // find an equivalent position for this anchor in an adjacent excerpt.
5099 if !kept_position {
5100 for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
5101 if excerpt.contains(&anchor) {
5102 anchor.excerpt_id = excerpt.id;
5103 kept_position = true;
5104 break;
5105 }
5106 }
5107 }
5108
5109 // If there's no adjacent excerpt that contains the anchor's position,
5110 // then report that the anchor has lost its position.
5111 if !kept_position {
5112 anchor = if let Some(excerpt) = next_excerpt {
5113 let mut text_anchor = excerpt
5114 .range
5115 .context
5116 .start
5117 .bias(anchor.text_anchor.bias, &excerpt.buffer);
5118 if text_anchor
5119 .cmp(&excerpt.range.context.end, &excerpt.buffer)
5120 .is_gt()
5121 {
5122 text_anchor = excerpt.range.context.end;
5123 }
5124 Anchor::in_buffer(excerpt.id, excerpt.buffer_id, text_anchor)
5125 } else if let Some(excerpt) = prev_excerpt {
5126 let mut text_anchor = excerpt
5127 .range
5128 .context
5129 .end
5130 .bias(anchor.text_anchor.bias, &excerpt.buffer);
5131 if text_anchor
5132 .cmp(&excerpt.range.context.start, &excerpt.buffer)
5133 .is_lt()
5134 {
5135 text_anchor = excerpt.range.context.start;
5136 }
5137 Anchor::in_buffer(excerpt.id, excerpt.buffer_id, text_anchor)
5138 } else if anchor.text_anchor.bias == Bias::Left {
5139 Anchor::min()
5140 } else {
5141 Anchor::max()
5142 };
5143 }
5144
5145 result.push((anchor_ix, anchor, kept_position));
5146 }
5147 }
5148 result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
5149 result
5150 }
5151
5152 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
5153 self.anchor_at(position, Bias::Left)
5154 }
5155
5156 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
5157 self.anchor_at(position, Bias::Right)
5158 }
5159
5160 pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
5161 let offset = position.to_offset(self);
5162
5163 // Find the given position in the diff transforms. Determine the corresponding
5164 // offset in the excerpts, and whether the position is within a deleted hunk.
5165 let mut diff_transforms = self
5166 .diff_transforms
5167 .cursor::<Dimensions<usize, ExcerptOffset>>(());
5168 diff_transforms.seek(&offset, Bias::Right);
5169
5170 if offset == diff_transforms.start().0
5171 && bias == Bias::Left
5172 && let Some(prev_item) = diff_transforms.prev_item()
5173 && let DiffTransform::DeletedHunk { .. } = prev_item
5174 {
5175 diff_transforms.prev();
5176 }
5177 let offset_in_transform = offset - diff_transforms.start().0;
5178 let mut excerpt_offset = diff_transforms.start().1;
5179 let mut diff_base_anchor = None;
5180 if let Some(DiffTransform::DeletedHunk {
5181 buffer_id,
5182 base_text_byte_range,
5183 has_trailing_newline,
5184 ..
5185 }) = diff_transforms.item()
5186 {
5187 let diff = self.diffs.get(buffer_id).expect("missing diff");
5188 if offset_in_transform > base_text_byte_range.len() {
5189 debug_assert!(*has_trailing_newline);
5190 bias = Bias::Right;
5191 } else {
5192 diff_base_anchor = Some(
5193 diff.base_text()
5194 .anchor_at(base_text_byte_range.start + offset_in_transform, bias),
5195 );
5196 bias = Bias::Left;
5197 }
5198 } else {
5199 excerpt_offset += ExcerptOffset::new(offset_in_transform);
5200 };
5201
5202 let mut excerpts = self
5203 .excerpts
5204 .cursor::<Dimensions<ExcerptOffset, Option<ExcerptId>>>(());
5205 excerpts.seek(&excerpt_offset, Bias::Right);
5206 if excerpts.item().is_none() && excerpt_offset == excerpts.start().0 && bias == Bias::Left {
5207 excerpts.prev();
5208 }
5209 if let Some(excerpt) = excerpts.item() {
5210 let mut overshoot = excerpt_offset.saturating_sub(excerpts.start().0).value;
5211 if excerpt.has_trailing_newline && excerpt_offset == excerpts.end().0 {
5212 overshoot -= 1;
5213 bias = Bias::Right;
5214 }
5215
5216 let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
5217 let text_anchor =
5218 excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
5219 let anchor = Anchor::in_buffer(excerpt.id, excerpt.buffer_id, text_anchor);
5220 match diff_base_anchor {
5221 Some(diff_base_anchor) => anchor.with_diff_base_anchor(diff_base_anchor),
5222 None => anchor,
5223 }
5224 } else if excerpt_offset.is_zero() && bias == Bias::Left {
5225 Anchor::min()
5226 } else {
5227 Anchor::max()
5228 }
5229 }
5230
5231 /// Returns an anchor for the given excerpt and text anchor,
5232 /// returns None if the excerpt_id is no longer valid.
5233 pub fn anchor_in_excerpt(
5234 &self,
5235 excerpt_id: ExcerptId,
5236 text_anchor: text::Anchor,
5237 ) -> Option<Anchor> {
5238 let excerpt_id = self.latest_excerpt_id(excerpt_id);
5239 let excerpt = self.excerpt(excerpt_id)?;
5240 Some(Anchor::in_buffer(
5241 excerpt_id,
5242 excerpt.buffer_id,
5243 text_anchor,
5244 ))
5245 }
5246
5247 pub fn context_range_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<Range<text::Anchor>> {
5248 Some(self.excerpt(excerpt_id)?.range.context.clone())
5249 }
5250
5251 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
5252 if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
5253 true
5254 } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
5255 excerpt.buffer.can_resolve(&anchor.text_anchor)
5256 } else {
5257 false
5258 }
5259 }
5260
5261 pub fn excerpts(
5262 &self,
5263 ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
5264 self.excerpts
5265 .iter()
5266 .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
5267 }
5268
5269 fn cursor<D: TextDimension + Default>(&self) -> MultiBufferCursor<'_, D> {
5270 let excerpts = self.excerpts.cursor(());
5271 let diff_transforms = self.diff_transforms.cursor(());
5272 MultiBufferCursor {
5273 excerpts,
5274 diff_transforms,
5275 diffs: &self.diffs,
5276 cached_region: None,
5277 }
5278 }
5279
5280 pub fn excerpt_before(&self, excerpt_id: ExcerptId) -> Option<MultiBufferExcerpt<'_>> {
5281 let start_locator = self.excerpt_locator_for_id(excerpt_id);
5282 let mut excerpts = self
5283 .excerpts
5284 .cursor::<Dimensions<Option<&Locator>, ExcerptDimension<usize>>>(());
5285 excerpts.seek(&Some(start_locator), Bias::Left);
5286 excerpts.prev();
5287
5288 let mut diff_transforms = self.diff_transforms.cursor::<DiffTransforms<usize>>(());
5289 diff_transforms.seek(&excerpts.start().1, Bias::Left);
5290 if diff_transforms.end().excerpt_dimension < excerpts.start().1 {
5291 diff_transforms.next();
5292 }
5293
5294 let excerpt = excerpts.item()?;
5295 Some(MultiBufferExcerpt {
5296 excerpt,
5297 offset: diff_transforms.start().output_dimension.0,
5298 buffer_offset: excerpt.range.context.start.to_offset(&excerpt.buffer),
5299 excerpt_offset: excerpts.start().1.clone(),
5300 diff_transforms,
5301 })
5302 }
5303
5304 pub fn excerpt_boundaries_in_range<R, T>(
5305 &self,
5306 range: R,
5307 ) -> impl Iterator<Item = ExcerptBoundary> + '_
5308 where
5309 R: RangeBounds<T>,
5310 T: ToOffset,
5311 {
5312 let start_offset;
5313 let start = match range.start_bound() {
5314 Bound::Included(start) => {
5315 start_offset = start.to_offset(self);
5316 Bound::Included(start_offset)
5317 }
5318 Bound::Excluded(_) => {
5319 panic!("not supported")
5320 }
5321 Bound::Unbounded => {
5322 start_offset = 0;
5323 Bound::Unbounded
5324 }
5325 };
5326 let end = match range.end_bound() {
5327 Bound::Included(end) => Bound::Included(end.to_offset(self)),
5328 Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
5329 Bound::Unbounded => Bound::Unbounded,
5330 };
5331 let bounds = (start, end);
5332
5333 let mut cursor = self.cursor::<DimensionPair<usize, Point>>();
5334 cursor.seek(&DimensionPair {
5335 key: start_offset,
5336 value: None,
5337 });
5338
5339 if cursor
5340 .region()
5341 .is_some_and(|region| bounds.contains(®ion.range.start.key))
5342 {
5343 cursor.prev_excerpt();
5344 } else {
5345 cursor.seek_to_start_of_current_excerpt();
5346 }
5347 let mut prev_region = cursor.region();
5348
5349 cursor.next_excerpt();
5350
5351 iter::from_fn(move || {
5352 loop {
5353 if self.singleton {
5354 return None;
5355 }
5356
5357 let next_region = cursor.region()?;
5358 cursor.next_excerpt();
5359 if !bounds.contains(&next_region.range.start.key) {
5360 prev_region = Some(next_region);
5361 continue;
5362 }
5363
5364 let next_region_start = next_region.range.start.value.unwrap();
5365 let next_region_end = if let Some(region) = cursor.region() {
5366 region.range.start.value.unwrap()
5367 } else {
5368 self.max_point()
5369 };
5370
5371 let prev = prev_region.as_ref().map(|region| ExcerptInfo {
5372 id: region.excerpt.id,
5373 buffer: region.excerpt.buffer.clone(),
5374 buffer_id: region.excerpt.buffer_id,
5375 range: region.excerpt.range.clone(),
5376 end_row: MultiBufferRow(next_region_start.row),
5377 });
5378
5379 let next = ExcerptInfo {
5380 id: next_region.excerpt.id,
5381 buffer: next_region.excerpt.buffer.clone(),
5382 buffer_id: next_region.excerpt.buffer_id,
5383 range: next_region.excerpt.range.clone(),
5384 end_row: if next_region.excerpt.has_trailing_newline {
5385 MultiBufferRow(next_region_end.row - 1)
5386 } else {
5387 MultiBufferRow(next_region_end.row)
5388 },
5389 };
5390
5391 let row = MultiBufferRow(next_region_start.row);
5392
5393 prev_region = Some(next_region);
5394
5395 return Some(ExcerptBoundary { row, prev, next });
5396 }
5397 })
5398 }
5399
5400 pub fn edit_count(&self) -> usize {
5401 self.edit_count
5402 }
5403
5404 pub fn non_text_state_update_count(&self) -> usize {
5405 self.non_text_state_update_count
5406 }
5407
5408 /// Returns the smallest enclosing bracket ranges containing the given range or
5409 /// None if no brackets contain range or the range is not contained in a single
5410 /// excerpt
5411 ///
5412 /// Can optionally pass a range_filter to filter the ranges of brackets to consider
5413 pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
5414 &self,
5415 range: Range<T>,
5416 range_filter: Option<&dyn Fn(&BufferSnapshot, Range<usize>, Range<usize>) -> bool>,
5417 ) -> Option<(Range<usize>, Range<usize>)> {
5418 let range = range.start.to_offset(self)..range.end.to_offset(self);
5419 let mut excerpt = self.excerpt_containing(range.clone())?;
5420 let buffer = excerpt.buffer();
5421 let excerpt_buffer_range = excerpt.buffer_range();
5422
5423 // Filter to ranges contained in the excerpt
5424 let range_filter = |open: Range<usize>, close: Range<usize>| -> bool {
5425 excerpt_buffer_range.contains(&open.start)
5426 && excerpt_buffer_range.contains(&close.end)
5427 && range_filter.is_none_or(|filter| filter(buffer, open, close))
5428 };
5429
5430 let (open, close) = excerpt.buffer().innermost_enclosing_bracket_ranges(
5431 excerpt.map_range_to_buffer(range),
5432 Some(&range_filter),
5433 )?;
5434
5435 Some((
5436 excerpt.map_range_from_buffer(open),
5437 excerpt.map_range_from_buffer(close),
5438 ))
5439 }
5440
5441 /// Returns enclosing bracket ranges containing the given range or returns None if the range is
5442 /// not contained in a single excerpt
5443 pub fn enclosing_bracket_ranges<T: ToOffset>(
5444 &self,
5445 range: Range<T>,
5446 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
5447 let range = range.start.to_offset(self)..range.end.to_offset(self);
5448 let mut excerpt = self.excerpt_containing(range.clone())?;
5449
5450 Some(
5451 excerpt
5452 .buffer()
5453 .enclosing_bracket_ranges(excerpt.map_range_to_buffer(range))
5454 .filter_map(move |pair| {
5455 if excerpt.contains_buffer_range(pair.open_range.start..pair.close_range.end) {
5456 Some((
5457 excerpt.map_range_from_buffer(pair.open_range),
5458 excerpt.map_range_from_buffer(pair.close_range),
5459 ))
5460 } else {
5461 None
5462 }
5463 }),
5464 )
5465 }
5466
5467 /// Returns enclosing bracket ranges containing the given range or returns None if the range is
5468 /// not contained in a single excerpt
5469 pub fn text_object_ranges<T: ToOffset>(
5470 &self,
5471 range: Range<T>,
5472 options: TreeSitterOptions,
5473 ) -> impl Iterator<Item = (Range<usize>, TextObject)> + '_ {
5474 let range = range.start.to_offset(self)..range.end.to_offset(self);
5475 self.excerpt_containing(range.clone())
5476 .map(|mut excerpt| {
5477 excerpt
5478 .buffer()
5479 .text_object_ranges(excerpt.map_range_to_buffer(range), options)
5480 .filter_map(move |(range, text_object)| {
5481 if excerpt.contains_buffer_range(range.clone()) {
5482 Some((excerpt.map_range_from_buffer(range), text_object))
5483 } else {
5484 None
5485 }
5486 })
5487 })
5488 .into_iter()
5489 .flatten()
5490 }
5491
5492 /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
5493 /// not contained in a single excerpt
5494 pub fn bracket_ranges<T: ToOffset>(
5495 &self,
5496 range: Range<T>,
5497 ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
5498 let range = range.start.to_offset(self)..range.end.to_offset(self);
5499 let mut excerpt = self.excerpt_containing(range.clone())?;
5500
5501 Some(
5502 excerpt
5503 .buffer()
5504 .bracket_ranges(excerpt.map_range_to_buffer(range))
5505 .filter_map(move |pair| {
5506 let buffer_range = pair.open_range.start..pair.close_range.end;
5507 if excerpt.contains_buffer_range(buffer_range) {
5508 Some((
5509 excerpt.map_range_from_buffer(pair.open_range),
5510 excerpt.map_range_from_buffer(pair.close_range),
5511 ))
5512 } else {
5513 None
5514 }
5515 }),
5516 )
5517 }
5518
5519 pub fn redacted_ranges<'a, T: ToOffset>(
5520 &'a self,
5521 range: Range<T>,
5522 redaction_enabled: impl Fn(Option<&Arc<dyn File>>) -> bool + 'a,
5523 ) -> impl Iterator<Item = Range<usize>> + 'a {
5524 let range = range.start.to_offset(self)..range.end.to_offset(self);
5525 self.lift_buffer_metadata(range, move |buffer, range| {
5526 if redaction_enabled(buffer.file()) {
5527 Some(buffer.redacted_ranges(range).map(|range| (range, ())))
5528 } else {
5529 None
5530 }
5531 })
5532 .map(|(range, _, _)| range)
5533 }
5534
5535 pub fn runnable_ranges(
5536 &self,
5537 range: Range<Anchor>,
5538 ) -> impl Iterator<Item = language::RunnableRange> + '_ {
5539 let range = range.start.to_offset(self)..range.end.to_offset(self);
5540 self.lift_buffer_metadata(range, move |buffer, range| {
5541 Some(
5542 buffer
5543 .runnable_ranges(range.clone())
5544 .filter(move |runnable| {
5545 runnable.run_range.start >= range.start
5546 && runnable.run_range.end < range.end
5547 })
5548 .map(|runnable| (runnable.run_range.clone(), runnable)),
5549 )
5550 })
5551 .map(|(run_range, runnable, _)| language::RunnableRange {
5552 run_range,
5553 ..runnable
5554 })
5555 }
5556
5557 pub fn line_indents(
5558 &self,
5559 start_row: MultiBufferRow,
5560 buffer_filter: impl Fn(&BufferSnapshot) -> bool,
5561 ) -> impl Iterator<Item = (MultiBufferRow, LineIndent, &BufferSnapshot)> {
5562 let max_point = self.max_point();
5563 let mut cursor = self.cursor::<Point>();
5564 cursor.seek(&Point::new(start_row.0, 0));
5565 iter::from_fn(move || {
5566 let mut region = cursor.region()?;
5567 while !buffer_filter(®ion.excerpt.buffer) {
5568 cursor.next();
5569 region = cursor.region()?;
5570 }
5571 let overshoot = start_row.0.saturating_sub(region.range.start.row);
5572 let buffer_start_row =
5573 (region.buffer_range.start.row + overshoot).min(region.buffer_range.end.row);
5574
5575 let buffer_end_row = if region.is_main_buffer
5576 && (region.has_trailing_newline || region.range.end == max_point)
5577 {
5578 region.buffer_range.end.row
5579 } else {
5580 region.buffer_range.end.row.saturating_sub(1)
5581 };
5582
5583 let line_indents = region
5584 .buffer
5585 .line_indents_in_row_range(buffer_start_row..buffer_end_row);
5586 cursor.next();
5587 Some(line_indents.map(move |(buffer_row, indent)| {
5588 let row = region.range.start.row + (buffer_row - region.buffer_range.start.row);
5589 (MultiBufferRow(row), indent, ®ion.excerpt.buffer)
5590 }))
5591 })
5592 .flatten()
5593 }
5594
5595 pub fn reversed_line_indents(
5596 &self,
5597 end_row: MultiBufferRow,
5598 buffer_filter: impl Fn(&BufferSnapshot) -> bool,
5599 ) -> impl Iterator<Item = (MultiBufferRow, LineIndent, &BufferSnapshot)> {
5600 let max_point = self.max_point();
5601 let mut cursor = self.cursor::<Point>();
5602 cursor.seek(&Point::new(end_row.0, 0));
5603 iter::from_fn(move || {
5604 let mut region = cursor.region()?;
5605 while !buffer_filter(®ion.excerpt.buffer) {
5606 cursor.prev();
5607 region = cursor.region()?;
5608 }
5609
5610 let buffer_start_row = region.buffer_range.start.row;
5611 let buffer_end_row = if region.is_main_buffer
5612 && (region.has_trailing_newline || region.range.end == max_point)
5613 {
5614 region.buffer_range.end.row + 1
5615 } else {
5616 region.buffer_range.end.row
5617 };
5618
5619 let overshoot = end_row.0 - region.range.start.row;
5620 let buffer_end_row =
5621 (region.buffer_range.start.row + overshoot + 1).min(buffer_end_row);
5622
5623 let line_indents = region
5624 .buffer
5625 .reversed_line_indents_in_row_range(buffer_start_row..buffer_end_row);
5626 cursor.prev();
5627 Some(line_indents.map(move |(buffer_row, indent)| {
5628 let row = region.range.start.row + (buffer_row - region.buffer_range.start.row);
5629 (MultiBufferRow(row), indent, ®ion.excerpt.buffer)
5630 }))
5631 })
5632 .flatten()
5633 }
5634
5635 pub async fn enclosing_indent(
5636 &self,
5637 mut target_row: MultiBufferRow,
5638 ) -> Option<(Range<MultiBufferRow>, LineIndent)> {
5639 let max_row = MultiBufferRow(self.max_point().row);
5640 if target_row >= max_row {
5641 return None;
5642 }
5643
5644 let mut target_indent = self.line_indent_for_row(target_row);
5645
5646 // If the current row is at the start of an indented block, we want to return this
5647 // block as the enclosing indent.
5648 if !target_indent.is_line_empty() && target_row < max_row {
5649 let next_line_indent = self.line_indent_for_row(MultiBufferRow(target_row.0 + 1));
5650 if !next_line_indent.is_line_empty()
5651 && target_indent.raw_len() < next_line_indent.raw_len()
5652 {
5653 target_indent = next_line_indent;
5654 target_row.0 += 1;
5655 }
5656 }
5657
5658 const SEARCH_ROW_LIMIT: u32 = 25000;
5659 const SEARCH_WHITESPACE_ROW_LIMIT: u32 = 2500;
5660 const YIELD_INTERVAL: u32 = 100;
5661
5662 let mut accessed_row_counter = 0;
5663
5664 // If there is a blank line at the current row, search for the next non indented lines
5665 if target_indent.is_line_empty() {
5666 let start = MultiBufferRow(target_row.0.saturating_sub(SEARCH_WHITESPACE_ROW_LIMIT));
5667 let end =
5668 MultiBufferRow((max_row.0 + 1).min(target_row.0 + SEARCH_WHITESPACE_ROW_LIMIT));
5669
5670 let mut non_empty_line_above = None;
5671 for (row, indent, _) in self.reversed_line_indents(target_row, |_| true) {
5672 if row < start {
5673 break;
5674 }
5675 accessed_row_counter += 1;
5676 if accessed_row_counter == YIELD_INTERVAL {
5677 accessed_row_counter = 0;
5678 yield_now().await;
5679 }
5680 if !indent.is_line_empty() {
5681 non_empty_line_above = Some((row, indent));
5682 break;
5683 }
5684 }
5685
5686 let mut non_empty_line_below = None;
5687 for (row, indent, _) in self.line_indents(target_row, |_| true) {
5688 if row > end {
5689 break;
5690 }
5691 accessed_row_counter += 1;
5692 if accessed_row_counter == YIELD_INTERVAL {
5693 accessed_row_counter = 0;
5694 yield_now().await;
5695 }
5696 if !indent.is_line_empty() {
5697 non_empty_line_below = Some((row, indent));
5698 break;
5699 }
5700 }
5701
5702 let (row, indent) = match (non_empty_line_above, non_empty_line_below) {
5703 (Some((above_row, above_indent)), Some((below_row, below_indent))) => {
5704 if above_indent.raw_len() >= below_indent.raw_len() {
5705 (above_row, above_indent)
5706 } else {
5707 (below_row, below_indent)
5708 }
5709 }
5710 (Some(above), None) => above,
5711 (None, Some(below)) => below,
5712 _ => return None,
5713 };
5714
5715 target_indent = indent;
5716 target_row = row;
5717 }
5718
5719 let start = MultiBufferRow(target_row.0.saturating_sub(SEARCH_ROW_LIMIT));
5720 let end = MultiBufferRow((max_row.0 + 1).min(target_row.0 + SEARCH_ROW_LIMIT));
5721
5722 let mut start_indent = None;
5723 for (row, indent, _) in self.reversed_line_indents(target_row, |_| true) {
5724 if row < start {
5725 break;
5726 }
5727 accessed_row_counter += 1;
5728 if accessed_row_counter == YIELD_INTERVAL {
5729 accessed_row_counter = 0;
5730 yield_now().await;
5731 }
5732 if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
5733 start_indent = Some((row, indent));
5734 break;
5735 }
5736 }
5737 let (start_row, start_indent_size) = start_indent?;
5738
5739 let mut end_indent = (end, None);
5740 for (row, indent, _) in self.line_indents(target_row, |_| true) {
5741 if row > end {
5742 break;
5743 }
5744 accessed_row_counter += 1;
5745 if accessed_row_counter == YIELD_INTERVAL {
5746 accessed_row_counter = 0;
5747 yield_now().await;
5748 }
5749 if !indent.is_line_empty() && indent.raw_len() < target_indent.raw_len() {
5750 end_indent = (MultiBufferRow(row.0.saturating_sub(1)), Some(indent));
5751 break;
5752 }
5753 }
5754 let (end_row, end_indent_size) = end_indent;
5755
5756 let indent = if let Some(end_indent_size) = end_indent_size {
5757 if start_indent_size.raw_len() > end_indent_size.raw_len() {
5758 start_indent_size
5759 } else {
5760 end_indent_size
5761 }
5762 } else {
5763 start_indent_size
5764 };
5765
5766 Some((start_row..end_row, indent))
5767 }
5768
5769 pub fn indent_guides_in_range<T: ToPoint>(
5770 &self,
5771 range: Range<T>,
5772 ignore_disabled_for_language: bool,
5773 cx: &App,
5774 ) -> impl Iterator<Item = IndentGuide> {
5775 let range = range.start.to_point(self)..range.end.to_point(self);
5776 let start_row = MultiBufferRow(range.start.row);
5777 let end_row = MultiBufferRow(range.end.row);
5778
5779 let mut row_indents = self.line_indents(start_row, |buffer| {
5780 let settings =
5781 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx);
5782 settings.indent_guides.enabled || ignore_disabled_for_language
5783 });
5784
5785 let mut result = Vec::new();
5786 let mut indent_stack = SmallVec::<[IndentGuide; 8]>::new();
5787
5788 let mut prev_settings = None;
5789 while let Some((first_row, mut line_indent, buffer)) = row_indents.next() {
5790 if first_row > end_row {
5791 break;
5792 }
5793 let current_depth = indent_stack.len() as u32;
5794
5795 // Avoid retrieving the language settings repeatedly for every buffer row.
5796 if let Some((prev_buffer_id, _)) = &prev_settings
5797 && prev_buffer_id != &buffer.remote_id()
5798 {
5799 prev_settings.take();
5800 }
5801 let settings = &prev_settings
5802 .get_or_insert_with(|| {
5803 (
5804 buffer.remote_id(),
5805 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx),
5806 )
5807 })
5808 .1;
5809 let tab_size = settings.tab_size.get();
5810
5811 // When encountering empty, continue until found useful line indent
5812 // then add to the indent stack with the depth found
5813 let mut found_indent = false;
5814 let mut last_row = first_row;
5815 if line_indent.is_line_blank() {
5816 while !found_indent {
5817 let Some((target_row, new_line_indent, _)) = row_indents.next() else {
5818 break;
5819 };
5820 const TRAILING_ROW_SEARCH_LIMIT: u32 = 25;
5821 if target_row > MultiBufferRow(end_row.0 + TRAILING_ROW_SEARCH_LIMIT) {
5822 break;
5823 }
5824
5825 if new_line_indent.is_line_blank() {
5826 continue;
5827 }
5828 last_row = target_row.min(end_row);
5829 line_indent = new_line_indent;
5830 found_indent = true;
5831 break;
5832 }
5833 } else {
5834 found_indent = true
5835 }
5836
5837 let depth = if found_indent {
5838 line_indent.len(tab_size) / tab_size
5839 } else {
5840 0
5841 };
5842
5843 match depth.cmp(¤t_depth) {
5844 cmp::Ordering::Less => {
5845 for _ in 0..(current_depth - depth) {
5846 let mut indent = indent_stack.pop().unwrap();
5847 if last_row != first_row {
5848 // In this case, we landed on an empty row, had to seek forward,
5849 // and discovered that the indent we where on is ending.
5850 // This means that the last display row must
5851 // be on line that ends this indent range, so we
5852 // should display the range up to the first non-empty line
5853 indent.end_row = MultiBufferRow(first_row.0.saturating_sub(1));
5854 }
5855
5856 result.push(indent)
5857 }
5858 }
5859 cmp::Ordering::Greater => {
5860 for next_depth in current_depth..depth {
5861 indent_stack.push(IndentGuide {
5862 buffer_id: buffer.remote_id(),
5863 start_row: first_row,
5864 end_row: last_row,
5865 depth: next_depth,
5866 tab_size,
5867 settings: settings.indent_guides.clone(),
5868 });
5869 }
5870 }
5871 _ => {}
5872 }
5873
5874 for indent in indent_stack.iter_mut() {
5875 indent.end_row = last_row;
5876 }
5877 }
5878
5879 result.extend(indent_stack);
5880 result.into_iter()
5881 }
5882
5883 pub fn trailing_excerpt_update_count(&self) -> usize {
5884 self.trailing_excerpt_update_count
5885 }
5886
5887 pub fn file_at<T: ToOffset>(&self, point: T) -> Option<&Arc<dyn File>> {
5888 self.point_to_buffer_offset(point)
5889 .and_then(|(buffer, _)| buffer.file())
5890 }
5891
5892 pub fn language_at<T: ToOffset>(&self, point: T) -> Option<&Arc<Language>> {
5893 self.point_to_buffer_offset(point)
5894 .and_then(|(buffer, offset)| buffer.language_at(offset))
5895 }
5896
5897 fn language_settings<'a>(&'a self, cx: &'a App) -> Cow<'a, LanguageSettings> {
5898 self.excerpts
5899 .first()
5900 .map(|excerpt| &excerpt.buffer)
5901 .map(|buffer| {
5902 language_settings(
5903 buffer.language().map(|language| language.name()),
5904 buffer.file(),
5905 cx,
5906 )
5907 })
5908 .unwrap_or_else(move || self.language_settings_at(0, cx))
5909 }
5910
5911 pub fn language_settings_at<'a, T: ToOffset>(
5912 &'a self,
5913 point: T,
5914 cx: &'a App,
5915 ) -> Cow<'a, LanguageSettings> {
5916 let mut language = None;
5917 let mut file = None;
5918 if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
5919 language = buffer.language_at(offset);
5920 file = buffer.file();
5921 }
5922 language_settings(language.map(|l| l.name()), file, cx)
5923 }
5924
5925 pub fn language_scope_at<T: ToOffset>(&self, point: T) -> Option<LanguageScope> {
5926 self.point_to_buffer_offset(point)
5927 .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
5928 }
5929
5930 pub fn char_classifier_at<T: ToOffset>(&self, point: T) -> CharClassifier {
5931 self.point_to_buffer_offset(point)
5932 .map(|(buffer, offset)| buffer.char_classifier_at(offset))
5933 .unwrap_or_default()
5934 }
5935
5936 pub fn language_indent_size_at<T: ToOffset>(
5937 &self,
5938 position: T,
5939 cx: &App,
5940 ) -> Option<IndentSize> {
5941 let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
5942 Some(buffer_snapshot.language_indent_size_at(offset, cx))
5943 }
5944
5945 pub fn is_dirty(&self) -> bool {
5946 self.is_dirty
5947 }
5948
5949 pub fn has_deleted_file(&self) -> bool {
5950 self.has_deleted_file
5951 }
5952
5953 pub fn has_conflict(&self) -> bool {
5954 self.has_conflict
5955 }
5956
5957 pub fn has_diagnostics(&self) -> bool {
5958 self.excerpts
5959 .iter()
5960 .any(|excerpt| excerpt.buffer.has_diagnostics())
5961 }
5962
5963 pub fn diagnostic_group(
5964 &self,
5965 buffer_id: BufferId,
5966 group_id: usize,
5967 ) -> impl Iterator<Item = DiagnosticEntryRef<'_, Point>> + '_ {
5968 self.lift_buffer_metadata(Point::zero()..self.max_point(), move |buffer, range| {
5969 if buffer.remote_id() != buffer_id {
5970 return None;
5971 };
5972 Some(
5973 buffer
5974 .diagnostics_in_range(range, false)
5975 .filter(move |diagnostic| diagnostic.diagnostic.group_id == group_id)
5976 .map(move |DiagnosticEntryRef { diagnostic, range }| (range, diagnostic)),
5977 )
5978 })
5979 .map(|(range, diagnostic, _)| DiagnosticEntryRef { diagnostic, range })
5980 }
5981
5982 pub fn diagnostics_in_range<'a, T>(
5983 &'a self,
5984 range: Range<T>,
5985 ) -> impl Iterator<Item = DiagnosticEntryRef<'a, T>> + 'a
5986 where
5987 T: 'a
5988 + text::ToOffset
5989 + text::FromAnchor
5990 + TextDimension
5991 + Ord
5992 + Sub<T, Output = T>
5993 + fmt::Debug,
5994 {
5995 self.lift_buffer_metadata(range, move |buffer, buffer_range| {
5996 Some(
5997 buffer
5998 .diagnostics_in_range(buffer_range.start..buffer_range.end, false)
5999 .map(|entry| (entry.range, entry.diagnostic)),
6000 )
6001 })
6002 .map(|(range, diagnostic, _)| DiagnosticEntryRef { diagnostic, range })
6003 }
6004
6005 pub fn diagnostics_with_buffer_ids_in_range<'a, T>(
6006 &'a self,
6007 range: Range<T>,
6008 ) -> impl Iterator<Item = (BufferId, DiagnosticEntryRef<'a, T>)> + 'a
6009 where
6010 T: 'a
6011 + text::ToOffset
6012 + text::FromAnchor
6013 + TextDimension
6014 + Ord
6015 + Sub<T, Output = T>
6016 + fmt::Debug,
6017 {
6018 self.lift_buffer_metadata(range, move |buffer, buffer_range| {
6019 Some(
6020 buffer
6021 .diagnostics_in_range(buffer_range.start..buffer_range.end, false)
6022 .map(|entry| (entry.range, entry.diagnostic)),
6023 )
6024 })
6025 .map(|(range, diagnostic, b)| (b.buffer_id, DiagnosticEntryRef { diagnostic, range }))
6026 }
6027
6028 pub fn syntax_ancestor<T: ToOffset>(
6029 &self,
6030 range: Range<T>,
6031 ) -> Option<(tree_sitter::Node<'_>, Range<usize>)> {
6032 let range = range.start.to_offset(self)..range.end.to_offset(self);
6033 let mut excerpt = self.excerpt_containing(range.clone())?;
6034 let node = excerpt
6035 .buffer()
6036 .syntax_ancestor(excerpt.map_range_to_buffer(range))?;
6037 let node_range = node.byte_range();
6038 if !excerpt.contains_buffer_range(node_range.clone()) {
6039 return None;
6040 };
6041 Some((node, excerpt.map_range_from_buffer(node_range)))
6042 }
6043
6044 pub fn syntax_next_sibling<T: ToOffset>(
6045 &self,
6046 range: Range<T>,
6047 ) -> Option<tree_sitter::Node<'_>> {
6048 let range = range.start.to_offset(self)..range.end.to_offset(self);
6049 let mut excerpt = self.excerpt_containing(range.clone())?;
6050 excerpt
6051 .buffer()
6052 .syntax_next_sibling(excerpt.map_range_to_buffer(range))
6053 }
6054
6055 pub fn syntax_prev_sibling<T: ToOffset>(
6056 &self,
6057 range: Range<T>,
6058 ) -> Option<tree_sitter::Node<'_>> {
6059 let range = range.start.to_offset(self)..range.end.to_offset(self);
6060 let mut excerpt = self.excerpt_containing(range.clone())?;
6061 excerpt
6062 .buffer()
6063 .syntax_prev_sibling(excerpt.map_range_to_buffer(range))
6064 }
6065
6066 pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
6067 let (excerpt_id, _, buffer) = self.as_singleton()?;
6068 let outline = buffer.outline(theme);
6069 Some(Outline::new(
6070 outline
6071 .items
6072 .into_iter()
6073 .flat_map(|item| {
6074 Some(OutlineItem {
6075 depth: item.depth,
6076 range: self.anchor_in_excerpt(*excerpt_id, item.range.start)?
6077 ..self.anchor_in_excerpt(*excerpt_id, item.range.end)?,
6078 text: item.text,
6079 highlight_ranges: item.highlight_ranges,
6080 name_ranges: item.name_ranges,
6081 body_range: item.body_range.and_then(|body_range| {
6082 Some(
6083 self.anchor_in_excerpt(*excerpt_id, body_range.start)?
6084 ..self.anchor_in_excerpt(*excerpt_id, body_range.end)?,
6085 )
6086 }),
6087 annotation_range: item.annotation_range.and_then(|annotation_range| {
6088 Some(
6089 self.anchor_in_excerpt(*excerpt_id, annotation_range.start)?
6090 ..self.anchor_in_excerpt(*excerpt_id, annotation_range.end)?,
6091 )
6092 }),
6093 })
6094 })
6095 .collect(),
6096 ))
6097 }
6098
6099 pub fn symbols_containing<T: ToOffset>(
6100 &self,
6101 offset: T,
6102 theme: Option<&SyntaxTheme>,
6103 ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
6104 let anchor = self.anchor_before(offset);
6105 let excerpt_id = anchor.excerpt_id;
6106 let excerpt = self.excerpt(excerpt_id)?;
6107 let buffer_id = excerpt.buffer_id;
6108 Some((
6109 buffer_id,
6110 excerpt
6111 .buffer
6112 .symbols_containing(anchor.text_anchor, theme)
6113 .into_iter()
6114 .flat_map(|item| {
6115 Some(OutlineItem {
6116 depth: item.depth,
6117 range: Anchor::range_in_buffer(excerpt_id, buffer_id, item.range),
6118 text: item.text,
6119 highlight_ranges: item.highlight_ranges,
6120 name_ranges: item.name_ranges,
6121 body_range: item.body_range.map(|body_range| {
6122 Anchor::range_in_buffer(excerpt_id, buffer_id, body_range)
6123 }),
6124 annotation_range: item.annotation_range.map(|body_range| {
6125 Anchor::range_in_buffer(excerpt_id, buffer_id, body_range)
6126 }),
6127 })
6128 })
6129 .collect(),
6130 ))
6131 }
6132
6133 fn excerpt_locator_for_id(&self, id: ExcerptId) -> &Locator {
6134 if id == ExcerptId::min() {
6135 Locator::min_ref()
6136 } else if id == ExcerptId::max() {
6137 Locator::max_ref()
6138 } else {
6139 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>(());
6140 cursor.seek(&id, Bias::Left);
6141 if let Some(entry) = cursor.item()
6142 && entry.id == id
6143 {
6144 return &entry.locator;
6145 }
6146 panic!("invalid excerpt id {id:?}")
6147 }
6148 }
6149
6150 /// Returns the locators referenced by the given excerpt IDs, sorted by locator.
6151 fn excerpt_locators_for_ids(
6152 &self,
6153 ids: impl IntoIterator<Item = ExcerptId>,
6154 ) -> SmallVec<[Locator; 1]> {
6155 let mut sorted_ids = ids.into_iter().collect::<SmallVec<[_; 1]>>();
6156 sorted_ids.sort_unstable();
6157 let mut locators = SmallVec::new();
6158
6159 while sorted_ids.last() == Some(&ExcerptId::max()) {
6160 sorted_ids.pop();
6161 if let Some(mapping) = self.excerpt_ids.last() {
6162 locators.push(mapping.locator.clone());
6163 }
6164 }
6165
6166 let mut sorted_ids = sorted_ids.into_iter().dedup().peekable();
6167 if sorted_ids.peek() == Some(&ExcerptId::min()) {
6168 sorted_ids.next();
6169 if let Some(mapping) = self.excerpt_ids.first() {
6170 locators.push(mapping.locator.clone());
6171 }
6172 }
6173
6174 let mut cursor = self.excerpt_ids.cursor::<ExcerptId>(());
6175 for id in sorted_ids {
6176 if cursor.seek_forward(&id, Bias::Left) {
6177 locators.push(cursor.item().unwrap().locator.clone());
6178 } else {
6179 panic!("invalid excerpt id {:?}", id);
6180 }
6181 }
6182
6183 locators.sort_unstable();
6184 locators
6185 }
6186
6187 pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<BufferId> {
6188 Some(self.excerpt(excerpt_id)?.buffer_id)
6189 }
6190
6191 pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
6192 Some(&self.excerpt(excerpt_id)?.buffer)
6193 }
6194
6195 pub fn range_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<Range<Point>> {
6196 let mut cursor = self
6197 .excerpts
6198 .cursor::<Dimensions<Option<&Locator>, ExcerptDimension<Point>>>(());
6199 let excerpt_id = self.clip_excerpt_id(excerpt_id);
6200 let locator = self.excerpt_locator_for_id(excerpt_id);
6201 let sought_exact = cursor.seek(&Some(locator), Bias::Left);
6202 if sought_exact {
6203 let start = cursor.start().1.clone();
6204 let end = cursor.end().1;
6205 let mut diff_transforms = self
6206 .diff_transforms
6207 .cursor::<Dimensions<ExcerptDimension<Point>, OutputDimension<Point>>>(());
6208 diff_transforms.seek(&start, Bias::Left);
6209 let overshoot = start.0 - diff_transforms.start().0.0;
6210 let start = diff_transforms.start().1.0 + overshoot;
6211 diff_transforms.seek(&end, Bias::Right);
6212 let overshoot = end.0 - diff_transforms.start().0.0;
6213 let end = diff_transforms.start().1.0 + overshoot;
6214 Some(start..end)
6215 } else {
6216 None
6217 }
6218 }
6219
6220 fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
6221 let mut cursor = self.excerpts.cursor::<Option<&Locator>>(());
6222 let excerpt_id = self.clip_excerpt_id(excerpt_id);
6223 let locator = self.excerpt_locator_for_id(excerpt_id);
6224 cursor.seek(&Some(locator), Bias::Left);
6225 cursor.item().filter(|excerpt| excerpt.id == excerpt_id)
6226 }
6227
6228 /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
6229 pub fn excerpt_containing<T: ToOffset>(
6230 &self,
6231 range: Range<T>,
6232 ) -> Option<MultiBufferExcerpt<'_>> {
6233 let range = range.start.to_offset(self)..range.end.to_offset(self);
6234 let mut cursor = self.cursor::<usize>();
6235 cursor.seek(&range.start);
6236
6237 let start_excerpt = cursor.excerpt()?;
6238 if range.end != range.start {
6239 cursor.seek_forward(&range.end);
6240 if cursor.excerpt()?.id != start_excerpt.id {
6241 return None;
6242 }
6243 }
6244
6245 cursor.seek_to_start_of_current_excerpt();
6246 let region = cursor.region()?;
6247 let offset = region.range.start;
6248 let buffer_offset = start_excerpt.buffer_start_offset();
6249 let excerpt_offset = cursor.excerpts.start().clone();
6250 Some(MultiBufferExcerpt {
6251 diff_transforms: cursor.diff_transforms,
6252 excerpt: start_excerpt,
6253 offset,
6254 buffer_offset,
6255 excerpt_offset,
6256 })
6257 }
6258
6259 pub fn buffer_id_for_anchor(&self, anchor: Anchor) -> Option<BufferId> {
6260 if let Some(id) = anchor.buffer_id {
6261 return Some(id);
6262 }
6263 let excerpt = self.excerpt_containing(anchor..anchor)?;
6264 Some(excerpt.buffer_id())
6265 }
6266
6267 pub fn selections_in_range<'a>(
6268 &'a self,
6269 range: &'a Range<Anchor>,
6270 include_local: bool,
6271 ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
6272 let mut cursor = self.excerpts.cursor::<ExcerptSummary>(());
6273 let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
6274 let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
6275 cursor.seek(start_locator, Bias::Left);
6276 cursor
6277 .take_while(move |excerpt| excerpt.locator <= *end_locator)
6278 .flat_map(move |excerpt| {
6279 let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
6280 if excerpt.id == range.start.excerpt_id {
6281 query_range.start = range.start.text_anchor;
6282 }
6283 if excerpt.id == range.end.excerpt_id {
6284 query_range.end = range.end.text_anchor;
6285 }
6286
6287 excerpt
6288 .buffer
6289 .selections_in_range(query_range, include_local)
6290 .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
6291 selections.map(move |selection| {
6292 let mut start =
6293 Anchor::in_buffer(excerpt.id, excerpt.buffer_id, selection.start);
6294 let mut end =
6295 Anchor::in_buffer(excerpt.id, excerpt.buffer_id, selection.end);
6296 if range.start.cmp(&start, self).is_gt() {
6297 start = range.start;
6298 }
6299 if range.end.cmp(&end, self).is_lt() {
6300 end = range.end;
6301 }
6302
6303 (
6304 replica_id,
6305 line_mode,
6306 cursor_shape,
6307 Selection {
6308 id: selection.id,
6309 start,
6310 end,
6311 reversed: selection.reversed,
6312 goal: selection.goal,
6313 },
6314 )
6315 })
6316 })
6317 })
6318 }
6319
6320 pub fn show_headers(&self) -> bool {
6321 self.show_headers
6322 }
6323
6324 pub fn diff_for_buffer_id(&self, buffer_id: BufferId) -> Option<&BufferDiffSnapshot> {
6325 self.diffs.get(&buffer_id)
6326 }
6327
6328 /// Visually annotates a position or range with the `Debug` representation of a value. The
6329 /// callsite of this function is used as a key - previous annotations will be removed.
6330 #[cfg(debug_assertions)]
6331 #[track_caller]
6332 pub fn debug<V, R>(&self, ranges: &R, value: V)
6333 where
6334 R: debug::ToMultiBufferDebugRanges,
6335 V: std::fmt::Debug,
6336 {
6337 self.debug_with_key(std::panic::Location::caller(), ranges, value);
6338 }
6339
6340 /// Visually annotates a position or range with the `Debug` representation of a value. Previous
6341 /// debug annotations with the same key will be removed. The key is also used to determine the
6342 /// annotation's color.
6343 #[cfg(debug_assertions)]
6344 #[track_caller]
6345 pub fn debug_with_key<K, R, V>(&self, key: &K, ranges: &R, value: V)
6346 where
6347 K: std::hash::Hash + 'static,
6348 R: debug::ToMultiBufferDebugRanges,
6349 V: std::fmt::Debug,
6350 {
6351 let text_ranges = ranges
6352 .to_multi_buffer_debug_ranges(self)
6353 .into_iter()
6354 .flat_map(|range| {
6355 self.range_to_buffer_ranges(range).into_iter().map(
6356 |(buffer, range, _excerpt_id)| {
6357 buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
6358 },
6359 )
6360 })
6361 .collect();
6362 text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
6363 debug_ranges.insert(key, text_ranges, format!("{value:?}").into())
6364 });
6365 }
6366}
6367
6368#[cfg(any(test, feature = "test-support"))]
6369impl MultiBufferSnapshot {
6370 pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
6371 let end = self.clip_offset(rng.random_range(start_offset..=self.len()), Bias::Right);
6372 let start = self.clip_offset(rng.random_range(start_offset..=end), Bias::Right);
6373 start..end
6374 }
6375
6376 #[cfg(any(test, feature = "test-support"))]
6377 fn check_invariants(&self) {
6378 let excerpts = self.excerpts.items(());
6379 let excerpt_ids = self.excerpt_ids.items(());
6380
6381 for (ix, excerpt) in excerpts.iter().enumerate() {
6382 if ix == 0 {
6383 if excerpt.locator <= Locator::min() {
6384 panic!("invalid first excerpt locator {:?}", excerpt.locator);
6385 }
6386 } else if excerpt.locator <= excerpts[ix - 1].locator {
6387 panic!("excerpts are out-of-order: {:?}", excerpts);
6388 }
6389 }
6390
6391 for (ix, entry) in excerpt_ids.iter().enumerate() {
6392 if ix == 0 {
6393 if entry.id.cmp(&ExcerptId::min(), self).is_le() {
6394 panic!("invalid first excerpt id {:?}", entry.id);
6395 }
6396 } else if entry.id <= excerpt_ids[ix - 1].id {
6397 panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
6398 }
6399 }
6400
6401 if self.diff_transforms.summary().input != self.excerpts.summary().text {
6402 panic!(
6403 "incorrect input summary. expected {:?}, got {:?}. transforms: {:+?}",
6404 self.excerpts.summary().text.len,
6405 self.diff_transforms.summary().input,
6406 self.diff_transforms.items(()),
6407 );
6408 }
6409
6410 let mut prev_transform: Option<&DiffTransform> = None;
6411 for item in self.diff_transforms.iter() {
6412 if let DiffTransform::BufferContent {
6413 summary,
6414 inserted_hunk_info,
6415 } = item
6416 {
6417 if let Some(DiffTransform::BufferContent {
6418 inserted_hunk_info: prev_inserted_hunk_info,
6419 ..
6420 }) = prev_transform
6421 && *inserted_hunk_info == *prev_inserted_hunk_info
6422 {
6423 panic!(
6424 "multiple adjacent buffer content transforms with is_inserted_hunk = {inserted_hunk_info:?}. transforms: {:+?}",
6425 self.diff_transforms.items(())
6426 );
6427 }
6428 if summary.len == 0 && !self.is_empty() {
6429 panic!("empty buffer content transform");
6430 }
6431 }
6432 prev_transform = Some(item);
6433 }
6434 }
6435
6436 fn clip_excerpt_id(&self, excerpt_id: ExcerptId) -> ExcerptId {
6437 // todo, are first and last always valid?
6438 if excerpt_id == ExcerptId::min() {
6439 self.excerpts
6440 .first()
6441 .map_or(excerpt_id, |excerpt| excerpt.id)
6442 } else if excerpt_id == ExcerptId::max() {
6443 self.excerpts
6444 .last()
6445 .map_or(excerpt_id, |excerpt| excerpt.id)
6446 } else {
6447 excerpt_id
6448 }
6449 }
6450}
6451
6452impl<'a, D> MultiBufferCursor<'a, D>
6453where
6454 D: TextDimension + Ord + Sub<D, Output = D>,
6455{
6456 fn seek(&mut self, position: &D) {
6457 self.cached_region.take();
6458 self.diff_transforms
6459 .seek(&OutputDimension(*position), Bias::Right);
6460 if self.diff_transforms.item().is_none()
6461 && *position == self.diff_transforms.start().output_dimension.0
6462 {
6463 self.diff_transforms.prev();
6464 }
6465
6466 let mut excerpt_position = self.diff_transforms.start().excerpt_dimension.0;
6467 if let Some(DiffTransform::BufferContent { .. }) = self.diff_transforms.item() {
6468 let overshoot = *position - self.diff_transforms.start().output_dimension.0;
6469 excerpt_position.add_assign(&overshoot);
6470 }
6471
6472 self.excerpts
6473 .seek(&ExcerptDimension(excerpt_position), Bias::Right);
6474 if self.excerpts.item().is_none() && excerpt_position == self.excerpts.start().0 {
6475 self.excerpts.prev();
6476 }
6477 }
6478
6479 fn seek_forward(&mut self, position: &D) {
6480 self.cached_region.take();
6481 self.diff_transforms
6482 .seek_forward(&OutputDimension(*position), Bias::Right);
6483 if self.diff_transforms.item().is_none()
6484 && *position == self.diff_transforms.start().output_dimension.0
6485 {
6486 self.diff_transforms.prev();
6487 }
6488
6489 let overshoot = *position - self.diff_transforms.start().output_dimension.0;
6490 let mut excerpt_position = self.diff_transforms.start().excerpt_dimension.0;
6491 if let Some(DiffTransform::BufferContent { .. }) = self.diff_transforms.item() {
6492 excerpt_position.add_assign(&overshoot);
6493 }
6494
6495 self.excerpts
6496 .seek_forward(&ExcerptDimension(excerpt_position), Bias::Right);
6497 if self.excerpts.item().is_none() && excerpt_position == self.excerpts.start().0 {
6498 self.excerpts.prev();
6499 }
6500 }
6501
6502 fn next_excerpt(&mut self) {
6503 self.excerpts.next();
6504 self.seek_to_start_of_current_excerpt();
6505 }
6506
6507 fn prev_excerpt(&mut self) {
6508 self.excerpts.prev();
6509 self.seek_to_start_of_current_excerpt();
6510 }
6511
6512 fn seek_to_start_of_current_excerpt(&mut self) {
6513 self.cached_region.take();
6514 self.diff_transforms.seek(self.excerpts.start(), Bias::Left);
6515 if self.diff_transforms.end().excerpt_dimension == *self.excerpts.start()
6516 && self.diff_transforms.start().excerpt_dimension < *self.excerpts.start()
6517 && self.diff_transforms.next_item().is_some()
6518 {
6519 self.diff_transforms.next();
6520 }
6521 }
6522
6523 fn next(&mut self) {
6524 self.cached_region.take();
6525 match self
6526 .diff_transforms
6527 .end()
6528 .excerpt_dimension
6529 .cmp(&self.excerpts.end())
6530 {
6531 cmp::Ordering::Less => self.diff_transforms.next(),
6532 cmp::Ordering::Greater => self.excerpts.next(),
6533 cmp::Ordering::Equal => {
6534 self.diff_transforms.next();
6535 if self.diff_transforms.end().excerpt_dimension > self.excerpts.end()
6536 || self.diff_transforms.item().is_none()
6537 {
6538 self.excerpts.next();
6539 } else if let Some(DiffTransform::DeletedHunk { hunk_info, .. }) =
6540 self.diff_transforms.item()
6541 && self
6542 .excerpts
6543 .item()
6544 .is_some_and(|excerpt| excerpt.id != hunk_info.excerpt_id)
6545 {
6546 self.excerpts.next();
6547 }
6548 }
6549 }
6550 }
6551
6552 fn prev(&mut self) {
6553 self.cached_region.take();
6554 match self
6555 .diff_transforms
6556 .start()
6557 .excerpt_dimension
6558 .cmp(self.excerpts.start())
6559 {
6560 cmp::Ordering::Less => self.excerpts.prev(),
6561 cmp::Ordering::Greater => self.diff_transforms.prev(),
6562 cmp::Ordering::Equal => {
6563 self.diff_transforms.prev();
6564 if self.diff_transforms.start().excerpt_dimension < *self.excerpts.start()
6565 || self.diff_transforms.item().is_none()
6566 {
6567 self.excerpts.prev();
6568 }
6569 }
6570 }
6571 }
6572
6573 fn region(&mut self) -> Option<MultiBufferRegion<'a, D>> {
6574 if self.cached_region.is_none() {
6575 self.cached_region = self.build_region();
6576 }
6577 self.cached_region.clone()
6578 }
6579
6580 fn is_at_start_of_excerpt(&mut self) -> bool {
6581 if self.diff_transforms.start().excerpt_dimension > *self.excerpts.start() {
6582 return false;
6583 } else if self.diff_transforms.start().excerpt_dimension < *self.excerpts.start() {
6584 return true;
6585 }
6586
6587 self.diff_transforms.prev();
6588 let prev_transform = self.diff_transforms.item();
6589 self.diff_transforms.next();
6590
6591 prev_transform.is_none_or(|next_transform| {
6592 matches!(next_transform, DiffTransform::BufferContent { .. })
6593 })
6594 }
6595
6596 fn is_at_end_of_excerpt(&mut self) -> bool {
6597 if self.diff_transforms.end().excerpt_dimension < self.excerpts.end() {
6598 return false;
6599 } else if self.diff_transforms.end().excerpt_dimension > self.excerpts.end()
6600 || self.diff_transforms.item().is_none()
6601 {
6602 return true;
6603 }
6604
6605 let next_transform = self.diff_transforms.next_item();
6606 next_transform.is_none_or(|next_transform| match next_transform {
6607 DiffTransform::BufferContent { .. } => true,
6608 DiffTransform::DeletedHunk { hunk_info, .. } => self
6609 .excerpts
6610 .item()
6611 .is_some_and(|excerpt| excerpt.id != hunk_info.excerpt_id),
6612 })
6613 }
6614
6615 fn main_buffer_position(&self) -> Option<D> {
6616 let excerpt = self.excerpts.item()?;
6617 let buffer = &excerpt.buffer;
6618 let buffer_context_start = excerpt.range.context.start.summary::<D>(buffer);
6619 let mut buffer_start = buffer_context_start;
6620 let overshoot = self.diff_transforms.end().excerpt_dimension.0 - self.excerpts.start().0;
6621 buffer_start.add_assign(&overshoot);
6622 Some(buffer_start)
6623 }
6624
6625 fn build_region(&self) -> Option<MultiBufferRegion<'a, D>> {
6626 let excerpt = self.excerpts.item()?;
6627 match self.diff_transforms.item()? {
6628 DiffTransform::DeletedHunk {
6629 buffer_id,
6630 base_text_byte_range,
6631 has_trailing_newline,
6632 hunk_info,
6633 ..
6634 } => {
6635 let diff = self.diffs.get(buffer_id)?;
6636 let buffer = diff.base_text();
6637 let mut rope_cursor = buffer.as_rope().cursor(0);
6638 let buffer_start = rope_cursor.summary::<D>(base_text_byte_range.start);
6639 let buffer_range_len = rope_cursor.summary::<D>(base_text_byte_range.end);
6640 let mut buffer_end = buffer_start;
6641 buffer_end.add_assign(&buffer_range_len);
6642 let start = self.diff_transforms.start().output_dimension.0;
6643 let end = self.diff_transforms.end().output_dimension.0;
6644 Some(MultiBufferRegion {
6645 buffer,
6646 excerpt,
6647 has_trailing_newline: *has_trailing_newline,
6648 is_main_buffer: false,
6649 diff_hunk_status: Some(DiffHunkStatus::deleted(
6650 hunk_info.hunk_secondary_status,
6651 )),
6652 buffer_range: buffer_start..buffer_end,
6653 range: start..end,
6654 })
6655 }
6656 DiffTransform::BufferContent {
6657 inserted_hunk_info, ..
6658 } => {
6659 let buffer = &excerpt.buffer;
6660 let buffer_context_start = excerpt.range.context.start.summary::<D>(buffer);
6661
6662 let mut start = self.diff_transforms.start().output_dimension.0;
6663 let mut buffer_start = buffer_context_start;
6664 if self.diff_transforms.start().excerpt_dimension < *self.excerpts.start() {
6665 let overshoot =
6666 self.excerpts.start().0 - self.diff_transforms.start().excerpt_dimension.0;
6667 start.add_assign(&overshoot);
6668 } else {
6669 let overshoot =
6670 self.diff_transforms.start().excerpt_dimension.0 - self.excerpts.start().0;
6671 buffer_start.add_assign(&overshoot);
6672 }
6673
6674 let mut end;
6675 let mut buffer_end;
6676 let has_trailing_newline;
6677 if self.diff_transforms.end().excerpt_dimension.0 < self.excerpts.end().0 {
6678 let overshoot =
6679 self.diff_transforms.end().excerpt_dimension.0 - self.excerpts.start().0;
6680 end = self.diff_transforms.end().output_dimension.0;
6681 buffer_end = buffer_context_start;
6682 buffer_end.add_assign(&overshoot);
6683 has_trailing_newline = false;
6684 } else {
6685 let overshoot =
6686 self.excerpts.end().0 - self.diff_transforms.start().excerpt_dimension.0;
6687 end = self.diff_transforms.start().output_dimension.0;
6688 end.add_assign(&overshoot);
6689 buffer_end = excerpt.range.context.end.summary::<D>(buffer);
6690 has_trailing_newline = excerpt.has_trailing_newline;
6691 };
6692
6693 Some(MultiBufferRegion {
6694 buffer,
6695 excerpt,
6696 has_trailing_newline,
6697 is_main_buffer: true,
6698 diff_hunk_status: inserted_hunk_info
6699 .map(|info| DiffHunkStatus::added(info.hunk_secondary_status)),
6700 buffer_range: buffer_start..buffer_end,
6701 range: start..end,
6702 })
6703 }
6704 }
6705 }
6706
6707 fn excerpt(&self) -> Option<&'a Excerpt> {
6708 self.excerpts.item()
6709 }
6710}
6711
6712impl History {
6713 fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
6714 self.transaction_depth += 1;
6715 if self.transaction_depth == 1 {
6716 let id = self.next_transaction_id.tick();
6717 self.undo_stack.push(Transaction {
6718 id,
6719 buffer_transactions: Default::default(),
6720 first_edit_at: now,
6721 last_edit_at: now,
6722 suppress_grouping: false,
6723 });
6724 Some(id)
6725 } else {
6726 None
6727 }
6728 }
6729
6730 fn end_transaction(
6731 &mut self,
6732 now: Instant,
6733 buffer_transactions: HashMap<BufferId, TransactionId>,
6734 ) -> bool {
6735 assert_ne!(self.transaction_depth, 0);
6736 self.transaction_depth -= 1;
6737 if self.transaction_depth == 0 {
6738 if buffer_transactions.is_empty() {
6739 self.undo_stack.pop();
6740 false
6741 } else {
6742 self.redo_stack.clear();
6743 let transaction = self.undo_stack.last_mut().unwrap();
6744 transaction.last_edit_at = now;
6745 for (buffer_id, transaction_id) in buffer_transactions {
6746 transaction
6747 .buffer_transactions
6748 .entry(buffer_id)
6749 .or_insert(transaction_id);
6750 }
6751 true
6752 }
6753 } else {
6754 false
6755 }
6756 }
6757
6758 fn push_transaction<'a, T>(
6759 &mut self,
6760 buffer_transactions: T,
6761 now: Instant,
6762 cx: &Context<MultiBuffer>,
6763 ) where
6764 T: IntoIterator<Item = (&'a Entity<Buffer>, &'a language::Transaction)>,
6765 {
6766 assert_eq!(self.transaction_depth, 0);
6767 let transaction = Transaction {
6768 id: self.next_transaction_id.tick(),
6769 buffer_transactions: buffer_transactions
6770 .into_iter()
6771 .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
6772 .collect(),
6773 first_edit_at: now,
6774 last_edit_at: now,
6775 suppress_grouping: false,
6776 };
6777 if !transaction.buffer_transactions.is_empty() {
6778 self.undo_stack.push(transaction);
6779 self.redo_stack.clear();
6780 }
6781 }
6782
6783 fn finalize_last_transaction(&mut self) {
6784 if let Some(transaction) = self.undo_stack.last_mut() {
6785 transaction.suppress_grouping = true;
6786 }
6787 }
6788
6789 fn forget(&mut self, transaction_id: TransactionId) -> Option<Transaction> {
6790 if let Some(ix) = self
6791 .undo_stack
6792 .iter()
6793 .rposition(|transaction| transaction.id == transaction_id)
6794 {
6795 Some(self.undo_stack.remove(ix))
6796 } else if let Some(ix) = self
6797 .redo_stack
6798 .iter()
6799 .rposition(|transaction| transaction.id == transaction_id)
6800 {
6801 Some(self.redo_stack.remove(ix))
6802 } else {
6803 None
6804 }
6805 }
6806
6807 fn transaction(&self, transaction_id: TransactionId) -> Option<&Transaction> {
6808 self.undo_stack
6809 .iter()
6810 .find(|transaction| transaction.id == transaction_id)
6811 .or_else(|| {
6812 self.redo_stack
6813 .iter()
6814 .find(|transaction| transaction.id == transaction_id)
6815 })
6816 }
6817
6818 fn transaction_mut(&mut self, transaction_id: TransactionId) -> Option<&mut Transaction> {
6819 self.undo_stack
6820 .iter_mut()
6821 .find(|transaction| transaction.id == transaction_id)
6822 .or_else(|| {
6823 self.redo_stack
6824 .iter_mut()
6825 .find(|transaction| transaction.id == transaction_id)
6826 })
6827 }
6828
6829 fn pop_undo(&mut self) -> Option<&mut Transaction> {
6830 assert_eq!(self.transaction_depth, 0);
6831 if let Some(transaction) = self.undo_stack.pop() {
6832 self.redo_stack.push(transaction);
6833 self.redo_stack.last_mut()
6834 } else {
6835 None
6836 }
6837 }
6838
6839 fn pop_redo(&mut self) -> Option<&mut Transaction> {
6840 assert_eq!(self.transaction_depth, 0);
6841 if let Some(transaction) = self.redo_stack.pop() {
6842 self.undo_stack.push(transaction);
6843 self.undo_stack.last_mut()
6844 } else {
6845 None
6846 }
6847 }
6848
6849 fn remove_from_undo(&mut self, transaction_id: TransactionId) -> Option<&Transaction> {
6850 let ix = self
6851 .undo_stack
6852 .iter()
6853 .rposition(|transaction| transaction.id == transaction_id)?;
6854 let transaction = self.undo_stack.remove(ix);
6855 self.redo_stack.push(transaction);
6856 self.redo_stack.last()
6857 }
6858
6859 fn group(&mut self) -> Option<TransactionId> {
6860 let mut count = 0;
6861 let mut transactions = self.undo_stack.iter();
6862 if let Some(mut transaction) = transactions.next_back() {
6863 while let Some(prev_transaction) = transactions.next_back() {
6864 if !prev_transaction.suppress_grouping
6865 && transaction.first_edit_at - prev_transaction.last_edit_at
6866 <= self.group_interval
6867 {
6868 transaction = prev_transaction;
6869 count += 1;
6870 } else {
6871 break;
6872 }
6873 }
6874 }
6875 self.group_trailing(count)
6876 }
6877
6878 fn group_until(&mut self, transaction_id: TransactionId) {
6879 let mut count = 0;
6880 for transaction in self.undo_stack.iter().rev() {
6881 if transaction.id == transaction_id {
6882 self.group_trailing(count);
6883 break;
6884 } else if transaction.suppress_grouping {
6885 break;
6886 } else {
6887 count += 1;
6888 }
6889 }
6890 }
6891
6892 fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
6893 let new_len = self.undo_stack.len() - n;
6894 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
6895 if let Some(last_transaction) = transactions_to_keep.last_mut() {
6896 if let Some(transaction) = transactions_to_merge.last() {
6897 last_transaction.last_edit_at = transaction.last_edit_at;
6898 }
6899 for to_merge in transactions_to_merge {
6900 for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
6901 last_transaction
6902 .buffer_transactions
6903 .entry(*buffer_id)
6904 .or_insert(*transaction_id);
6905 }
6906 }
6907 }
6908
6909 self.undo_stack.truncate(new_len);
6910 self.undo_stack.last().map(|t| t.id)
6911 }
6912}
6913
6914impl Excerpt {
6915 fn new(
6916 id: ExcerptId,
6917 locator: Locator,
6918 buffer_id: BufferId,
6919 buffer: BufferSnapshot,
6920 range: ExcerptRange<text::Anchor>,
6921 has_trailing_newline: bool,
6922 ) -> Self {
6923 Excerpt {
6924 id,
6925 locator,
6926 max_buffer_row: range.context.end.to_point(&buffer).row,
6927 text_summary: buffer
6928 .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
6929 buffer_id,
6930 buffer,
6931 range,
6932 has_trailing_newline,
6933 }
6934 }
6935
6936 fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks<'_> {
6937 let content_start = self.range.context.start.to_offset(&self.buffer);
6938 let chunks_start = content_start + range.start;
6939 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
6940
6941 let footer_height = if self.has_trailing_newline
6942 && range.start <= self.text_summary.len
6943 && range.end > self.text_summary.len
6944 {
6945 1
6946 } else {
6947 0
6948 };
6949
6950 let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
6951
6952 ExcerptChunks {
6953 excerpt_id: self.id,
6954 content_chunks,
6955 footer_height,
6956 }
6957 }
6958
6959 fn seek_chunks(&self, excerpt_chunks: &mut ExcerptChunks, range: Range<usize>) {
6960 let content_start = self.range.context.start.to_offset(&self.buffer);
6961 let chunks_start = content_start + range.start;
6962 let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
6963 excerpt_chunks.content_chunks.seek(chunks_start..chunks_end);
6964 excerpt_chunks.footer_height = if self.has_trailing_newline
6965 && range.start <= self.text_summary.len
6966 && range.end > self.text_summary.len
6967 {
6968 1
6969 } else {
6970 0
6971 };
6972 }
6973
6974 fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
6975 if text_anchor
6976 .cmp(&self.range.context.start, &self.buffer)
6977 .is_lt()
6978 {
6979 self.range.context.start
6980 } else if text_anchor
6981 .cmp(&self.range.context.end, &self.buffer)
6982 .is_gt()
6983 {
6984 self.range.context.end
6985 } else {
6986 text_anchor
6987 }
6988 }
6989
6990 fn contains(&self, anchor: &Anchor) -> bool {
6991 (anchor.buffer_id == None || anchor.buffer_id == Some(self.buffer_id))
6992 && self
6993 .range
6994 .context
6995 .start
6996 .cmp(&anchor.text_anchor, &self.buffer)
6997 .is_le()
6998 && self
6999 .range
7000 .context
7001 .end
7002 .cmp(&anchor.text_anchor, &self.buffer)
7003 .is_ge()
7004 }
7005
7006 /// The [`Excerpt`]'s start offset in its [`Buffer`]
7007 fn buffer_start_offset(&self) -> usize {
7008 self.range.context.start.to_offset(&self.buffer)
7009 }
7010
7011 /// The [`Excerpt`]'s end offset in its [`Buffer`]
7012 fn buffer_end_offset(&self) -> usize {
7013 self.buffer_start_offset() + self.text_summary.len
7014 }
7015}
7016
7017impl<'a> MultiBufferExcerpt<'a> {
7018 pub fn id(&self) -> ExcerptId {
7019 self.excerpt.id
7020 }
7021
7022 pub fn buffer_id(&self) -> BufferId {
7023 self.excerpt.buffer_id
7024 }
7025
7026 pub fn start_anchor(&self) -> Anchor {
7027 Anchor::in_buffer(
7028 self.excerpt.id,
7029 self.excerpt.buffer_id,
7030 self.excerpt.range.context.start,
7031 )
7032 }
7033
7034 pub fn end_anchor(&self) -> Anchor {
7035 Anchor::in_buffer(
7036 self.excerpt.id,
7037 self.excerpt.buffer_id,
7038 self.excerpt.range.context.end,
7039 )
7040 }
7041
7042 pub fn buffer(&self) -> &'a BufferSnapshot {
7043 &self.excerpt.buffer
7044 }
7045
7046 pub fn buffer_range(&self) -> Range<usize> {
7047 self.buffer_offset
7048 ..self
7049 .excerpt
7050 .range
7051 .context
7052 .end
7053 .to_offset(&self.excerpt.buffer.text)
7054 }
7055
7056 pub fn start_offset(&self) -> usize {
7057 self.offset
7058 }
7059
7060 /// Maps an offset within the [`MultiBuffer`] to an offset within the [`Buffer`]
7061 pub fn map_offset_to_buffer(&mut self, offset: usize) -> usize {
7062 self.map_range_to_buffer(offset..offset).start
7063 }
7064
7065 /// Maps a range within the [`MultiBuffer`] to a range within the [`Buffer`]
7066 pub fn map_range_to_buffer(&mut self, range: Range<usize>) -> Range<usize> {
7067 self.diff_transforms
7068 .seek(&OutputDimension(range.start), Bias::Right);
7069 let start = self.map_offset_to_buffer_internal(range.start);
7070 let end = if range.end > range.start {
7071 self.diff_transforms
7072 .seek_forward(&OutputDimension(range.end), Bias::Right);
7073 self.map_offset_to_buffer_internal(range.end)
7074 } else {
7075 start
7076 };
7077 start..end
7078 }
7079
7080 fn map_offset_to_buffer_internal(&self, offset: usize) -> usize {
7081 let mut excerpt_offset = self.diff_transforms.start().excerpt_dimension.clone();
7082 if let Some(DiffTransform::BufferContent { .. }) = self.diff_transforms.item() {
7083 excerpt_offset.0 += offset - self.diff_transforms.start().output_dimension.0;
7084 };
7085 let offset_in_excerpt = excerpt_offset.0.saturating_sub(self.excerpt_offset.0);
7086 self.buffer_offset + offset_in_excerpt
7087 }
7088
7089 /// Map an offset within the [`Buffer`] to an offset within the [`MultiBuffer`]
7090 pub fn map_offset_from_buffer(&mut self, buffer_offset: usize) -> usize {
7091 self.map_range_from_buffer(buffer_offset..buffer_offset)
7092 .start
7093 }
7094
7095 /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
7096 pub fn map_range_from_buffer(&mut self, buffer_range: Range<usize>) -> Range<usize> {
7097 if buffer_range.start < self.buffer_offset {
7098 log::warn!(
7099 "Attempting to map a range from a buffer offset that starts before the current buffer offset"
7100 );
7101 return buffer_range;
7102 }
7103 let overshoot = buffer_range.start - self.buffer_offset;
7104 let excerpt_offset = ExcerptDimension(self.excerpt_offset.0 + overshoot);
7105 self.diff_transforms.seek(&excerpt_offset, Bias::Right);
7106 if excerpt_offset.0 < self.diff_transforms.start().excerpt_dimension.0 {
7107 log::warn!(
7108 "Attempting to map a range from a buffer offset that starts before the current buffer offset"
7109 );
7110 return buffer_range;
7111 }
7112 let overshoot = excerpt_offset.0 - self.diff_transforms.start().excerpt_dimension.0;
7113 let start = self.diff_transforms.start().output_dimension.0 + overshoot;
7114
7115 let end = if buffer_range.end > buffer_range.start {
7116 let overshoot = buffer_range.end - self.buffer_offset;
7117 let excerpt_offset = ExcerptDimension(self.excerpt_offset.0 + overshoot);
7118 self.diff_transforms
7119 .seek_forward(&excerpt_offset, Bias::Right);
7120 let overshoot = excerpt_offset.0 - self.diff_transforms.start().excerpt_dimension.0;
7121 self.diff_transforms.start().output_dimension.0 + overshoot
7122 } else {
7123 start
7124 };
7125
7126 start..end
7127 }
7128
7129 /// Returns true if the entirety of the given range is in the buffer's excerpt
7130 pub fn contains_buffer_range(&self, range: Range<usize>) -> bool {
7131 range.start >= self.excerpt.buffer_start_offset()
7132 && range.end <= self.excerpt.buffer_end_offset()
7133 }
7134
7135 pub fn max_buffer_row(&self) -> u32 {
7136 self.excerpt.max_buffer_row
7137 }
7138}
7139
7140impl ExcerptId {
7141 pub fn min() -> Self {
7142 Self(0)
7143 }
7144
7145 pub fn max() -> Self {
7146 Self(u32::MAX)
7147 }
7148
7149 pub fn to_proto(self) -> u64 {
7150 self.0 as _
7151 }
7152
7153 pub fn from_proto(proto: u64) -> Self {
7154 Self(proto as _)
7155 }
7156
7157 pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
7158 let a = snapshot.excerpt_locator_for_id(*self);
7159 let b = snapshot.excerpt_locator_for_id(*other);
7160 a.cmp(b).then_with(|| self.0.cmp(&other.0))
7161 }
7162}
7163
7164impl From<ExcerptId> for usize {
7165 fn from(val: ExcerptId) -> Self {
7166 val.0 as usize
7167 }
7168}
7169
7170impl fmt::Debug for Excerpt {
7171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7172 f.debug_struct("Excerpt")
7173 .field("id", &self.id)
7174 .field("locator", &self.locator)
7175 .field("buffer_id", &self.buffer_id)
7176 .field("range", &self.range)
7177 .field("text_summary", &self.text_summary)
7178 .field("has_trailing_newline", &self.has_trailing_newline)
7179 .finish()
7180 }
7181}
7182
7183impl sum_tree::Item for Excerpt {
7184 type Summary = ExcerptSummary;
7185
7186 fn summary(&self, _cx: ()) -> Self::Summary {
7187 let mut text = self.text_summary;
7188 if self.has_trailing_newline {
7189 text += TextSummary::from("\n");
7190 }
7191 ExcerptSummary {
7192 excerpt_id: self.id,
7193 excerpt_locator: self.locator.clone(),
7194 widest_line_number: self.max_buffer_row,
7195 text,
7196 }
7197 }
7198}
7199
7200impl sum_tree::Item for ExcerptIdMapping {
7201 type Summary = ExcerptId;
7202
7203 fn summary(&self, _cx: ()) -> Self::Summary {
7204 self.id
7205 }
7206}
7207
7208impl sum_tree::KeyedItem for ExcerptIdMapping {
7209 type Key = ExcerptId;
7210
7211 fn key(&self) -> Self::Key {
7212 self.id
7213 }
7214}
7215
7216impl DiffTransform {
7217 fn hunk_info(&self) -> Option<DiffTransformHunkInfo> {
7218 match self {
7219 DiffTransform::DeletedHunk { hunk_info, .. } => Some(*hunk_info),
7220 DiffTransform::BufferContent {
7221 inserted_hunk_info, ..
7222 } => *inserted_hunk_info,
7223 }
7224 }
7225}
7226
7227impl sum_tree::Item for DiffTransform {
7228 type Summary = DiffTransformSummary;
7229
7230 fn summary(&self, _: <Self::Summary as sum_tree::Summary>::Context<'_>) -> Self::Summary {
7231 match self {
7232 DiffTransform::BufferContent { summary, .. } => DiffTransformSummary {
7233 input: *summary,
7234 output: *summary,
7235 },
7236 DiffTransform::DeletedHunk { summary, .. } => DiffTransformSummary {
7237 input: TextSummary::default(),
7238 output: *summary,
7239 },
7240 }
7241 }
7242}
7243
7244impl DiffTransformSummary {
7245 fn excerpt_len(&self) -> ExcerptOffset {
7246 ExcerptOffset::new(self.input.len)
7247 }
7248}
7249
7250impl sum_tree::ContextLessSummary for DiffTransformSummary {
7251 fn zero() -> Self {
7252 DiffTransformSummary {
7253 input: TextSummary::default(),
7254 output: TextSummary::default(),
7255 }
7256 }
7257
7258 fn add_summary(&mut self, other: &Self) {
7259 self.input += other.input;
7260 self.output += other.output;
7261 }
7262}
7263
7264impl sum_tree::ContextLessSummary for ExcerptId {
7265 fn zero() -> Self {
7266 Self(0)
7267 }
7268
7269 fn add_summary(&mut self, summary: &Self) {
7270 *self = cmp::max(*self, *summary);
7271 }
7272}
7273
7274impl sum_tree::ContextLessSummary for ExcerptSummary {
7275 fn zero() -> Self {
7276 Self::default()
7277 }
7278
7279 fn add_summary(&mut self, summary: &Self) {
7280 debug_assert!(summary.excerpt_locator > self.excerpt_locator);
7281 self.excerpt_locator = summary.excerpt_locator.clone();
7282 Summary::add_summary(&mut self.text, &summary.text, ());
7283 self.widest_line_number = cmp::max(self.widest_line_number, summary.widest_line_number);
7284 }
7285}
7286
7287impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for ExcerptOffset {
7288 fn zero(_cx: ()) -> Self {
7289 Default::default()
7290 }
7291
7292 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: ()) {
7293 self.value += summary.text.len;
7294 }
7295}
7296
7297impl sum_tree::SeekTarget<'_, ExcerptSummary, ExcerptSummary> for ExcerptOffset {
7298 fn cmp(&self, cursor_location: &ExcerptSummary, _: ()) -> cmp::Ordering {
7299 Ord::cmp(&self.value, &cursor_location.text.len)
7300 }
7301}
7302
7303impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
7304 fn cmp(&self, cursor_location: &Option<&'a Locator>, _: ()) -> cmp::Ordering {
7305 Ord::cmp(&Some(self), cursor_location)
7306 }
7307}
7308
7309impl sum_tree::SeekTarget<'_, ExcerptSummary, ExcerptSummary> for Locator {
7310 fn cmp(&self, cursor_location: &ExcerptSummary, _: ()) -> cmp::Ordering {
7311 Ord::cmp(self, &cursor_location.excerpt_locator)
7312 }
7313}
7314
7315impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for ExcerptPoint {
7316 fn zero(_cx: ()) -> Self {
7317 Default::default()
7318 }
7319
7320 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: ()) {
7321 self.value += summary.text.lines;
7322 }
7323}
7324
7325impl<'a, D: TextDimension + Default> sum_tree::Dimension<'a, ExcerptSummary>
7326 for ExcerptDimension<D>
7327{
7328 fn zero(_: ()) -> Self {
7329 ExcerptDimension(D::default())
7330 }
7331
7332 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: ()) {
7333 self.0.add_assign(&D::from_text_summary(&summary.text))
7334 }
7335}
7336
7337impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
7338 fn zero(_cx: ()) -> Self {
7339 Default::default()
7340 }
7341
7342 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: ()) {
7343 *self = Some(&summary.excerpt_locator);
7344 }
7345}
7346
7347impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
7348 fn zero(_cx: ()) -> Self {
7349 Default::default()
7350 }
7351
7352 fn add_summary(&mut self, summary: &'a ExcerptSummary, _: ()) {
7353 *self = Some(summary.excerpt_id);
7354 }
7355}
7356
7357#[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
7358struct ExcerptDimension<T>(T);
7359
7360#[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
7361struct OutputDimension<T>(T);
7362
7363impl<'a> sum_tree::Dimension<'a, DiffTransformSummary> for ExcerptOffset {
7364 fn zero(_: ()) -> Self {
7365 ExcerptOffset::new(0)
7366 }
7367
7368 fn add_summary(&mut self, summary: &'a DiffTransformSummary, _: ()) {
7369 self.value += summary.input.len;
7370 }
7371}
7372
7373impl<'a> sum_tree::Dimension<'a, DiffTransformSummary> for ExcerptPoint {
7374 fn zero(_: ()) -> Self {
7375 ExcerptPoint::new(0, 0)
7376 }
7377
7378 fn add_summary(&mut self, summary: &'a DiffTransformSummary, _: ()) {
7379 self.value += summary.input.lines;
7380 }
7381}
7382
7383impl<D: TextDimension + Ord> sum_tree::SeekTarget<'_, DiffTransformSummary, DiffTransformSummary>
7384 for ExcerptDimension<D>
7385{
7386 fn cmp(&self, cursor_location: &DiffTransformSummary, _: ()) -> cmp::Ordering {
7387 Ord::cmp(&self.0, &D::from_text_summary(&cursor_location.input))
7388 }
7389}
7390
7391impl<D: TextDimension + Ord> sum_tree::SeekTarget<'_, DiffTransformSummary, DiffTransforms<D>>
7392 for ExcerptDimension<D>
7393{
7394 fn cmp(&self, cursor_location: &DiffTransforms<D>, _: ()) -> cmp::Ordering {
7395 Ord::cmp(&self.0, &cursor_location.excerpt_dimension.0)
7396 }
7397}
7398
7399impl<'a, D: TextDimension> sum_tree::Dimension<'a, DiffTransformSummary> for ExcerptDimension<D> {
7400 fn zero(_: ()) -> Self {
7401 ExcerptDimension(D::default())
7402 }
7403
7404 fn add_summary(&mut self, summary: &'a DiffTransformSummary, _: ()) {
7405 self.0.add_assign(&D::from_text_summary(&summary.input))
7406 }
7407}
7408
7409impl<D: TextDimension + Ord> sum_tree::SeekTarget<'_, DiffTransformSummary, DiffTransforms<D>>
7410 for OutputDimension<D>
7411{
7412 fn cmp(&self, cursor_location: &DiffTransforms<D>, _: ()) -> cmp::Ordering {
7413 Ord::cmp(&self.0, &cursor_location.output_dimension.0)
7414 }
7415}
7416
7417impl<'a, D: TextDimension> sum_tree::Dimension<'a, DiffTransformSummary> for OutputDimension<D> {
7418 fn zero(_: ()) -> Self {
7419 OutputDimension(D::default())
7420 }
7421
7422 fn add_summary(&mut self, summary: &'a DiffTransformSummary, _: ()) {
7423 self.0.add_assign(&D::from_text_summary(&summary.output))
7424 }
7425}
7426
7427impl<'a> sum_tree::Dimension<'a, DiffTransformSummary> for TextSummary {
7428 fn zero(_: ()) -> Self {
7429 TextSummary::default()
7430 }
7431
7432 fn add_summary(&mut self, summary: &'a DiffTransformSummary, _: ()) {
7433 *self += summary.output
7434 }
7435}
7436
7437impl<'a> sum_tree::Dimension<'a, DiffTransformSummary> for usize {
7438 fn zero(_: ()) -> Self {
7439 0
7440 }
7441
7442 fn add_summary(&mut self, summary: &'a DiffTransformSummary, _: ()) {
7443 *self += summary.output.len
7444 }
7445}
7446
7447impl<'a> sum_tree::Dimension<'a, DiffTransformSummary> for Point {
7448 fn zero(_: ()) -> Self {
7449 Point::new(0, 0)
7450 }
7451
7452 fn add_summary(&mut self, summary: &'a DiffTransformSummary, _: ()) {
7453 *self += summary.output.lines
7454 }
7455}
7456
7457impl MultiBufferRows<'_> {
7458 pub fn seek(&mut self, MultiBufferRow(row): MultiBufferRow) {
7459 self.point = Point::new(row, 0);
7460 self.cursor.seek(&self.point);
7461 }
7462}
7463
7464impl Iterator for MultiBufferRows<'_> {
7465 type Item = RowInfo;
7466
7467 fn next(&mut self) -> Option<Self::Item> {
7468 if self.is_empty && self.point.row == 0 {
7469 self.point += Point::new(1, 0);
7470 return Some(RowInfo {
7471 buffer_id: None,
7472 buffer_row: Some(0),
7473 multibuffer_row: Some(MultiBufferRow(0)),
7474 diff_status: None,
7475 expand_info: None,
7476 });
7477 }
7478
7479 let mut region = self.cursor.region()?;
7480 while self.point >= region.range.end {
7481 self.cursor.next();
7482 if let Some(next_region) = self.cursor.region() {
7483 region = next_region;
7484 } else if self.point == self.cursor.diff_transforms.end().output_dimension.0 {
7485 let multibuffer_row = MultiBufferRow(self.point.row);
7486 let last_excerpt = self
7487 .cursor
7488 .excerpts
7489 .item()
7490 .or(self.cursor.excerpts.prev_item())?;
7491 let last_row = last_excerpt
7492 .range
7493 .context
7494 .end
7495 .to_point(&last_excerpt.buffer)
7496 .row;
7497
7498 let first_row = last_excerpt
7499 .range
7500 .context
7501 .start
7502 .to_point(&last_excerpt.buffer)
7503 .row;
7504
7505 let expand_info = if self.is_singleton {
7506 None
7507 } else {
7508 let needs_expand_up = first_row == last_row
7509 && last_row > 0
7510 && !region.diff_hunk_status.is_some_and(|d| d.is_deleted());
7511 let needs_expand_down = last_row < last_excerpt.buffer.max_point().row;
7512
7513 if needs_expand_up && needs_expand_down {
7514 Some(ExpandExcerptDirection::UpAndDown)
7515 } else if needs_expand_up {
7516 Some(ExpandExcerptDirection::Up)
7517 } else if needs_expand_down {
7518 Some(ExpandExcerptDirection::Down)
7519 } else {
7520 None
7521 }
7522 .map(|direction| ExpandInfo {
7523 direction,
7524 excerpt_id: last_excerpt.id,
7525 })
7526 };
7527 self.point += Point::new(1, 0);
7528 return Some(RowInfo {
7529 buffer_id: Some(last_excerpt.buffer_id),
7530 buffer_row: Some(last_row),
7531 multibuffer_row: Some(multibuffer_row),
7532 diff_status: None,
7533 expand_info,
7534 });
7535 } else {
7536 return None;
7537 };
7538 }
7539
7540 let overshoot = self.point - region.range.start;
7541 let buffer_point = region.buffer_range.start + overshoot;
7542 let expand_info = if self.is_singleton {
7543 None
7544 } else {
7545 let needs_expand_up = self.point.row == region.range.start.row
7546 && self.cursor.is_at_start_of_excerpt()
7547 && buffer_point.row > 0;
7548 let needs_expand_down = (region.excerpt.has_trailing_newline
7549 && self.point.row + 1 == region.range.end.row
7550 || !region.excerpt.has_trailing_newline && self.point.row == region.range.end.row)
7551 && self.cursor.is_at_end_of_excerpt()
7552 && buffer_point.row < region.buffer.max_point().row;
7553
7554 if needs_expand_up && needs_expand_down {
7555 Some(ExpandExcerptDirection::UpAndDown)
7556 } else if needs_expand_up {
7557 Some(ExpandExcerptDirection::Up)
7558 } else if needs_expand_down {
7559 Some(ExpandExcerptDirection::Down)
7560 } else {
7561 None
7562 }
7563 .map(|direction| ExpandInfo {
7564 direction,
7565 excerpt_id: region.excerpt.id,
7566 })
7567 };
7568
7569 let result = Some(RowInfo {
7570 buffer_id: Some(region.buffer.remote_id()),
7571 buffer_row: Some(buffer_point.row),
7572 multibuffer_row: Some(MultiBufferRow(self.point.row)),
7573 diff_status: region
7574 .diff_hunk_status
7575 .filter(|_| self.point < region.range.end),
7576 expand_info,
7577 });
7578 self.point += Point::new(1, 0);
7579 result
7580 }
7581}
7582
7583impl<'a> MultiBufferChunks<'a> {
7584 pub fn offset(&self) -> usize {
7585 self.range.start
7586 }
7587
7588 pub fn seek(&mut self, range: Range<usize>) {
7589 self.diff_transforms.seek(&range.end, Bias::Right);
7590 let mut excerpt_end = self.diff_transforms.start().1;
7591 if let Some(DiffTransform::BufferContent { .. }) = self.diff_transforms.item() {
7592 let overshoot = range.end - self.diff_transforms.start().0;
7593 excerpt_end.value += overshoot;
7594 }
7595
7596 self.diff_transforms.seek(&range.start, Bias::Right);
7597 let mut excerpt_start = self.diff_transforms.start().1;
7598 if let Some(DiffTransform::BufferContent { .. }) = self.diff_transforms.item() {
7599 let overshoot = range.start - self.diff_transforms.start().0;
7600 excerpt_start.value += overshoot;
7601 }
7602
7603 self.seek_to_excerpt_offset_range(excerpt_start..excerpt_end);
7604 self.buffer_chunk.take();
7605 self.range = range;
7606 }
7607
7608 fn seek_to_excerpt_offset_range(&mut self, new_range: Range<ExcerptOffset>) {
7609 self.excerpt_offset_range = new_range.clone();
7610 self.excerpts.seek(&new_range.start, Bias::Right);
7611 if let Some(excerpt) = self.excerpts.item() {
7612 let excerpt_start = *self.excerpts.start();
7613 if let Some(excerpt_chunks) = self
7614 .excerpt_chunks
7615 .as_mut()
7616 .filter(|chunks| excerpt.id == chunks.excerpt_id)
7617 {
7618 excerpt.seek_chunks(
7619 excerpt_chunks,
7620 (self.excerpt_offset_range.start - excerpt_start).value
7621 ..(self.excerpt_offset_range.end - excerpt_start).value,
7622 );
7623 } else {
7624 self.excerpt_chunks = Some(excerpt.chunks_in_range(
7625 (self.excerpt_offset_range.start - excerpt_start).value
7626 ..(self.excerpt_offset_range.end - excerpt_start).value,
7627 self.language_aware,
7628 ));
7629 }
7630 } else {
7631 self.excerpt_chunks = None;
7632 }
7633 }
7634
7635 fn next_excerpt_chunk(&mut self) -> Option<Chunk<'a>> {
7636 loop {
7637 if self.excerpt_offset_range.is_empty() {
7638 return None;
7639 } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
7640 self.excerpt_offset_range.start.value += chunk.text.len();
7641 return Some(chunk);
7642 } else {
7643 self.excerpts.next();
7644 let excerpt = self.excerpts.item()?;
7645 self.excerpt_chunks = Some(excerpt.chunks_in_range(
7646 0..(self.excerpt_offset_range.end - *self.excerpts.start()).value,
7647 self.language_aware,
7648 ));
7649 }
7650 }
7651 }
7652}
7653
7654impl<'a> Iterator for ReversedMultiBufferChunks<'a> {
7655 type Item = &'a str;
7656
7657 fn next(&mut self) -> Option<Self::Item> {
7658 let mut region = self.cursor.region()?;
7659 if self.offset == region.range.start {
7660 self.cursor.prev();
7661 region = self.cursor.region()?;
7662 let start_overshoot = self.start.saturating_sub(region.range.start);
7663 self.current_chunks = Some(region.buffer.reversed_chunks_in_range(
7664 region.buffer_range.start + start_overshoot..region.buffer_range.end,
7665 ));
7666 }
7667
7668 if self.offset == region.range.end && region.has_trailing_newline {
7669 self.offset -= 1;
7670 Some("\n")
7671 } else {
7672 let chunk = self.current_chunks.as_mut().unwrap().next()?;
7673 self.offset -= chunk.len();
7674 Some(chunk)
7675 }
7676 }
7677}
7678
7679impl<'a> Iterator for MultiBufferChunks<'a> {
7680 type Item = Chunk<'a>;
7681
7682 fn next(&mut self) -> Option<Chunk<'a>> {
7683 if self.range.start >= self.range.end {
7684 return None;
7685 }
7686 if self.range.start == self.diff_transforms.end().0 {
7687 self.diff_transforms.next();
7688 }
7689
7690 let diff_transform_start = self.diff_transforms.start().0;
7691 let diff_transform_end = self.diff_transforms.end().0;
7692 debug_assert!(self.range.start < diff_transform_end);
7693
7694 let diff_transform = self.diff_transforms.item()?;
7695 match diff_transform {
7696 DiffTransform::BufferContent { .. } => {
7697 let chunk = if let Some(chunk) = &mut self.buffer_chunk {
7698 chunk
7699 } else {
7700 let chunk = self.next_excerpt_chunk().unwrap();
7701 self.buffer_chunk.insert(chunk)
7702 };
7703
7704 let chunk_end = self.range.start + chunk.text.len();
7705 let diff_transform_end = diff_transform_end.min(self.range.end);
7706
7707 if diff_transform_end < chunk_end {
7708 let split_idx = diff_transform_end - self.range.start;
7709 let (before, after) = chunk.text.split_at(split_idx);
7710 self.range.start = diff_transform_end;
7711 let mask = (1 << split_idx) - 1;
7712 let chars = chunk.chars & mask;
7713 let tabs = chunk.tabs & mask;
7714
7715 chunk.text = after;
7716 chunk.chars = chunk.chars >> split_idx;
7717 chunk.tabs = chunk.tabs >> split_idx;
7718
7719 Some(Chunk {
7720 text: before,
7721 chars,
7722 tabs,
7723 ..chunk.clone()
7724 })
7725 } else {
7726 self.range.start = chunk_end;
7727 self.buffer_chunk.take()
7728 }
7729 }
7730 DiffTransform::DeletedHunk {
7731 buffer_id,
7732 base_text_byte_range,
7733 has_trailing_newline,
7734 ..
7735 } => {
7736 let base_text_start =
7737 base_text_byte_range.start + self.range.start - diff_transform_start;
7738 let base_text_end =
7739 base_text_byte_range.start + self.range.end - diff_transform_start;
7740 let base_text_end = base_text_end.min(base_text_byte_range.end);
7741
7742 let mut chunks = if let Some((_, mut chunks)) = self
7743 .diff_base_chunks
7744 .take()
7745 .filter(|(id, _)| id == buffer_id)
7746 {
7747 if chunks.range().start != base_text_start || chunks.range().end < base_text_end
7748 {
7749 chunks.seek(base_text_start..base_text_end);
7750 }
7751 chunks
7752 } else {
7753 let base_buffer = &self.diffs.get(buffer_id)?.base_text();
7754 base_buffer.chunks(base_text_start..base_text_end, self.language_aware)
7755 };
7756
7757 let chunk = if let Some(chunk) = chunks.next() {
7758 self.range.start += chunk.text.len();
7759 self.diff_base_chunks = Some((*buffer_id, chunks));
7760 chunk
7761 } else {
7762 debug_assert!(has_trailing_newline);
7763 self.range.start += "\n".len();
7764 Chunk {
7765 text: "\n",
7766 chars: 1u128,
7767 ..Default::default()
7768 }
7769 };
7770 Some(chunk)
7771 }
7772 }
7773 }
7774}
7775
7776impl MultiBufferBytes<'_> {
7777 fn consume(&mut self, len: usize) {
7778 self.range.start += len;
7779 self.chunk = &self.chunk[len..];
7780
7781 if !self.range.is_empty() && self.chunk.is_empty() {
7782 if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
7783 self.chunk = chunk;
7784 } else if self.has_trailing_newline {
7785 self.has_trailing_newline = false;
7786 self.chunk = b"\n";
7787 } else {
7788 self.cursor.next();
7789 if let Some(region) = self.cursor.region() {
7790 let mut excerpt_bytes = region.buffer.bytes_in_range(
7791 region.buffer_range.start
7792 ..(region.buffer_range.start + self.range.end - region.range.start)
7793 .min(region.buffer_range.end),
7794 );
7795 self.chunk = excerpt_bytes.next().unwrap_or(&[]);
7796 self.excerpt_bytes = Some(excerpt_bytes);
7797 self.has_trailing_newline =
7798 region.has_trailing_newline && self.range.end >= region.range.end;
7799 if self.chunk.is_empty() && self.has_trailing_newline {
7800 self.has_trailing_newline = false;
7801 self.chunk = b"\n";
7802 }
7803 }
7804 }
7805 }
7806 }
7807}
7808
7809impl<'a> Iterator for MultiBufferBytes<'a> {
7810 type Item = &'a [u8];
7811
7812 fn next(&mut self) -> Option<Self::Item> {
7813 let chunk = self.chunk;
7814 if chunk.is_empty() {
7815 None
7816 } else {
7817 self.consume(chunk.len());
7818 Some(chunk)
7819 }
7820 }
7821}
7822
7823impl io::Read for MultiBufferBytes<'_> {
7824 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
7825 let len = cmp::min(buf.len(), self.chunk.len());
7826 buf[..len].copy_from_slice(&self.chunk[..len]);
7827 if len > 0 {
7828 self.consume(len);
7829 }
7830 Ok(len)
7831 }
7832}
7833
7834impl io::Read for ReversedMultiBufferBytes<'_> {
7835 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
7836 let len = cmp::min(buf.len(), self.chunk.len());
7837 buf[..len].copy_from_slice(&self.chunk[..len]);
7838 buf[..len].reverse();
7839 if len > 0 {
7840 self.range.end -= len;
7841 self.chunk = &self.chunk[..self.chunk.len() - len];
7842 if !self.range.is_empty()
7843 && self.chunk.is_empty()
7844 && let Some(chunk) = self.chunks.next()
7845 {
7846 self.chunk = chunk.as_bytes();
7847 }
7848 }
7849 Ok(len)
7850 }
7851}
7852
7853impl<'a> Iterator for ExcerptChunks<'a> {
7854 type Item = Chunk<'a>;
7855
7856 fn next(&mut self) -> Option<Self::Item> {
7857 if let Some(chunk) = self.content_chunks.next() {
7858 return Some(chunk);
7859 }
7860
7861 if self.footer_height > 0 {
7862 let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
7863 let chars = (1 << self.footer_height) - 1;
7864 self.footer_height = 0;
7865 return Some(Chunk {
7866 text,
7867 chars,
7868 ..Default::default()
7869 });
7870 }
7871
7872 None
7873 }
7874}
7875
7876impl ToOffset for Point {
7877 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
7878 snapshot.point_to_offset(*self)
7879 }
7880}
7881
7882impl ToOffset for usize {
7883 #[track_caller]
7884 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
7885 assert!(
7886 *self <= snapshot.len(),
7887 "offset {} is greater than the snapshot.len() {}",
7888 *self,
7889 snapshot.len(),
7890 );
7891 *self
7892 }
7893}
7894
7895impl ToOffset for OffsetUtf16 {
7896 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
7897 snapshot.offset_utf16_to_offset(*self)
7898 }
7899}
7900
7901impl ToOffset for PointUtf16 {
7902 fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
7903 snapshot.point_utf16_to_offset(*self)
7904 }
7905}
7906
7907impl ToOffsetUtf16 for OffsetUtf16 {
7908 fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
7909 *self
7910 }
7911}
7912
7913impl ToOffsetUtf16 for usize {
7914 fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
7915 snapshot.offset_to_offset_utf16(*self)
7916 }
7917}
7918
7919impl ToPoint for usize {
7920 fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
7921 snapshot.offset_to_point(*self)
7922 }
7923}
7924
7925impl ToPoint for Point {
7926 fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
7927 *self
7928 }
7929}
7930
7931impl ToPointUtf16 for usize {
7932 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
7933 snapshot.offset_to_point_utf16(*self)
7934 }
7935}
7936
7937impl ToPointUtf16 for Point {
7938 fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
7939 snapshot.point_to_point_utf16(*self)
7940 }
7941}
7942
7943impl ToPointUtf16 for PointUtf16 {
7944 fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
7945 *self
7946 }
7947}
7948
7949impl From<ExcerptId> for EntityId {
7950 fn from(id: ExcerptId) -> Self {
7951 EntityId::from(id.0 as u64)
7952 }
7953}
7954
7955#[cfg(debug_assertions)]
7956pub mod debug {
7957 use super::*;
7958
7959 pub trait ToMultiBufferDebugRanges {
7960 fn to_multi_buffer_debug_ranges(&self, snapshot: &MultiBufferSnapshot)
7961 -> Vec<Range<usize>>;
7962 }
7963
7964 impl<T: ToOffset> ToMultiBufferDebugRanges for T {
7965 fn to_multi_buffer_debug_ranges(
7966 &self,
7967 snapshot: &MultiBufferSnapshot,
7968 ) -> Vec<Range<usize>> {
7969 [self.to_offset(snapshot)].to_multi_buffer_debug_ranges(snapshot)
7970 }
7971 }
7972
7973 impl<T: ToOffset> ToMultiBufferDebugRanges for Range<T> {
7974 fn to_multi_buffer_debug_ranges(
7975 &self,
7976 snapshot: &MultiBufferSnapshot,
7977 ) -> Vec<Range<usize>> {
7978 [self.start.to_offset(snapshot)..self.end.to_offset(snapshot)]
7979 .to_multi_buffer_debug_ranges(snapshot)
7980 }
7981 }
7982
7983 impl<T: ToOffset> ToMultiBufferDebugRanges for Vec<T> {
7984 fn to_multi_buffer_debug_ranges(
7985 &self,
7986 snapshot: &MultiBufferSnapshot,
7987 ) -> Vec<Range<usize>> {
7988 self.as_slice().to_multi_buffer_debug_ranges(snapshot)
7989 }
7990 }
7991
7992 impl<T: ToOffset> ToMultiBufferDebugRanges for Vec<Range<T>> {
7993 fn to_multi_buffer_debug_ranges(
7994 &self,
7995 snapshot: &MultiBufferSnapshot,
7996 ) -> Vec<Range<usize>> {
7997 self.as_slice().to_multi_buffer_debug_ranges(snapshot)
7998 }
7999 }
8000
8001 impl<T: ToOffset> ToMultiBufferDebugRanges for [T] {
8002 fn to_multi_buffer_debug_ranges(
8003 &self,
8004 snapshot: &MultiBufferSnapshot,
8005 ) -> Vec<Range<usize>> {
8006 self.iter()
8007 .map(|item| {
8008 let offset = item.to_offset(snapshot);
8009 offset..offset
8010 })
8011 .collect()
8012 }
8013 }
8014
8015 impl<T: ToOffset> ToMultiBufferDebugRanges for [Range<T>] {
8016 fn to_multi_buffer_debug_ranges(
8017 &self,
8018 snapshot: &MultiBufferSnapshot,
8019 ) -> Vec<Range<usize>> {
8020 self.iter()
8021 .map(|range| range.start.to_offset(snapshot)..range.end.to_offset(snapshot))
8022 .collect()
8023 }
8024 }
8025}