给Pelican增加数学公式和图表的显示

AI时代,我觉得数学在我接下来的学习和工作中太重要了,所以我决定给Pelican加上显示数学表达式的功能。

MathJax 数学公式

方案选择

Pelican显示数学公式,大概有三种实现方式:

方案 插件 方式
KaTeX预渲染 pelican-katex 生成时将公式转为HTML/MathML
MathJax浏览器渲染 pelican-render-math 浏览器加载MathJax.js动态渲染
LaTeX转SVG pelican-math-svg 调用LaTeX将公式编译为SVG图片嵌入页面

我比较了一下,第二个pelican-render-math的实现起来比较简单,利用Pelican原有的运行环境就能跑。

安装配置

使用pip安装:

pip install pelican-render-math

如果是用了uv就用:

uv add pelican-render-math

然后在pelicanconf.py中添加:

PLUGINS = ["render_math"]
MATH_JAX = {
    "align": "center",
    "auto_insert": True,
    "process_escapes": True,
    "latex_preview": "TeX",
    "color": "inherit",
    "linebreak_automatic": False,
    "responsive": True,
    "responsive_break": 768,
    "process_summary": True,
}

各参数注解

效果示例

现在我们试试效果:

同一行数学公式:\(\dfrac{1}{1+x^2}\)

代码是:

同一行数学公式:$\dfrac{1}{1+x^2}$

独立行复杂数学公式:

$$ \begin{pmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{n1} & a_{n2} & \cdots & a_{nn} \end{pmatrix} \begin{pmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{pmatrix} = \lambda \begin{pmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{pmatrix} $$

代码是:

独立行复杂数学公式:

$$
\begin{pmatrix}
a_{11} & a_{12} & \cdots & a_{1n} \\
a_{21} & a_{22} & \cdots & a_{2n} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1} & a_{n2} & \cdots & a_{nn}
\end{pmatrix}
\begin{pmatrix}
x_1 \\ x_2 \\ \vdots \\ x_n
\end{pmatrix}
=
\lambda
\begin{pmatrix}
x_1 \\ x_2 \\ \vdots \\ x_n
\end{pmatrix}
$$

Graphviz 图表

除了数学公式,我还加了 Graphviz 图表的功能,因为我感觉也很重要。

安装 Graphviz 程序

首先需要安装 Graphviz 程序本身。

scoop install graphviz
brew install graphviz
apt install graphviz

安装 pelican-graphviz 插件

如果使用pip安装:

pip install pelican-graphviz

如果是用了uv就用:

uv add pelican-graphviz

pelicanconf.py中修改:

PLUGINS = ["graphviz", "render_math"]

效果示例

一个比较复杂的例子:

finite_state_machine

看看效果,它的代码是:

一个比较复杂的例子:

..graphviz dot
digraph finite_state_machine {
    rankdir=LR;
    size="8,5";
    fontsize=10;
    ranksep=1.5;
    nodesep=1.0;
    overlap=false;
    splines=true;
    node [fontsize=14];
    edge [fontsize=12];
    node [shape = doublecircle]; S3 [color=red, style=filled, fillcolor=lightpink];
    node [shape = circle];
    S1 [color=blue, style=filled, fillcolor=lightblue];
    S2 [color=darkgreen, style=filled, fillcolor=lightgreen];
    subgraph cluster_guard {
        label = "守护条件:计数 < 3";
        style=dashed;
        fontsize=10;
        color=purple;
        C1 [shape=box, label="错误计数器", style=filled, fillcolor=gold, fontsize=8];
    }
    S1 -> S2 [ label = "开始", xlabel="动作:重置计数器", fontsize=10, color=blue ];
    S2 -> S1 [ label = "停止", fontsize=10, color=darkgreen ];
    S2 -> S3 [ label = "错误", xlabel="条件:增加计数器", fontsize=10, color=red ];
    S3 -> S2 [ label = "恢复", fontsize=10, color=red ];
    S2 -> C1 [style=dotted, arrowhead=none, color=purple];
}

注意..graphviz dot代码块里不能有空行。