Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewrite to support generic Display types inside of ANSIString #79

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ documentation = "https://docs.rs/ansi_term"
homepage = "https://github.com/ogham/rust-ansi-term"
license = "MIT"
readme = "README.md"
version = "0.12.1"
version = "0.13.0"
repository = "https://github.com/ogham/rust-ansi-term"

[lib]
Expand Down
152 changes: 90 additions & 62 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,47 +17,69 @@ ansi_term = "0.12"

## Basic usage

There are three main types in this crate that you need to be concerned with: `ANSIString`, `Style`, and `Colour`.
There are three main types in this crate that you need to be
concerned with: `ANSIString`, `Style`, and `Colour`.

A `Style` holds stylistic information: foreground and background colours, whether the text should be bold, or blinking, or other properties.
The `Colour` enum represents the available colours.
And an `ANSIString` is a string paired with a `Style`.
A `Style` holds stylistic information: foreground and background colours,
whether the text should be bold, or blinking, or other properties. The
`Colour` enum represents the available colours. And an `ANSIString` is
a string paired with a `Style`.

`Color` is also available as an alias to `Colour`.

To format a string, call the `paint` method on a `Style` or a `Colour`, passing in the string you want to format as the argument.
For example, here’s how to get some red text:
To format a string, call the `Style::paint` or `Colour::paint` method,
passing in the string you want to format as the argument. For example,
here’s how to get some red text:

```rust
use ansi_term::Colour::Red;

println!("This is in red: {}", Red.paint("a red string"));
```

It’s important to note that the `paint` method does *not* actually return a string with the ANSI control characters surrounding it.
Instead, it returns an `ANSIString` value that has a `Display` implementation that, when formatted, returns the characters.
This allows strings to be printed with a minimum of `String` allocations being performed behind the scenes.
Note that the `paint` method doesn’t return a string with the ANSI control
sequence surrounding it. Instead, it returns an `ANSIString` value which
has a `Display` implementation that outputs the sequence. This allows
strings to be printed without additional `String` allocations.

If you *do* want to get at the escape codes, then you can convert the `ANSIString` to a string as you would any other `Display` value:
In fact, `ANSIString` is a generic type which doesn’t require the element
to be a `String` at all. Any type which implements `Display` can be
painted. Other related traits (such as `LowerHex`) are supported as well.
For example:

```rust
use ansi_term::Colour::Red;
use ansi_term::Colour::{Red, Green, Blue};

let red_string = Red.paint("a red string").to_string();
let red = Red.paint(255);
let green = Green.paint(248);
let blue = Blue.paint(231);

let latte = format!("rgb({red}, {green}, {blue})");
assert_eq!("rgb(\u{1b}[31m255\u{1b}[0m, \
\u{1b}[32m248\u{1b}[0m, \
\u{1b}[34m231\u{1b}[0m)", latte);

let latte = format!("#{red:02x}{green:02x}{blue:02x}");
assert_eq!("#\u{1b}[31mff\u{1b}[0m\
\u{1b}[32mf8\u{1b}[0m\
\u{1b}[34me7\u{1b}[0m", latte);
```

**Note for Windows 10 users:** On Windows 10, the application must enable ANSI support first:
If you want to get at the escape codes, you can convert an `ANSIString` to
a string with `to_string` method as you would any other `Display` value:

```rust,ignore
let enabled = ansi_term::enable_ansi_support();
```rustrust
use ansi_term::Colour::Red;

