home ~ projects ~ socials

Highlight Code In Rust With syntect

TODO

    look at this and combine it: id: 2ujekgik

```cargo
[dependencies]
syntect = "5.2.0"
```

use syntect::highlighting::ThemeSet;
use syntect::html::highlighted_html_for_string;
use syntect::parsing::SyntaxSet;

fn main() {
    let code = r#"<p>a
    b
    c
    </p>"#;
    let output = highlight_html(code);
    println!("{}", output)
}

pub fn highlight_html(name: &str) -> String {
    let ss = SyntaxSet::load_defaults_nonewlines();
    let ts = ThemeSet::load_defaults();
    let theme = &ts.themes["base16-ocean.dark"];
    let html = highlighted_html_for_string(name, &ss, &ss.syntaxes()[1], theme).unwrap();
    html
}
Output:
<pre style="background-color:#2b303b;">
<span style="color:#c0c5ce;">&lt;</span><span style="color:#bf616a;">p</span><span style="color:#c0c5ce;">&gt;</span><span style="color:#bf616a;">a
</span><span style="color:#c0c5ce;">    </span><span style="color:#bf616a;">b
</span><span style="color:#c0c5ce;">    </span><span style="color:#bf616a;">c
</span><span style="color:#c0c5ce;">    &lt;/</span><span style="color:#bf616a;">p</span><span style="color:#c0c5ce;">&gt;</span></pre>

This is the version from the docs for testing newline stuff I'm trying to figure out.

---
[dependencies]
syntect = "5.2.0"
---

use syntect::easy::HighlightLines;
use syntect::parsing::SyntaxSet;
use syntect::highlighting::{ThemeSet, Style};
use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};

fn main () {
// Load these once at the start of your program
let ps = SyntaxSet::load_defaults_newlines();
let ts = ThemeSet::load_defaults();

let syntax = ps.find_syntax_by_extension("rs").unwrap();
let mut h = HighlightLines::new(syntax, &ts.themes["base16-ocean.dark"]);
let s = "pub struct Wow { hi: u64 }\nfn blah() -> u64 {}";
for line in LinesWithEndings::from(s) { // LinesWithEndings enables use of newlines mode
    let ranges: Vec<(Style, &str)> = h.highlight_line(line, &ps).unwrap();
    let escaped = as_24_bit_terminal_escaped(&ranges[..], true);
    // NOTE: This is off since outputting it
    // in the grimoire causes issues when
    // publishing to the site. 
    //print!("{}", escaped);
    println!("See note");
}
}
Output:
See note
See note

warning: unused variable: `escaped`
  --> /Users/alan/.cargo/target/4b/0baba35be9214e/_active_nvim_run:21:9
   |
21 |     let escaped = as_24_bit_terminal_escaped(&ranges[..], true);
   |         ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_escaped`
   |
   = note: `#[warn(unused_variables)]` on by default
Output:

Notes

  • It took a while to figure out the &ss.syntaxes()[1] part based off the docs.
  • I don't understand what's going on there either. Something to investigate.
  • TODO is to look at this for a possibly simpler way: https://docs.rs/syntect/latest/syntect/easy/struct.HighlightLines.html
-- end of line --

References