Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ANSI Terminal

nu-ansi-term Command line

ANSI Terminal

nu-ansi-term Command line

This program depicts the use of nu-ansi-term crate and how it is used for controlling colors and formatting, such as blue bold text or yellow underlined text, on ANSI terminals. nu-ansi-term is a maintained fork of the archived ansi_term crate with a nearly identical API.

There are two main data structures in nu-ansi-term: AnsiString and Style. A Style holds stylistic information: colors, whether the text should be bold, or blinking, or whatever. There are also Color variants that represent simple foreground color styles. An AnsiString is a string paired with a Style.

Printing colored text to the Terminal

use nu_ansi_term::Color;

fn main() {
    println!(
        "This is {} in color, {} in color and {} in color",
        Color::Red.paint("red"),
        Color::Blue.paint("blue"),
        Color::Green.paint("green")
    );
}

Bold text in Terminal

For anything more complex than plain foreground color changes, the code needs to construct Style struct. Style::new() creates the struct, and properties chained.

use nu_ansi_term::Style;

fn main() {
    println!(
        "{} and this is not",
        Style::new().bold().paint("This is Bold")
    );
}

Bold and colored text in terminal

Color implements many similar functions as Style and can chain methods.

use nu_ansi_term::Color;
use nu_ansi_term::Style;

fn main() {
    println!(
        "{}, {} and {}",
        Color::Yellow.paint("This is colored"),
        Style::new().bold().paint("this is bold"),
        Color::Yellow.bold().paint("this is bold and colored")
    );
}