由于犇犇只支持 Markdown 渲染,没有 的渲染,遂写了一个脚本渲染 。
源代码:
// ==UserScript==
// @name 洛谷犇犇 LaTeX 渲染
// @namespace http://tampermonkey.net/
// @version 1.2
// @description 自动将犇犇中$$包裹的LateX渲染出来
// @author a_small_OIer
// @match www.luogu.com.cn
// @grant GM_addStyle
// @grant GM_getResourceText
// @require https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js
// @resource katexCSS https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css
// ==/UserScript==
(function() {
'use strict';
GM_addStyle(GM_getResourceText('katexCSS'));
const SELECTOR = '.am-comment-bd';
/**
* 渲染元素内的所有 $...$ 公式
* @param {Element} el 容器元素
*/
function renderLaTeXInElement(el) {
if (!el || el.dataset.katexRendered) return;
const walker = document.createTreeWalker(
el,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
return node.nodeValue.includes('$') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
}
);
const textNodes = [];
while (walker.nextNode()) {
textNodes.push(walker.currentNode);
}
let renderedCount = 0;
for (const textNode of textNodes) {
const text = textNode.nodeValue;
const regex = /(?<!\$)\$([^$]+?)\$(?!\$)/g;
const fragment = document.createDocumentFragment();
let lastIndex = 0;
let match;
while ((match = regex.exec(text)) !== null) {
if (match.index > lastIndex) {
fragment.appendChild(document.createTextNode(text.slice(lastIndex, match.index)));
}
const formula = match[1];
try {
const span = document.createElement('span');
katex.render(formula, span, {
throwOnError: false,
displayMode: false // 行内公式
});
fragment.appendChild(span);
renderedCount++;
} catch (e) {
console.warn('KaTeX 渲染失败:', formula, e);
fragment.appendChild(document.createTextNode(match[0]));
}
lastIndex = match.index + match[0].length;
}
if (lastIndex < text.length) {
fragment.appendChild(document.createTextNode(text.slice(lastIndex)));
}
textNode.parentNode.replaceChild(fragment, textNode);
}
if (renderedCount > 0) {
console.log(`[LaTeX] 已渲染 ${renderedCount} 个公式`, el);
}
el.dataset.katexRendered = 'true';
}
function scanAll() {
const containers = document.querySelectorAll(SELECTOR);
containers.forEach(renderLaTeXInElement);
}
scanAll();
const observer = new MutationObserver(mutations => {
let hasNew = false;
for (const mutation of mutations) {
if (mutation.addedNodes.length) {
hasNew = true;
break;
}
}
if (hasNew) {
clearTimeout(observer._timer);
observer._timer = setTimeout(scanAll, 50);
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
})();