Crate annotate_snippets

source ·
Expand description

A library for formatting of text or programming code snippets.

It’s primary purpose is to build an ASCII-graphical representation of the snippet with annotations.

§Example

use annotate_snippets::{Level, Renderer, Snippet};

fn main() {
    let source = r#"                annotations: vec![SourceAnnotation {
                label: "expected struct `annotate_snippets::snippet::Slice`, found reference"
                    ,
                range: <22, 25>,"#;
    let message = Level::Error.title("expected type, found `22`").snippet(
        Snippet::source(source)
            .line_start(26)
            .origin("examples/footer.rs")
            .fold(true)
            .annotation(
                Level::Error
                    .span(193..195)
                    .label("expected struct `annotate_snippets::snippet::Slice`, found reference"),
            )
            .annotation(Level::Info.span(34..50).label("while parsing this struct")),
    );

    let renderer = Renderer::styled();
    anstream::println!("{}", renderer.render(message));
}
error: expected type, found `22` --> examples/footer.rs:29:25 | 26 | annotations: vec![SourceAnnotation { | ---------------- info: while parsing this struct 27 | label: "expected struct `annotate_snippets::snippet::Slice`, found reference" 28 | , 29 | range: <22, 25>, | ^^ expected struct `annotate_snippets::snippet::Slice`, found reference |

The crate uses a three stage process with two conversions between states:

Message --> Renderer --> impl Display

The input type - Message is a structure designed to align with likely output from any parser whose code snippet is to be annotated.

The middle structure - Renderer is a structure designed to convert a snippet into an internal structure that is designed to store the snippet data in a way that is easy to format. Renderer also handles the user-configurable formatting options, such as color, or margins.

Finally, impl Display into a final String output.

§features

  • testing-colors - Makes Renderer::styled colors OS independent, which allows for easier testing when testing colored output. It should be added as a feature in [dev-dependencies], which can be done with the following command:
cargo add annotate-snippets --dev --feature testing-colors

Modules§

Structs§

  • An annotation for a Snippet.
  • Primary structure provided for formatting
  • A renderer for Messages
  • Structure containing the slice of text to be annotated and basic information about the location of the slice.

Enums§

  • Types of annotations.