mod anchor; pub use anchor::{Anchor, AnchorRangeExt}; use anyhow::Result; use clock::ReplicaId; use collections::{HashMap, HashSet}; use gpui::{AppContext, ElementBox, Entity, ModelContext, ModelHandle, Task}; use language::{ Buffer, BufferChunks, BufferSnapshot, Chunk, DiagnosticEntry, Event, File, Language, Selection, ToOffset as _, ToPoint as _, TransactionId, }; use std::{ cell::{Ref, RefCell}, cmp, fmt, io, iter::{self, FromIterator}, ops::{Range, Sub}, str, sync::Arc, time::{Duration, Instant}, }; use sum_tree::{Bias, Cursor, SumTree}; use text::{ locator::Locator, rope::TextDimension, subscription::{Subscription, Topic}, AnchorRangeExt as _, Edit, Point, PointUtf16, TextSummary, }; use theme::SyntaxTheme; use util::post_inc; const NEWLINES: &'static [u8] = &[b'\n'; u8::MAX as usize]; pub type ExcerptId = Locator; pub struct MultiBuffer { snapshot: RefCell, buffers: HashMap, subscriptions: Topic, singleton: bool, replica_id: ReplicaId, history: History, } struct History { next_transaction_id: usize, undo_stack: Vec, redo_stack: Vec, transaction_depth: usize, group_interval: Duration, } struct Transaction { id: usize, buffer_transactions: HashSet<(usize, text::TransactionId)>, first_edit_at: Instant, last_edit_at: Instant, } pub trait ToOffset: 'static + fmt::Debug { fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize; } pub trait ToPoint: 'static + fmt::Debug { fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point; } pub trait FromAnchor: 'static { fn from_anchor(anchor: &Anchor, snapshot: &MultiBufferSnapshot) -> Self; } #[derive(Debug)] struct BufferState { buffer: ModelHandle, last_version: clock::Global, last_parse_count: usize, last_diagnostics_update_count: usize, excerpts: Vec, } #[derive(Clone, Default)] pub struct MultiBufferSnapshot { excerpts: SumTree, parse_count: usize, diagnostics_update_count: usize, is_dirty: bool, has_conflict: bool, } pub type RenderHeaderFn = Arc ElementBox>; pub struct ExcerptProperties<'a, T> { pub buffer: &'a ModelHandle, pub range: Range, pub header_height: u8, pub render_header: Option, } #[derive(Clone)] struct Excerpt { id: ExcerptId, buffer_id: usize, buffer: BufferSnapshot, range: Range, render_header: Option, text_summary: TextSummary, header_height: u8, has_trailing_newline: bool, } #[derive(Clone, Debug, Default)] struct ExcerptSummary { excerpt_id: ExcerptId, text: TextSummary, } pub struct MultiBufferRows<'a> { buffer_row_range: Range, excerpts: Cursor<'a, Excerpt, Point>, } pub struct MultiBufferChunks<'a> { range: Range, excerpts: Cursor<'a, Excerpt, usize>, excerpt_chunks: Option>, theme: Option<&'a SyntaxTheme>, } pub struct MultiBufferBytes<'a> { range: Range, excerpts: Cursor<'a, Excerpt, usize>, excerpt_bytes: Option>, chunk: &'a [u8], } struct ExcerptChunks<'a> { content_chunks: BufferChunks<'a>, footer_height: usize, } struct ExcerptBytes<'a> { content_bytes: language::rope::Bytes<'a>, footer_height: usize, } impl MultiBuffer { pub fn new(replica_id: ReplicaId) -> Self { Self { snapshot: Default::default(), buffers: Default::default(), subscriptions: Default::default(), singleton: false, replica_id, history: History { next_transaction_id: Default::default(), undo_stack: Default::default(), redo_stack: Default::default(), transaction_depth: 0, group_interval: Duration::from_millis(300), }, } } pub fn singleton(buffer: ModelHandle, cx: &mut ModelContext) -> Self { let mut this = Self::new(buffer.read(cx).replica_id()); this.singleton = true; this.push_excerpt( ExcerptProperties { buffer: &buffer, range: text::Anchor::min()..text::Anchor::max(), header_height: 0, render_header: None, }, cx, ); this } #[cfg(any(test, feature = "test-support"))] pub fn build_simple(text: &str, cx: &mut gpui::MutableAppContext) -> ModelHandle { let buffer = cx.add_model(|cx| Buffer::new(0, text, cx)); cx.add_model(|cx| Self::singleton(buffer, cx)) } #[cfg(any(test, feature = "test-support"))] pub fn build_random( mut rng: &mut impl rand::Rng, cx: &mut gpui::MutableAppContext, ) -> ModelHandle { use rand::prelude::*; use std::env; use text::RandomCharIter; let max_excerpts = env::var("MAX_EXCERPTS") .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable")) .unwrap_or(5); let excerpts = rng.gen_range(1..=max_excerpts); cx.add_model(|cx| { let mut multibuffer = MultiBuffer::new(0); let mut buffers = Vec::new(); for _ in 0..excerpts { let buffer_handle = if rng.gen() || buffers.is_empty() { let text = RandomCharIter::new(&mut rng).take(10).collect::(); buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx))); let buffer = buffers.last().unwrap(); log::info!( "Creating new buffer {} with text: {:?}", buffer.id(), buffer.read(cx).text() ); buffers.last().unwrap() } else { buffers.choose(rng).unwrap() }; let buffer = buffer_handle.read(cx); let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right); let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left); let header_height = rng.gen_range(0..=5); log::info!( "Inserting excerpt from buffer {} with header height {} and range {:?}: {:?}", buffer_handle.id(), header_height, start_ix..end_ix, &buffer.text()[start_ix..end_ix] ); multibuffer.push_excerpt( ExcerptProperties { buffer: buffer_handle, range: start_ix..end_ix, header_height, render_header: None, }, cx, ); } multibuffer }) } pub fn replica_id(&self) -> ReplicaId { self.replica_id } pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot { self.sync(cx); self.snapshot.borrow().clone() } pub fn read(&self, cx: &AppContext) -> Ref { self.sync(cx); self.snapshot.borrow() } pub fn as_singleton(&self) -> Option<&ModelHandle> { if self.singleton { return Some(&self.buffers.values().next().unwrap().buffer); } else { None } } pub fn subscribe(&mut self) -> Subscription { self.subscriptions.subscribe() } pub fn edit(&mut self, ranges: I, new_text: T, cx: &mut ModelContext) where I: IntoIterator>, S: ToOffset, T: Into, { self.edit_internal(ranges, new_text, false, cx) } pub fn edit_with_autoindent( &mut self, ranges: I, new_text: T, cx: &mut ModelContext, ) where I: IntoIterator>, S: ToOffset, T: Into, { self.edit_internal(ranges, new_text, true, cx) } pub fn edit_internal( &mut self, ranges_iter: I, new_text: T, autoindent: bool, cx: &mut ModelContext, ) where I: IntoIterator>, S: ToOffset, T: Into, { if let Some(buffer) = self.as_singleton() { let snapshot = self.read(cx); let ranges = ranges_iter .into_iter() .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot)); return buffer.update(cx, |buffer, cx| { if autoindent { buffer.edit_with_autoindent(ranges, new_text, cx) } else { buffer.edit(ranges, new_text, cx) } }); } let snapshot = self.read(cx); let mut buffer_edits: HashMap, bool)>> = Default::default(); let mut cursor = snapshot.excerpts.cursor::(); for range in ranges_iter { let start = range.start.to_offset(&snapshot); let end = range.end.to_offset(&snapshot); cursor.seek(&start, Bias::Right, &()); if cursor.item().is_none() && start == *cursor.start() { cursor.prev(&()); } let start_excerpt = cursor.item().expect("start offset out of bounds"); let start_overshoot = start - cursor.start(); let buffer_start = start_excerpt.range.start.to_offset(&start_excerpt.buffer) + start_overshoot; cursor.seek(&end, Bias::Right, &()); if cursor.item().is_none() && end == *cursor.start() { cursor.prev(&()); } let end_excerpt = cursor.item().expect("end offset out of bounds"); let end_overshoot = end - cursor.start(); let buffer_end = end_excerpt.range.start.to_offset(&end_excerpt.buffer) + end_overshoot; if start_excerpt.id == end_excerpt.id { buffer_edits .entry(start_excerpt.buffer_id) .or_insert(Vec::new()) .push((buffer_start..buffer_end, true)); } else { let start_excerpt_range = buffer_start..start_excerpt.range.end.to_offset(&start_excerpt.buffer); let end_excerpt_range = end_excerpt.range.start.to_offset(&end_excerpt.buffer)..buffer_end; buffer_edits .entry(start_excerpt.buffer_id) .or_insert(Vec::new()) .push((start_excerpt_range, true)); buffer_edits .entry(end_excerpt.buffer_id) .or_insert(Vec::new()) .push((end_excerpt_range, false)); cursor.seek(&start, Bias::Right, &()); cursor.next(&()); while let Some(excerpt) = cursor.item() { if excerpt.id == end_excerpt.id { break; } buffer_edits .entry(excerpt.buffer_id) .or_insert(Vec::new()) .push((excerpt.range.to_offset(&excerpt.buffer), false)); cursor.next(&()); } } } let new_text = new_text.into(); for (buffer_id, mut edits) in buffer_edits { edits.sort_unstable_by_key(|(range, _)| range.start); self.buffers[&buffer_id].buffer.update(cx, |buffer, cx| { let mut edits = edits.into_iter().peekable(); let mut insertions = Vec::new(); let mut deletions = Vec::new(); while let Some((mut range, mut is_insertion)) = edits.next() { while let Some((next_range, next_is_insertion)) = edits.peek() { if range.end >= next_range.start { range.end = cmp::max(next_range.end, range.end); is_insertion |= *next_is_insertion; edits.next(); } else { break; } } if is_insertion { insertions.push( buffer.anchor_before(range.start)..buffer.anchor_before(range.end), ); } else if !range.is_empty() { deletions.push( buffer.anchor_before(range.start)..buffer.anchor_before(range.end), ); } } if autoindent { buffer.edit_with_autoindent(deletions, "", cx); buffer.edit_with_autoindent(insertions, new_text.clone(), cx); } else { buffer.edit(deletions, "", cx); buffer.edit(insertions, new_text.clone(), cx); } }) } } pub fn start_transaction(&mut self, cx: &mut ModelContext) -> Option { self.start_transaction_at(Instant::now(), cx) } pub(crate) fn start_transaction_at( &mut self, now: Instant, cx: &mut ModelContext, ) -> Option { if let Some(buffer) = self.as_singleton() { return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now)); } for BufferState { buffer, .. } in self.buffers.values() { buffer.update(cx, |buffer, _| buffer.start_transaction_at(now)); } self.history.start_transaction(now) } pub fn end_transaction(&mut self, cx: &mut ModelContext) -> Option { self.end_transaction_at(Instant::now(), cx) } pub(crate) fn end_transaction_at( &mut self, now: Instant, cx: &mut ModelContext, ) -> Option { if let Some(buffer) = self.as_singleton() { return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx)); } let mut buffer_transactions = HashSet::default(); for BufferState { buffer, .. } in self.buffers.values() { if let Some(transaction_id) = buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx)) { buffer_transactions.insert((buffer.id(), transaction_id)); } } if self.history.end_transaction(now, buffer_transactions) { let transaction_id = self.history.group().unwrap(); Some(transaction_id) } else { None } } pub fn set_active_selections( &mut self, selections: &[Selection], cx: &mut ModelContext, ) { let mut selections_by_buffer: HashMap>> = Default::default(); let snapshot = self.read(cx); let mut cursor = snapshot.excerpts.cursor::>(); for selection in selections { cursor.seek(&Some(&selection.start.excerpt_id), Bias::Left, &()); while let Some(excerpt) = cursor.item() { if excerpt.id > selection.end.excerpt_id { break; } let mut start = excerpt.range.start.clone(); let mut end = excerpt.range.end.clone(); if excerpt.id == selection.start.excerpt_id { start = selection.start.text_anchor.clone(); } if excerpt.id == selection.end.excerpt_id { end = selection.end.text_anchor.clone(); } selections_by_buffer .entry(excerpt.buffer_id) .or_default() .push(Selection { id: selection.id, start, end, reversed: selection.reversed, goal: selection.goal, }); cursor.next(&()); } } for (buffer_id, mut selections) in selections_by_buffer { self.buffers[&buffer_id].buffer.update(cx, |buffer, cx| { selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer).unwrap()); let mut selections = selections.into_iter().peekable(); let merged_selections = Arc::from_iter(iter::from_fn(|| { let mut selection = selections.next()?; while let Some(next_selection) = selections.peek() { if selection .end .cmp(&next_selection.start, buffer) .unwrap() .is_ge() { let next_selection = selections.next().unwrap(); if next_selection .end .cmp(&selection.end, buffer) .unwrap() .is_ge() { selection.end = next_selection.end; } } else { break; } } Some(selection) })); buffer.set_active_selections(merged_selections, cx); }); } } pub fn remove_active_selections(&mut self, cx: &mut ModelContext) { for buffer in self.buffers.values() { buffer .buffer .update(cx, |buffer, cx| buffer.remove_active_selections(cx)); } } pub fn undo(&mut self, cx: &mut ModelContext) -> Option { if let Some(buffer) = self.as_singleton() { return buffer.update(cx, |buffer, cx| buffer.undo(cx)); } while let Some(transaction) = self.history.pop_undo() { let mut undone = false; for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions { if let Some(BufferState { buffer, .. }) = self.buffers.get(&buffer_id) { undone |= buffer.update(cx, |buf, cx| { buf.undo_transaction(*buffer_transaction_id, cx) }); } } if undone { return Some(transaction.id); } } None } pub fn redo(&mut self, cx: &mut ModelContext) -> Option { if let Some(buffer) = self.as_singleton() { return buffer.update(cx, |buffer, cx| buffer.redo(cx)); } while let Some(transaction) = self.history.pop_redo() { let mut redone = false; for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions { if let Some(BufferState { buffer, .. }) = self.buffers.get(&buffer_id) { redone |= buffer.update(cx, |buf, cx| { buf.redo_transaction(*buffer_transaction_id, cx) }); } } if redone { return Some(transaction.id); } } None } pub fn push_excerpt( &mut self, props: ExcerptProperties, cx: &mut ModelContext, ) -> ExcerptId where O: text::ToOffset, { assert_eq!(self.history.transaction_depth, 0); self.sync(cx); let buffer = props.buffer.clone(); cx.observe(&buffer, |_, _, cx| cx.notify()).detach(); cx.subscribe(&buffer, Self::on_buffer_event).detach(); let buffer_snapshot = buffer.read(cx).snapshot(); let range = buffer_snapshot.anchor_before(&props.range.start) ..buffer_snapshot.anchor_after(&props.range.end); let last_version = buffer_snapshot.version().clone(); let last_parse_count = buffer_snapshot.parse_count(); let last_diagnostics_update_count = buffer_snapshot.diagnostics_update_count(); let mut snapshot = self.snapshot.borrow_mut(); let mut prev_id = None; let edit_start = snapshot.excerpts.summary().text.bytes; snapshot.excerpts.update_last( |excerpt| { excerpt.has_trailing_newline = true; prev_id = Some(excerpt.id.clone()); }, &(), ); let id = ExcerptId::between(&prev_id.unwrap_or(ExcerptId::min()), &ExcerptId::max()); let excerpt = Excerpt::new( id.clone(), buffer.id(), buffer_snapshot, range, props.header_height, props.render_header, false, ); snapshot.excerpts.push(excerpt, &()); self.buffers .entry(props.buffer.id()) .or_insert_with(|| BufferState { buffer, last_version, last_parse_count, last_diagnostics_update_count, excerpts: Default::default(), }) .excerpts .push(id.clone()); self.subscriptions.publish_mut([Edit { old: edit_start..edit_start, new: edit_start..snapshot.excerpts.summary().text.bytes, }]); cx.notify(); id } fn on_buffer_event( &mut self, _: ModelHandle, event: &Event, cx: &mut ModelContext, ) { cx.emit(event.clone()); } pub fn save(&mut self, cx: &mut ModelContext) -> Result>> { let mut save_tasks = Vec::new(); for BufferState { buffer, .. } in self.buffers.values() { save_tasks.push(buffer.update(cx, |buffer, cx| buffer.save(cx))?); } Ok(cx.spawn(|_, _| async move { for save in save_tasks { save.await?; } Ok(()) })) } pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc> { self.buffers .values() .next() .and_then(|state| state.buffer.read(cx).language()) } pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> { self.as_singleton()?.read(cx).file() } #[cfg(test)] pub fn is_parsing(&self, cx: &AppContext) -> bool { self.as_singleton().unwrap().read(cx).is_parsing() } fn sync(&self, cx: &AppContext) { let mut snapshot = self.snapshot.borrow_mut(); let mut excerpts_to_edit = Vec::new(); let mut reparsed = false; let mut diagnostics_updated = false; let mut is_dirty = false; let mut has_conflict = false; for buffer_state in self.buffers.values() { let buffer = buffer_state.buffer.read(cx); let buffer_edited = buffer.version().gt(&buffer_state.last_version); let buffer_reparsed = buffer.parse_count() > buffer_state.last_parse_count; let buffer_diagnostics_updated = buffer.diagnostics_update_count() > buffer_state.last_diagnostics_update_count; if buffer_edited || buffer_reparsed || buffer_diagnostics_updated { excerpts_to_edit.extend( buffer_state .excerpts .iter() .map(|excerpt_id| (excerpt_id, buffer_state, buffer_edited)), ); } reparsed |= buffer_reparsed; diagnostics_updated |= buffer_diagnostics_updated; is_dirty |= buffer.is_dirty(); has_conflict |= buffer.has_conflict(); } if reparsed { snapshot.parse_count += 1; } if diagnostics_updated { snapshot.diagnostics_update_count += 1; } snapshot.is_dirty = is_dirty; snapshot.has_conflict = has_conflict; excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id); let mut edits = Vec::new(); let mut new_excerpts = SumTree::new(); let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>(); for (id, buffer_state, buffer_edited) in excerpts_to_edit { new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &()); let old_excerpt = cursor.item().unwrap(); let buffer = buffer_state.buffer.read(cx); let mut new_excerpt; if buffer_edited { edits.extend( buffer .edits_since_in_range::( old_excerpt.buffer.version(), old_excerpt.range.clone(), ) .map(|mut edit| { let excerpt_old_start = cursor.start().1; let excerpt_new_start = new_excerpts.summary().text.bytes; edit.old.start += excerpt_old_start; edit.old.end += excerpt_old_start; edit.new.start += excerpt_new_start; edit.new.end += excerpt_new_start; edit }), ); new_excerpt = Excerpt::new( id.clone(), buffer_state.buffer.id(), buffer.snapshot(), old_excerpt.range.clone(), old_excerpt.header_height, old_excerpt.render_header.clone(), old_excerpt.has_trailing_newline, ); } else { new_excerpt = old_excerpt.clone(); new_excerpt.buffer = buffer.snapshot(); } new_excerpts.push(new_excerpt, &()); cursor.next(&()); } new_excerpts.push_tree(cursor.suffix(&()), &()); drop(cursor); snapshot.excerpts = new_excerpts; self.subscriptions.publish(edits); } } #[cfg(any(test, feature = "test-support"))] impl MultiBuffer { pub fn randomly_edit( &mut self, rng: &mut impl rand::Rng, count: usize, cx: &mut ModelContext, ) { use text::RandomCharIter; let snapshot = self.read(cx); let mut old_ranges: Vec> = Vec::new(); for _ in 0..count { let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1); if last_end > snapshot.len() { break; } let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right); let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left); old_ranges.push(start_ix..end_ix); } let new_text_len = rng.gen_range(0..10); let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect(); log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text); drop(snapshot); self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx); } } impl Entity for MultiBuffer { type Event = language::Event; } impl MultiBufferSnapshot { pub fn text(&self) -> String { self.chunks(0..self.len(), None) .map(|chunk| chunk.text) .collect() } pub fn excerpt_headers_in_range<'a>( &'a self, range: Range, ) -> impl 'a + Iterator { let mut cursor = self.excerpts.cursor::(); cursor.seek(&Point::new(range.start, 0), Bias::Right, &()); if cursor.item().is_some() && range.start > cursor.start().row { cursor.next(&()); } iter::from_fn(move || { while let Some(excerpt) = cursor.item() { if cursor.start().row >= range.end { break; } if let Some(render) = excerpt.render_header.clone() { let start = cursor.start().row; cursor.next(&()); return Some((start, excerpt.header_height, render)); } else { cursor.next(&()); } } None }) } pub fn reversed_chars_at<'a, T: ToOffset>( &'a self, position: T, ) -> impl Iterator + 'a { let mut offset = position.to_offset(self); let mut cursor = self.excerpts.cursor::(); cursor.seek(&offset, Bias::Left, &()); let mut excerpt_chunks = cursor.item().map(|excerpt| { let end_before_footer = cursor.start() + excerpt.text_summary.bytes; let start = excerpt.range.start.to_offset(&excerpt.buffer); let end = start + (cmp::min(offset, end_before_footer) - cursor.start()); excerpt.buffer.reversed_chunks_in_range(start..end) }); iter::from_fn(move || { if offset == *cursor.start() { cursor.prev(&()); let excerpt = cursor.item()?; excerpt_chunks = Some( excerpt .buffer .reversed_chunks_in_range(excerpt.range.clone()), ); } let excerpt = cursor.item().unwrap(); if offset == cursor.end(&()) && excerpt.has_trailing_newline { offset -= 1; Some("\n") } else { let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap(); offset -= chunk.len(); Some(chunk) } }) .flat_map(|c| c.chars().rev()) } pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator + 'a { let offset = position.to_offset(self); self.text_for_range(offset..self.len()) .flat_map(|chunk| chunk.chars()) } pub fn text_for_range<'a, T: ToOffset>( &'a self, range: Range, ) -> impl Iterator { self.chunks(range, None).map(|chunk| chunk.text) } pub fn is_line_blank(&self, row: u32) -> bool { self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row))) .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none()) } pub fn contains_str_at(&self, position: T, needle: &str) -> bool where T: ToOffset, { let position = position.to_offset(self); position == self.clip_offset(position, Bias::Left) && self .bytes_in_range(position..self.len()) .flatten() .copied() .take(needle.len()) .eq(needle.bytes()) } fn as_singleton(&self) -> Option<&BufferSnapshot> { let mut excerpts = self.excerpts.iter(); let buffer = excerpts.next().map(|excerpt| &excerpt.buffer); if excerpts.next().is_none() { buffer } else { None } } pub fn len(&self) -> usize { self.excerpts.summary().text.bytes } pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize { let mut cursor = self.excerpts.cursor::(); cursor.seek(&offset, Bias::Right, &()); let overshoot = if let Some(excerpt) = cursor.item() { let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer); let buffer_offset = excerpt .buffer .clip_offset(excerpt_start + (offset - cursor.start()), bias); buffer_offset.saturating_sub(excerpt_start) } else { 0 }; cursor.start() + overshoot } pub fn clip_point(&self, point: Point, bias: Bias) -> Point { let mut cursor = self.excerpts.cursor::(); cursor.seek(&point, Bias::Right, &()); let overshoot = if let Some(excerpt) = cursor.item() { let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer); let buffer_point = excerpt .buffer .clip_point(excerpt_start + (point - cursor.start()), bias); buffer_point.saturating_sub(excerpt_start) } else { Point::zero() }; *cursor.start() + overshoot } pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 { let mut cursor = self.excerpts.cursor::(); cursor.seek(&point, Bias::Right, &()); let overshoot = if let Some(excerpt) = cursor.item() { let excerpt_start = excerpt .buffer .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer)); let buffer_point = excerpt .buffer .clip_point_utf16(excerpt_start + (point - cursor.start()), bias); buffer_point.saturating_sub(excerpt_start) } else { PointUtf16::zero() }; *cursor.start() + overshoot } pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range) -> MultiBufferBytes<'a> { let range = range.start.to_offset(self)..range.end.to_offset(self); let mut excerpts = self.excerpts.cursor::(); excerpts.seek(&range.start, Bias::Right, &()); let mut chunk = &[][..]; let excerpt_bytes = if let Some(excerpt) = excerpts.item() { let mut excerpt_bytes = excerpt .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start()); chunk = excerpt_bytes.next().unwrap_or(&[][..]); Some(excerpt_bytes) } else { None }; MultiBufferBytes { range, excerpts, excerpt_bytes, chunk, } } pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> { let mut result = MultiBufferRows { buffer_row_range: 0..0, excerpts: self.excerpts.cursor(), }; result.seek(start_row); result } pub fn chunks<'a, T: ToOffset>( &'a self, range: Range, theme: Option<&'a SyntaxTheme>, ) -> MultiBufferChunks<'a> { let range = range.start.to_offset(self)..range.end.to_offset(self); let mut chunks = MultiBufferChunks { range: range.clone(), excerpts: self.excerpts.cursor(), excerpt_chunks: None, theme, }; chunks.seek(range.start); chunks } pub fn offset_to_point(&self, offset: usize) -> Point { let mut cursor = self.excerpts.cursor::<(usize, Point)>(); cursor.seek(&offset, Bias::Right, &()); if let Some(excerpt) = cursor.item() { let (start_offset, start_point) = cursor.start(); let overshoot = offset - start_offset; let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer); let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer); let buffer_point = excerpt .buffer .offset_to_point(excerpt_start_offset + overshoot); *start_point + (buffer_point - excerpt_start_point) } else { self.excerpts.summary().text.lines } } pub fn point_to_offset(&self, point: Point) -> usize { let mut cursor = self.excerpts.cursor::<(Point, usize)>(); cursor.seek(&point, Bias::Right, &()); if let Some(excerpt) = cursor.item() { let (start_point, start_offset) = cursor.start(); let overshoot = point - start_point; let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer); let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer); let buffer_offset = excerpt .buffer .point_to_offset(excerpt_start_point + overshoot); *start_offset + buffer_offset - excerpt_start_offset } else { self.excerpts.summary().text.bytes } } pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize { let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>(); cursor.seek(&point, Bias::Right, &()); if let Some(excerpt) = cursor.item() { let (start_point, start_offset) = cursor.start(); let overshoot = point - start_point; let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer); let excerpt_start_point = excerpt .buffer .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer)); let buffer_offset = excerpt .buffer .point_utf16_to_offset(excerpt_start_point + overshoot); *start_offset + (buffer_offset - excerpt_start_offset) } else { self.excerpts.summary().text.bytes } } pub fn indent_column_for_line(&self, row: u32) -> u32 { if let Some((buffer, range)) = self.buffer_line_for_row(row) { buffer .indent_column_for_line(range.start.row) .min(range.end.column) .saturating_sub(range.start.column) } else { 0 } } pub fn line_len(&self, row: u32) -> u32 { if let Some((_, range)) = self.buffer_line_for_row(row) { range.end.column - range.start.column } else { 0 } } fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range)> { let mut cursor = self.excerpts.cursor::(); cursor.seek(&Point::new(row, 0), Bias::Right, &()); if let Some(excerpt) = cursor.item() { let overshoot = row - cursor.start().row; let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer); let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer); let buffer_row = excerpt_start.row + overshoot; let line_start = Point::new(buffer_row, 0); let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row)); return Some(( &excerpt.buffer, line_start.max(excerpt_start)..line_end.min(excerpt_end), )); } None } pub fn max_point(&self) -> Point { self.text_summary().lines } pub fn text_summary(&self) -> TextSummary { self.excerpts.summary().text } pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range) -> D where D: TextDimension, O: ToOffset, { let mut summary = D::default(); let mut range = range.start.to_offset(self)..range.end.to_offset(self); let mut cursor = self.excerpts.cursor::(); cursor.seek(&range.start, Bias::Right, &()); if let Some(excerpt) = cursor.item() { let mut end_before_newline = cursor.end(&()); if excerpt.has_trailing_newline { end_before_newline -= 1; } let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer); let start_in_excerpt = excerpt_start + (range.start - cursor.start()); let end_in_excerpt = excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start()); summary.add_assign( &excerpt .buffer .text_summary_for_range(start_in_excerpt..end_in_excerpt), ); if range.end > end_before_newline { summary.add_assign(&D::from_text_summary(&TextSummary { bytes: 1, lines: Point::new(1 as u32, 0), lines_utf16: PointUtf16::new(1 as u32, 0), first_line_chars: 0, last_line_chars: 0, longest_row: 0, longest_row_chars: 0, })); } cursor.next(&()); } if range.end > *cursor.start() { summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>( &range.end, Bias::Right, &(), ))); if let Some(excerpt) = cursor.item() { range.end = cmp::max(*cursor.start(), range.end); let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer); let end_in_excerpt = excerpt_start + (range.end - cursor.start()); summary.add_assign( &excerpt .buffer .text_summary_for_range(excerpt_start..end_in_excerpt), ); } } summary } pub fn summary_for_anchor(&self, anchor: &Anchor) -> D where D: TextDimension + Ord + Sub, { let mut cursor = self.excerpts.cursor::(); cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &()); if cursor.item().is_none() { cursor.next(&()); } let mut position = D::from_text_summary(&cursor.start().text); if let Some(excerpt) = cursor.item() { if excerpt.id == anchor.excerpt_id { let excerpt_buffer_start = excerpt.range.start.summary::(&excerpt.buffer); let buffer_position = anchor.text_anchor.summary::(&excerpt.buffer); if buffer_position > excerpt_buffer_start { position.add_assign(&(buffer_position - excerpt_buffer_start)); } } } position } pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec where D: TextDimension + Ord + Sub, I: 'a + IntoIterator, { let mut anchors = anchors.into_iter().peekable(); let mut cursor = self.excerpts.cursor::(); let mut summaries = Vec::new(); while let Some(anchor) = anchors.peek() { let excerpt_id = &anchor.excerpt_id; let excerpt_anchors = iter::from_fn(|| { let anchor = anchors.peek()?; if anchor.excerpt_id == *excerpt_id { Some(&anchors.next().unwrap().text_anchor) } else { None } }); cursor.seek_forward(&Some(excerpt_id), Bias::Left, &()); if cursor.item().is_none() { cursor.next(&()); } let position = D::from_text_summary(&cursor.start().text); if let Some(excerpt) = cursor.item() { if excerpt.id == *excerpt_id { let excerpt_buffer_start = excerpt.range.start.summary::(&excerpt.buffer); summaries.extend( excerpt .buffer .summaries_for_anchors::(excerpt_anchors) .map(move |summary| { let mut position = position.clone(); let excerpt_buffer_start = excerpt_buffer_start.clone(); if summary > excerpt_buffer_start { position.add_assign(&(summary - excerpt_buffer_start)); } position }), ); continue; } } summaries.extend(excerpt_anchors.map(|_| position.clone())); } summaries } pub fn anchor_before(&self, position: T) -> Anchor { self.anchor_at(position, Bias::Left) } pub fn anchor_after(&self, position: T) -> Anchor { self.anchor_at(position, Bias::Right) } pub fn anchor_at(&self, position: T, mut bias: Bias) -> Anchor { let offset = position.to_offset(self); let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>(); cursor.seek(&offset, Bias::Right, &()); if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left { cursor.prev(&()); } if let Some(excerpt) = cursor.item() { let mut overshoot = offset.saturating_sub(cursor.start().0); if excerpt.has_trailing_newline && offset == cursor.end(&()).0 { overshoot -= 1; bias = Bias::Right; } let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer); let text_anchor = excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias)); Anchor { excerpt_id: excerpt.id.clone(), text_anchor, } } else if offset == 0 && bias == Bias::Left { Anchor::min() } else { Anchor::max() } } pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor { let mut cursor = self.excerpts.cursor::>(); cursor.seek(&Some(&excerpt_id), Bias::Left, &()); if let Some(excerpt) = cursor.item() { if excerpt.id == excerpt_id { let text_anchor = excerpt.clip_anchor(text_anchor); drop(cursor); return Anchor { excerpt_id, text_anchor, }; } } panic!("excerpt not found"); } pub fn parse_count(&self) -> usize { self.parse_count } pub fn enclosing_bracket_ranges( &self, range: Range, ) -> Option<(Range, Range)> { let range = range.start.to_offset(self)..range.end.to_offset(self); let mut cursor = self.excerpts.cursor::(); cursor.seek(&range.start, Bias::Right, &()); let start_excerpt = cursor.item(); cursor.seek(&range.end, Bias::Right, &()); let end_excerpt = cursor.item(); start_excerpt .zip(end_excerpt) .and_then(|(start_excerpt, end_excerpt)| { if start_excerpt.id != end_excerpt.id { return None; } let excerpt_buffer_start = start_excerpt.range.start.to_offset(&start_excerpt.buffer); let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes; let start_in_buffer = excerpt_buffer_start + range.start.saturating_sub(*cursor.start()); let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(*cursor.start()); let (mut start_bracket_range, mut end_bracket_range) = start_excerpt .buffer .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?; if start_bracket_range.start >= excerpt_buffer_start && end_bracket_range.end < excerpt_buffer_end { start_bracket_range.start = cursor.start() + (start_bracket_range.start - excerpt_buffer_start); start_bracket_range.end = cursor.start() + (start_bracket_range.end - excerpt_buffer_start); end_bracket_range.start = cursor.start() + (end_bracket_range.start - excerpt_buffer_start); end_bracket_range.end = cursor.start() + (end_bracket_range.end - excerpt_buffer_start); Some((start_bracket_range, end_bracket_range)) } else { None } }) } pub fn diagnostics_update_count(&self) -> usize { self.diagnostics_update_count } pub fn language(&self) -> Option<&Arc> { self.excerpts .iter() .next() .and_then(|excerpt| excerpt.buffer.language()) } pub fn is_dirty(&self) -> bool { self.is_dirty } pub fn has_conflict(&self) -> bool { self.has_conflict } pub fn diagnostic_group<'a, O>( &'a self, group_id: usize, ) -> impl Iterator> + 'a where O: text::FromAnchor + 'a, { self.as_singleton() .into_iter() .flat_map(move |buffer| buffer.diagnostic_group(group_id)) } pub fn diagnostics_in_range<'a, T, O>( &'a self, range: Range, ) -> impl Iterator> + 'a where T: 'a + ToOffset, O: 'a + text::FromAnchor, { self.as_singleton().into_iter().flat_map(move |buffer| { buffer.diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self)) }) } pub fn range_for_syntax_ancestor(&self, range: Range) -> Option> { let range = range.start.to_offset(self)..range.end.to_offset(self); let mut cursor = self.excerpts.cursor::(); cursor.seek(&range.start, Bias::Right, &()); let start_excerpt = cursor.item(); cursor.seek(&range.end, Bias::Right, &()); let end_excerpt = cursor.item(); start_excerpt .zip(end_excerpt) .and_then(|(start_excerpt, end_excerpt)| { if start_excerpt.id != end_excerpt.id { return None; } let excerpt_buffer_start = start_excerpt.range.start.to_offset(&start_excerpt.buffer); let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes; let start_in_buffer = excerpt_buffer_start + range.start.saturating_sub(*cursor.start()); let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(*cursor.start()); let mut ancestor_buffer_range = start_excerpt .buffer .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?; ancestor_buffer_range.start = cmp::max(ancestor_buffer_range.start, excerpt_buffer_start); ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end); let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start); let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start); Some(start..end) }) } fn buffer_snapshot_for_excerpt<'a>( &'a self, excerpt_id: &'a ExcerptId, ) -> Option<&'a BufferSnapshot> { let mut cursor = self.excerpts.cursor::>(); cursor.seek(&Some(excerpt_id), Bias::Left, &()); if let Some(excerpt) = cursor.item() { if excerpt.id == *excerpt_id { return Some(&excerpt.buffer); } } None } pub fn remote_selections_in_range<'a>( &'a self, range: &'a Range, ) -> impl 'a + Iterator)> { let mut cursor = self.excerpts.cursor::>(); cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &()); cursor .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id) .flat_map(move |excerpt| { let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone(); if excerpt.id == range.start.excerpt_id { query_range.start = range.start.text_anchor.clone(); } if excerpt.id == range.end.excerpt_id { query_range.end = range.end.text_anchor.clone(); } excerpt .buffer .remote_selections_in_range(query_range) .flat_map(move |(replica_id, selections)| { selections.map(move |selection| { let mut start = Anchor { excerpt_id: excerpt.id.clone(), text_anchor: selection.start.clone(), }; let mut end = Anchor { excerpt_id: excerpt.id.clone(), text_anchor: selection.end.clone(), }; if range.start.cmp(&start, self).unwrap().is_gt() { start = range.start.clone(); } if range.end.cmp(&end, self).unwrap().is_lt() { end = range.end.clone(); } ( replica_id, Selection { id: selection.id, start, end, reversed: selection.reversed, goal: selection.goal, }, ) }) }) }) } } impl History { fn start_transaction(&mut self, now: Instant) -> Option { self.transaction_depth += 1; if self.transaction_depth == 1 { let id = post_inc(&mut self.next_transaction_id); self.undo_stack.push(Transaction { id, buffer_transactions: Default::default(), first_edit_at: now, last_edit_at: now, }); Some(id) } else { None } } fn end_transaction( &mut self, now: Instant, buffer_transactions: HashSet<(usize, TransactionId)>, ) -> bool { assert_ne!(self.transaction_depth, 0); self.transaction_depth -= 1; if self.transaction_depth == 0 { if buffer_transactions.is_empty() { self.undo_stack.pop(); false } else { let transaction = self.undo_stack.last_mut().unwrap(); transaction.last_edit_at = now; transaction.buffer_transactions.extend(buffer_transactions); true } } else { false } } fn pop_undo(&mut self) -> Option<&Transaction> { assert_eq!(self.transaction_depth, 0); if let Some(transaction) = self.undo_stack.pop() { self.redo_stack.push(transaction); self.redo_stack.last() } else { None } } fn pop_redo(&mut self) -> Option<&Transaction> { assert_eq!(self.transaction_depth, 0); if let Some(transaction) = self.redo_stack.pop() { self.undo_stack.push(transaction); self.undo_stack.last() } else { None } } fn group(&mut self) -> Option { let mut new_len = self.undo_stack.len(); let mut transactions = self.undo_stack.iter_mut(); if let Some(mut transaction) = transactions.next_back() { while let Some(prev_transaction) = transactions.next_back() { if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval { transaction = prev_transaction; new_len -= 1; } else { break; } } } let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len); if let Some(last_transaction) = transactions_to_keep.last_mut() { if let Some(transaction) = transactions_to_merge.last() { last_transaction.last_edit_at = transaction.last_edit_at; } } self.undo_stack.truncate(new_len); self.undo_stack.last().map(|t| t.id) } } impl Excerpt { fn new( id: ExcerptId, buffer_id: usize, buffer: BufferSnapshot, range: Range, header_height: u8, render_header: Option, has_trailing_newline: bool, ) -> Self { Excerpt { id, text_summary: buffer.text_summary_for_range::(range.to_offset(&buffer)), buffer_id, buffer, range, header_height, render_header, has_trailing_newline, } } fn chunks_in_range<'a>( &'a self, range: Range, theme: Option<&'a SyntaxTheme>, ) -> ExcerptChunks<'a> { let content_start = self.range.start.to_offset(&self.buffer); let chunks_start = content_start + range.start; let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes); let footer_height = if self.has_trailing_newline && range.start <= self.text_summary.bytes && range.end > self.text_summary.bytes { 1 } else { 0 }; let content_chunks = self.buffer.chunks(chunks_start..chunks_end, theme); ExcerptChunks { content_chunks, footer_height, } } fn bytes_in_range(&self, range: Range) -> ExcerptBytes { let content_start = self.range.start.to_offset(&self.buffer); let bytes_start = content_start + range.start; let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes); let footer_height = if self.has_trailing_newline && range.start <= self.text_summary.bytes && range.end > self.text_summary.bytes { 1 } else { 0 }; let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end); ExcerptBytes { content_bytes, footer_height, } } fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor { if text_anchor .cmp(&self.range.start, &self.buffer) .unwrap() .is_lt() { self.range.start.clone() } else if text_anchor .cmp(&self.range.end, &self.buffer) .unwrap() .is_gt() { self.range.end.clone() } else { text_anchor } } } impl fmt::Debug for Excerpt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Excerpt") .field("id", &self.id) .field("buffer_id", &self.buffer_id) .field("range", &self.range) .field("text_summary", &self.text_summary) .field("has_trailing_newline", &self.has_trailing_newline) .finish() } } impl sum_tree::Item for Excerpt { type Summary = ExcerptSummary; fn summary(&self) -> Self::Summary { let mut text = self.text_summary.clone(); if self.has_trailing_newline { text += TextSummary::from("\n"); } ExcerptSummary { excerpt_id: self.id.clone(), text, } } } impl sum_tree::Summary for ExcerptSummary { type Context = (); fn add_summary(&mut self, summary: &Self, _: &()) { debug_assert!(summary.excerpt_id > self.excerpt_id); self.excerpt_id = summary.excerpt_id.clone(); self.text.add_summary(&summary.text, &()); } } impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary { fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) { *self += &summary.text; } } impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize { fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) { *self += summary.text.bytes; } } impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize { fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering { Ord::cmp(self, &cursor_location.text.bytes) } } impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> { fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering { Ord::cmp(self, &Some(&cursor_location.excerpt_id)) } } impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point { fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) { *self += summary.text.lines; } } impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 { fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) { *self += summary.text.lines_utf16 } } impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> { fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) { *self = Some(&summary.excerpt_id); } } impl<'a> MultiBufferRows<'a> { pub fn seek(&mut self, row: u32) { self.buffer_row_range = 0..0; self.excerpts .seek_forward(&Point::new(row, 0), Bias::Right, &()); if self.excerpts.item().is_none() { self.excerpts.prev(&()); if self.excerpts.item().is_none() && row == 0 { self.buffer_row_range = 0..1; return; } } if let Some(excerpt) = self.excerpts.item() { let overshoot = row - self.excerpts.start().row; let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row; self.buffer_row_range.start = excerpt_start + overshoot; self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1; } } } impl<'a> Iterator for MultiBufferRows<'a> { type Item = Option; fn next(&mut self) -> Option { loop { if !self.buffer_row_range.is_empty() { let row = Some(self.buffer_row_range.start); self.buffer_row_range.start += 1; return Some(row); } self.excerpts.item()?; self.excerpts.next(&()); let excerpt = self.excerpts.item()?; self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row; self.buffer_row_range.end = self.buffer_row_range.start + excerpt.text_summary.lines.row + 1; } } } impl<'a> MultiBufferChunks<'a> { pub fn offset(&self) -> usize { self.range.start } pub fn seek(&mut self, offset: usize) { self.range.start = offset; self.excerpts.seek(&offset, Bias::Right, &()); if let Some(excerpt) = self.excerpts.item() { self.excerpt_chunks = Some(excerpt.chunks_in_range( self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(), self.theme, )); } else { self.excerpt_chunks = None; } } } impl<'a> Iterator for MultiBufferChunks<'a> { type Item = Chunk<'a>; fn next(&mut self) -> Option { if self.range.is_empty() { None } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() { self.range.start += chunk.text.len(); Some(chunk) } else { self.excerpts.next(&()); let excerpt = self.excerpts.item()?; self.excerpt_chunks = Some( excerpt.chunks_in_range(0..self.range.end - self.excerpts.start(), self.theme), ); self.next() } } } impl<'a> MultiBufferBytes<'a> { fn consume(&mut self, len: usize) { self.range.start += len; self.chunk = &self.chunk[len..]; if !self.range.is_empty() && self.chunk.is_empty() { if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) { self.chunk = chunk; } else { self.excerpts.next(&()); if let Some(excerpt) = self.excerpts.item() { let mut excerpt_bytes = excerpt.bytes_in_range(0..self.range.end - self.excerpts.start()); self.chunk = excerpt_bytes.next().unwrap(); self.excerpt_bytes = Some(excerpt_bytes); } } } } } impl<'a> Iterator for MultiBufferBytes<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option { let chunk = self.chunk; if chunk.is_empty() { None } else { self.consume(chunk.len()); Some(chunk) } } } impl<'a> io::Read for MultiBufferBytes<'a> { fn read(&mut self, buf: &mut [u8]) -> io::Result { let len = cmp::min(buf.len(), self.chunk.len()); buf[..len].copy_from_slice(&self.chunk[..len]); if len > 0 { self.consume(len); } Ok(len) } } impl<'a> Iterator for ExcerptBytes<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option { if let Some(chunk) = self.content_bytes.next() { if !chunk.is_empty() { return Some(chunk); } } if self.footer_height > 0 { let result = &NEWLINES[..self.footer_height]; self.footer_height = 0; return Some(result); } None } } impl<'a> Iterator for ExcerptChunks<'a> { type Item = Chunk<'a>; fn next(&mut self) -> Option { if let Some(chunk) = self.content_chunks.next() { return Some(chunk); } if self.footer_height > 0 { let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) }; self.footer_height = 0; return Some(Chunk { text, ..Default::default() }); } None } } impl ToOffset for Point { fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize { snapshot.point_to_offset(*self) } } impl ToOffset for PointUtf16 { fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize { snapshot.point_utf16_to_offset(*self) } } impl ToOffset for usize { fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize { assert!(*self <= snapshot.len(), "offset is out of range"); *self } } impl ToPoint for usize { fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point { snapshot.offset_to_point(*self) } } impl ToPoint for Point { fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point { *self } } #[cfg(test)] mod tests { use super::*; use gpui::{elements::Empty, Element, MutableAppContext}; use language::{Buffer, Rope}; use rand::prelude::*; use std::env; use text::{Point, RandomCharIter}; use util::test::sample_text; #[gpui::test] fn test_singleton_multibuffer(cx: &mut MutableAppContext) { let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx)); let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx)); let snapshot = multibuffer.read(cx).snapshot(cx); assert_eq!(snapshot.text(), buffer.read(cx).text()); assert_eq!( snapshot.buffer_rows(0).collect::>(), (0..buffer.read(cx).row_count()) .map(Some) .collect::>() ); buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx)); let snapshot = multibuffer.read(cx).snapshot(cx); assert_eq!(snapshot.text(), buffer.read(cx).text()); assert_eq!( snapshot.buffer_rows(0).collect::>(), (0..buffer.read(cx).row_count()) .map(Some) .collect::>() ); } #[gpui::test] fn test_excerpt_buffer(cx: &mut MutableAppContext) { let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx)); let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx)); let multibuffer = cx.add_model(|_| MultiBuffer::new(0)); let subscription = multibuffer.update(cx, |multibuffer, cx| { let subscription = multibuffer.subscribe(); multibuffer.push_excerpt( ExcerptProperties { buffer: &buffer_1, range: Point::new(1, 2)..Point::new(2, 5), header_height: 2, render_header: Some(Arc::new(|_| Empty::new().named("header 1"))), }, cx, ); assert_eq!( subscription.consume().into_inner(), [Edit { old: 0..0, new: 0..10 }] ); multibuffer.push_excerpt( ExcerptProperties { buffer: &buffer_1, range: Point::new(3, 3)..Point::new(4, 4), header_height: 1, render_header: Some(Arc::new(|_| Empty::new().named("header 2"))), }, cx, ); multibuffer.push_excerpt( ExcerptProperties { buffer: &buffer_2, range: Point::new(3, 1)..Point::new(3, 3), header_height: 3, render_header: Some(Arc::new(|_| Empty::new().named("header 3"))), }, cx, ); assert_eq!( subscription.consume().into_inner(), [Edit { old: 10..10, new: 10..22 }] ); subscription }); let snapshot = multibuffer.read(cx).snapshot(cx); assert_eq!( snapshot.text(), concat!( "bbbb\n", // Preserve newlines "ccccc\n", // "ddd\n", // "eeee\n", // "jj" // ) ); assert_eq!( snapshot.buffer_rows(0).collect::>(), [Some(1), Some(2), Some(3), Some(4), Some(3)] ); assert_eq!( snapshot.buffer_rows(2).collect::>(), [Some(3), Some(4), Some(3)] ); assert_eq!(snapshot.buffer_rows(4).collect::>(), [Some(3)]); assert_eq!(snapshot.buffer_rows(5).collect::>(), []); { let snapshot = multibuffer.read(cx).read(cx); assert_eq!( snapshot .excerpt_headers_in_range(0..snapshot.max_point().row + 1) .map(|(start_row, header_height, render)| ( start_row, header_height, render(cx).name().unwrap().to_string() )) .collect::>(), &[ (0, 2, "header 1".into()), (2, 1, "header 2".into()), (4, 3, "header 3".into()) ] ); assert_eq!( snapshot .excerpt_headers_in_range(1..4) .map(|(start_row, header_height, render)| ( start_row, header_height, render(cx).name().unwrap().to_string() )) .collect::>(), &[(2, 1, "header 2".into())] ); assert_eq!( snapshot .excerpt_headers_in_range(2..5) .map(|(start_row, header_height, render)| ( start_row, header_height, render(cx).name().unwrap().to_string() )) .collect::>(), &[(2, 1, "header 2".into()), (4, 3, "header 3".into())] ); } buffer_1.update(cx, |buffer, cx| { buffer.edit( [ Point::new(0, 0)..Point::new(0, 0), Point::new(2, 1)..Point::new(2, 3), ], "\n", cx, ); }); assert_eq!( multibuffer.read(cx).snapshot(cx).text(), concat!( "bbbb\n", // Preserve newlines "c\n", // "cc\n", // "ddd\n", // "eeee\n", // "jj" // ) ); assert_eq!( subscription.consume().into_inner(), [Edit { old: 6..8, new: 6..7 }] ); // bbbb\nc\ncc\nddd\neeee\njj let multibuffer = multibuffer.read(cx).snapshot(cx); assert_eq!( multibuffer.clip_point(Point::new(0, 5), Bias::Left), Point::new(0, 4) ); assert_eq!( multibuffer.clip_point(Point::new(0, 5), Bias::Right), Point::new(0, 4) ); assert_eq!( multibuffer.clip_point(Point::new(5, 1), Bias::Right), Point::new(5, 1) ); assert_eq!( multibuffer.clip_point(Point::new(5, 2), Bias::Right), Point::new(5, 2) ); assert_eq!( multibuffer.clip_point(Point::new(5, 3), Bias::Right), Point::new(5, 2) ); } #[gpui::test] fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) { let multibuffer = cx.add_model(|_| MultiBuffer::new(0)); let snapshot = multibuffer.read(cx).snapshot(cx); assert_eq!(snapshot.text(), ""); assert_eq!(snapshot.buffer_rows(0).collect::>(), &[Some(0)]); assert_eq!(snapshot.buffer_rows(1).collect::>(), &[]); } #[gpui::test] fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) { let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx)); let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx)); let old_snapshot = multibuffer.read(cx).snapshot(cx); buffer.update(cx, |buffer, cx| { buffer.edit([0..0], "X", cx); buffer.edit([5..5], "Y", cx); }); let new_snapshot = multibuffer.read(cx).snapshot(cx); assert_eq!(old_snapshot.text(), "abcd"); assert_eq!(new_snapshot.text(), "XabcdY"); assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0); assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1); assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5); assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6); } #[gpui::test] fn test_multibuffer_anchors(cx: &mut MutableAppContext) { let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx)); let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx)); let multibuffer = cx.add_model(|cx| { let mut multibuffer = MultiBuffer::new(0); multibuffer.push_excerpt( ExcerptProperties { buffer: &buffer_1, range: 0..4, header_height: 1, render_header: None, }, cx, ); multibuffer.push_excerpt( ExcerptProperties { buffer: &buffer_2, range: 0..5, header_height: 1, render_header: None, }, cx, ); multibuffer }); let old_snapshot = multibuffer.read(cx).snapshot(cx); assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0); assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0); assert_eq!(Anchor::min().to_offset(&old_snapshot), 0); assert_eq!(Anchor::min().to_offset(&old_snapshot), 0); assert_eq!(Anchor::max().to_offset(&old_snapshot), 10); assert_eq!(Anchor::max().to_offset(&old_snapshot), 10); buffer_1.update(cx, |buffer, cx| { buffer.edit([0..0], "W", cx); buffer.edit([5..5], "X", cx); }); buffer_2.update(cx, |buffer, cx| { buffer.edit([0..0], "Y", cx); buffer.edit([6..0], "Z", cx); }); let new_snapshot = multibuffer.read(cx).snapshot(cx); assert_eq!(old_snapshot.text(), "abcd\nefghi"); assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ"); assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0); assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1); assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2); assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2); assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3); assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3); assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7); assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8); assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13); assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14); } #[gpui::test(iterations = 100)] fn test_random_excerpts(cx: &mut MutableAppContext, mut rng: StdRng) { let operations = env::var("OPERATIONS") .map(|i| i.parse().expect("invalid `OPERATIONS` variable")) .unwrap_or(10); let mut buffers: Vec> = Vec::new(); let list = cx.add_model(|_| MultiBuffer::new(0)); let mut excerpt_ids = Vec::new(); let mut expected_excerpts = Vec::new(); let mut old_versions = Vec::new(); for _ in 0..operations { match rng.gen_range(0..100) { 0..=19 if !buffers.is_empty() => { let buffer = buffers.choose(&mut rng).unwrap(); buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx)); } _ => { let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) { let base_text = RandomCharIter::new(&mut rng).take(10).collect::(); buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx))); buffers.last().unwrap() } else { buffers.choose(&mut rng).unwrap() }; let buffer = buffer_handle.read(cx); let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right); let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left); let header_height = rng.gen_range(0..=5); let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix); log::info!( "Pushing excerpt wih header {}, buffer {}: {:?}[{:?}] = {:?}", header_height, buffer_handle.id(), buffer.text(), start_ix..end_ix, &buffer.text()[start_ix..end_ix] ); let excerpt_id = list.update(cx, |list, cx| { list.push_excerpt( ExcerptProperties { buffer: &buffer_handle, range: start_ix..end_ix, header_height, render_header: None, }, cx, ) }); excerpt_ids.push(excerpt_id); expected_excerpts.push((buffer_handle.clone(), anchor_range, header_height)); } } if rng.gen_bool(0.3) { list.update(cx, |list, cx| { old_versions.push((list.snapshot(cx), list.subscribe())); }) } let snapshot = list.read(cx).snapshot(cx); let mut excerpt_starts = Vec::new(); let mut expected_text = String::new(); let mut expected_buffer_rows = Vec::new(); for (buffer, range, _) in &expected_excerpts { let buffer = buffer.read(cx); let buffer_range = range.to_offset(buffer); excerpt_starts.push(TextSummary::from(expected_text.as_str())); expected_text.extend(buffer.text_for_range(buffer_range.clone())); expected_text.push('\n'); let buffer_row_range = buffer.offset_to_point(buffer_range.start).row ..=buffer.offset_to_point(buffer_range.end).row; for row in buffer_row_range { expected_buffer_rows.push(Some(row)); } } // Remove final trailing newline. if !expected_excerpts.is_empty() { expected_text.pop(); } assert_eq!(snapshot.text(), expected_text); log::info!("MultiBuffer text: {:?}", expected_text); assert_eq!( snapshot.buffer_rows(0).collect::>(), expected_buffer_rows, ); for _ in 0..5 { let start_row = rng.gen_range(0..=expected_buffer_rows.len()); assert_eq!( snapshot.buffer_rows(start_row as u32).collect::>(), &expected_buffer_rows[start_row..], "buffer_rows({})", start_row ); } let mut excerpt_starts = excerpt_starts.into_iter(); for (buffer, range, _) in &expected_excerpts { let buffer_id = buffer.id(); let buffer = buffer.read(cx); let buffer_range = range.to_offset(buffer); let buffer_start_point = buffer.offset_to_point(buffer_range.start); let buffer_start_point_utf16 = buffer.text_summary_for_range::(0..buffer_range.start); let excerpt_start = excerpt_starts.next().unwrap(); let mut offset = excerpt_start.bytes; let mut buffer_offset = buffer_range.start; let mut point = excerpt_start.lines; let mut buffer_point = buffer_start_point; let mut point_utf16 = excerpt_start.lines_utf16; let mut buffer_point_utf16 = buffer_start_point_utf16; for ch in buffer .snapshot() .chunks(buffer_range.clone(), None) .flat_map(|c| c.text.chars()) { for _ in 0..ch.len_utf8() { let left_offset = snapshot.clip_offset(offset, Bias::Left); let right_offset = snapshot.clip_offset(offset, Bias::Right); let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left); let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right); assert_eq!( left_offset, excerpt_start.bytes + (buffer_left_offset - buffer_range.start), "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}", offset, buffer_id, buffer_offset, ); assert_eq!( right_offset, excerpt_start.bytes + (buffer_right_offset - buffer_range.start), "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}", offset, buffer_id, buffer_offset, ); let left_point = snapshot.clip_point(point, Bias::Left); let right_point = snapshot.clip_point(point, Bias::Right); let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left); let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right); assert_eq!( left_point, excerpt_start.lines + (buffer_left_point - buffer_start_point), "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}", point, buffer_id, buffer_point, ); assert_eq!( right_point, excerpt_start.lines + (buffer_right_point - buffer_start_point), "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}", point, buffer_id, buffer_point, ); assert_eq!( snapshot.point_to_offset(left_point), left_offset, "point_to_offset({:?})", left_point, ); assert_eq!( snapshot.offset_to_point(left_offset), left_point, "offset_to_point({:?})", left_offset, ); offset += 1; buffer_offset += 1; if ch == '\n' { point += Point::new(1, 0); buffer_point += Point::new(1, 0); } else { point += Point::new(0, 1); buffer_point += Point::new(0, 1); } } for _ in 0..ch.len_utf16() { let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left); let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right); let buffer_left_point_utf16 = buffer.clip_point_utf16(buffer_point_utf16, Bias::Left); let buffer_right_point_utf16 = buffer.clip_point_utf16(buffer_point_utf16, Bias::Right); assert_eq!( left_point_utf16, excerpt_start.lines_utf16 + (buffer_left_point_utf16 - buffer_start_point_utf16), "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}", point_utf16, buffer_id, buffer_point_utf16, ); assert_eq!( right_point_utf16, excerpt_start.lines_utf16 + (buffer_right_point_utf16 - buffer_start_point_utf16), "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}", point_utf16, buffer_id, buffer_point_utf16, ); if ch == '\n' { point_utf16 += PointUtf16::new(1, 0); buffer_point_utf16 += PointUtf16::new(1, 0); } else { point_utf16 += PointUtf16::new(0, 1); buffer_point_utf16 += PointUtf16::new(0, 1); } } } } for (row, line) in expected_text.split('\n').enumerate() { assert_eq!( snapshot.line_len(row as u32), line.len() as u32, "line_len({}).", row ); } let text_rope = Rope::from(expected_text.as_str()); for _ in 0..10 { let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right); let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left); assert_eq!( snapshot .text_for_range(start_ix..end_ix) .collect::(), &expected_text[start_ix..end_ix], "incorrect text for range {:?}", start_ix..end_ix ); let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]); assert_eq!( snapshot.text_summary_for_range::(start_ix..end_ix), expected_summary, "incorrect summary for range {:?}", start_ix..end_ix ); } for _ in 0..10 { let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right); assert_eq!( snapshot.reversed_chars_at(end_ix).collect::(), expected_text[..end_ix].chars().rev().collect::(), ); } for _ in 0..10 { let end_ix = rng.gen_range(0..=text_rope.len()); let start_ix = rng.gen_range(0..=end_ix); assert_eq!( snapshot .bytes_in_range(start_ix..end_ix) .flatten() .copied() .collect::>(), expected_text.as_bytes()[start_ix..end_ix].to_vec(), "bytes_in_range({:?})", start_ix..end_ix, ); } } let snapshot = list.read(cx).snapshot(cx); for (old_snapshot, subscription) in old_versions { let edits = subscription.consume().into_inner(); log::info!( "applying subscription edits to old text: {:?}: {:?}", old_snapshot.text(), edits, ); let mut text = old_snapshot.text(); for edit in edits { let new_text: String = snapshot.text_for_range(edit.new.clone()).collect(); text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text); } assert_eq!(text.to_string(), snapshot.text()); } } #[gpui::test] fn test_history(cx: &mut MutableAppContext) { let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx)); let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx)); let multibuffer = cx.add_model(|_| MultiBuffer::new(0)); let group_interval = multibuffer.read(cx).history.group_interval; multibuffer.update(cx, |multibuffer, cx| { multibuffer.push_excerpt( ExcerptProperties { buffer: &buffer_1, range: 0..buffer_1.read(cx).len(), header_height: 0, render_header: None, }, cx, ); multibuffer.push_excerpt( ExcerptProperties { buffer: &buffer_2, range: 0..buffer_2.read(cx).len(), header_height: 0, render_header: None, }, cx, ); }); let mut now = Instant::now(); multibuffer.update(cx, |multibuffer, cx| { multibuffer.start_transaction_at(now, cx); multibuffer.edit( [ Point::new(0, 0)..Point::new(0, 0), Point::new(1, 0)..Point::new(1, 0), ], "A", cx, ); multibuffer.edit( [ Point::new(0, 1)..Point::new(0, 1), Point::new(1, 1)..Point::new(1, 1), ], "B", cx, ); multibuffer.end_transaction_at(now, cx); assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678"); now += 2 * group_interval; multibuffer.start_transaction_at(now, cx); multibuffer.edit([2..2], "C", cx); multibuffer.end_transaction_at(now, cx); assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678"); multibuffer.undo(cx); assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678"); multibuffer.undo(cx); assert_eq!(multibuffer.read(cx).text(), "1234\n5678"); multibuffer.redo(cx); assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678"); multibuffer.redo(cx); assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678"); buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx)); assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678"); multibuffer.undo(cx); assert_eq!(multibuffer.read(cx).text(), "1234\n5678"); multibuffer.redo(cx); assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678"); multibuffer.redo(cx); assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678"); multibuffer.undo(cx); assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678"); buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx)); assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678"); multibuffer.undo(cx); assert_eq!(multibuffer.read(cx).text(), "C1234\n5678"); }); } }