Crate pygmentize

source ·
Expand description

Rust library and wrapper around the pygmentize CLI. Apply syntax highlighting to over 500 languages and other text formatted. Render into HTML, SVG, LaTeX, and Terminal (ANSI color sequences).

Rendered HTML Output

Rendered example of examples/html.rs.

Rendered Example

Example

use pygmentize::{HtmlFormatter, PygmentizeError};

let code = r#"fn main() {
    println!("Hello, world!");
}"#;

let html = pygmentize::highlight(code, Some("rust"), &HtmlFormatter::default())?;
println!("{html}");

Output

(whitespace added to improve clarity)

<div class="highlight">
<pre>
    <span></span>

    <span class="k">fn</span>
    <span class="nf">main</span>
    <span class="p">()</span>
    <span class="w"> </span>
    <span class="p">{</span>

    <span class="w">    </span>
    <span class="fm">println!</span>
    <span class="p">(</span>
    <span class="s">&quot;Hello, world!&quot;</span>
    <span class="p">);</span>

    <span class="p">}</span>
</pre>
</div>

Rendered

(with the Dracula theme)

image

Override Pygmentize Path

The path to the pygmentize binary, can be overridden using pygmentize::set_bin_path(). The default path is "pygmentize".

If pygmentize is installed in a virtual environment, within your crate directory, i.e. Cargo.lock and env/ being within the same directory. Then assuming that the current directory is the same. Then the path can be overridden by doing:

pygmentize::set_bin_path("./env/Scripts/pygmentize");

Structs

  • Format tokens as HTML 4 <span> tags.
  • Format tokens as LaTeX code. This needs the fancyvrb and color standard packages.
  • Format tokens as an SVG graphics file. This formatter is still experimental. Each line of code is a <text> element with explicit x and y coordinates containing <tspan> elements with the individual token styles.
  • Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in TerminalFormatter color sequences are terminated at newlines, so that paging the output works correctly.
  • Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.
  • Format tokens with ANSI color sequences, for output in a true-color terminal or console. Like in TerminalFormatter color sequences are terminated at newlines, so that paging the output works correctly.

Enums

Traits

Functions

  • Applies syntax highlighting to code written in lang, and outputs in the format of F: PygmentizeFormatter.
  • Overwrite the path to the pygmentize binary. The default path is "pygmentize".