Skip to content

Commit

Permalink
🐛 fix: Incorrect math parser (#186)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhuozhiyongde authored Jul 25, 2024
1 parent c06429f commit 5a94c8c
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 42 deletions.
7 changes: 7 additions & 0 deletions src/Markdown/demos/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ $$
$$
\\int_{a}^{b} f(x) \\, dx
$$
---
我是一个嵌套测试:
\`\`\`
$1
\`\`\`
`;

export const content2 = `# Customize Markdown Components
Expand Down
4 changes: 2 additions & 2 deletions src/Markdown/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { CodeFullFeatured, CodeLite } from './CodeBlock';
import type { TypographyProps } from './Typography';
import { useStyles as useMarkdownStyles } from './markdown.style';
import { useStyles } from './style';
import { escapeBrackets, escapeDollarNumber, escapeMhchem } from './utils';
import { escapeBrackets, escapeMhchem } from './utils';

export interface MarkdownProps extends TypographyProps {
allowHtml?: boolean;
Expand Down Expand Up @@ -65,7 +65,7 @@ const Markdown = memo<MarkdownProps>(

const escapedContent = useMemo(() => {
if (!enableLatex) return children;
return escapeMhchem(escapeBrackets(escapeDollarNumber(children)));
return escapeMhchem(escapeBrackets(children));
}, [children, enableLatex]);

const components: Components = useMemo(
Expand Down
40 changes: 0 additions & 40 deletions src/Markdown/utils.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,3 @@
export function escapeDollarNumber(text: string): string {
let escapedText = '';
let inCodeBlock = false;
let inSingleLineCodeBlock = false;
let i = 0;
while (i < text.length) {
let char = text[i];
if (char === '`') {
let tickCount = 1;
while (text[i + tickCount] === '`') {
tickCount++;
}
if (tickCount === 3) {
inCodeBlock = !inCodeBlock;
escapedText += '```';
i += tickCount;
continue;
} else if (tickCount === 1) {
inSingleLineCodeBlock = !inSingleLineCodeBlock;
escapedText += '`';
i += tickCount;
continue;
}
}
if (
!inCodeBlock &&
!inSingleLineCodeBlock &&
char === '$' &&
i + 1 < text.length &&
text[i + 1] >= '0' &&
text[i + 1] <= '9'
) {
char = '\\$';
}
escapedText += char;
i++;
}
return escapedText;
}

export function escapeBrackets(text: string) {
const pattern = /(```[\S\s]*?```|`.*?`)|\\\[([\S\s]*?[^\\])\\]|\\\((.*?)\\\)/g;
return text.replaceAll(pattern, (match, codeBlock, squareBracket, roundBracket) => {
Expand Down

0 comments on commit 5a94c8c

Please sign in to comment.