evo-frontend / web /src /math-preprocessing.ts
fraudTech's picture
fix latex
401629b
Raw History Blame
4.65 kB
/**
* Math Preprocessing for KaTeX Rendering
*
* This file contains utilities to preprocess mathematical content before
* KaTeX rendering. It handles common LaTeX formatting issues, delimiter
* normalization, and edge cases that would otherwise break rendering.
*/
/**
* Preprocesses content to make it KaTeX-compatible.
* Comprehensive preprocessing to handle user input edge cases.
* Backend prompt reduces LLM errors, but this handles ALL input.
*/
export function preprocessMathContent(content: string): string {
if (!content) return content;
let processed = content;
// Step 1: Normalize delimiters (MUST BE FIRST)
// Convert \(...\) to $...$ and \[...\] to $$...$$
processed = processed
.replace(/\\\(/g, '$')
.replace(/\\\)/g, '$')
.replace(/\\\[/g, '\n$$')
.replace(/\\\]/g, '$$\n');
// Step 2: Remove nested inline math delimiters inside display math
// Pattern: $$...$ ... $...$$ → $$... ... ...$$
// Must handle both single-line and multi-line display math
processed = processed.replace(/\$\$([\s\S]*?)\$\$/g, (_match, content) => {
// Remove ALL $ signs inside display math (they're always wrong)
const cleaned = content.replace(/\$/g, '');
return `$$${cleaned}$$`;
});
// Step 3: Clean up delimiter stacking ($$$$, $$$, etc.)
while (processed.includes('$$$')) {
processed = processed.replace(/\$\$\$\$+/g, '$$');
processed = processed.replace(/\$\$\$/g, '$$');
}
// Step 4: Fix malformed \left and \right
processed = processed.replace(/\\left\\frac/g, '\\frac');
processed = processed.replace(/\\right\\frac/g, '\\frac');
processed = processed.replace(/\\left(?![(\[{|])/g, '');
processed = processed.replace(/\\right(?![)\]}|])/g, '');
// Step 5: Fix list markers contaminating delimiters
processed = processed.replace(/(\d+)\$\$/g, '$1. $$');
processed = processed.replace(/\$\$(\d+)\$/g, '$$ $1.');
processed = processed.replace(/\$(\d+)\$/g, '$ $1. $');
// Step 6: Ensure display math has proper newlines
processed = processed.replace(/\$\$([\s\S]*?)\$\$/g, (_match, math) => {
const trimmed = math.trim();
if (trimmed.includes('\n')) {
return `$$\n${trimmed}\n$$\n`;
}
return `$$${trimmed}$$\n`;
});
// Step 7: Clean up multiple newlines
processed = processed.replace(/\n{3,}/g, '\n\n');
return processed;
}
/**
* Extract math expressions from content for validation/preview
*/
export function extractMathExpressions(content: string): Array<{
type: 'inline' | 'display';
content: string;
raw: string;
}> {
const expressions: Array<{ type: 'inline' | 'display'; content: string; raw: string }> = [];
// Extract display math $$...$$
const displayRegex = /\$\$([\s\S]*?)\$\$/g;
let match;
while ((match = displayRegex.exec(content)) !== null) {
expressions.push({
type: 'display',
content: match[1].trim(),
raw: match[0]
});
}
// Extract inline math $...$ (but not $$...$$)
const inlineRegex = /(?<!\$)\$([^$\n]+?)\$(?!\$)/g;
while ((match = inlineRegex.exec(content)) !== null) {
expressions.push({
type: 'inline',
content: match[1].trim(),
raw: match[0]
});
}
return expressions;
}
/**
* Check if content contains valid-looking math
*/
export function hasMathContent(content: string): boolean {
if (!content) return false;
// Check for common math patterns
const patterns = [
/\$[^$]+\$/, // Inline math
/\$\$[\s\S]*?\$\$/, // Display math
/\\\([\s\S]*?\\\)/, // \(...\)
/\\\[[\s\S]*?\\\]/, // \[...\]
/\\begin\{(align|aligned|equation|gather|multline|math|displaymath)/, // Environments
/\\(frac|sum|prod|int|lim|sqrt|alpha|beta|gamma|delta|epsilon|pi|theta|phi|lambda)/, // Common commands
/_[a-zA-Z0-9]/, // Subscripts
/\^[a-zA-Z0-9]/, // Superscripts
];
return patterns.some(pattern => pattern.test(content));
}
/**
* Sanitize math content to prevent XSS while preserving LaTeX
* MathJax's safe extension handles most of this, but we add extra protection
*/
export function sanitizeMathContent(content: string): string {
if (!content) return content;
// Remove script tags (though MathJax shouldn't execute them anyway)
let sanitized = content.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
// Remove event handlers
sanitized = sanitized.replace(/\s*on\w+\s*=\s*["'][^"']*["']/gi, '');
// Allow only safe HTML tags that don't interfere with math
// (MathJax handles the rest)
return sanitized;
}