#![crate_name = "ansi_term"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
use Colour::*;
use Style::*;
use Difference::*;
use std::fmt;
#[derive(Copy)]
pub struct ANSIString<'a> {
string: &'a str,
style: Style,
}
impl<'a> ANSIString<'a> {
pub fn new(contents: &'a str, style: Style) -> ANSIString<'a> {
ANSIString { string: contents, style: style }
}
}
impl<'a> fmt::Display for ANSIString<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(self.style.write_prefix(f));
try!(write!(f, "{}", self.string));
self.style.write_suffix(f)
}
}
#[derive(PartialEq, Copy, Debug)]
pub enum Colour {
Black, Red, Green, Yellow, Blue, Purple, Cyan, White, Fixed(u8),
}
impl Colour {
fn write_foreground_code(self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Black => f.write_str("30"),
Red => f.write_str("31"),
Green => f.write_str("32"),
Yellow => f.write_str("33"),
Blue => f.write_str("34"),
Purple => f.write_str("35"),
Cyan => f.write_str("36"),
White => f.write_str("37"),
Fixed(num) => write!(f, "38;5;{}", num),
}
}
fn write_background_code(self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Black => f.write_str("40"),
Red => f.write_str("41"),
Green => f.write_str("42"),
Yellow => f.write_str("43"),
Blue => f.write_str("44"),
Purple => f.write_str("45"),
Cyan => f.write_str("46"),
White => f.write_str("47"),
Fixed(num) => write!(f, "48;5;{}", num),
}
}
pub fn normal(self) -> Style {
Styled { foreground: Some(self), background: None, bold: false, underline: false }
}
pub fn paint(self, input: &str) -> ANSIString {
ANSIString::new(input, Foreground(self))
}
pub fn underline(self) -> Style {
Styled { foreground: Some(self), background: None, bold: false, underline: true }
}
pub fn bold(self) -> Style {
Styled { foreground: Some(self), background: None, bold: true, underline: false }
}
pub fn on(self, background: Colour) -> Style {
Styled { foreground: Some(self), background: Some(background), bold: false, underline: false }
}
}
#[derive(PartialEq, Copy, Debug)]
pub enum Style {
Plain,
Foreground(Colour),
Styled { foreground: Option<Colour>, background: Option<Colour>, bold: bool, underline: bool },
}
impl Style {
pub fn paint(self, input: &str) -> ANSIString {
ANSIString::new(input, self)
}
pub fn bold(self) -> Style {
match self {
Plain => Styled { foreground: None, background: None, bold: true, underline: false },
Foreground(c) => Styled { foreground: Some(c), background: None, bold: true, underline: false },
Styled { foreground, background, bold: _, underline } => Styled { foreground: foreground, background: background, bold: true, underline: underline },
}
}
pub fn underline(self) -> Style {
match self {
Plain => Styled { foreground: None, background: None, bold: false, underline: true },
Foreground(c) => Styled { foreground: Some(c), background: None, bold: false, underline: true },
Styled { foreground, background, bold, underline: _ } => Styled { foreground: foreground, background: background, bold: bold, underline: true },
}
}
pub fn on(self, background: Colour) -> Style {
match self {
Plain => Styled { foreground: None, background: Some(background), bold: false, underline: false },
Foreground(c) => Styled { foreground: Some(c), background: Some(background), bold: false, underline: false },
Styled { foreground, background: _, bold, underline } => Styled { foreground: foreground, background: Some(background), bold: bold, underline: underline },
}
}
fn write_prefix(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Plain => Ok(()),
Foreground(colour) => {
try!(f.write_str("\x1B["));
try!(colour.write_foreground_code(f));
write!(f, "m")
},
Styled { foreground, background, bold, underline } => {
let mut semicolon = false;
try!(f.write_str("\x1B["));
if bold {
try!(f.write_str("1"));
semicolon = true;
}
if underline {
if semicolon { try!(f.write_str(";")); }
try!(f.write_str("4"));
semicolon = true;
}
match background {
Some(c) => {
if semicolon { try!(f.write_str(";")); }
try!(c.write_background_code(f));
semicolon = true;
},
None => {},
}
if let Some(fg) = foreground {
if semicolon { try!(f.write_str(";")); }
try!(fg.write_foreground_code(f));
}
write!(f, "m")
},
}
}
fn write_suffix(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Plain => Ok(()),
_ => write!(f, "\x1B[0m"),
}
}
fn difference(&self, next_style: Style) -> Difference {
match (*self, next_style) {
(Plain, Plain) => NoDifference,
(Plain, _) => ExtraStyles(next_style),
(Foreground(_), Plain) => Reset,
(Foreground(c), Foreground(d)) if c == d => NoDifference,
(Foreground(_), Foreground(d)) => ExtraStyles(Foreground(d)),
(Foreground(c), Styled { foreground: d, background, bold, underline }) => {
if d == Some(c) {
ExtraStyles(Styled { foreground: None, background: background, bold: bold, underline: underline })
}
else {
ExtraStyles(next_style)
}
},
(Styled { foreground: _, background: _, bold: _, underline: _ }, Plain) => Reset,
(Styled { foreground, background, bold, underline }, Foreground(c)) => {
if background.is_some() || bold || underline {
Reset
}
else if foreground == Some(c) {
NoDifference
}
else {
ExtraStyles(Foreground(c))
}
},
(Styled { foreground: c, background, bold, underline }, Styled { foreground: d, background: background2, bold: bold2, underline: underline2 }) => {
if (background.is_some() && background2.is_none()) || (bold && !bold2) || (underline && !underline2) {
Reset
}
else {
let mut style = Style::Plain;
if c != d { style = d.unwrap().normal() }
if background != background2 { style = style.on(background2.unwrap()) }
if bold != bold2 { style = style.bold() }
if underline != underline2 { style = style.underline() }
if let Style::Plain = style {
NoDifference
}
else {
ExtraStyles(style)
}
}
},
}
}
}
#[derive(PartialEq, Copy, Debug)]
enum Difference {
ExtraStyles(Style),
Reset,
NoDifference,
}
pub struct ANSIStrings<'a>(pub &'a [ANSIString<'a>]);
impl<'a> fmt::Display for ANSIStrings<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let first = match self.0.first() {
None => return Ok(()),
Some(f) => f,
};
try!(first.style.write_prefix(f));
try!(write!(f, "{}", first.string));
for window in self.0.windows(2) {
match window[0].style.difference(window[1].style) {
ExtraStyles(style) => try!(style.write_prefix(f)),
Reset => {
try!(f.write_str("\x1B[0m"));
try!(window[1].style.write_prefix(f));
},
NoDifference => { },
}
try!(write!(f, "{}", window[1].string));
}
try!(f.write_str("\x1B[0m"));
Ok(())
}
}
#[cfg(test)]
mod tests {
pub use super::Style::*;
pub use super::Colour::*;
pub use super::Difference::*;
macro_rules! test {
($name: ident: $style: expr; $input: expr => $result: expr) => {
#[test]
fn $name() {
assert_eq!($style.paint($input).to_string(), $result.to_string())
}
};
}
test!(plain: Plain; "text/plain" => "text/plain");
test!(red: Red; "hi" => "\x1B[31mhi\x1B[0m");
test!(black: Black.normal(); "hi" => "\x1B[30mhi\x1B[0m");
test!(yellow_bold: Yellow.bold(); "hi" => "\x1B[1;33mhi\x1B[0m");
test!(yellow_bold_2: Yellow.normal().bold(); "hi" => "\x1B[1;33mhi\x1B[0m");
test!(blue_underline: Blue.underline(); "hi" => "\x1B[4;34mhi\x1B[0m");
test!(green_bold_ul: Green.bold().underline(); "hi" => "\x1B[1;4;32mhi\x1B[0m");
test!(green_bold_ul_2: Green.underline().bold(); "hi" => "\x1B[1;4;32mhi\x1B[0m");
test!(purple_on_white: Purple.on(White); "hi" => "\x1B[47;35mhi\x1B[0m");
test!(purple_on_white_2: Purple.normal().on(White); "hi" => "\x1B[47;35mhi\x1B[0m");
test!(cyan_bold_on_white: Cyan.bold().on(White); "hi" => "\x1B[1;47;36mhi\x1B[0m");
test!(cyan_ul_on_white: Cyan.underline().on(White); "hi" => "\x1B[4;47;36mhi\x1B[0m");
test!(cyan_bold_ul_on_white: Cyan.bold().underline().on(White); "hi" => "\x1B[1;4;47;36mhi\x1B[0m");
test!(cyan_ul_bold_on_white: Cyan.underline().bold().on(White); "hi" => "\x1B[1;4;47;36mhi\x1B[0m");
test!(fixed: Fixed(100); "hi" => "\x1B[38;5;100mhi\x1B[0m");
test!(fixed_on_purple: Fixed(100).on(Purple); "hi" => "\x1B[45;38;5;100mhi\x1B[0m");
test!(fixed_on_fixed: Fixed(100).on(Fixed(200)); "hi" => "\x1B[48;5;200;38;5;100mhi\x1B[0m");
test!(bold: Plain.bold(); "hi" => "\x1B[1mhi\x1B[0m");
test!(underline: Plain.underline(); "hi" => "\x1B[4mhi\x1B[0m");
test!(bunderline: Plain.bold().underline(); "hi" => "\x1B[1;4mhi\x1B[0m");
mod difference {
use super::*;
#[test]
fn diff() {
let expected = ExtraStyles(Plain.bold());
let got = Green.normal().difference(Green.bold());
assert_eq!(expected, got)
}
#[test]
fn dlb() {
let got = Green.bold().difference(Green.normal());
assert_eq!(Reset, got)
}
#[test]
fn nothing() {
assert_eq!(NoDifference, Green.bold().difference(Green.bold()));
}
#[test]
fn nothing_2() {
assert_eq!(NoDifference, Green.normal().difference(Green.normal()));
}
#[test]
fn colour_change() {
assert_eq!(ExtraStyles(Blue.normal()), Red.normal().difference(Blue.normal()))
}
}
}