From df9a98d810fa8a625a42eb027b33c78bd2fb5eb0 Mon Sep 17 00:00:00 2001 From: Jordan MacDonald Date: Fri, 9 Feb 2024 21:15:51 -0500 Subject: [PATCH] Update buffer reload to retain cursor position when possible --- src/buffer/mod.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/buffer/mod.rs b/src/buffer/mod.rs index 54ad664..67893ba 100644 --- a/src/buffer/mod.rs +++ b/src/buffer/mod.rs @@ -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), } @@ -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.