mod anchor;mod diff_map;mod excerpt_map;mod position; pub use anchor::{Anchor, AnchorRangeExt, Offset};use diff_map::DiffMap;use excerpt_map::{ExcerptMap, ExcerptMapSnapshot}; use anyhow::{anyhow, Result};use clock::ReplicaId;use collections::{BTreeMap, Bound, HashMap, HashSet};use futures::{channel::mpsc, SinkExt};use git::diff::DiffHunkStatus;use gpui::{AppContext, EntityId, EventEmitter, Model, ModelContext, Task};use itertools::Itertools;use language::{ language_settings::{language_settings, LanguageSettings}, AutoindentMode, Buffer, BufferChunks, BufferRow, BufferSnapshot, Capability, CharClassifier, CharKind, Chunk, CursorShape, DiagnosticEntry, DiskState, File, IndentGuide, IndentSize, Language, LanguageScope, OffsetRangeExt, OffsetUtf16, Outline, OutlineItem, Point, PointUtf16, Selection, TextDimension, ToOffset as _, ToOffsetUtf16 as _, ToPoint as _, ToPointUtf16 as _, TransactionId, Unclipped,};use smallvec::SmallVec;use std::{ any::type_name, borrow::Cow, cell::{Ref, RefCell}, cmp, fmt, future::Future, io, iter::{self, FromIterator}, mem, ops::{Range, RangeBounds, Sub}, str, sync::Arc, time::{Duration, Instant},};use sum_tree::{Bias, Cursor, SumTree};use text::{ locator::Locator, subscription::{Subscription, Topic}, BufferId, Edit, TextSummary,};use theme::SyntaxTheme; use util::post_inc; #[cfg(any(test, feature = "test-support"))]use gpui::Context; const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize]; #[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]pub struct ExcerptId(usize); impl From<ExcerptId> for EntityId { fn from(id: ExcerptId) -> Self { EntityId::from(id.0 as u64) }} /// One or more [`Buffers`](Buffer) being edited in a single view.////// See <https://zed.dev/features#multi-buffers>pub struct MultiBuffer { /// A snapshot of the [`Excerpt`]s in the MultiBuffer. /// Use [`MultiBuffer::snapshot`] to get a up-to-date snapshot. snapshot: RefCell<MultiBufferSnapshot>, excerpt_map: ExcerptMap, diff_map: DiffMap, /// Contains the state of the buffers being edited buffers: RefCell<HashMap<BufferId, BufferState>>, subscriptions: Topic, /// If true, the multi-buffer only contains a single [`Buffer`] and a single [`Excerpt`] singleton: bool, history: History, title: Option<String>, capability: Capability,} #[derive(Clone, Debug, PartialEq, Eq)]pub enum Event { ExcerptsAdded { buffer: Model<Buffer>, predecessor: ExcerptId, excerpts: Vec<(ExcerptId, ExcerptRange<text::Anchor>)>, }, ExcerptsRemoved { ids: Vec<ExcerptId>, }, ExcerptsExpanded { ids: Vec<ExcerptId>, }, ExcerptsEdited { ids: Vec<ExcerptId>, }, Edited { singleton_buffer_edited: bool, edited_buffer: Option<Model<Buffer>>, }, TransactionUndone { transaction_id: TransactionId, }, Reloaded, ReloadNeeded, LanguageChanged(BufferId), CapabilityChanged, Reparsed(BufferId), Saved, FileHandleChanged, Closed, Discarded, DirtyChanged, DiagnosticsUpdated,} /// A diff hunk, representing a range of consequent lines in a multibuffer.#[derive(Debug, Clone, PartialEq, Eq)]pub struct MultiBufferDiffHunk { /// The row range in the multibuffer where this diff hunk appears. pub row_range: Range<MultiBufferRow>, /// The buffer ID that this hunk belongs to. pub buffer_id: BufferId, /// The range of the underlying buffer that this hunk corresponds to. pub buffer_range: Range<text::Anchor>, /// The range within the buffer's diff base that this hunk corresponds to. pub diff_base_byte_range: Range<usize>,} pub type MultiBufferPoint = Point; #[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq, Hash, serde::Deserialize)]#[serde(transparent)]pub struct MultiBufferRow(pub u32); impl MultiBufferRow { pub const MIN: Self = Self(0); pub const MAX: Self = Self(u32::MAX);} #[derive(Clone)]struct History { next_transaction_id: TransactionId, undo_stack: Vec<Transaction>, redo_stack: Vec<Transaction>, transaction_depth: usize, group_interval: Duration,} #[derive(Clone)]struct Transaction { id: TransactionId, buffer_transactions: HashMap<BufferId, text::TransactionId>, first_edit_at: Instant, last_edit_at: Instant, suppress_grouping: bool,} pub trait ToOffset: 'static + fmt::Debug { fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;} pub trait ToOffsetUtf16: 'static + fmt::Debug { fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16;} pub trait ToPoint: 'static + fmt::Debug { fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;} pub trait ToPointUtf16: 'static + fmt::Debug { fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16;} #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]pub struct RowInfo { pub buffer_row: Option<u32>, pub diff_status: Option<DiffHunkStatus>,} struct BufferState { buffer: Model<Buffer>, last_version: clock::Global, last_non_text_state_update_count: usize, excerpts: Vec<Locator>, _subscriptions: [gpui::Subscription; 2],} /// The contents of a [`MultiBuffer`] at a single point in time.#[derive(Clone, Default)]pub struct MultiBufferSnapshot { singleton: bool, excerpts: SumTree<Excerpt>, // diff_map_snapshot: DiffMapSnapshot, excerpt_ids: SumTree<ExcerptIdMapping>, trailing_excerpt_update_count: usize, non_text_state_update_count: usize, edit_count: usize, is_dirty: bool, has_deleted_file: bool, has_conflict: bool, show_headers: bool,} #[derive(Clone)]pub struct ExcerptInfo { pub id: ExcerptId, pub buffer: BufferSnapshot, pub buffer_id: BufferId, pub range: ExcerptRange<text::Anchor>, pub text_summary: TextSummary,} impl std::fmt::Debug for ExcerptInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct(type_name::<Self>()) .field("id", &self.id) .field("buffer_id", &self.buffer_id) .field("path", &self.buffer.file().map(|f| f.path())) .field("range", &self.range) .finish() }} /// A boundary between [`Excerpt`]s in a [`MultiBuffer`]#[derive(Debug)]pub struct ExcerptBoundary { pub prev: Option<ExcerptInfo>, pub next: Option<ExcerptInfo>, /// The row in the `MultiBuffer` where the boundary is located pub row: MultiBufferRow,} impl ExcerptBoundary { pub fn starts_new_buffer(&self) -> bool { match (self.prev.as_ref(), self.next.as_ref()) { (None, _) => true, (Some(_), None) => false, (Some(prev), Some(next)) => prev.buffer_id != next.buffer_id, } }} /// A slice into a [`Buffer`] that is being edited in a [`MultiBuffer`].#[derive(Clone)]struct Excerpt { /// The unique identifier for this excerpt id: ExcerptId, /// The location of the excerpt in the [`MultiBuffer`] locator: Locator, /// The buffer being excerpted buffer_id: BufferId, /// A snapshot of the buffer being excerpted buffer: BufferSnapshot, /// The range of the buffer to be shown in the excerpt range: ExcerptRange<text::Anchor>, /// The last row in the excerpted slice of the buffer max_buffer_row: BufferRow, /// A summary of the text in the excerpt text_summary: TextSummary, has_trailing_newline: bool,} /// A public view into an [`Excerpt`] in a [`MultiBuffer`].////// Contains methods for getting the [`Buffer`] of the excerpt,/// as well as mapping offsets to/from buffer and multibuffer coordinates.#[derive(Clone)]pub struct MultiBufferExcerpt<'a> { excerpt: &'a Excerpt, excerpt_offset: usize, excerpt_position: Point,} #[derive(Clone, Debug)]struct ExcerptIdMapping { id: ExcerptId, locator: Locator,} /// A range of text from a single [`Buffer`], to be shown as an [`Excerpt`]./// These ranges are relative to the buffer itself#[derive(Clone, Debug, Eq, PartialEq)]pub struct ExcerptRange<T> { /// The full range of text to be shown in the excerpt. pub context: Range<T>, /// The primary range of text to be highlighted in the excerpt. /// In a multi-buffer search, this would be the text that matched the search pub primary: Option<Range<T>>,} #[derive(Clone, Debug, Default)]pub struct ExcerptSummary { excerpt_id: ExcerptId, /// The location of the last [`Excerpt`] being summarized excerpt_locator: Locator, widest_line_number: u32, text: TextSummary,} #[derive(Clone)]pub struct MultiBufferRows<'a> { buffer_row_range: Range<u32>, excerpts: Cursor<'a, Excerpt, Point>,} pub struct MultiBufferChunks<'a> { range: Range<usize>, excerpts: Cursor<'a, Excerpt, usize>, excerpt_chunks: Option<ExcerptChunks<'a>>, language_aware: bool,} pub struct MultiBufferBytes<'a> { range: Range<usize>, excerpts: Cursor<'a, Excerpt, usize>, excerpt_bytes: Option<ExcerptBytes<'a>>, chunk: &'a [u8],} pub struct ReversedMultiBufferBytes<'a> { range: Range<usize>, excerpts: Cursor<'a, Excerpt, usize>, excerpt_bytes: Option<ExcerptBytes<'a>>, chunk: &'a [u8],} struct ExcerptChunks<'a> { excerpt_id: ExcerptId, content_chunks: BufferChunks<'a>, footer_height: usize,} struct ExcerptBytes<'a> { content_bytes: text::Bytes<'a>, padding_height: usize, reversed: bool,} struct BufferEdit { range: Range<usize>, new_text: Arc<str>, is_insertion: bool, original_indent_column: u32,} #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum ExpandExcerptDirection { Up, Down, UpAndDown,} impl ExpandExcerptDirection { pub fn should_expand_up(&self) -> bool { match self { ExpandExcerptDirection::Up => true, ExpandExcerptDirection::Down => false, ExpandExcerptDirection::UpAndDown => true, } } pub fn should_expand_down(&self) -> bool { match self { ExpandExcerptDirection::Up => false, ExpandExcerptDirection::Down => true, ExpandExcerptDirection::UpAndDown => true, } }} #[derive(Clone, Debug, PartialEq)]pub struct MultiBufferIndentGuide { pub multibuffer_row_range: Range<MultiBufferRow>, pub buffer: IndentGuide,} impl std::ops::Deref for MultiBufferIndentGuide { type Target = IndentGuide; fn deref(&self) -> &Self::Target { &self.buffer }} impl MultiBuffer { pub fn new(capability: Capability) -> Self { let excerpt_map = ExcerptMap::new(capability); Self { diff_map: DiffMap::new(excerpt_map), snapshot: RefCell::new(MultiBufferSnapshot { show_headers: true, ..MultiBufferSnapshot::default() }), buffers: RefCell::default(), subscriptions: Topic::default(), singleton: false, capability, title: None, history: History { next_transaction_id: clock::Lamport::default(), undo_stack: Vec::new(), redo_stack: Vec::new(), transaction_depth: 0, group_interval: Duration::from_millis(300), }, } } pub fn without_headers(capability: Capability) -> Self { Self { snapshot: Default::default(), buffers: Default::default(), excerpt_map: ExcerptMap::new(capability), subscriptions: Default::default(), singleton: false, capability, history: History { next_transaction_id: Default::default(), undo_stack: Default::default(), redo_stack: Default::default(), transaction_depth: 0, group_interval: Duration::from_millis(300), }, title: Default::default(), } } pub fn clone(&self, new_cx: &mut ModelContext<Self>) -> Self { let mut buffers = HashMap::default(); for (buffer_id, buffer_state) in self.buffers.borrow().iter() { buffers.insert( *buffer_id, BufferState { buffer: buffer_state.buffer.clone(), last_version: buffer_state.last_version.clone(), last_non_text_state_update_count: buffer_state.last_non_text_state_update_count, excerpts: buffer_state.excerpts.clone(), _subscriptions: [ new_cx.observe(&buffer_state.buffer, |_, _, cx| cx.notify()), new_cx.subscribe(&buffer_state.buffer, Self::on_buffer_event), ], }, ); } Self { snapshot: RefCell::new(self.snapshot.borrow().clone()), buffers: RefCell::new(buffers), excerpt_map: self.excerpt_map.clone(new_cx), subscriptions: Default::default(), singleton: self.singleton, capability: self.capability, history: self.history.clone(), title: self.title.clone(), } } pub fn with_title(mut self, title: String) -> Self { self.title = Some(title); self } pub fn read_only(&self) -> bool { self.capability == Capability::ReadOnly } pub fn singleton(buffer: Model<Buffer>, cx: &mut ModelContext<Self>) -> Self { let mut this = Self::new(buffer.read(cx).capability()); this.singleton = true; this.push_excerpts( buffer, [ExcerptRange { context: text::Anchor::MIN..text::Anchor::MAX, primary: None, }], cx, ); this.snapshot.borrow_mut().singleton = true; this } /// Returns an up-to-date snapshot of the MultiBuffer. pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot { self.sync(cx); self.snapshot.borrow().clone() } pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> { self.sync(cx); self.snapshot.borrow() } pub fn as_singleton(&self) -> Option<Model<Buffer>> { if self.singleton { return Some( self.buffers .borrow()Lines 1–500 of 7343. Load more
mod anchor; mod diff_map; mod excerpt_map; mod position; pub use anchor::{Anchor, AnchorRangeExt, Offset}; use diff_map::DiffMap; use excerpt_map::{ExcerptMap, ExcerptMapSnapshot}; use anyhow::{anyhow, Result}; use clock::ReplicaId; use collections::{BTreeMap, Bound, HashMap, HashSet}; use futures::{channel::mpsc, SinkExt}; use git::diff::DiffHunkStatus; use gpui::{AppContext, EntityId, EventEmitter, Model, ModelContext, Task}; use itertools::Itertools; use language::{ language_settings::{language_settings, LanguageSettings}, AutoindentMode, Buffer, BufferChunks, BufferRow, BufferSnapshot, Capability, CharClassifier, CharKind, Chunk, CursorShape, DiagnosticEntry, DiskState, File, IndentGuide, IndentSize, Language, LanguageScope, OffsetRangeExt, OffsetUtf16, Outline, OutlineItem, Point, PointUtf16, Selection, TextDimension, ToOffset as _, ToOffsetUtf16 as _, ToPoint as _, ToPointUtf16 as _, TransactionId, Unclipped, }; use smallvec::SmallVec; use std::{ any::type_name, borrow::Cow, cell::{Ref, RefCell}, cmp, fmt, future::Future, io, iter::{self, FromIterator}, mem, ops::{Range, RangeBounds, Sub}, str, sync::Arc, time::{Duration, Instant}, }; use sum_tree::{Bias, Cursor, SumTree}; use text::{ locator::Locator, subscription::{Subscription, Topic}, BufferId, Edit, TextSummary, }; use theme::SyntaxTheme; use util::post_inc; #[cfg(any(test, feature = "test-support"))] use gpui::Context; const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize]; #[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct ExcerptId(usize); impl From<ExcerptId> for EntityId { fn from(id: ExcerptId) -> Self { EntityId::from(id.0 as u64) } } /// One or more [`Buffers`](Buffer) being edited in a single view. /// /// See <https://zed.dev/features#multi-buffers> pub struct MultiBuffer { /// A snapshot of the [`Excerpt`]s in the MultiBuffer. /// Use [`MultiBuffer::snapshot`] to get a up-to-date snapshot. snapshot: RefCell<MultiBufferSnapshot>, excerpt_map: ExcerptMap, diff_map: DiffMap, /// Contains the state of the buffers being edited buffers: RefCell<HashMap<BufferId, BufferState>>, subscriptions: Topic, /// If true, the multi-buffer only contains a single [`Buffer`] and a single [`Excerpt`] singleton: bool, history: History, title: Option<String>, capability: Capability, } #[derive(Clone, Debug, PartialEq, Eq)] pub enum Event { ExcerptsAdded { buffer: Model<Buffer>, predecessor: ExcerptId, excerpts: Vec<(ExcerptId, ExcerptRange<text::Anchor>)>, }, ExcerptsRemoved { ids: Vec<ExcerptId>, }, ExcerptsExpanded { ids: Vec<ExcerptId>, }, ExcerptsEdited { ids: Vec<ExcerptId>, }, Edited { singleton_buffer_edited: bool, edited_buffer: Option<Model<Buffer>>, }, TransactionUndone { transaction_id: TransactionId, }, Reloaded, ReloadNeeded, LanguageChanged(BufferId), CapabilityChanged, Reparsed(BufferId), Saved, FileHandleChanged, Closed, Discarded, DirtyChanged, DiagnosticsUpdated, } /// A diff hunk, representing a range of consequent lines in a multibuffer. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MultiBufferDiffHunk { /// The row range in the multibuffer where this diff hunk appears. pub row_range: Range<MultiBufferRow>, /// The buffer ID that this hunk belongs to. pub buffer_id: BufferId, /// The range of the underlying buffer that this hunk corresponds to. pub buffer_range: Range<text::Anchor>, /// The range within the buffer's diff base that this hunk corresponds to. pub diff_base_byte_range: Range<usize>, } pub type MultiBufferPoint = Point; #[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq, Hash, serde::Deserialize)] #[serde(transparent)] pub struct MultiBufferRow(pub u32); impl MultiBufferRow { pub const MIN: Self = Self(0); pub const MAX: Self = Self(u32::MAX); } #[derive(Clone)] struct History { next_transaction_id: TransactionId, undo_stack: Vec<Transaction>, redo_stack: Vec<Transaction>, transaction_depth: usize, group_interval: Duration, } #[derive(Clone)] struct Transaction { id: TransactionId, buffer_transactions: HashMap<BufferId, text::TransactionId>, first_edit_at: Instant, last_edit_at: Instant, suppress_grouping: bool, } pub trait ToOffset: 'static + fmt::Debug { fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize; } pub trait ToOffsetUtf16: 'static + fmt::Debug { fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16; } pub trait ToPoint: 'static + fmt::Debug { fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point; } pub trait ToPointUtf16: 'static + fmt::Debug { fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16; } #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct RowInfo { pub buffer_row: Option<u32>, pub diff_status: Option<DiffHunkStatus>, } struct BufferState { buffer: Model<Buffer>, last_version: clock::Global, last_non_text_state_update_count: usize, excerpts: Vec<Locator>, _subscriptions: [gpui::Subscription; 2], } /// The contents of a [`MultiBuffer`] at a single point in time. #[derive(Clone, Default)] pub struct MultiBufferSnapshot { singleton: bool, excerpts: SumTree<Excerpt>, // diff_map_snapshot: DiffMapSnapshot, excerpt_ids: SumTree<ExcerptIdMapping>, trailing_excerpt_update_count: usize, non_text_state_update_count: usize, edit_count: usize, is_dirty: bool, has_deleted_file: bool, has_conflict: bool, show_headers: bool, } #[derive(Clone)] pub struct ExcerptInfo { pub id: ExcerptId, pub buffer: BufferSnapshot, pub buffer_id: BufferId, pub range: ExcerptRange<text::Anchor>, pub text_summary: TextSummary, } impl std::fmt::Debug for ExcerptInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct(type_name::<Self>()) .field("id", &self.id) .field("buffer_id", &self.buffer_id) .field("path", &self.buffer.file().map(|f| f.path())) .field("range", &self.range) .finish() } } /// A boundary between [`Excerpt`]s in a [`MultiBuffer`] #[derive(Debug)] pub struct ExcerptBoundary { pub prev: Option<ExcerptInfo>, pub next: Option<ExcerptInfo>, /// The row in the `MultiBuffer` where the boundary is located pub row: MultiBufferRow, } impl ExcerptBoundary { pub fn starts_new_buffer(&self) -> bool { match (self.prev.as_ref(), self.next.as_ref()) { (None, _) => true, (Some(_), None) => false, (Some(prev), Some(next)) => prev.buffer_id != next.buffer_id, } } } /// A slice into a [`Buffer`] that is being edited in a [`MultiBuffer`]. #[derive(Clone)] struct Excerpt { /// The unique identifier for this excerpt id: ExcerptId, /// The location of the excerpt in the [`MultiBuffer`] locator: Locator, /// The buffer being excerpted buffer_id: BufferId, /// A snapshot of the buffer being excerpted buffer: BufferSnapshot, /// The range of the buffer to be shown in the excerpt range: ExcerptRange<text::Anchor>, /// The last row in the excerpted slice of the buffer max_buffer_row: BufferRow, /// A summary of the text in the excerpt text_summary: TextSummary, has_trailing_newline: bool, } /// A public view into an [`Excerpt`] in a [`MultiBuffer`]. /// /// Contains methods for getting the [`Buffer`] of the excerpt, /// as well as mapping offsets to/from buffer and multibuffer coordinates. #[derive(Clone)] pub struct MultiBufferExcerpt<'a> { excerpt: &'a Excerpt, excerpt_offset: usize, excerpt_position: Point, } #[derive(Clone, Debug)] struct ExcerptIdMapping { id: ExcerptId, locator: Locator, } /// A range of text from a single [`Buffer`], to be shown as an [`Excerpt`]. /// These ranges are relative to the buffer itself #[derive(Clone, Debug, Eq, PartialEq)] pub struct ExcerptRange<T> { /// The full range of text to be shown in the excerpt. pub context: Range<T>, /// The primary range of text to be highlighted in the excerpt. /// In a multi-buffer search, this would be the text that matched the search pub primary: Option<Range<T>>, } #[derive(Clone, Debug, Default)] pub struct ExcerptSummary { excerpt_id: ExcerptId, /// The location of the last [`Excerpt`] being summarized excerpt_locator: Locator, widest_line_number: u32, text: TextSummary, } #[derive(Clone)] pub struct MultiBufferRows<'a> { buffer_row_range: Range<u32>, excerpts: Cursor<'a, Excerpt, Point>, } pub struct MultiBufferChunks<'a> { range: Range<usize>, excerpts: Cursor<'a, Excerpt, usize>, excerpt_chunks: Option<ExcerptChunks<'a>>, language_aware: bool, } pub struct MultiBufferBytes<'a> { range: Range<usize>, excerpts: Cursor<'a, Excerpt, usize>, excerpt_bytes: Option<ExcerptBytes<'a>>, chunk: &'a [u8], } pub struct ReversedMultiBufferBytes<'a> { range: Range<usize>, excerpts: Cursor<'a, Excerpt, usize>, excerpt_bytes: Option<ExcerptBytes<'a>>, chunk: &'a [u8], } struct ExcerptChunks<'a> { excerpt_id: ExcerptId, content_chunks: BufferChunks<'a>, footer_height: usize, } struct ExcerptBytes<'a> { content_bytes: text::Bytes<'a>, padding_height: usize, reversed: bool, } struct BufferEdit { range: Range<usize>, new_text: Arc<str>, is_insertion: bool, original_indent_column: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ExpandExcerptDirection { Up, Down, UpAndDown, } impl ExpandExcerptDirection { pub fn should_expand_up(&self) -> bool { match self { ExpandExcerptDirection::Up => true, ExpandExcerptDirection::Down => false, ExpandExcerptDirection::UpAndDown => true, } } pub fn should_expand_down(&self) -> bool { match self { ExpandExcerptDirection::Up => false, ExpandExcerptDirection::Down => true, ExpandExcerptDirection::UpAndDown => true, } } } #[derive(Clone, Debug, PartialEq)] pub struct MultiBufferIndentGuide { pub multibuffer_row_range: Range<MultiBufferRow>, pub buffer: IndentGuide, } impl std::ops::Deref for MultiBufferIndentGuide { type Target = IndentGuide; fn deref(&self) -> &Self::Target { &self.buffer } } impl MultiBuffer { pub fn new(capability: Capability) -> Self { let excerpt_map = ExcerptMap::new(capability); Self { diff_map: DiffMap::new(excerpt_map), snapshot: RefCell::new(MultiBufferSnapshot { show_headers: true, ..MultiBufferSnapshot::default() }), buffers: RefCell::default(), subscriptions: Topic::default(), singleton: false, capability, title: None, history: History { next_transaction_id: clock::Lamport::default(), undo_stack: Vec::new(), redo_stack: Vec::new(), transaction_depth: 0, group_interval: Duration::from_millis(300), }, } } pub fn without_headers(capability: Capability) -> Self { Self { snapshot: Default::default(), buffers: Default::default(), excerpt_map: ExcerptMap::new(capability), subscriptions: Default::default(), singleton: false, capability, history: History { next_transaction_id: Default::default(), undo_stack: Default::default(), redo_stack: Default::default(), transaction_depth: 0, group_interval: Duration::from_millis(300), }, title: Default::default(), } } pub fn clone(&self, new_cx: &mut ModelContext<Self>) -> Self { let mut buffers = HashMap::default(); for (buffer_id, buffer_state) in self.buffers.borrow().iter() { buffers.insert( *buffer_id, BufferState { buffer: buffer_state.buffer.clone(), last_version: buffer_state.last_version.clone(), last_non_text_state_update_count: buffer_state.last_non_text_state_update_count, excerpts: buffer_state.excerpts.clone(), _subscriptions: [ new_cx.observe(&buffer_state.buffer, |_, _, cx| cx.notify()), new_cx.subscribe(&buffer_state.buffer, Self::on_buffer_event), ], }, ); } Self { snapshot: RefCell::new(self.snapshot.borrow().clone()), buffers: RefCell::new(buffers), excerpt_map: self.excerpt_map.clone(new_cx), subscriptions: Default::default(), singleton: self.singleton, capability: self.capability, history: self.history.clone(), title: self.title.clone(), } } pub fn with_title(mut self, title: String) -> Self { self.title = Some(title); self } pub fn read_only(&self) -> bool { self.capability == Capability::ReadOnly } pub fn singleton(buffer: Model<Buffer>, cx: &mut ModelContext<Self>) -> Self { let mut this = Self::new(buffer.read(cx).capability()); this.singleton = true; this.push_excerpts( buffer, [ExcerptRange { context: text::Anchor::MIN..text::Anchor::MAX, primary: None, }], cx, ); this.snapshot.borrow_mut().singleton = true; this } /// Returns an up-to-date snapshot of the MultiBuffer. pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot { self.sync(cx); self.snapshot.borrow().clone() } pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> { self.sync(cx); self.snapshot.borrow() } pub fn as_singleton(&self) -> Option<Model<Buffer>> { if self.singleton { return Some( self.buffers .borrow()