首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Remark js Markdown + Latex 渲染

Remark js Markdown + Latex 渲染

原创
作者头像
TomoriNao
发布2025-05-15 21:48:59
发布2025-05-15 21:48:59
2170
举报
文章被收录于专栏:每月技术成长每月技术成长

之前有提到使用 mdtex 库来实现混合 Latex 的 Markdown 渲染,但其出现的渲染错误实在太多,只能另寻其他解决方案。了解到 Lobe Chat 开源了其组件库 Lobe UI,便深扒其源码,相关代码如下:

代码语言:ts
复制
// 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 如下

代码语言:txt
复制
生成 js 代码,实现以下功能
1. 使用正则表达式
2. 将 \(*\) 转换为 $*$
3. 将 \[*\]转换为 $$*$$

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档