* 扫描元素中的所有文本节点,找到未渲染的公式并渲染 * @param {HTMLElement} rootElement - 要扫描的根元素
(rootElement)
| 62 | * @param {HTMLElement} rootElement - 要扫描的根元素 |
| 63 | */ |
| 64 | function processFormulasInElement(rootElement) { |
| 65 | if (!rootElement) return; |
| 66 | |
| 67 | const startTime = performance.now(); |
| 68 | let processedCount = 0; |
| 69 | let removedCount = 0; |
| 70 | |
| 71 | // 先清理错误的 katex-fallback 元素(不完整的公式) |
| 72 | const fallbackElements = rootElement.querySelectorAll('.katex-fallback'); |
| 73 | fallbackElements.forEach(el => { |
| 74 | const text = el.textContent.trim(); |
| 75 | |
| 76 | // 检测不完整的环境标记 |
| 77 | if (/^\\begin\{(aligned|array|matrix|cases|split|gather)\}$/.test(text) || |
| 78 | /^\\end\{(aligned|array|matrix|cases|split|gather)\}$/.test(text)) { |
| 79 | console.log('[FormulaPostProcessor] 删除不完整的公式块:', text); |
| 80 | el.remove(); |
| 81 | removedCount++; |
| 82 | return; |
| 83 | } |
| 84 | |
| 85 | // 检测常见的 LaTeX 错误并尝试修正 |
| 86 | const errorTitle = el.getAttribute('title') || ''; |
| 87 | const errorMatch = errorTitle.match(/Undefined control sequence: (\\[A-Za-z]+)/); |
| 88 | const fontMetricsError = errorTitle.includes('Font metrics not found'); |
| 89 | |
| 90 | if (errorMatch || fontMetricsError) { |
| 91 | const wrongCmd = errorMatch ? errorMatch[1] : ''; |
| 92 | let fixedText = text; |
| 93 | let fixed = false; |
| 94 | |
| 95 | // 修复字体嵌套问题(如 \texttt{\textbf{M}} ) |
| 96 | if (fontMetricsError) { |
| 97 | // 移除嵌套的字体命令,只保留外层 |
| 98 | fixedText = text |
| 99 | // \texttt{\textbf{X}} → \texttt{X} |
| 100 | .replace(/\\texttt\s*\{\s*\\text(bf|it|rm)\s*\{([^}]+)\}\s*\}/g, '\\texttt{$2}') |
| 101 | // \textbf{\texttt{X}} → \textbf{X} |
| 102 | .replace(/\\text(bf|it|rm)\s*\{\s*\\texttt\s*\{([^}]+)\}\s*\}/g, '\\text$1{$2}') |
| 103 | // 任意嵌套字体 → 保留外层 |
| 104 | .replace(/\\(text(tt|bf|it|rm|sf)|math(tt|bf|it|rm|sf|cal|bb))\s*\{\s*\\(text(tt|bf|it|rm|sf)|math(tt|bf|it|rm|sf|cal|bb))\s*\{([^}]+)\}\s*\}/g, '\\$1{$6}'); |
| 105 | |
| 106 | if (fixedText !== text) { |
| 107 | fixed = true; |
| 108 | console.log('[FormulaPostProcessor] 修正字体嵌套:', text.substring(0, 50), '→', fixedText.substring(0, 50)); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // 常见错误映射 |
| 113 | if (!fixed && errorMatch) { |
| 114 | const fixes = { |
| 115 | // 向量和重音符号(大写→小写) |
| 116 | '\\Vec': '\\vec', |
| 117 | '\\Hat': '\\hat', |
| 118 | '\\Bar': '\\bar', |
| 119 | '\\Tilde': '\\tilde', |
| 120 | '\\Dot': '\\dot', |
| 121 | '\\Ddot': '\\ddot', |
nothing calls this directly
no test coverage detected