Expand description
This crate provides a cross platform abstraction for writing colored text toa terminal. Colors are written using either ANSI escape sequences or bycommunicating with a Windows console. Much of this API was motivated by useinside command line applications, where colors or styles can be configuredby the end user and/or the environment.
This crate also provides platform independent support for writing colored textto 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 theWindows console API, which requires synchronous communication.
In ANSI mode, this crate also provides support for writing hyperlinks.
§Organization
TheWriteColor
trait extends theio::Write
trait with methods for settingcolors or resetting them.
StandardStream
andStandardStreamLock
both satisfyWriteColor
and areanalogous tostd::io::Stdout
andstd::io::StdoutLock
, orstd::io::Stderr
andstd::io::StderrLock
.
Buffer
is an in memory buffer that supports colored text. In a parallelprogram, each thread might write to its own buffer. A buffer can be printed tousing aBufferWriter
. The advantage of this design is that each thread canwork in parallel on a buffer without having to synchronize access to globalresources such as the Windows console. Moreover, this design also preventsinterleaving of buffer output.
Ansi
andNoColor
both satisfyWriteColor
for arbitrary implementors ofio::Write
. These types are useful when you know exactly what you need. Ananalogous type for the Windows console is not provided since it cannot exist.
§Example: usingStandardStream
TheStandardStream
type in this crate works similarly tostd::io::Stdout
,except it is augmented with methods for coloring by theWriteColor
trait.For example, to write some green text:
usestd::io::Write;usetermcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};letmutstdout = StandardStream::stdout(ColorChoice::Always);stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;writeln!(&mutstdout,"green text!")?;
Note that any text written to the terminal now will be coloredgreen when using ANSI escape sequences, even if it is written viastderr, and even if stderr had previously been set toColor::Red
.Users will need to manage any color changes themselves by callingWriteColor::set_color
, and thismay include callingWriteColor::reset
before the program exits to a shell.
§Example: usingBufferWriter
ABufferWriter
can create buffers and write buffers to stdout or stderr. Itdoesnot implementio::Write
orWriteColor
itself. Instead,Buffer
implementsio::Write
andio::WriteColor
.
This example shows how to print some green text to stderr.
usestd::io::Write;usetermcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};letmutbufwtr = BufferWriter::stderr(ColorChoice::Always);letmutbuffer = bufwtr.buffer();buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;writeln!(&mutbuffer,"green text!")?;bufwtr.print(&buffer)?;
§Detecting presence of a terminal
In many scenarios when using color, one often wants to enable colorsautomatically when writing to a terminal and disable colors automatically whenwriting to anything else. The typical way to achieve this in Unix environmentsis via libc’sisatty
function.Unfortunately, this notoriously does not work well in Windows environments. Towork around that, the recommended solution is to use the standard library’sIsTerminal
trait.It goes out of its way to get it 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:
usestd::io::IsTerminal;usetermcolor::{ColorChoice, StandardStream};letpreference = argv.get_flag("color").unwrap_or("auto");letmutchoice = preference.parse::<ColorChoice>()?;ifchoice == ColorChoice::Auto && !std::io::stdin().is_terminal() { choice = ColorChoice::Never;}letstdout = StandardStream::stdout(choice);// ... write to stdout
Currently,termcolor
does not provide anything to do this for you.
Structs§
- Ansi
- Satisfies
WriteColor
using standard ANSI escape sequences. - Buffer
- Write colored text to memory.
- Buffer
Writer - Writes colored buffers to stdout or stderr.
- Buffered
Standard Stream - Like
StandardStream
, but does buffered writing. - Color
Choice Parse Error - An error that occurs when parsing a
ColorChoice
fails. - Color
Spec - A color specification.
- Hyperlink
Spec - A hyperlink specification.
- NoColor
- Satisfies
WriteColor
but ignores all color options. - Parse
Color Error - An error from parsing an invalid color specification.
- Standard
Stream - Satisfies
io::Write
andWriteColor
, and supports optional coloringto either of the standard output streams, stdout and stderr. - Standard
Stream Lock StandardStreamLock
is a locked reference to aStandardStream
.
Enums§
- Color
- The set of available colors for the terminal foreground/background.
- Color
Choice - ColorChoice represents the color preferences of an end user.
Traits§
- Write
Color - This trait describes the behavior of writers that support colored output.