| |
| const containsLatexRegex = |
| /\\\(.*?\\\)|\\\[.*?\\\]|\$.*?\$|\\begin\{equation\}.*?\\end\{equation\}/; |
|
|
| |
| const inlineLatex = new RegExp(/\\\((.+?)\\\)/, 'g'); |
| const blockLatex = new RegExp(/\\\[(.*?[^\\])\\\]/, 'gs'); |
|
|
| |
| const restoreCodeBlocks = (content: string, codeBlocks: string[]) => { |
| return content.replace(/<<CODE_BLOCK_(\d+)>>/g, (match, index) => codeBlocks[index]); |
| }; |
|
|
| |
| const codeBlockRegex = /(```[\s\S]*?```|`.*?`)/g; |
|
|
| export const processLaTeX = (_content: string) => { |
| let content = _content; |
| |
| const codeBlocks: string[] = []; |
| let index = 0; |
| content = content.replace(codeBlockRegex, (match) => { |
| codeBlocks[index] = match; |
| return `<<CODE_BLOCK_${index++}>>`; |
| }); |
|
|
| |
| let processedContent = content.replace(/(\$)(?=\s?\d)/g, '\\$'); |
|
|
| |
| if (!containsLatexRegex.test(processedContent)) { |
| return restoreCodeBlocks(processedContent, codeBlocks); |
| } |
|
|
| |
| processedContent = processedContent |
| .replace(inlineLatex, (match: string, equation: string) => `$${equation}$`) |
| .replace(blockLatex, (match: string, equation: string) => `$$${equation}$$`); |
|
|
| |
| return restoreCodeBlocks(processedContent, codeBlocks); |
| }; |
|
|