terminal
import std::io::terminal; · source
Colours and text attributes written as ANSI escape sequences, and whether a standard stream should get them. A Style names a foreground and background Color and the attributes bold, dim, italic, and underline; paint wraps a Display value so that printing it writes the style, the value, and a reset.
A style with nothing set writes the value alone, so a program picks its styles once, from Terminal::supports_color, and prints the same way either way:
import std::fmt;
import std::io::terminal::{ Color, StandardStream, Style, Styled, Terminal };
mut error: Style = Style::new();
if (Terminal::supports_color(StandardStream::Error)) {
error = Style::new().foreground(Color::Red).bold();
}
const label: Styled<Str> = error.paint(Str::new("error"));
fmt::eprintln(f"{label}: file not found");
Types
Style
type struct Style with [Eq, Clone, Debug] {
private foreground_color: Option<Color>;
private background_color: Option<Color>;
private is_bold: boolean;
private is_dim: boolean;
private is_italic: boolean;
private is_underlined: boolean;
}
Built up from Style::new(), which sets nothing; each builder method takes the style by value and returns it with one more thing set. is_plain() is true while nothing is set. write_start and write_end write the escape sequences that turn the style on and reset it, for a Display implementation that styles part of its own output; both write nothing for a plain style. The start sequence resets first, so the text gets exactly this style whatever was on before it.
Constructors
static new() -> Style;
static new() -> Style;A style that sets nothing: painting with it writes the value alone.
Methods
foreground(mut this, color: Color) -> Style;
foreground(mut this, color: Color) -> Style;This style with the text in color.
background(mut this, color: Color) -> Style;
background(mut this, color: Color) -> Style;This style with the cells behind the text in color.
bold(mut this) -> Style;
bold(mut this) -> Style;This style in bold.
dim(mut this) -> Style;
dim(mut this) -> Style;This style dimmed, as the terminal renders faint text.
italic(mut this) -> Style;
italic(mut this) -> Style;This style in italics, where the terminal has them.
underline(mut this) -> Style;
underline(mut this) -> Style;This style underlined.
is_plain(&this) -> boolean;
is_plain(&this) -> boolean;True when the style sets nothing, so it writes no escape sequences.
paint<D>(&this, value: D) -> Styled<D> where D: Display;
paint<D>(&this, value: D) -> Styled<D> where D: Display;value, to be printed in this style: its Display writes the escape sequence that turns the style on, the value, and the one that resets every style.
write_start(&this, f: mut &Formatter) -> Result<(), FormatError>;
write_start(&this, f: mut &Formatter) -> Result<(), FormatError>;Write the escape sequence that turns this style on; nothing for a plain style. The sequence resets first (ESC[0;...m), so the text gets exactly this style whatever was on before it.
write_end(&this, f: mut &Formatter) -> Result<(), FormatError>;
write_end(&this, f: mut &Formatter) -> Result<(), FormatError>;Write the escape sequence that resets every style; nothing for a plain style, which turned none on.
Styled<D>
type struct Styled<D> where D: Display {
style: Style;
value: D;
}
A value with the style it is printed in, made by Style.paint. Its Display writes the start sequence, the value, and the reset.
Color
type enum Color with [Eq, Clone, Debug] {
Black;
Red;
Green;
Yellow;
Blue;
Magenta;
Cyan;
White;
BrightBlack;
BrightRed;
BrightGreen;
BrightYellow;
BrightBlue;
BrightMagenta;
BrightCyan;
BrightWhite;
}
The sixteen colours every ANSI terminal has: eight, and a bright form of each. The terminal's theme decides the exact shade. foreground_code() and background_code() are the SGR parameters that select the colour.
Variants
| Variant |
|---|
Black |
Red |
Green |
Yellow |
Blue |
Magenta |
Cyan |
White |
BrightBlack |
BrightRed |
BrightGreen |
BrightYellow |
BrightBlue |
BrightMagenta |
BrightCyan |
BrightWhite |
Methods
foreground_code(&this) -> u8;
foreground_code(&this) -> u8;The SGR parameter that sets this colour as the foreground; the background's is 10 more.
background_code(&this) -> u8;
background_code(&this) -> u8;The SGR parameter that sets this colour as the background.
StandardStream
type enum StandardStream with [Eq, Clone, Debug] {
Output;
Error;
}
The two standard streams text is styled for.
Terminal
type struct Terminal {}
supports_color(stream) answers whether text written to stream should be styled: the stream is a terminal, NO_COLOR is unset or empty, and TERM is not dumb. On Windows it also turns on the console's escape-sequence processing, and answers false where the console refuses it.
Static functions
static supports_color(stream: StandardStream) -> boolean;
static supports_color(stream: StandardStream) -> boolean;Whether text written to stream should be styled: the stream is a terminal, NO_COLOR is unset or empty, and TERM is not dumb. On Windows this also turns on the console's escape-sequence processing, and answers false where the console refuses it.
Trait implementations
implement<D> trait Display for struct Styled<D> where D: Display
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
namespace std::io::terminal;Terminal styling: colours and text attributes written as ANSI escape sequences, and whether a standard stream should get them.
module pagetype enum Color with [Eq, Clone, Debug] {
Black;
Red;
Green;
Yellow;
Blue;
Magenta;
Cyan;
White;
BrightBlack;
BrightRed;
BrightGreen;
BrightYellow;
BrightBlue;
BrightMagenta;
BrightCyan;
BrightWhite;
}The sixteen colours every ANSI terminal has: eight, and a bright form of each. The terminal's theme decides the exact shade.
std::io::terminaltype enum StandardStream with [Eq, Clone, Debug] {
Output;
Error;
}The two standard streams text is styled for.
std::io::terminaltype struct Style with [Eq, Clone, Debug] {}A foreground and background colour and a set of attributes, built up from Style::new(), which sets nothing.
type struct Styled<D> where D: Display {
style: Style;
value: D;
}A value with the style it is printed in; made by Style.paint.
mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut error: Stylestatic Style::new() -> StyleA style that sets nothing: painting with it writes the value alone.
std::io::terminalif (condition) { ... } else if (condition) { ... } else { ... }Branches on a parenthesised boolean condition. Bodies are always braced; there is no single-statement form. Used as an expression, both arms are required and must produce the same type: const sign = if (n < 0) { -1 } else { 1 };.
static Terminal::supports_color(stream: StandardStream) -> booleanWhether text written to stream should be styled: the stream is a terminal, NO_COLOR is unset or empty, and TERM is not dumb. On Windows this also turns on the console's escape-sequence processing, and answers false where the console refuses it.
StandardStream::Errormut error: StyleStyle::foreground(mut this, color: Color) -> StyleThis style with the text in color.
Color::Redconst NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const label: Styled<Str>type struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
Style::paint<D>(&this, value: D) -> Styled<D>
where D: Displayvalue, to be printed in this style: its Display writes the escape sequence that turns the style on, the value, and the one that resets every style.
static Str::new(text: string) -> StrConstruct from a NUL-terminated C-style string literal. The caller certifies that text is valid UTF-8 and outlives this view. The NUL terminator is not included in the view.
const label: Styled<Str>type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct Style with [Eq, Clone, Debug] {}A foreground and background colour and a set of attributes, built up from Style::new(), which sets nothing.
type struct Point with [Eq, Clone, Debug] { .. }Asks the compiler to generate implementations of the listed traits for the type, each working through its fields or variants in declaration order. The derivable traits are Eq, Ord, Hash, Clone, Debug, Default, ToValue and FromValue, and the text formats' FromJson, ToJson, FromYaml, ToYaml, FromToml and ToToml. The clause comes after the name and its parameters, before where.
type trait Eq<Rhs = This> {
equals(&this, other: &Rhs) -> boolean;
}Types that support value equality with a value of Rhs, which is the type itself unless an implementation names another: implement trait Eq for Str compares two Strs, and implement trait Eq<string> for Str a Str with a string.
type trait Clone {
clone(&this) -> This;
}A type whose values can be duplicated into independent copies. A type takes it with with [Clone] on its declaration, or by implementing clone by hand.
type trait Debug {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
}How a value reads to a programmer: what {x:?} writes, and {x:#?} over several lines. with [Debug] on a declaration writes it field by field.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
Style.foreground_color: Option<Color>type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
Style.background_color: Option<Color>Style.is_bold: booleanStyle.is_dim: booleanStyle.is_italic: booleanStyle.is_underlined: booleantype struct Styled<D> where D: Display {
style: Style;
value: D;
}A value with the style it is printed in; made by Style.paint.
type parameter Dwhere D: Display
where T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
type trait Display {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
to_string(&this) -> String;
}How a value reads to a person: what {x} in an f-string and println write. Implement it for a type a user sees.
Styled.style: StyleStyled.value: Dtype enum Name {
Unit,
Payload(T),
Named { x: i32 },
}An algebraic data type. Variants may be bare or carry a tuple or struct payload, and a match on an enum must cover every variant. Name::Variant names a variant; methods are added with implement enum Name { ... }.
type enum Color with [Eq, Clone, Debug] {
Black;
Red;
Green;
Yellow;
Blue;
Magenta;
Cyan;
White;
BrightBlack;
BrightRed;
BrightGreen;
BrightYellow;
BrightBlue;
BrightMagenta;
BrightCyan;
BrightWhite;
}The sixteen colours every ANSI terminal has: eight, and a bright form of each. The terminal's theme decides the exact shade.
Color::BlackColor::RedColor::GreenColor::YellowColor::BlueColor::MagentaColor::CyanColor::WhiteColor::BrightBlackColor::BrightRedColor::BrightGreenColor::BrightYellowColor::BrightBlueColor::BrightMagentaColor::BrightCyanColor::BrightWhitetype enum StandardStream with [Eq, Clone, Debug] {
Output;
Error;
}The two standard streams text is styled for.
StandardStream::OutputStandardStream::Errortype struct Terminal {}What the standard streams are attached to.
Style::is_plain(&this) -> booleanTrue when the style sets nothing, so it writes no escape sequences.
std::io::terminalStyle::write_start(&this, f: mut &Formatter) -> Result<(), FormatError>Write the escape sequence that turns this style on; nothing for a plain style. The sequence resets first (ESC[0;...m), so the text gets exactly this style whatever was on before it.
Style::write_end(&this, f: mut &Formatter) -> Result<(), FormatError>Write the escape sequence that resets every style; nothing for a plain style, which turned none on.
std::io::terminalstatic name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
mut thisA by-value receiver the body may also reassign. The receiver is moved into the method and consumed; the caller's value may not be used afterwards.
language reference&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
(parameter) color: ColorStyle::background(mut this, color: Color) -> StyleThis style with the cells behind the text in color.
Style::dim(mut this) -> StyleThis style dimmed, as the terminal renders faint text.
std::io::terminalStyle::italic(mut this) -> StyleThis style in italics, where the terminal has them.
std::io::terminal(parameter) value: DStyled.value: D(parameter) f: mut &Formattermut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
type struct Formatter {}Where a Display or Debug implementation writes its text: a sink (standard output, a String, a file) with the format's options. write_str writes text; debug_struct and debug_tuple lay out a value's members.
type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
primitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
type enum FormatError {
Io(IoError);
Allocation(AllocationError);
}Why formatting a value failed: the sink refused the bytes, or a sink that grows (a String) could not.
function name(count: i32, args...)A variadic parameter: the trailing bucket receives any number of further arguments with C's calling convention, so the function stays ABI-compatible with the printf family. Wrap the bucket in VariadicArguments to read typed values from it.
Color::foreground_code(&this) -> u8The SGR parameter that sets this colour as the foreground; the background's is 10 more.
std::io::terminalColor::background_code(&this) -> u8The SGR parameter that sets this colour as the background.
std::io::terminalColor::BlackColor::GreenColor::YellowColor::BlueColor::MagentaColor::CyanColor::WhiteColor::BrightBlackColor::BrightRedColor::BrightGreenColor::BrightYellowColor::BrightBlueColor::BrightMagentaColor::BrightCyanColor::BrightWhite(parameter) stream: StandardStreamimplement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
type trait Name : Base {
method(&this, other: &This) -> Ret;
}Names a set of methods a type may implement. Inside the body This is the implementing type; methods may carry default bodies, and a trait may require a base trait (type trait Ord : Eq). Generic code asks for a trait with where T: Name.
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language reference