diff --git a/src/tests.rs b/src/tests.rs index c19f8c8..fc0b4c2 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -203,6 +203,58 @@ fn simple_insert() { } } +#[test] +fn unified_diff_context_lines_near_input_start_and_end() { + let before = r#"a +b +c +d +e +f +g +h +i +"#; + + let after = r#"a +b +c +d +edit +f +g +h +i +"#; + + let input = InternedInput::new(before, after); + for algorithm in Algorithm::ALL { + println!("{algorithm:?}"); + let mut diff = Diff::compute(algorithm, &input); + diff.postprocess_lines(&input); + expect![[r#" + @@ -2,7 +2,7 @@ + b + c + d + -e + +edit + f + g + h + "#]] + .assert_eq( + &diff + .unified_diff( + &BasicLineDiffPrinter(&input.interner), + UnifiedDiffConfig::default(), + &input, + ) + .to_string(), + ); + } +} + pub fn project_root() -> PathBuf { let dir = env!("CARGO_MANIFEST_DIR"); let mut res = PathBuf::from(dir); diff --git a/src/unified_diff.rs b/src/unified_diff.rs index ecdbd5a..ee9517b 100644 --- a/src/unified_diff.rs +++ b/src/unified_diff.rs @@ -143,18 +143,18 @@ pub struct UnifiedDiff<'a, P: UnifiedDiffPrinter> { impl Display for UnifiedDiff<'_, P> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut pos = 0; - let mut before_context_len = 0; - let mut after_context_len = 0; let first_hunk = self.diff.hunks().next().unwrap_or_default(); - let mut before_context_start = first_hunk + let mut pos = first_hunk .before .start .saturating_sub(self.config.context_len); + let mut before_context_start = pos; let mut after_context_start = first_hunk .after .start .saturating_sub(self.config.context_len); + let mut before_context_len = 0; + let mut after_context_len = 0; let mut buffer = String::new(); for hunk in self.diff.hunks() { if hunk.before.start - pos > 2 * self.config.context_len {