Added initial support for inline diff highlighting

This commit is contained in:
Armin Ronacher 2021-01-31 18:22:37 +01:00
parent 182a998e0f
commit b601164a60
6 changed files with 245 additions and 50 deletions

View file

@ -0,0 +1,30 @@
use console::Style;
use similar::text::{ChangeTag, TextDiff};
fn main() {
let diff = TextDiff::from_lines(
"Hello World\nThis is the second line.\nThis is the third.",
"Hallo Welt\nThis is the second line.\nThis is life.\nMoar and more",
);
for op in diff.ops() {
for change in diff.iter_inline_changes(op) {
let (sign, style) = match change.tag() {
ChangeTag::Delete => ("-", Style::new().red()),
ChangeTag::Insert => ("+", Style::new().green()),
ChangeTag::Equal => (" ", Style::new()),
};
print!("{}", style.apply_to(sign).bold(),);
for &(emphasized, value) in change.values() {
if emphasized {
print!("{}", style.apply_to(value).underlined());
} else {
print!("{}", style.apply_to(value));
}
}
if change.is_missing_newline() {
println!();
}
}
}
}

View file

@ -14,11 +14,7 @@ fn main() {
ChangeTag::Insert => ("+", Style::new().green()),
ChangeTag::Equal => (" ", Style::new()),
};
print!(
"{}{}",
style.apply_to(sign).bold(),
style.apply_to(change.value())
);
print!("{}{}", style.apply_to(sign).bold(), style.apply_to(change),);
}
}
}