Files
perry/clean-text.js
T
2026-10-07 09:27:20 -05:00

60 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const TEX_SYMBOLS = Object.freeze({
"\\rightarrow": "→",
"\\to": "→",
"\\leftarrow": "←",
"\\leftrightarrow": "↔",
"\\Rightarrow": "⇒",
"\\Leftarrow": "⇐",
"\\Leftrightarrow": "⇔",
"\\times": "×",
"\\cdot": "·",
"\\pm": "±",
"\\neq": "≠",
"\\ne": "≠",
"\\leq": "≤",
"\\le": "≤",
"\\geq": "≥",
"\\ge": "≥",
"\\ldots": "…",
"\\dots": "…",
"\\bullet": "•",
});
function cleanText(value) {
let text = String(value ?? "");
// The models commonly wrap ordinary words in TeX text commands, sometimes
// inside math delimiters. Convert the presentation intent, not the math language.
text = text.replace(/\$\\textbf\{([^{}]*)\}\$/g, "**$1**");
text = text.replace(/\$\\(?:textit|emph)\{([^{}]*)\}\$/g, "//$1//");
text = text.replace(/\$\\text\{([^{}]*)\}\$/g, "$1");
text = text.replace(/\\textbf\{([^{}]*)\}/g, "**$1**");
text = text.replace(/\\(?:textit|emph)\{([^{}]*)\}/g, "//$1//");
text = text.replace(/\\text\{([^{}]*)\}/g, "$1");
// Unwrap a TeX math span only when a known presentation command was actually
// converted. Unknown TeX remains visible rather than being guessed at.
text = text.replace(/\$([^$\n]+)\$/g, (whole, inner) => {
const converted = replaceKnownTexSymbols(inner);
return converted !== inner && !/\\[A-Za-z]+/.test(converted) ? converted : whole;
});
text = replaceKnownTexSymbols(text);
// Normalize common Markdown emphasis into the tiny inline dialect used by
// Cumorah renderers. Existing Cumorah **bold** and //italic// pass through.
text = text.replace(/__([^_\n]+)__/g, "**$1**");
text = text.replace(/(?<!\*)\*([^*\n]+)\*(?!\*)/g, "//$1//");
text = text.replace(/(?<![\w])_([^_\n]+)_(?![\w])/g, "//$1//");
return text;
}
function replaceKnownTexSymbols(value) {
let text = value;
for (const [source, target] of Object.entries(TEX_SYMBOLS)) text = text.split(source).join(target);
return text;
}
module.exports = cleanText;