Skip to content

Style

A text style: colors and attributes, applied to a string with paint.

Built by chaining: Style::new().bold().fg(Color::Red). Painting wraps the text in the escape sequence for the style and a reset (ESC [ 0 m); a style with nothing set returns the text unchanged. This only builds the strings: whether to emit colors at all (a terminal, NO_COLOR) is for the caller to decide.

use helpers4::ansi::Style;

Cargo feature ansi (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features ansi

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.6", default-features = false, features = ["ansi"] }
pub struct Style { /* private fields */ }
use helpers4::ansi::{strip, Color, Style};

let error = Style::new().bold().fg(Color::Red);
assert_eq!(error.paint("failed"), "\u{1b}[1;31mfailed\u{1b}[0m");
assert_eq!(strip(&error.paint("failed")), "failed");
pub fn new() -> Self

An empty style: painting with it changes nothing.

Returns

Self — A style with no color and no attribute.

pub fn fg(mut self, color: Color) -> Self

Sets the text color.

Parameters

ParameterTypeDescription
selmut self
colorColorThe foreground color.

Returns

Self — The style with that text color.

pub fn bg(mut self, color: Color) -> Self

Sets the background color.

Parameters

ParameterTypeDescription
selmut self
colorColorThe background color.

Returns

Self — The style with that background.

pub fn bold(mut self) -> Self

Makes the text bold.

Parameters

ParameterType
selmut self

Returns

Self — The style with bold on.

pub fn dim(mut self) -> Self

Makes the text dim (faint).

Parameters

ParameterType
selmut self

Returns

Self — The style with dim on.

pub fn italic(mut self) -> Self

Makes the text italic.

Parameters

ParameterType
selmut self

Returns

Self — The style with italic on.

pub fn underline(mut self) -> Self

Underlines the text.

Parameters

ParameterType
selmut self

Returns

Self — The style with underline on.

pub fn strikethrough(mut self) -> Self

Strikes the text through.

Parameters

ParameterType
selmut self

Returns

Self — The style with strikethrough on.

pub fn is_plain(&self) -> bool

Whether the style does nothing.

Returns

booltrue for a style with no color and no attribute.

pub fn paint(&self, text: &str) -> String

Applies the style to text.

Parameters

ParameterTypeDescription
text&strThe text to style.

Returns

String — The text between the style’s escape sequence and a reset, or the text unchanged for a plain style.

src/ansi/style.rs