prism_js/lib.rs
1use quick_js::Context;
2
3const PRISM_JS: &str = include_str!("../prism/prism.js");
4pub const PRISM_CSS: &str = include_str!("../prism/prism.css");
5
6// not publicly exported
7pub type PrismContext = Context;
8
9/// initialize prism.js
10pub fn init() -> PrismContext {
11 let context = Context::new().unwrap();
12 context.eval(PRISM_JS).unwrap();
13 // context.eval("function highlight(text, grammar, language) { return Prism.highlight(text, grammer, language); }").unwrap();
14 context
15}
16
17/// text: the code to be highlighted
18/// grammar: the name of the prism.js language definition in the context
19/// language: the name of the language definition passed to grammar
20///
21/// Example:
22/// ```rust
23/// use prism_js::{init, highlight_internal};
24///
25/// let mut context = init();
26///
27/// let text = "var foo = true;";
28/// let grammar = "Prism.languages.javascript";
29/// let language = "javascript";
30///
31/// let html = highlight_internal(&mut context, text, grammar, language);
32/// assert!(html.is_some());
33/// assert!(html.unwrap() == r#"<span class="token keyword">var</span> foo <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>"#);
34/// ```
35pub fn highlight_internal(
36 context: &mut PrismContext,
37 text: &str,
38 grammar: &str,
39 language: &str,
40) -> Option<String> {
41 // context.call_function doesn't work here since the actual value for grammer is too large
42 context.set_global("text", text).ok()?;
43 context.set_global("language", language).ok()?;
44 context
45 .eval(&format!("Prism.highlight(text, {}, language)", grammar))
46 .ok()
47 .and_then(|v| v.as_str().map(|s| s.to_string()))
48}
49
50/// text: the code to be highlighted
51/// language: the language to highlight the code in
52///
53/// Example:
54/// ```rust
55/// use prism_js::{init, highlight};
56///
57/// let mut context = init();
58///
59/// let html = highlight(&mut context, "var foo = true;", "javascript");
60/// assert!(html.is_some());
61/// assert!(html.unwrap() == r#"<span class="token keyword">var</span> foo <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>"#);
62/// ```
63pub fn highlight(context: &mut PrismContext, text: &str, language: &str) -> Option<String> {
64 highlight_internal(context, text, format!("Prism.languages.{}", language).as_str(), language)
65}