Skip to content

Commit

Permalink
Update buffer reload to retain cursor position when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
jmacdonald committed Feb 10, 2024
1 parent b938b80 commit df9a98d
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/buffer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,9 @@ impl Buffer {
self.id = buf.id;
self.syntax_definition = buf.syntax_definition;
self.change_callback = buf.change_callback;
if !self.cursor.move_to(*buf.cursor) {
self.cursor.move_to(Position{ line: buf.cursor.line, offset: 0 });
}
},
Err(e) => return Err(e),
}
Expand Down Expand Up @@ -510,6 +513,57 @@ mod tests {
assert!(buffer.syntax_definition.is_some());
}

#[test]
fn reload_retains_full_position_when_possible() {
// Load a buffer with some data and modify it.
let file_path = Path::new("tests/sample/file");
let mut buffer = Buffer::from_file(file_path).unwrap();

// Move to a position that will exist after reload.
buffer.cursor.move_to(Position { line: 0, offset: 3 });

// Reload the buffer
buffer.reload().unwrap();

// Verify that the position is retained.
assert_eq!(*buffer.cursor, Position { line: 0, offset: 3 });
}

#[test]
fn reload_retains_position_line_when_possible() {
// Load a buffer with some data and modify it.
let file_path = Path::new("tests/sample/file");
let mut buffer = Buffer::from_file(file_path).unwrap();

// Move to an in-memory-only position whose line
// is also available in the on-disk version.
buffer.insert("amp\neditor");
buffer.cursor.move_to(Position { line: 1, offset: 1 });

// Reload the buffer
buffer.reload().unwrap();

// Verify that the position is set to the start of the same line.
assert_eq!(*buffer.cursor, Position { line: 1, offset: 0 });
}

#[test]
fn reload_discards_position_when_impossible() {
// Load a buffer with some data and modify it.
let file_path = Path::new("tests/sample/file");
let mut buffer = Buffer::from_file(file_path).unwrap();

// Move to a truly in-memory-only position.
buffer.insert("\namp\neditor");
buffer.cursor.move_to(Position { line: 2, offset: 1 });

// Reload the buffer
buffer.reload().unwrap();

// Verify that the position is discarded.
assert_eq!(*buffer.cursor, Position::new());
}

#[test]
fn reload_calls_change_callback_with_zero_position() {
// Load a buffer with some data and modify it.
Expand Down

0 comments on commit df9a98d

Please sign in to comment.