Skip to content

Commit f27e27c

Browse files
committed
fix(katex): correct \text macro handling (no extra backslash); normalize \ -> \ for fallback; render TeX-looking lines without delimiters
1 parent 596bd08 commit f27e27c

1 file changed

Lines changed: 22 additions & 3 deletions

File tree

static/js/katex_init.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,23 +45,39 @@
4545
if (ch === '_' && (i===0 || inner[i-1] !== '\\')){ out += '\\\\_'; }
4646
else { out += ch; }
4747
}
48-
return '\\\\text{' + out + '}';
48+
return '\\text{' + out + '}';
4949
});
5050
}
5151
function rebuildWithKatex(el){
5252
if (!window.katex) return;
5353
var txt = el.textContent;
5454
if (!(/[\$]/.test(txt) || /\\\(|\\\)|\\\[|\\\]/.test(txt))) return;
5555
var tokens = tokenizeMath(txt);
56-
if (!tokens.some(function(x){return x.t==='m';})) return;
56+
var hasMath = tokens.some(function(x){return x.t==='m';});
57+
if (!hasMath) {
58+
var trimmed = txt.trim();
59+
// If content uses double backslashes (e.g., \\text), normalise to single backslash for KaTeX
60+
var normalised = trimmed.replace(/\\\\/g, "\\");
61+
if (/\\\\?[a-zA-Z]+/.test(trimmed) || /\\[a-zA-Z]+/.test(normalised)) {
62+
// Try to render whole node as inline math when it looks like TeX but lacks delimiters
63+
try {
64+
var span = document.createElement('span');
65+
window.katex.render(escapeUnderscoresInTextCommand(normalised), span, {displayMode:false, strict:'ignore'});
66+
while (el.firstChild) el.removeChild(el.firstChild);
67+
el.appendChild(span);
68+
el.setAttribute('data-katex-rebuilt','1');
69+
} catch (_) {}
70+
}
71+
return;
72+
}
5773
while (el.firstChild) el.removeChild(el.firstChild);
5874
tokens.forEach(function(tok){
5975
if (tok.t==='t'){
6076
el.appendChild(document.createTextNode(tok.s));
6177
} else if (tok.t==='m'){
6278
var content = escapeUnderscoresInTextCommand(tok.s);
6379
var span = document.createElement('span');
64-
try { window.katex.render(content, span, {displayMode: tok.d}); } catch(_) { span.textContent = tok.s; }
80+
try { window.katex.render(content, span, {displayMode: tok.d, strict: "ignore"}); } catch(_) { span.textContent = tok.s; }
6581
el.appendChild(span);
6682
}
6783
});
@@ -77,6 +93,9 @@
7793
{left: "\\[", right: "\\]", display: true}
7894
],
7995
ignoredTags: ["script","noscript","style","textarea","pre","code","option"],
96+
preProcess: function (s) { return escapeUnderscoresInTextCommand(s); },
97+
errorCallback: function () { /* suppress autorender errors; fallback will handle */ },
98+
strict: "ignore",
8099
});
81100
} catch (_) {}
82101
}

0 commit comments

Comments
 (0)