Crate text_style

Source
Expand description

The text_style crate provides types and conversions for styled text.

§Overview

The central types of this crate are StyledStr and StyledString: owned and borrowed strings that are annotated with an optional style information, Style. This style information consists of foreground and background colors (Color) and multiple effects (Effect: bold, italic, underline or strikeout).

text_style’s types can be created directly or converted from or to several formats (all optional and activated by features):

§Background

There is a plethora of crates that produce or consume styled text. Most of these crates use very similar types: ANSI and RGB colors, text effects, styled strings. But converting between these types requires a lot of boilerplate code. The goal of this crate is to provide a subset of common style types to enable conversion between the different crates.

§Usage

§Creating styled text

The StyledString and StyledStr structs provide many utility methods for creating styled strings easily:

use text_style::{AnsiColor, Effect, StyledStr};
let s = StyledStr::plain("text")
    .with(AnsiColor::Red.light())
    .on(AnsiColor::Green.dark())
    .bold();
text_style::ansi_term::render(std::io::stdout(), s)
    .expect("Could not render line");

If the syntect feature is activated, conversion traits from syntect’s style types are implemented:

use syntect::{easy, parsing, highlighting, util};

let ps = parsing::SyntaxSet::load_defaults_newlines();
let ts = highlighting::ThemeSet::load_defaults();

let syntax = ps.find_syntax_by_extension("rs").unwrap();
let mut h = easy::HighlightLines::new(syntax, &ts.themes["base16-ocean.dark"]);
let s = "pub struct Wow { hi: u64 }\nfn blah() -> u64 {}";
for line in util::LinesWithEndings::from(s) {
    let ranges: Vec<(highlighting::Style, &str)> = h.highlight(line, &ps);
    text_style::ansi_term::render_iter(std::io::stdout(), ranges.iter())
        .expect("Could not render line");
}

§Rendering styled text

The backends define conversion traits from or to the text_style types where applicable.

Most backends also define render and render_iter methods to display a styled string or an iterator over styled strings:

let s = text_style::StyledStr::plain("test").bold();

let mut w = std::io::stdout();
text_style::ansi_term::render(&mut w, &s).expect("Rendering failed");
text_style::crossterm::render(&mut w, &s).expect("Rendering failed");
text_style::termion::render(&mut w, &s).expect("Rendering failed");

For more information, see the module documentations.

Modules§

Structs§

  • A set of text effects.
  • An iterator over text effects.
  • A text style, a combination of a foreground color, a background color and text effects (all optional).
  • A borrowed string with an optional style annotation.
  • An owned string with an optional style annotation.

Enums§

Constants§