nargo_document/plugin/
shiki.rs1use crate::plugin::{DocumentPlugin, PluginContext, PluginMeta};
6use lazy_static::lazy_static;
7use regex::Regex;
8
9lazy_static! {
10 static ref CODE_BLOCK_RE: Regex = Regex::new(r"```([a-zA-Z0-9_]*)\s*\n([\s\S]*?)\n```").unwrap();
12}
13
14pub struct ShikiPlugin {
16 meta: PluginMeta,
18}
19
20impl ShikiPlugin {
21 pub fn new() -> Self {
23 Self { meta: PluginMeta::new("nargo-document-plugin-shiki".to_string(), "0.1.0".to_string(), "Shiki 代码高亮插件,提供代码块语法高亮功能".to_string()) }
24 }
25
26 fn process_code_blocks(&self, content: &str) -> String {
36 CODE_BLOCK_RE
37 .replace_all(content, |caps: ®ex::Captures| {
38 let lang = caps.get(1).map_or("", |m| m.as_str());
39 let code = &caps[2];
40 if lang.is_empty() {
41 format!("<pre class=\"shiki\"><code>{}</code></pre>", code.trim())
42 }
43 else {
44 format!("<pre class=\"shiki\" data-language=\"{}\"><code>{}</code></pre>", lang, code.trim())
45 }
46 })
47 .to_string()
48 }
49}
50
51impl Default for ShikiPlugin {
52 fn default() -> Self {
53 Self::new()
54 }
55}
56
57impl DocumentPlugin for ShikiPlugin {
58 fn meta(&self) -> &PluginMeta {
60 &self.meta
61 }
62
63 fn before_render(&self, context: PluginContext) -> PluginContext {
73 let content = self.process_code_blocks(&context.content);
74
75 PluginContext { content, frontmatter: context.frontmatter, path: context.path }
76 }
77}