@mdit/plugin-katex
Plugins to render math expressions with KaTeX.
Note
This plugin is based on @mdit/plugin-tex.
Usage Node.js runtime only
TS
import MarkdownIt from "markdown-it";
import { katex } from "@mdit/plugin-katex";
const mdIt = MarkdownIt().use(katex);
mdIt.render("$E=mc^2$");
JS
const MarkdownIt = require("markdown-it");
const { katex } = require("@mdit/plugin-katex");
const mdIt = MarkdownIt().use(katex);
mdIt.render("$E=mc^2$");
We also have a package called @mdit/plugin-katex-slim
which katex
is an optional peer.
Syntax
You should use $tex expression$
inline, and use $$tex expression$$
for block.
Style
You should import katex/dist/katex.min.css
from katex
package or CDN yourself.
Escaping
You can use
\
to escape$
:Euler’s identity \$e^{i\pi}+1=0$
will be
Euler’s identity $e^{i\pi}+1=0$
Demo
Euler’s identity
Euler’s identity $e^{i\pi}+1=0$ is a beautiful formula in $\mathbb{R}^2$.
$$
\frac {\partial^r} {\partial \omega^r} \left(\frac {y^{\omega}} {\omega}\right)
= \left(\frac {y^{\omega}} {\omega}\right) \left\{(\log y)^r + \sum_{i=1}^r \frac {(-1)^ Ir \cdots (r-i+1) (\log y)^{ri}} {\omega^i} \right\}
$$
mhchem extension
If you want to load the mhchem
extension, you should import loadMhchem
from @mdit/plugin-katex
:
import { loadMhchem } from "@mdit/plugin-katex";
await loadMhchem();
Since it's async, you should call it in prepare stage as markdown-it rendering is sync.
Options
type KatexLogger<MarkdownItEnv = unknown> = (
errorCode:
| "unknownSymbol"
| "unicodeTextInMathMode"
| "mathVsTextUnits"
| "commentAtEnd"
| "htmlExtension"
| "newLineInDisplayMode",
errorMsg: string,
token: Token,
env: MarkdownItEnv,
) => "error" | "warn" | "ignore" | boolean | undefined | void;
type TeXTransformer = (content: string, displayMode: boolean) => string;
interface MarkdownItKatexOptions<MarkdownItEnv = unknown> extends KatexOptions {
/**
* Whether to allow inline math with spaces on ends
*
* @description NOT recommended to set this to true, because it will likely break the default usage of $
*
* @default false
*/
allowInlineWithSpace?: boolean;
/**
* Whether parsed fence block with math language to display mode math
*
* @default false
*/
mathFence?: boolean;
/**
* Error logger
*/
logger?: KatexLogger<MarkdownItEnv>;
/**
* transformer on output content
*/
transformer?: TeXTransformer;
}