let red_string = Red.paint("a red string").to_string();
```

## Bold, underline, background, and other styles

For anything more complex than plain foreground colour changes, you need to construct `Style` values themselves, rather than beginning with a `Colour`.
You can do this by chaining methods based on a new `Style`, created with `Style::new()`.
Each method creates a new style that has that specific property set.
For example:
For anything more complex than plain foreground colour changes, you need to
construct `Style` values. You can do this by chaining methods based on
a object created with `Style::new`. Each method creates a new style that
has that specific property set. For example:

```rust
use ansi_term::Style;
Expand All @@ -67,7 +89,9 @@ println!("How about some {} and {}?",
Style::new().underline().paint("underline"));
```

For brevity, these methods have also been implemented for `Colour` values, so you can give your styles a foreground colour without having to begin with an empty `Style` value:
For brevity, these methods have also been implemented for `Colour` values,
so you can give your styles a foreground colour without having to begin with
an empty `Style` value:

```rust
use ansi_term::Colour::{Blue, Yellow};
Expand All @@ -79,10 +103,12 @@ println!("Demonstrating {} and {}!",
println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!"));
```

The complete list of styles you can use are:
`bold`, `dimmed`, `italic`, `underline`, `blink`, `reverse`, `hidden`, and `on` for background colours.
The complete list of styles you can use are: `bold`, `dimmed`, `italic`,
`underline`, `blink`, `reverse`, `hidden`, `strikethrough`, and `on` for
background colours.

In some cases, you may find it easier to change the foreground on an existing `Style` rather than starting from the appropriate `Colour`.
In some cases, you may find it easier to change the foreground on an
existing `Style` rather than starting from the appropriate `Colour`.
You can do this using the `fg` method:

```rust
Expand All @@ -93,8 +119,10 @@ println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!"));
println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!"));
```

You can turn a `Colour` into a `Style` with the `normal` method.
This will produce the exact same `ANSIString` as if you just used the `paint` method on the `Colour` directly, but it’s useful in certain cases: for example, you may have a method that returns `Styles`, and need to represent both the “red bold” and “red, but not bold” styles with values of the same type. The `Style` struct also has a `Default` implementation if you want to have a style with *nothing* set.
You can turn a `Colour` into a `Style` with the `normal` method. This
produces the exact same `ANSIString` as if you just used the
`Colour::paint` method directly, but it’s useful if you need to represent
both the “red bold” and “red, but not bold” with values of the same type.

```rust
use ansi_term::Style;
Expand All @@ -104,11 +132,11 @@ Red.normal().paint("yet another red string");
Style::default().paint("a completely regular string");
```


## Extended colours

You can access the extended range of 256 colours by using the `Colour::Fixed` variant, which takes an argument of the colour number to use.
This can be included wherever you would use a `Colour`:
You can access the 256-colour palette by using the `Colour::Fixed`
variant. It takes an argument of the colour number to use. This can be
included wherever you would use a `Colour`:

```rust
use ansi_term::Colour::Fixed;
Expand All @@ -117,10 +145,8 @@ Fixed(134).paint("A sort of light purple");
Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup");
```

The first sixteen of these values are the same as the normal and bold standard colour variants.
There’s nothing stopping you from using these as `Fixed` colours instead, but there’s nothing to be gained by doing so either.

You can also access full 24-bit colour by using the `Colour::RGB` variant, which takes separate `u8` arguments for red, green, and blue:
You can also access full 24-bit colour by using the `Colour::RGB` variant,
which takes separate red, green, and blue arguments:

```rust
use ansi_term::Colour::RGB;
Expand All @@ -130,54 +156,56 @@ RGB(70, 130, 180).paint("Steel blue");

## Combining successive coloured strings

The benefit of writing ANSI escape codes to the terminal is that they *stack*: you do not need to end every coloured string with a reset code if the text that follows it is of a similar style.
For example, if you want to have some blue text followed by some blue bold text, it’s possible to send the ANSI code for blue, followed by the ANSI code for bold, and finishing with a reset code without having to have an extra one between the two strings.
The benefit of writing ANSI escape codes to the terminal is that they
*stack*: you do not need to end every coloured string with a reset code if
the text that follows it is of a similar style. For example, if you want to
have some blue text followed by some blue bold text, it’s possible to send
the ANSI code for blue, followed by the ANSI code for bold, and finishing
with a reset code without having to have an extra one between the two
strings.

This crate can optimise the ANSI codes that get printed in situations like this, making life easier for your terminal renderer.
The `ANSIStrings` struct takes a slice of several `ANSIString` values, and will iterate over each of them, printing only the codes for the styles that need to be updated as part of its formatting routine.
This crate can optimise the ANSI codes that get printed in situations like
this, making life easier for your terminal renderer. The `ANSIStrings`
type takes a slice of several `ANSIString` values, and will iterate over
each of them, printing only the codes for the styles that need to be updated
as part of its formatting routine.

The following code snippet uses this to enclose a binary number displayed in red bold text inside some red, but not bold, brackets:
The following code snippet uses this to enclose a binary number displayed in
red bold text inside some red, but not bold, brackets:

```rust
use ansi_term::Colour::Red;
use ansi_term::{ANSIString, ANSIStrings};

let some_value = format!("{:b}", 42);
let strings: &[ANSIString<'static>] = &[
Red.paint("["),
Red.bold().paint(some_value),
Red.paint("]"),
let strings: &[ANSIString<_>] = &[
Red.paint_cow("["),
Red.bold().paint_cow(some_value),
Red.paint_cow("]"),
];

println!("Value: {}", ANSIStrings(strings));
```

There are several things to note here.
Firstly, the `paint` method can take *either* an owned `String` or a borrowed `&str`.
Internally, an `ANSIString` holds a copy-on-write (`Cow`) string value to deal with both owned and borrowed strings at the same time.
This is used here to display a `String`, the result of the `format!` call, using the same mechanism as some statically-available `&str` slices.
Secondly, that the `ANSIStrings` value works in the same way as its singular counterpart, with a `Display` implementation that only performs the formatting when required.
In this example, the `paint_cow` method can take *either* an owned `String`
or a borrowed `&str` value. It converts the argument into a copy-on-write
string (`Cow`) and wraps that inside of an `ANSIString`.

## Byte strings
The `ANSIStrings` value works in the same way as its singular counterpart,
with a `Display` implementation that only performs the formatting when
required.

This library also supports formatting `[u8]` byte strings; this supports applications working with text in an unknown encoding.
`Style` and `Colour` support painting `[u8]` values, resulting in an `ANSIByteString`.
This type does not implement `Display`, as it may not contain UTF-8, but it does provide a method `write_to` to write the result to any value that implements `Write`:

```rust
use ansi_term::Colour::Green;

Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap();
```
## Byte strings

Similarly, the type `ANSIByteStrings` supports writing a list of `ANSIByteString` values with minimal escape sequences:
This library also handles formatting `[u8]` byte strings. This supports
applications working with text in an unknown encoding. More specifically,
any type which implements `AsRef<[u8]>` can be painted. For such types
`ANSIString::write_to` method is provided to write the value to any object
that implements `Write`:

```rust
use ansi_term::Colour::Green;
use ansi_term::ANSIByteStrings;

ANSIByteStrings(&[
Green.paint("user data 1\n".as_bytes()),
Green.bold().paint("user data 2\n".as_bytes()),
]).write_to(&mut std::io::stdout()).unwrap();
Green.paint("user data".as_bytes())
.write_to(&mut std::io::stdout()).unwrap();
```
Loading