0%

Hexo Next主题渲染 Latex 公式的配置方法

Next 主题可以使用 mathjax 和 katex 两种渲染 latex 的方式。

  • katex 渲染速度更快,但仅支持 latex 的子集。
  • mathjax 渲染速度稍慢,但对 latex 的支持较好。

Next 主题的配置文件 _config.yml 中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Math Formulas Render Support
math:
# Default (true) will load mathjax / katex script on demand.
# That is it only render those page which has `mathjax: true` in Front-matter.
# If you set it to false, it will load mathjax / katex srcipt EVERY PAGE.
per_page: true

# hexo-renderer-pandoc (or hexo-renderer-kramed) required for full MathJax support.
mathjax:
enable: true
# See: https://mhchem.github.io/MathJax-mhchem/
mhchem: false

# hexo-renderer-markdown-it-plus (or hexo-renderer-markdown-it with markdown-it-katex plugin) required for full Katex support.
katex:
enable: false
# See: https://github.com/KaTeX/KaTeX/tree/master/contrib/copy-tex
copy_tex: false

mathjax 和 katex 是互斥的两个选项,enable 不能同时 true或 false。

如果设置 mathjax : true ,就需要更换渲染引擎, hexo-renderer-pandochexo-renderer-kramed

1
2
npm uninstall hexo-renderer-marked --save
npm install hexo-renderer-pandoc --save

如果 katex : true ,则需要更换 hexo-renderer-markdown-it ,或者在原来的 hexo-renderer-marked 引擎下使用 markdown-it-katex plugin。

另外需要注意,如果置 mathjax: true,且使用了 hexo-renderer-kramed渲染引擎,会遇到一行只能使用一个行内公式的情况。
解决方法是直接修改hexo-renderer-kramed相关源码,把文件 node_modules/kramed/lib/rules/inline.js 做如下修改:

1
2
3
4
5
6
var inline = {
escape: /^\\([\\`*{}\[\]()#$+\-.!_>])/,
// ...
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
// ...
};

修改为:

1
2
3
4
5
6
var inline = {
escape: /^\\([`*\[\]()#$+\-.!_>])/,
// ...
em: /^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
// ...
};

笔者有一些高数笔记,因此使用了 pandoc。 per_page 取值的差异在注释中已经说得很清楚了:

  • true: 仅当 front-matter 中存在 mathjax: true 时,该页面才会被渲染。因为渲染会影响速度,推荐用“此选项 + front-matter”进行控制。
  • false: 每篇文章都会进行渲染,不论其中有无公式。

相关知识:

LaTex 行内公式、行间公式

行内公式:包含在行内的公式。

行内公式统一使用 $...$ 来表达,$ 前后一般要有空格, 除非公式后面有标点符号。

行间公式:独立成行的公式。

mhchem

mhchem for MathJax

显示化学公式的 JS库。

Katex

KaTex wiki

katex 是一个JS库,可以在多种浏览器上显示数学公式。相对 Latex 更加轻量,但支持更少的数学符号。特点是轻量、快速、易于使用。

-------------本文结束,感谢您的阅读-------------