版本比较
洛谷题目转 PDF
正文
增加 154 行删除 123 行
27 行未改动282930313233323334353637383940416 行未改动4849505152535455565758596061626364656667686944 行未改动11411511611711811912012112238 行未改动1611621631641521651661671681697 行未改动17717817918018116816918218318418518618715 行未改动20320420520619319419519619719819920020120220320420520720820921021121221321421521621721821922022122222322422522622722822923023123223323423514 行未改动25025125225325422825525625725825910 行未改动2702712722732472742752762772512782792802812822832842852862572582872882892902912922932632942952962972982682993003013023033043052743063073083093103113123133142823153163173183192 行未改动3223233243252933263272952963283293302993003013313323033333343053063353363373093103113123133143383393403413163173183193423433443453463473223233243253483493503273283293303313323333343353363373383393403413423433443453463473483493503513523533543513523533543563553563593573583593623603613623633673643653693663673683693703753763773783793803813823833713723733743753763773783793853803813883823833843853863873883963893903913922 行未改动39539639739840739940040140241141241341441541641740340440540641840740840941041141241341442741541641741841942042142242943042342442543342642742842943043943143243343443543643743844743944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347445047547647747847913 行未改动49349449549649749849947350050150250350447650550650750850916 行未改动52652752852950153053153253353453553653753853954054154254354454554651254754854955031 行未改动5825835845855525865875885895907 行未改动5985996006015685696026036046056066076085756096106116126 行未改动6196206216225906236246256266 行未改动6336346356366056376386396409 行未改动65065165265362365465562565627 行未改动```javascript// ==UserScript==// @name 洛谷题目转 PDF// @namespace http://tampermonkey.net/// @version 5.2// @description 从JSON重建页面,完美支持洛谷扩展Markdown(折叠框、引言、表格合并、居中、cute-table)// @version 5.2.7// @description 从JSON重建页面,修复题目背景、合并表格、编号加粗、特殊性质对齐等问题,已修复XSS漏洞// @match https://www.luogu.com.cn/problem/*// @require https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js// @require https://cdn.jsdelivr.net/npm/marked/marked.min.js// @require https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js// @grant GM_addStyle// ==/UserScript==
(function () {6 行未改动 if (typeof marked === 'undefined') { console.error('[Luogu-RER] 致命错误:marked 未加载'); return; } if (typeof DOMPurify === 'undefined') { console.error('[Luogu-RER] 致命错误:DOMPurify 未加载'); return; }
marked.setOptions({ breaks: true, gfm: true });
// HTML 转义函数,用于防止 XSS function escapeHtml(str) { const div = document.createElement('div'); div.textContent = str; return div.innerHTML; }
window.addEventListener('load', () => { setTimeout(MainScript, 500); });
44 行未改动 const pid = problemData.pid; const name = problemData.name; const content = problemData.content || {}; const desc = content.description || ''; const background = content.background || ''; const fmtIn = content.formatI || ''; const fmtOut = content.formatO || ''; const hint = content.hint || ''; const samples = problemData.samples || [];38 行未改动
mainContainer.innerHTML = ''; mainContainer.style.cssText = 'margin:12px auto;width:100%;max-width:1191px;padding:0;';
BuildPage(mainContainer, { pid, name, desc, fmtIn, fmtOut, hint, samples, hidden, timeLimit, memoryLimit }); BuildPage(mainContainer, { pid, name, desc, background, fmtIn, fmtOut, hint, samples, hidden, timeLimit, memoryLimit }); }
function BuildPage(container, data) { // 工具栏7 行未改动 flex-wrap:wrap;gap:6px; `; const leftDiv = document.createElement('div'); leftDiv.style.cssText = 'display:flex;align-items:center;gap:10px;font-size:15px;'; // 对 pid 和 name 进行 HTML 转义 leftDiv.innerHTML = `<span style="font-weight:700;color:#61dafb">${data.pid}</span> <span style="color:#ecf0f1;max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${data.name}</span>`; leftDiv.innerHTML = `<span style="font-weight:700;color:#61dafb">${escapeHtml(data.pid)}</span> <span style="color:#ecf0f1;max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escapeHtml(data.name)}</span>`; const rightDiv = document.createElement('div'); rightDiv.style.cssText = 'display:flex;align-items:center;gap:4px;flex-wrap:wrap;';
const hiddenBtns = data.hidden.querySelectorAll('button, a');15 行未改动 background:rgba(255,255,255,0.08);color:#ecf0f1; transition:0.2s;white-space:nowrap; `; if (cls === 'tb-submit') b.style.background='#3498db'; if (hiddenBtn) { b.onclick = e => { e.preventDefault(); try { hiddenBtn.click(); } catch (err) { console.error(err); } }; } else { b.onclick = e => { e.preventDefault(); if (label === '提交') window.location.hash = 'submit'; else if (label === '题解') window.location.hash = 'solution'; else if (label.includes('复制 Markdown')) { const content = document.querySelector('#Problem-element')?.innerText || ''; navigator.clipboard.writeText(content).then(() => alert('已复制')).catch(() => alert('复制失败')); } }; }
b.onclick = e => { e.preventDefault();
// 提交按钮:直接跳转 submit 并刷新 if (label === '提交') { window.location.hash = 'submit'; window.location.reload(); return; }
// 其他按钮:如果存在原始按钮则触发,否则按类型处理 if (hiddenBtn) { try { hiddenBtn.click(); } catch (err) { console.error(err); } return; }
if (label === '题解') { window.location.hash = 'solution'; } else if (label.includes('复制 Markdown')) { const content = document.querySelector('#Problem-element')?.innerText || ''; navigator.clipboard.writeText(content).then(() => alert('已复制')).catch(() => alert('复制失败')); } };
return b; };
rightDiv.appendChild(mkBtn('提交', hSubmit, 'tb-submit'));14 行未改动
// 头部 const hdr = document.createElement('header'); hdr.style.cssText = 'font-size:20px;display:flex;flex-wrap:wrap;margin-bottom:48px;font-family:KaTeX_Main,SimSun,serif;'; // 对 pid 和 name 进行 HTML 转义 hdr.innerHTML = `<div style="margin-right:auto">洛谷 Luogu</div><div>${data.pid} ${data.name}</div><hr style="flex-basis:100%;border:1px solid #bfbfbf;margin:0">`; hdr.innerHTML = `<div style="margin-right:auto">洛谷 Luogu</div><div>${escapeHtml(data.pid)} ${escapeHtml(data.name)}</div><hr style="flex-basis:100%;border:1px solid #bfbfbf;margin:0">`; problemDiv.appendChild(hdr);
const title = document.createElement('h1'); title.textContent = data.name;10 行未改动 limitsDiv.textContent = parts.join(' '); problemDiv.appendChild(limitsDiv); }
// ========== 洛谷自定义语法预处理 ========== // ========== 渲染函数 ========== function preprocessLuoguSyntax(md) { if (!md) return '';
// 1. 处理表格合并(必须在其他处理之前,因为可能包含公式等) // 0. 显式处理图片 md = md.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" style="max-width:100%;height:auto;">');
// 1. 处理表格合并 md = convertMergedTables(md);
// 2. cute-table 标记 md = md.replace(/^::cute-table\{tuack\}\n/gm, '<!--tuack-->\n');
// 3. 折叠框、引言、居中/居右(四个冒号/三个冒号) // 四个冒号(三层嵌套的最外层,暂只支持三层,即四个冒号) // 3. 折叠框等 md = md.replace(/::::(\w+)(?:\[([^\]]*)\])?(?:\{([^}]*)\})?\n([\s\S]*?)\n::::/g, (_, type, title, attrs, content) => { const open = attrs && attrs.includes('open') ? ' open' : ''; // 对 title 进行 HTML 转义 const safeTitle = title ? escapeHtml(title) : ''; return `<details class="luogu-fold luogu-${type}"${open}> <summary>${title || ''}</summary> <summary>${safeTitle}</summary> ${content} </details>`; } ); // 三个冒号 md = md.replace(/:::(\w+)(?:\[([^\]]*)\])?(?:\{([^}]*)\})?\n([\s\S]*?)\n:::/g, (_, type, title, attrs, content) => { if (type === 'epigraph') { // 对 cite 内容进行 HTML 转义 const safeTitle = title ? escapeHtml(title) : ''; return `<blockquote class="epigraph"> <p>${content}</p> ${title ? `<cite>${title}</cite>` : ''} ${safeTitle ? `<cite>${safeTitle}</cite>` : ''} </blockquote>`; } else if (type === 'align') { if (attrs === 'center') return `<div class="align-center">${content}</div>`; if (attrs === 'right') return `<div class="align-right">${content}</div>`; } else if (['info', 'success', 'warning', 'error'].includes(type)) { const open = attrs && attrs.includes('open') ? ' open' : ''; const safeTitle = title ? escapeHtml(title) : ''; return `<details class="luogu-fold luogu-${type}"${open}> <summary>${title || ''}</summary> <summary>${safeTitle}</summary> ${content} </details>`; } return _;2 行未改动
return md; }
// 将包含 ^ 或 < 的表格转换为 HTML // ---------- 表格合并解析 ---------- function convertMergedTables(md) { // 匹配整个表格:连续的行,每行以 | 开头,且包含至少一个 | 作为分隔(含分隔行) const tableRegex = /(^\|.+\|\s*$[\r\n])+/gm; const tableRegex = /(^\|.*$[\r\n]*)+/gm; return md.replace(tableRegex, (tableBlock) => { const lines = tableBlock.split(/\r?\n/).filter(line => line.trim().length > 0); if (lines.length < 2) return tableBlock; // 至少两行
// 检测是否有合并标记 if (lines.length < 2) return tableBlock; const hasMerge = lines.some(line => /(?:^|\|)\s*(\^|<)\s*(?:\||$)/.test(line)); if (!hasMerge) return tableBlock; // 无标记,保留原样 if (!hasMerge) return tableBlock;
// 解析表格 const rows = []; const parsedRows = lines.map(parseRow); let header = []; let hasHeader = false;
// 判断是否有分隔行(第二行且包含 :---) let startIdx = 0; if (lines.length >= 2 && /^\|[\s\-:]+\|/.test(lines[1])) { // 有表头:第一行是表头,第二行是分隔行 header = parseRow(lines[0]); let bodyStart = 0; if (parsedRows.length >= 2 && isSeparatorLine(lines[1])) { header = parsedRows[0]; hasHeader = true; startIdx = 2; } else { // 无表头:第一行就是数据行 startIdx = 0; bodyStart = 2; } const bodyRows = parsedRows.slice(bodyStart); const allRowLengths = [header.length, ...bodyRows.map(r => r.length)]; const colCount = Math.max(...allRowLengths, 1);
// 解析数据行 for (let i = startIdx; i < lines.length; i++) { rows.push(parseRow(lines[i])); } const grid = Array.from({ length: bodyRows.length }, () => new Array(colCount).fill(null)); const occupied = Array.from({ length: bodyRows.length }, () => new Array(colCount).fill(false));
// 如果 rows 为空且有表头,则表头也是数据(实际上无表头情况我们已经处理了) if (rows.length === 0 && hasHeader) { rows.push(header); hasHeader = false; }
// 计算列数:取最大单元格数 const colCount = Math.max(...rows.map(r => r.length)); if (hasHeader && header.length < colCount) { // 补齐表头 while (header.length < colCount) header.push(''); }
// 处理合并标记:构建最终单元格的 rowspan 和 colspan,以及内容 // 我们使用一个二维数组 track[row][col] 记录 { content, rowspan, colspan } const grid = []; const rowCount = rows.length; // 初始化跟踪矩阵 for (let r = 0; r < rowCount; r++) { grid[r] = new Array(colCount).fill(null); } // 记录哪些位置已被合并占用 const occupied = Array.from({ length: rowCount }, () => new Array(colCount).fill(false));
// 填充数据 for (let r = 0; r < rowCount; r++) { const cells = rows[r]; let colIdx = 0; // 当前逻辑列 for (let r = 0; r < bodyRows.length; r++) { const cells = bodyRows[r]; let colIdx = 0; for (let c = 0; c < cells.length; c++) { // 跳过已占用的列 while (colIdx < colCount && occupied[r][colIdx]) colIdx++; if (colIdx >= colCount) break;
const val = cells[c].trim();
if (val === '^') { // 向上合并:找到上方最近一个非空单元格,增加其 rowspan,并标记本位置为被合并 let targetRow = r - 1; while (targetRow >= 0 && grid[targetRow][colIdx] === null) targetRow--; if (targetRow >= 0) { grid[targetRow][colIdx].rowspan++; occupied[r][colIdx] = true; // 该位置被上方合并占用 occupied[r][colIdx] = true; } else { // 无法向上合并,视为普通空单元格 grid[r][colIdx] = { content: '', rowspan: 1, colspan: 1 }; occupied[r][colIdx] = true; } colIdx++; } else if (val === '<') { // 向左合并:与左边单元格合并,增加左边单元格的 colspan,标记当前位置被合并 if (colIdx > 0) { // 找到左边最近的单元格 let leftCol = colIdx - 1; while (leftCol >= 0 && grid[r][leftCol] === null) leftCol--; if (leftCol >= 0) { grid[r][leftCol].colspan++; occupied[r][colIdx] = true; } let leftCol = colIdx - 1; while (leftCol >= 0 && grid[r][leftCol] === null) leftCol--; if (leftCol >= 0) { grid[r][leftCol].colspan++; occupied[r][colIdx] = true; } else { grid[r][colIdx] = { content: '', rowspan: 1, colspan: 1 }; occupied[r][colIdx] = true; } // 如果 colIdx == 0 无法向左合并,则当作空单元格 colIdx++; } else { // 普通内容 grid[r][colIdx] = { content: val, rowspan: 1, colspan: 1 }; occupied[r][colIdx] = true; colIdx++; } } }
// 构建 HTML 表格 let html = '<table>'; if (hasHeader) { html += '<thead><tr>'; for (let c = 0; c < colCount; c++) {2 行未改动 } html += '</tr></thead>'; } html += '<tbody>'; for (let r = 0; r < rowCount; r++) { for (let r = 0; r < bodyRows.length; r++) { html += '<tr>'; for (let c = 0; c < colCount; c++) { const cell = grid[r][c]; if (!cell || occupied[r][c] === false) continue; // 被合并占用的跳过 if (cell.rowspan === 1 && cell.colspan === 1) { html += `<td>${cell.content}</td>`; } else { const rowspan = cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : ''; const colspan = cell.colspan > 1 ? ` colspan="${cell.colspan}"` : ''; html += `<td${rowspan}${colspan}>${cell.content}</td>`; if (!cell || !occupied[r][c]) continue; const rowspan = cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : ''; const colspan = cell.colspan > 1 ? ` colspan="${cell.colspan}"` : ''; html += `<td${rowspan}${colspan}>${cell.content}</td>`; } } html += '</tr>'; } html += '</tbody></table>'; return html; }); }
// 解析一行单元格,返回数组 function isSeparatorLine(line) { const trimmed = line.trim(); if (!trimmed.startsWith('|')) return false; const content = trimmed.replace(/^\|/, '').replace(/\|$/, ''); return content.split('|').every(seg => /^[\s\-:]+$/.test(seg) && seg.includes('-')); }
function parseRow(line) { // 去除首尾空格和管道符,然后按 | 分割 return line.replace(/^\||\|$/g, '').split('|').map(c => c.trim()); return line.replace(/^\|/, '').replace(/\|$/, '').split('|').map(c => c.trim()); }
// ========== Markdown + LaTeX 渲染 ========== function renderMarkdownWithMath(md) { if (!md) return '';
let processed = preprocessLuoguSyntax(md);
// 保护公式 // 1. 保护公式 const formulas = []; processed = processed.replace(/(\$\$[\s\S]*?\$\$|\$[^$]+\$)/g, (match) => { const id = formulas.length; formulas.push(match); return `⧙FORMULA${id}⧘`; });
// marked 解析 // 2. 保护行内代码 const codes = []; processed = processed.replace(/`([^`]+)`/g, (match) => { const id = codes.length; codes.push(match); return `⧙CODE${id}⧘`; });
// 3. 手动转换粗体(保留内部空格,不压缩) processed = processed.replace(/\*\*([\s\S]*?)\*\*/g, (_, c) => { const t = c.trim(); if (/^\d+(\.\d+)*\.?$/.test(t)) return t; return `<strong>${t}</strong>`; }); processed = processed.replace(/__([\s\S]*?)__/g, (_, c) => { const t = c.trim(); if (/^\d+(\.\d+)*\.?$/.test(t)) return t; return `<strong>${t}</strong>`; });
// 4. 手动转换斜体(保留内部空格) processed = processed.replace(/\*([^*\n]+?)\*/g, (_, c) => `<em>${c.trim()}</em>`); processed = processed.replace(/_([^_\n]+?)_/g, (_, c) => `<em>${c.trim()}</em>`);
// 5. 恢复行内代码 processed = processed.replace(/⧙CODE(\d+)⧘/g, (_, idx) => codes[parseInt(idx)]);
// 6. 将连续空格和制表符替换为 ,避免折叠导致错位 processed = processed.replace(/( {2,}|\t+)/g, (spaces) => ' '.repeat(spaces.length));
// 7. marked 解析块级元素 let html = marked.parse(processed);
// 8. 使用 DOMPurify 清理 HTML,防止 XSS html = DOMPurify.sanitize(html);
// 恢复公式并渲染 // 9. 恢复公式并渲染 html = html.replace(/⧙FORMULA(\d+)⧘/g, (_, idx) => { const formula = formulas[parseInt(idx)]; const isDisplay = formula.startsWith('$$'); const clean = isDisplay ? formula.slice(2, -2).trim() : formula.slice(1, -1).trim();13 行未改动 const html = renderMarkdownWithMath(md); const div = document.createElement('div'); div.innerHTML = html;
// 不再强制设置 text-indent,保持原始格式 // 对包含连续空格的段落保留空格(pre-wrap) div.querySelectorAll('p').forEach(p => { if (!p.style.textIndent) p.style.textIndent = '2em'; if (/\s{2,}/.test(p.textContent)) { p.style.whiteSpace = 'pre-wrap'; } });
// 处理 <!--tuack--> 标记 // 处理 tuack 表格 const walker = document.createTreeWalker(div, NodeFilter.SHOW_COMMENT); const comments = []; while (walker.nextNode()) comments.push(walker.currentNode); comments.forEach(comment => {16 行未改动 problemDiv.appendChild(div.firstChild); } }
// 添加各部分 // 插入背景 if (data.background) { insertContent(data.background); }
// 插入题目描述 insertContent(data.desc);
if (data.fmtIn) { problemDiv.appendChild(createH2('【输入格式】')); insertContent(data.fmtIn); } if (data.fmtOut) { problemDiv.appendChild(createH2('【输出格式】')); insertContent(data.fmtOut); }
// 样例 data.samples.forEach((s, i) => { problemDiv.appendChild(createH2('【样例 ' + (i+1) + '】')); const inp = document.createElement('p'); inp.textContent = '输入 #' + (i+1);31 行未改动 function applyStyles() { GM_addStyle(` @media (prefers-color-scheme: light) { body { background-color: #e6e6e6; } } @media (prefers-color-scheme: dark) { body { background-color: #333333; } #Problem-element { background: #f5f5f5; } } #Problem-element p { margin: 0.5em 0; text-indent: 2em; } #Problem-element p { margin: 0.5em 0; } /* 不再强制 text-indent */ #Problem-element strong { font-weight: bold; } #Problem-element em { font-style: italic; } #Problem-element h1, #Problem-element h2, #Problem-element h3, #Problem-element h4, #Problem-element h5, #Problem-element h6 { font-weight: normal; font-family: KaTeX_Main, SimHei, sans-serif;7 行未改动 #Problem-element a:hover { text-decoration: underline; } #Problem-element img { max-width: 100%; height: auto; } #Problem-element code { font-family: Consolas, monospace; background: #f0f0f0; padding: 2px 6px; border-radius: 3px; } #Problem-element pre { white-space: pre-wrap; background: #f8f8f8; border: 1px solid #ddd; padding: 10px; font-family: Consolas, monospace; font-size: 18px; } #Problem-element table { border-collapse: collapse; margin: 1em 0; width: auto; } #Problem-element th, #Problem-element td { border: 1px solid #ccc; padding: 6px 12px; text-align: center; } #Problem-element table { border-collapse: collapse; margin: 1em 0; width: auto; table-layout: auto; } #Problem-element th, #Problem-element td { border: 1px solid #ccc; padding: 6px 12px; text-align: center; vertical-align: middle; word-break: break-word; } #Problem-element th { background: #f2f2f2; } #Problem-element ::selection { background-color: #99c1da; mix-blend-mode: multiply; color: inherit; } #Custom-toolbar .tb-btn:hover { background: rgba(255,255,255,0.18) !important; color: white !important; } #Custom-toolbar .tb-submit:hover { background: #2980b9 !important; }
/* 洛谷自定义折叠框 */ #Problem-element details.luogu-fold { margin: 1em 0; border: 1px solid #e0e0e0; border-radius: 4px;6 行未改动 #Problem-element details.luogu-success { border-left: 4px solid #27ae60; } #Problem-element details.luogu-warning { border-left: 4px solid #f39c12; } #Problem-element details.luogu-error { border-left: 4px solid #e74c3c; }
/* 引言 */ #Problem-element blockquote.epigraph { margin: 1em 0; padding: 1em; background: #f5f5f5;6 行未改动 font-style: normal; font-weight: bold; }
/* 对齐 */ #Problem-element .align-center { text-align: center; } #Problem-element .align-right { text-align: right; }
@media (max-width: 768px) {9 行未改动 }})();```
*(本文脚本版本:v5.2,最后更新于 2026年7月)**(本文脚本版本:v5.2.5,最后更新于 2026 年 8 月)*
本文使用了大语言模型进行润色。本文使用了大语言模型进行润色,Deepseek 参与了脚本的编写。