Use indices to simplify `goto_buffer`

pull/11790/head
emilylime 2 months ago
parent 8373919e6d
commit f943fb947e

@ -868,33 +868,24 @@ fn goto_previous_buffer(cx: &mut Context) {
} }
fn goto_buffer(editor: &mut Editor, direction: Direction, count: usize) { fn goto_buffer(editor: &mut Editor, direction: Direction, count: usize) {
let current = view!(editor).doc; let index = editor.focused_document_index();
let len = editor.documents.len();
let id = match direction { let index = match direction {
Direction::Forward => { Direction::Forward => (index + count) % len,
let iter = editor.documents.keys(); // Equivalent to `(i - count).rem_euclid(len)` but avoids overflow.
// skip 'count' times past current buffer Direction::Backward => (index + len - count % len) % len,
iter.cycle().skip_while(|id| *id != &current).nth(count) };
}
Direction::Backward => {
let iter = editor.documents.keys();
// skip 'count' times past current buffer
iter.rev()
.cycle()
.skip_while(|id| *id != &current)
.nth(count)
}
}
.unwrap();
let id = *id; let id = *editor.documents.get_index(index).unwrap().0;
// This could've probably been faster with an `editor.switch_by_index()` but
// the document indices are not integrated enough to implement that easily.
editor.switch(id, Action::Replace); editor.switch(id, Action::Replace);
} }
fn move_buffer_left(cx: &mut Context) { fn move_buffer_left(cx: &mut Context) {
let count = cx.count(); let count = cx.count();
// Equivalent to `(i - count).rem_euclid(len)` but avoids overflow issues.
move_buffer(cx.editor, |i, len| (i + len - count % len) % len) move_buffer(cx.editor, |i, len| (i + len - count % len) % len)
} }
fn move_buffer_right(cx: &mut Context) { fn move_buffer_right(cx: &mut Context) {
@ -910,8 +901,7 @@ fn move_buffer_end(cx: &mut Context) {
#[inline] #[inline]
fn move_buffer(editor: &mut Editor, index_transform: impl FnOnce(usize, usize) -> usize) { fn move_buffer(editor: &mut Editor, index_transform: impl FnOnce(usize, usize) -> usize) {
let current = view!(editor).doc; let index = editor.focused_document_index();
let index = editor.documents.get_index_of(&current).unwrap();
let new_index = index_transform(index, editor.documents.len()); let new_index = index_transform(index, editor.documents.len());
editor.documents.move_index(index, new_index); editor.documents.move_index(index, new_index);
} }

@ -1939,6 +1939,13 @@ impl Editor {
self.documents.values_mut() self.documents.values_mut()
} }
#[inline]
pub fn focused_document_index(&self) -> usize {
self.documents
.get_index_of(&view!(self).doc)
.expect("focused document should always be present")
}
pub fn document_by_path<P: AsRef<Path>>(&self, path: P) -> Option<&Document> { pub fn document_by_path<P: AsRef<Path>>(&self, path: P) -> Option<&Document> {
self.documents() self.documents()
.find(|doc| doc.path().map(|p| p == path.as_ref()).unwrap_or(false)) .find(|doc| doc.path().map(|p| p == path.as_ref()).unwrap_or(false))

Loading…
Cancel
Save