Colored Terminal Output

Wrapping words around a character limit is one way to improve readability, but coloring the output improves readability even moreso. We can use the term crate to change the color of stdout. Add the term crate to your Cargo.toml file:

term = "*"

Then we can add it to our main.rs file:

extern crate term;

And finally in our phoronix.rs file:

use term;

How To Use the Term Crate

Let's create a new function named phoronix::print_homepage_colored(). We begin by creating a mutable stdout terminal, which gets a handle of stdout and will later allows us to change the colors and attributes.

let mut terminal = term::stdout().unwrap();

If you want to change the color of the terminal, you can use the fg() function with a term::color enum as the input.

terminal.fg(term::color::BRIGHT_GREEN).unwrap();

Now if you want to make your text bold, use the attr() function with a term::Attr enum as the input.

terminal.attr(term::Attr::Bold).unwrap();

The next time you print to the terminal, it will be bright green and bold. You can later reset the terminal back to defaults using the reset() function.

Writing a Colored Printer Function

phoronix_cli.rs

If we put all of this together, we can create a new function, which we shall name print_colored().

pub fn print_colored() {
    let phoronix_articles = Article::get_articles(homepage::offline());
    let mut terminal = term::stdout().unwrap();
    for article in phoronix_articles.iter().rev() {
        print!("Title:   ");
        terminal.fg(term::color::BRIGHT_GREEN).unwrap();
        terminal.attr(term::Attr::Bold).unwrap();
        println!("{}", article.title);
        terminal.reset().unwrap();
        print!("Link:    ");
        terminal.fg(term::color::BRIGHT_CYAN).unwrap();
        println!("https://www.phoronix.com/{}", article.link);
        terminal.reset().unwrap();
        println!("Details: {}\nSummary:", article.details);
        for line in linesplit::split_by_chars(&article.summary, 77).iter() {
            print!(" - ");
            terminal.attr(term::Attr::Bold).unwrap();
            println!("{}", line);
            terminal.reset().unwrap();
        }
        println!("");
    }
}

main.rs

Now we can rewrite main.rs so that your copy should look precisely as this:

extern crate hyper;
extern crate select;
extern crate term;
mod article;
mod homepage;
mod linesplit;
mod phoronix_cli;

fn main() {
    phoronix_cli::print_colored();
}