Skip to content

Commit

Permalink
fix displaying non-printable characters
Browse files Browse the repository at this point in the history
  • Loading branch information
pilleye committed Jun 2, 2024
1 parent b36dd1a commit 6c99816
Showing 1 changed file with 53 additions and 5 deletions.
58 changes: 53 additions & 5 deletions crates/ruff_linter/src/source_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,11 +217,49 @@ impl<'a> CodeDiff<'a> {
}
}

trait ShowNonprinting {
fn show_nonprinting(&self) -> String;
}

impl ShowNonprinting for &str {
fn show_nonprinting(&self) -> String {
let mut output = String::with_capacity(self.len());

for byte in self.bytes() {
match byte {
b'\n' | b'\t' => {
output.push(byte as char);
}
0..=31 => {
output.push_str(&format!("^{}", (byte + 64) as char));
}
32..=126 => {
output.push(byte as char);
}
127 => {
output.push_str("^?");
}
128..=159 => {
output.push_str(&format!("M-^{}", (byte - 64) as char));
}
160..=254 => {
output.push_str(&format!("M-{}", (byte - 128) as char));
}
_ => {
output.push_str("M-^?");
}
}
}

output
}
}

impl std::fmt::Display for CodeDiff<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some((original, modified)) = self.header {
writeln!(f, "--- {}", original.red())?;
writeln!(f, "+++ {}", modified.green())?;
writeln!(f, "--- {}", original.show_nonprinting().red())?;
writeln!(f, "+++ {}", modified.show_nonprinting().green())?;
}

let mut unified = self.diff.unified_diff();
Expand All @@ -234,9 +272,19 @@ impl std::fmt::Display for CodeDiff<'_> {
// individual lines
for change in hunk.iter_changes() {
match change.tag() {
ChangeTag::Equal => write!(f, " {}", change.value())?,
ChangeTag::Delete => write!(f, "{}{}", "-".red(), change.value().red())?,
ChangeTag::Insert => write!(f, "{}{}", "+".green(), change.value().green())?,
ChangeTag::Equal => write!(f, " {}", change.value().show_nonprinting())?,
ChangeTag::Delete => write!(
f,
"{}{}",
"-".red(),
change.value().show_nonprinting().red()
)?,
ChangeTag::Insert => write!(
f,
"{}{}",
"+".green(),
change.value().show_nonprinting().green()
)?,
}

if !self.diff.newline_terminated() {
Expand Down

0 comments on commit 6c99816

Please sign in to comment.