Expand description

This crate provides a cross platform abstraction for writing colored text to a terminal. Colors are written using either ANSI escape sequences or by communicating with a Windows console. Much of this API was motivated by use inside command line applications, where colors or styles can be configured by the end user and/or the environment.

This crate also provides platform independent support for writing colored text to an in memory buffer. While this is easy to do with ANSI escape sequences (because they are in the buffer themselves), it is trickier to do with the Windows console API, which requires synchronous communication.

Organization

The WriteColor trait extends the io::Write trait with methods for setting colors or resetting them.

StandardStream and StandardStreamLock both satisfy WriteColor and are analogous to std::io::Stdout and std::io::StdoutLock, or std::io::Stderr and std::io::StderrLock.

Buffer is an in memory buffer that supports colored text. In a parallel program, each thread might write to its own buffer. A buffer can be printed to using a BufferWriter. The advantage of this design is that each thread can work in parallel on a buffer without having to synchronize access to global resources such as the Windows console. Moreover, this design also prevents interleaving of buffer output.

Ansi and NoColor both satisfy WriteColor for arbitrary implementors of io::Write. These types are useful when you know exactly what you need. An analogous type for the Windows console is not provided since it cannot exist.

Example: using StandardStream

The StandardStream type in this crate works similarly to std::io::Stdout, except it is augmented with methods for coloring by the WriteColor trait. For example, to write some green text:

use std::io::Write;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};

let mut stdout = StandardStream::stdout(ColorChoice::Always);
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
writeln!(&mut stdout, "green text!")?;

Note that any text written to the terminal now will be colored green when using ANSI escape sequences, even if it is written via stderr, and even if stderr had previously been set to Color::Red. Users will need to manage any color changes themselves by calling WriteColor::set_color, and this may include calling WriteColor::reset before the program exits to a shell.

Example: using BufferWriter

A BufferWriter can create buffers and write buffers to stdout or stderr. It does not implement io::Write or WriteColor itself. Instead, Buffer implements io::Write and io::WriteColor.

This example shows how to print some green text to stderr.

use std::io::Write;
use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};

let mut bufwtr = BufferWriter::stderr(ColorChoice::Always);
let mut buffer = bufwtr.buffer();
buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
writeln!(&mut buffer, "green text!")?;
bufwtr.print(&buffer)?;

Detecting presence of a terminal

In many scenarios when using color, one often wants to enable colors automatically when writing to a terminal and disable colors automatically when writing to anything else. The typical way to achieve this in Unix environments is via libc’s isatty function. Unfortunately, this notoriously does not work well in Windows environments. To work around that, the currently recommended solution is to use the atty crate, which goes out of its way to get this as right as possible in Windows environments.

For example, in a command line application that exposes a --color flag, your logic for how to enable colors might look like this:

use atty;
use termcolor::{ColorChoice, StandardStream};

let preference = argv.get_flag("color").unwrap_or("auto");
let choice = match preference {
    "always" => ColorChoice::Always,
    "ansi" => ColorChoice::AlwaysAnsi,
    "auto" => {
        if atty::is(atty::Stream::Stdout) {
            ColorChoice::Auto
        } else {
            ColorChoice::Never
        }
    }
    _ => ColorChoice::Never,
};
let stdout = StandardStream::stdout(choice);
// ... write to stdout

Currently, termcolor does not provide anything to do this for you.

Structs

Satisfies WriteColor using standard ANSI escape sequences.

Write colored text to memory.

Writes colored buffers to stdout or stderr.

Like StandardStream, but does buffered writing.

A color specification.

Satisfies WriteColor but ignores all color options.

An error from parsing an invalid color specification.

Satisfies io::Write and WriteColor, and supports optional coloring to either of the standard output streams, stdout and stderr.

StandardStreamLock is a locked reference to a StandardStream.

Enums

The set of available colors for the terminal foreground/background.

ColorChoice represents the color preferences of an end user.

Traits

This trait describes the behavior of writers that support colored output.