Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Fix: Fixed an issue where math formulas could not be displayed correctly #4405 (#4506)

balibabu37235315e14b
diff --git a/web/src/components/highlight-markdown/index.tsx b/web/src/components/highlight-markdown/index.tsx
index 8f754fdfc5..5147a03eac 100644
--- a/web/src/components/highlight-markdown/index.tsx
+++ b/web/src/components/highlight-markdown/index.tsx
@@ -8,6 +8,7 @@ import remarkMath from 'remark-math';
import 'katex/dist/katex.min.css'; // `rehype-katex` does not import the CSS for you
+import { preprocessLaTeX } from '@/utils/chat';
import styles from './index.less';
const HightLightMarkdown = ({
@@ -43,7 +44,7 @@ const HightLightMarkdown = ({
} as any
}
>
- {children}
+ {children ? preprocessLaTeX(children) : children}
</Markdown>
);
};
diff --git a/web/src/pages/chat/markdown-content/index.tsx b/web/src/pages/chat/markdown-content/index.tsx
index b265656fd2..02ec95a6b5 100644
--- a/web/src/pages/chat/markdown-content/index.tsx
+++ b/web/src/pages/chat/markdown-content/index.tsx
@@ -20,7 +20,9 @@ import { useTranslation } from 'react-i18next';
import 'katex/dist/katex.min.css'; // `rehype-katex` does not import the CSS for you
+import { preprocessLaTeX } from '@/utils/chat';
import { replaceTextByOldReg } from '../utils';
+
import styles from './index.less';
const reg = /(~{2}\d+={2})/g;
@@ -48,7 +50,7 @@ const MarkdownContent = ({
text = t('chat.searching');
}
const nextText = replaceTextByOldReg(text);
- return loading ? nextText?.concat('~~2$$') : nextText;
+ return loading ? nextText?.concat('~~2$$') : preprocessLaTeX(nextText);
}, [content, loading, t]);
useEffect(() => {
diff --git a/web/src/utils/chat.ts b/web/src/utils/chat.ts
index 44a5c4b305..d8f956d2f0 100644
--- a/web/src/utils/chat.ts
+++ b/web/src/utils/chat.ts
@@ -34,3 +34,18 @@ export const buildMessageUuidWithRole = (
) => {
return `${message.role}_${message.id}`;
};
+
+// Preprocess LaTeX equations to be rendered by KaTeX
+// ref: https://github.com/remarkjs/react-markdown/issues/785
+
+export const preprocessLaTeX = (content: string) => {
+ const blockProcessedContent = content.replace(
+ /\\\[([\s\S]*?)\\\]/g,
+ (_, equation) => `$$${equation}$$`,
+ );
+ const inlineProcessedContent = blockProcessedContent.replace(
+ /\\\(([\s\S]*?)\\\)/g,
+ (_, equation) => `$${equation}$`,
+ );
+ return inlineProcessedContent;
+};