Function pygmentize::highlight
source · pub fn highlight<F>(
code: impl AsRef<str>,
lang: Option<&str>,
fmt: &F
) -> Result<String, PygmentizeError>where
F: PygmentizeFormatter,
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">"Hello, world!"</span>
<span class="p">);</span>
<span class="p">}</span>
</pre>
</div>
Examples found in repository?
More examples
examples/html.rs (line 11)
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
fn main() {
let fmt = HtmlFormatter {
line_numbers: true,
..HtmlFormatter::default()
};
let code = include_str!("html.rs");
let html = highlight(code, Some("rust"), &fmt).unwrap();
println!("{html}");
// dracula.css is Dracula for Pygments
// https://draculatheme.com/pygments
let html = format!(
r#"<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
body {{
color: #f8f8f2;
background: #44475a;
}}
.highlight, .code {{
background: #282a36;
}}
.linenos {{
background: #44475a;
}}
</style>
<link rel="stylesheet" href="dracula.css">
</head>
<body>
{}
</body>
</html>"#,
html
);
fs::write("index.html", html).unwrap();
}