
之前有提到使用 mdtex 库来实现混合 Latex 的 Markdown 渲染,但其出现的渲染错误实在太多,只能另寻其他解决方案。了解到 Lobe Chat 开源了其组件库 Lobe UI,便深扒其源码,相关代码如下:
// src/hooks/useMarkdown/utils.ts
import rehypeKatex from 'rehype-katex';
import rehypeRaw from 'rehype-raw';
import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import type { Pluggable } from 'unified';
import { animatedPlugin } from '../../Markdown/plugins/animated';
import { rehypeFootnoteLinks, remarkCustomFootnotes } from '../../Markdown/plugins/footnote';
import { rehypeKatexDir } from '../../Markdown/plugins/katexDir';
import { preprocessLaTeX } from './latex';
// createPlugins()
// Create rehype plugins list
const rehypePluginsList = [
allowHtml && rehypeRaw,
enableLatex && rehypeKatex,
enableLatex && rehypeKatexDir,
enableCustomFootnotes && rehypeFootnoteLinks,
animated && animatedPlugin,
...normalizedRehypePlugins,
].filter(Boolean) as Pluggable[];
// Create remark plugins list
const remarkPluginsList = [
...normalizedRemarkPluginsAhead,
enableLatex && remarkMath,
[remarkGfm, { singleTilde: false }],
enableCustomFootnotes && remarkCustomFootnotes,
isChatMode && remarkBreaks,
...normalizedRemarkPlugins,
].filter(Boolean) as Pluggable[];由上述代码可见 Lobe UI 的混合 Latex 的 Markdown 渲染是基于 remark js 实现的。而进一步深入 remark-math 库,可发现其仅支持 $$ 、$ 格式的 Latex 文本,因此想要实现对\(\)、\[\] 格式的 Latex 支持,只能对其进行预处理,通过正则匹配的形式将\(\)、\[\] 转换为 $ 、$$,实现此功能的正则表达式并不复杂,要求编程助手生成即可,prompt 如下
生成 js 代码,实现以下功能
1. 使用正则表达式
2. 将 \(*\) 转换为 $*$
3. 将 \[*\]转换为 $$*$$原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。