Don't write reset control code for Plain diffs
This fixes a bug in exa where invisible reset control codes were sent even if its output was not to a terminal! It took me an embarrassingly long time to figure out, because the codes were, well, invisible, and didn't show up in the output...
diff --git a/Cargo.toml b/Cargo.toml
index 1caaf86..1a39d8d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -7,7 +7,7 @@
homepage = "https://github.com/ogham/rust-ansi-term"
license = "MIT"
readme = "README.md"
-version = "0.6.1"
+version = "0.6.2"
[lib]
name = "ansi_term"
diff --git a/src/lib.rs b/src/lib.rs
index ef074ce..15e5f22 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -177,7 +177,7 @@
}
/// Return a Style with the foreground colour set to this colour.
- pub fn normal(self) -> Style {
+ pub fn normal(self) -> Style {
Style { foreground: Some(self), .. Style::default() }
}
@@ -348,7 +348,7 @@
}
fn write_suffix(&self, f: &mut fmt::Formatter) -> fmt::Result {
- if self == &Style::default() {
+ if self == &Style::default() {
write!(f, "")
} else {
write!(f, "\x1B[0m")
@@ -450,6 +450,12 @@
ExtraStyles(extra_styles)
}
+
+ /// Return true if this `Style` has no actual styles, and can be written
+ /// without any control characters.
+ fn is_plain(self) -> bool {
+ self == Style::default()
+ }
}
impl Default for Style {
@@ -512,7 +518,14 @@
try!(write!(f, "{}", window[1].string));
}
- try!(f.write_str("\x1B[0m"));
+ // Write the final reset string after all of the ANSIStrings have been
+ // written, *except* if the last one has no styles, because it would
+ // have already been written by this point.
+ if let Some(last) = self.0.last() {
+ if !last.style.is_plain() {
+ try!(f.write_str("\x1B[0m"));
+ }
+ }
Ok(())
}
@@ -522,6 +535,7 @@
mod tests {
pub use super::Style;
pub use super::Colour::*;
+ pub use super::ANSIStrings;
macro_rules! test {
($name: ident: $style: expr; $input: expr => $result: expr) => {
@@ -656,5 +670,13 @@
assert_eq!(extra_styles, normal.difference(&hidden));
}
+
+ #[test]
+ fn no_control_codes_for_plain() {
+ let one = Style::default().paint("one");
+ let two = Style::default().paint("two");
+ let output = format!("{}", ANSIStrings( &[ one, two ] ));
+ assert_eq!(&*output, "onetwo");
+ }
}
}