diff --git a/crates/ide-notebook/src/document.rs b/crates/ide-notebook/src/document.rs index c845a52825..c87bcdac29 100644 --- a/crates/ide-notebook/src/document.rs +++ b/crates/ide-notebook/src/document.rs @@ -905,7 +905,9 @@ fn rewritten_source(old: Option<&Node>, text: String) -> Node { let mut start = 0; while first < parts.len() { let part = parts[first].string().expect("validated source text"); - if !text[start..].starts_with(part) { + // Only whole lines are kept: a part without its newline (typing at the end of a line, or a + // source saved one character per element) is rewritten with the rest of its line. + if !part.ends_with('\n') || !text[start..].starts_with(part) { break; } start += part.len(); @@ -918,6 +920,11 @@ fn rewritten_source(old: Option<&Node>, text: String) -> Node { if end - start < part.len() || !text[start..end].ends_with(part) { break; } + // ...and only from the start of a line. + let at = end - part.len(); + if at > 0 && !text[..at].ends_with('\n') { + break; + } end -= part.len(); last -= 1; } @@ -993,3 +1000,50 @@ fn validate_output_node(node: &Node) -> IdeResult<()> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn typing_characters_preserves_source_lines() { + let mut source = Node::new(Value::Array(Vec::new())); + + for text in ["a", "ab", "abc"] { + source = rewritten_source(Some(&source), text.to_string()); + } + + let mut actual = String::new(); + source.write(&mut actual); + + assert_eq!(actual, r#"["abc"]"#); + } + + fn written(node: &Node) -> String { + let mut out = String::new(); + node.write(&mut out); + out + } + + #[test] + fn typing_keeps_one_element_per_line_and_the_untouched_lines() { + let mut source = Node::new(Value::Array(Vec::new())); + let code = "if True:\n print('hello')\nx = 1"; + for end in 1..=code.len() { + source = rewritten_source(Some(&source), code[..end].to_string()); + } + assert_eq!(written(&source), r#"["if True:\n"," print('hello')\n","x = 1"]"#); + + // Typing at the end of the middle line leaves the other lines' elements as they were. + let edited = "if True:\n print('hello!')\nx = 1"; + let source = rewritten_source(Some(&source), edited.to_string()); + assert_eq!(written(&source), r#"["if True:\n"," print('hello!')\n","x = 1"]"#); + } + + #[test] + fn a_source_saved_one_character_per_element_is_joined_into_lines_where_it_is_edited() { + let parts = "ab\ncd".chars().map(|c| Value::String(c.to_string())).collect(); + let source = rewritten_source(Some(&Node::new(Value::Array(parts))), "ab\ncde".to_string()); + assert_eq!(written(&source), r#"["ab\n","cde"]"#); + } +}