[][src]Macro termcolor_output::colored

macro_rules! colored {
    ($($arg:tt)*) => { ... };
}

The macro writing colored text.

Like the standard write! macro, it takes the writer, format string and the sequence of arguments. The arguments may be either formattable with the corresponding formatter (Display for {}, Debug for {:?}, etc.), or the control sequences, which are written in macro-like style:

  • reset!() yields call to ColorSpec::clear;
  • fg!(color), bg!(color), bold!(bool), underline!(bool) and intense!(bool) are translated into corresponding ColorSpec::set_* calls with the provided arguments.

Internally, this expands to the following:

  • imports of all necessary traits;
  • call to the guard method on the WriteColorGuard trait (as a sanity check);
  • an immediately called closure, containing:
    • creation of ColorSpec;
    • calls to write! for every formattable input;
    • updates for ColorSpec for every control sequence. Every error generated inside the closure is returned early and yielded by the macro as an std::io::Result<()>.

When the arguments list is malformed, macro generates a compile error trying to point on the exact origin.

Examples

Simple formatting is provided in exactly the same way as for standard writes:

colored!(writer, "This text is {} styled", "not").unwrap();

Styled formatting is provided by using any formatter argument in format string, wherever you need to apply the style:

colored!(writer, "This text is not styled\n{}And this is colored", fg!(Some(Color::Blue))).unwrap();

You can chain several styling commands by specifying several formatter arguments without text between them:

colored!(
    writer,
    "{}{}{}This text is bold blue on yellow background
     {}{}{}And this has default colors, but is bold and underlined",
    fg!(Some(Color::Blue)), bg!(Some(Color::Yellow)), bold!(true),
    fg!(None), bg!(None), underline!(true),
).unwrap();

Note that the bold being set in the first block of control sequences is preserved after the second one.

And, of course, you can mix ordinary formatting outputs with the control sequences:

colored!(writer, "{}{:?}{} unwraps to {}", bold!(true), Some(0), bold!(false), 0).unwrap();