Function highlight

Source
pub fn highlight<F>(
    code: impl AsRef<str>,
    lang: Option<&str>,
    fmt: &F,
) -> Result<String, PygmentizeError>
Expand description

Applies syntax highlighting to code written in lang, and outputs in the format of F: PygmentizeFormatter.

If lang is None then the language is guessed from code. Note though, that this option is not very reliable.

See supported languages at https://pygments.org/languages/.

§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>
Examples found in repository?
examples/terminal.rs (line 11)
3fn main() {
4    // See also `TerminalFormatter` and `TerminalTrueColorFormatter`
5    let fmt = Terminal256Formatter {
6        line_numbers: false,
7        ..Terminal256Formatter::default()
8    };
9
10    let code = include_str!("terminal.rs");
11    let output = highlight(code, Some("rust"), &fmt).unwrap();
12    println!("{output}");
13}
More examples
Hide additional examples
examples/html.rs (line 11)
4fn main() {
5    let fmt = HtmlFormatter {
6        line_numbers: true,
7        ..HtmlFormatter::default()
8    };
9
10    let code = include_str!("html.rs");
11    let html = highlight(code, Some("rust"), &fmt).unwrap();
12    println!("{html}");
13
14    // dracula.css is Dracula for Pygments
15    // https://draculatheme.com/pygments
16    let html = format!(
17        r#"<!DOCTYPE html>
18<html lang="en-US">
19<head>
20    <style>
21        body {{
22            color: #f8f8f2;
23            background: #44475a;
24        }}
25
26        .highlight, .code {{
27            background: #282a36;
28        }}
29
30        .linenos {{
31            background: #44475a;
32        }}
33    </style>
34    <link rel="stylesheet" href="dracula.css">
35</head>
36<body>
37    {}
38</body>
39</html>"#,
40        html
41    );
42    fs::write("index.html", html).unwrap();
43}