Module crossterm::style

source ·
Expand description

A module to apply attributes and colors on your text.

Style

The style module provides a functionality to apply attributes and colors on your text.

This documentation does not contain a lot of examples. The reason is that it’s fairly obvious how to use this crate. Although, we do provide examples repository to demonstrate the capabilities.

Platform-specific Notes

Not all features are supported on all terminals/platforms. You should always consult platform-specific notes of the following types:

Examples

A few examples of how to use the style module.

Colors

How to change the terminal text color.

Command API:

Using the Command API to color text.

use std::io::{self, Write};
use crossterm::execute;
use crossterm::style::{Print, SetForegroundColor, SetBackgroundColor, ResetColor, Color, Attribute};

fn main() -> io::Result<()> {
    execute!(
        io::stdout(),
        // Blue foreground
        SetForegroundColor(Color::Blue),
        // Red background
        SetBackgroundColor(Color::Red),
        // Print text
        Print("Blue text on Red.".to_string()),
        // Reset to default colors
        ResetColor
    )
}

Functions:

Using functions from Stylize on a String or &'static str to color it.

use crossterm::style::Stylize;

println!("{}", "Red foreground color & blue background.".red().on_blue());

Attributes

How to apply terminal attributes to text.

Command API:

Using the Command API to set attributes.

use std::io::{self, Write};

use crossterm::execute;
use crossterm::style::{Attribute, Print, SetAttribute};

fn main() -> io::Result<()> {
    execute!(
        io::stdout(),
        // Set to bold
        SetAttribute(Attribute::Bold),
        Print("Bold text here.".to_string()),
        // Reset all attributes
        SetAttribute(Attribute::Reset)
    )
}

Functions:

Using Stylize functions on a String or &'static str to set attributes to it.

use crossterm::style::Stylize;

println!("{}", "Bold".bold());
println!("{}", "Underlined".underlined());
println!("{}", "Negative".negative());

Displayable:

Attribute implements Display and therefore it can be formatted like:

use crossterm::style::Attribute;

println!(
    "{} Underlined {} No Underline",
    Attribute::Underlined,
    Attribute::NoUnderline
);

Structs

Enums

  • Represents an attribute.
  • Represents a color.
  • Represents a foreground or background color.

Traits

  • Provides a set of methods to set attributes and colors.

Functions