diff options
author | metamuffin <metamuffin@disroot.org> | 2022-08-30 16:54:57 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2022-08-30 16:54:57 +0200 |
commit | 802efbca25cb92d8567761361b6513fd57e05578 (patch) | |
tree | 62eb0139143cc343d83d92091eee8efaf0888001 /code/src/syntax_highlight | |
parent | ed6186a764701e702032156c9632ac19305652be (diff) | |
download | metamuffin-blog-802efbca25cb92d8567761361b6513fd57e05578.tar metamuffin-blog-802efbca25cb92d8567761361b6513fd57e05578.tar.bz2 metamuffin-blog-802efbca25cb92d8567761361b6513fd57e05578.tar.zst |
basic syntax highlighting
Diffstat (limited to 'code/src/syntax_highlight')
-rw-r--r-- | code/src/syntax_highlight/grammar.rs | 6 | ||||
-rw-r--r-- | code/src/syntax_highlight/mod.rs | 29 | ||||
-rw-r--r-- | code/src/syntax_highlight/theme.rs | 6 |
3 files changed, 41 insertions, 0 deletions
diff --git a/code/src/syntax_highlight/grammar.rs b/code/src/syntax_highlight/grammar.rs new file mode 100644 index 0000000..95417ab --- /dev/null +++ b/code/src/syntax_highlight/grammar.rs @@ -0,0 +1,6 @@ +pub fn grammar_for(syntax: &str) -> &'static [(&'static [&'static str], &'static str)] { + match syntax { + "rs" => &[(&["fn", "pub", "async"], "keyword")], + _ => unreachable!(), + } +} diff --git a/code/src/syntax_highlight/mod.rs b/code/src/syntax_highlight/mod.rs new file mode 100644 index 0000000..688b010 --- /dev/null +++ b/code/src/syntax_highlight/mod.rs @@ -0,0 +1,29 @@ +pub mod grammar; +pub mod theme; + +use crate::{markdown::escape, syntax_highlight::theme::theme}; +use grammar::grammar_for; +use synoptic::{Highlighter, Token}; + +pub fn syntax_highlight(lang: &str, source: &str) -> String { + let mut h = Highlighter::new(); + for (regex, kind) in grammar_for(lang) { + h.join(regex, kind).unwrap(); + } + let highlighting = h.run(source); + let mut out = String::new(); + + for (_c, row) in highlighting.iter().enumerate() { + eprintln!("{row:?}"); + for tok in row { + match tok { + Token::Start(kind) => out += &format!("<span style=\"color:{}\">", theme(kind)), + Token::Text(text) => out += &escape(text), + Token::End(_kind) => out += "</span>", + } + } + out += "\n" + } + eprintln!("{out:?}"); + out +} diff --git a/code/src/syntax_highlight/theme.rs b/code/src/syntax_highlight/theme.rs new file mode 100644 index 0000000..40434ad --- /dev/null +++ b/code/src/syntax_highlight/theme.rs @@ -0,0 +1,6 @@ +pub fn theme(kind: &str) -> &'static str { + match kind { + "keyword" => "#9999ff", + _ => "#ff00ff", + } +} |