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)
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}