在 hexo-theme-fluid 使用 prismjs 语法高亮

Last updated on 2022-04-18, Mon, 03:02 PM

View English Version

为啥

highlight.js 固然更受欢迎,不过在 hexo-theme-fluid 载入的效果不是很好,对于某些语言的高亮有点糟糕。

那就换 prismjs 苟一下吧,等作者修好再说。

配置

_config.fluid.yml 中修改代码高亮的字段。

行号暂时想不到怎么对齐,只能关掉了。

# _config.fluid.yml

  highlight:
    enable: true

    # 代码块是否显示行号
    # If true, the code block display line numbers
-   line_number: true
+   line_number: false

    # 实现高亮的库,对应下面的设置
    # Highlight library
    # Options: highlightjs | prismjs
-   lib: "highlightjs"
+   lib: "prismjs"

然后自行选择高亮的 style.

生成方式尽量还是选 js 吧。

# _config.fluid.yml

    prismjs:
      # 在下方链接页面右侧的圆形按钮挑选 style 填入,也可以直接填入 css 链接
      # Select the style button on the right side of the link page, you can also set the CSS link
      # See: https://prismjs.com/
      style: "tomorrow-night"

      # 设为 true 高亮将本地静态生成(并只支持部分 prismjs 插件),设为 false 高亮将在浏览器通过 js 生成
      # If true, it will be generated locally (but some prismjs plugins are not supported). If false, it will be generated via JS in the browser
      preprocess: false

魔改

某次上线自行欣赏的时候,发现代码块和段落的间距不大对。

之前没出现过,应该是 prismjs 的问题。

对照了 highlight.js 生成的页面,发现是 figure 元素的作用。

那就在渲染高亮的代码里面修一下,在返回的内容外面包裹一下就好。

修改 node_modules/hexo-theme-fluid/scripts/events/lib/highlight.js

// node_modules/hexo-theme-fluid/scripts/events/lib/highlight.js

    hexo.extend.filter.register('after_post_render', (page) => {
      page.content = page.content.replace(/(?<!<div class="code-wrapper">)(<pre.+?<\/pre>)/gims, (str, p1) => {
        if (/<code[^>]+?mermaid[^>]+?>/ims.test(p1)) {
          str = str.replace(/<pre[^>]*?>/gims, '<pre>')
            .replace(/(class=".*?)language-mermaid(.*?")/gims, '$1mermaid$2');
          if (hexo.config.highlight.line_number) {
            str = str.replace(/<span.+?line-numbers-rows.+?>.+?<\/span><\/code>/, '</code>');
          }
          return str;
        }
-       return `<div class="code-wrapper">${p1}</div>`;
+       return `<figure><div class="code-wrapper">${p1}</div></figure>`;
      });

      page.content = page.content.replace(/<pre><code>/gims, (str) => {
        return '<pre class="language-none"><code class="language-none">';
      });

      return page;
    });

保存修改

对付 node_modules 这种黑洞,可以在外面创建一个副本。

然后用脚本作为构建命令,先覆盖,再构建。

之前我有写过


在 hexo-theme-fluid 使用 prismjs 语法高亮
https://blog.h3a.moe/src/d07582/
Author
H3arn
Posted on
2022-04-18, Mon, 02:08 PM
Updated on
2022-04-18, Mon, 03:02 PM
Licensed under