版本比较
插件集合、常用软件
标题
增加 1 行删除 1 行
11插件集合插件集合、常用软件正文
增加 5 行删除 645 行
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464512345::::info[可以复制 oj 题目源码的插件]```// ==UserScript==// @name OJ 题目 Markdown / LaTeX 源码复制助手// @namespace oj-copy-helper// @version 1.1.0// @description 在 oj.gxyzh.com 题目页一键复制题目 Markdown / LaTeX 源码,自动还原 KaTeX / MathJax 公式为 LaTeX,自动过滤 Copy 按钮等杂质// @author GX6zm// @match http*://oj.gxyzh.com/*// @grant GM_setClipboard// @grant GM_getValue// @grant GM_setValue// @run-at document-idle// @noframes// @license MIT// ==/UserScript==
(function () { 'use strict'; if (window.top !== window.self) return;
/* ================= 常量与状态 ================= */ const CONTENT_SELECTORS = [ '[data-fragment-id="problem-content"]', // Hydro '.typo', // Hydro / typo.css '.problem-content', '#problem-content', '.ui.problem.detail', // SYZOJ '#problem_content', '.problem_content', // HUSTOJ 等 '#problembody', '.problembody', '#problem-body', '.problem-body', '.problem-detail', '.problem_detail', '#problemDetail', '.problemDetail', '.statement', '.problem-statement', '#statement', '#problem-description', '.problem-description', '#problem_text', '.problem_text', '.problemText', '.markdown-body', '#problem', '.problem', 'article', 'main', ]; const PUA_L = '\uE000', PUA_R = '\uE001'; // 公式占位符定界符 const BLOCK_TAGS = new Set(['ADDRESS','BLOCKQUOTE','CENTER','DIV','DL','FIELDSET','FIGURE', 'FOOTER','FORM','H1','H2','H3','H4','H5','H6','HEADER','HR','OL','P','PRE','SAMP', 'SECTION','TABLE','UL']);
let mathStore = []; // 每次提取时重建 let manualRoot = null;
/* ================= 小工具 ================= */ const $all = (sel, root) => Array.from((root || document).querySelectorAll(sel)); const byId = id => document.getElementById(id); const escCss = s => (window.CSS && CSS.escape) ? CSS.escape(s) : String(s).replace(/[^a-zA-Z0-9_-]/g, c => '\\' + c); const hasBlockChild = node => Array.from(node.children).some(c => BLOCK_TAGS.has(c.tagName));
function absUrl(u) { if (!u) return ''; try { return new URL(u, location.href).href; } catch (e) { return u; } } function cleanInline(s) { return String(s).replace(/[\r\n\t]+/g, ' ').replace(/ {2,}/g, ' '); }
function* allDocs() { yield document; for (const f of $all('iframe')) { try { if (f.contentDocument) yield f.contentDocument; } catch (e) { /* 跨域忽略 */ } } }
async function copyText(text) { if (typeof GM_setClipboard === 'function') { GM_setClipboard(text, 'text/plain'); return; } try { await navigator.clipboard.writeText(text); return; } catch (e) { /* 继续兜底 */ } const ta = document.createElement('textarea'); ta.value = text; ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0'; document.body.appendChild(ta); ta.select(); let ok = false; try { ok = document.execCommand('copy'); } catch (e) {} ta.remove(); if (!ok) throw new Error('浏览器禁止写剪贴板'); }
/* ================= 内容区域检测 ================= */ function getContentRoot() { if (manualRoot && manualRoot.isConnected) return manualRoot; let saved = ''; try { saved = GM_getValue('ojcp_selector', ''); } catch (e) {} if (saved) { for (const d of allDocs()) { let el = null; try { el = d.querySelector(saved); } catch (e) {} if (el && (el.innerText || '').trim().length > 30) return el; } } for (const d of allDocs()) { for (const s of CONTENT_SELECTORS) { let el = null; try { el = d.querySelector(s); } catch (e) {} if (el && (el.innerText || '').trim().length > 40) return el; } } return heuristicRoot(); }
function heuristicRoot() { let best = null, score = -1; document.querySelectorAll('div,section,article,main,td').forEach(el => { if (el.closest && el.closest('#ojcopy-panel')) return; const txt = (el.innerText || '').trim(); if (txt.length < 120) return; let s = Math.min(txt.length, 4000); s += el.querySelectorAll('pre,samp').length * 120; s += el.querySelectorAll('.katex,mjx-container,script[type^="math/tex"],math').length * 80; s += el.querySelectorAll('h1,h2,h3').length * 30; if (el.tagName === 'BODY') s -= 2000; if (s > score) { score = s; best = el; } }); return best || document.body; }
function findTitle(root) { const sels = ['#problem_title', '#problemTitle', '.problem-title', '.problem__title', '.problem_title']; for (const d of allDocs()) for (const s of sels) { let el = null; try { el = d.querySelector(s); } catch (e) {} if (el) { const t = (el.textContent || '').trim(); if (t && t.length < 120) return t; } } const inRoot = root && root.querySelector && root.querySelector('h1,h2'); if (inRoot) { const t = inRoot.textContent.trim(); if (t && t.length < 120) return t; } const h1 = document.querySelector('h1'); if (h1) { const t = h1.textContent.trim(); if (t && t.length < 120) return t; } return (document.title || '题目').split(/\s*[-|_|–—]\s*/)[0].trim(); }
/* ================= 公式提取(还原 LaTeX) ================= */ function prepare(root) { mathStore = []; const clone = root.cloneNode(true); harvestMath(clone); $all('script,style,noscript,button,select,input,textarea,iframe,svg,nav,form', clone).forEach(e => e.remove()); $all('.MathJax_Preview,mjx-assistive-mml,.copy,.copy-button,.copy-btn,.btn-copy,[data-clipboard-target],[data-copy],[hidden],.no-print', clone) .forEach(e => e.remove()); // 删掉 href="javascript:..." 且文字是 Copy/复制 的伪链接(样例复制按钮) $all('a[href^="javascript:"]', clone).forEach(el => { const t = (el.textContent || '').trim(); if (!t || /^(copy|复制|拷贝)/i.test(t)) el.remove(); }); // 兜底:任何内容只有 "Copy/复制" 字样的小元素一律删除 $all('a,span,i,b,em,strong,label,div', clone).forEach(el => { if (el.children.length === 0 && /^(copy|复制|拷贝)$/i.test((el.textContent || '').trim())) { el.remove(); } }); return clone; }
function harvestMath(clone) { const add = (tex, display) => { mathStore.push({ tex: String(tex || '').trim(), display: !!display }); return PUA_L + (mathStore.length - 1) + PUA_R; }; // 1) KaTeX $all('.katex', clone).forEach(el => { const ann = el.querySelector('annotation[encoding="application/x-tex"]'); const tex = ann ? ann.textContent : ((el.querySelector('.katex-mathml') || {}).textContent || '公式'); const display = !!el.closest('.katex-display'); el.replaceWith(document.createTextNode(add(tex, display))); }); // 2) MathJax v2 原始 script $all('script[type^="math/tex"]', clone).forEach(el => { const display = /mode\s*=\s*display/.test(el.getAttribute('type') || ''); el.replaceWith(document.createTextNode(add(el.textContent, display))); }); // 3) MathJax v3 容器 $all('mjx-container', clone).forEach(el => { let tex = el.getAttribute('aria-label') || ''; if (!tex) { const ann = el.querySelector('annotation[encoding="application/x-tex"]'); tex = ann ? ann.textContent : ''; } if (!tex) { el.replaceWith(document.createTextNode('[公式]')); return; } const display = el.hasAttribute('display'); el.replaceWith(document.createTextNode(add(tex, display))); }); // 4) MathJax v2 渲染结果(若含 annotation) $all('.MathJax', clone).forEach(el => { const ann = el.querySelector('annotation[encoding="application/x-tex"]'); el.replaceWith(document.createTextNode(ann ? add(ann.textContent, false) : '[公式]')); }); // 5) 裸 MathML $all('math', clone).forEach(el => { const ann = el.querySelector('annotation[encoding="application/x-tex"]'); const display = el.getAttribute('display') === 'block'; el.replaceWith(document.createTextNode(ann ? add(ann.textContent, display) : '[公式]')); }); }
function restoreMath(str) { return str.replace(new RegExp(PUA_L + '(\\d+)' + PUA_R, 'g'), (m, i) => { const it = mathStore[+i]; if (!it) return ''; return it.display ? '\n\n$$\n' + it.tex + '\n$$\n\n' : '$' + it.tex + '$'; }); }
/* ================= Markdown 转换 ================= */ function mdFence(text) { let t = String(text).replace(/\s+$/, '').replace(/^\n+/, ''); let f = '```'; const m = t.match(/`{3,}/g); if (m) f = '`'.repeat(Math.max.apply(null, m.map(x => x.length)) + 1); return '\n\n' + f + '\n' + t + '\n' + f + '\n\n'; }
function mdChildren(node) { return Array.from(node.childNodes).map(mdBlock).join(''); } function mdInlineAll(node) { return Array.from(node.childNodes).map(mdInline).join(''); }
function mdBlock(node) { if (node.nodeType === Node.TEXT_NODE) return cleanInline(node.nodeValue); if (node.nodeType !== Node.ELEMENT_NODE) return ''; const tag = node.tagName; if (/^H[1-6]$/.test(tag)) { return '\n\n' + '#'.repeat(+tag[1]) + ' ' + mdInlineAll(node).trim() + '\n\n'; } switch (tag) { case 'BR': return '\n'; case 'HR': return '\n\n---\n\n'; case 'P': return '\n\n' + mdInlineAll(node).trim() + '\n\n'; case 'PRE': case 'SAMP': return mdFence(node.textContent); case 'UL': return '\n\n' + mdList(node, false, 0) + '\n\n'; case 'OL': return '\n\n' + mdList(node, true, 0) + '\n\n'; case 'TABLE': return mdTable(node); case 'BLOCKQUOTE': { const inner = mdChildren(node).trim().split('\n').map(l => '> ' + l).join('\n'); return '\n\n' + inner + '\n\n'; } default: { if (hasBlockChild(node)) return mdChildren(node); const t = mdInlineAll(node).trim(); return t ? '\n\n' + t + '\n\n' : ''; } } }
function mdInline(node) { if (node.nodeType === Node.TEXT_NODE) return cleanInline(node.nodeValue); if (node.nodeType !== Node.ELEMENT_NODE) return ''; const tag = node.tagName; switch (tag) { case 'BR': return ' \n'; case 'STRONG': case 'B': { const t = mdInlineAll(node).trim(); return t ? '**' + t + '**' : ''; } case 'EM': case 'I': { const t = mdInlineAll(node).trim(); return t ? '*' + t + '*' : ''; } case 'DEL': case 'S': { const t = mdInlineAll(node).trim(); return t ? '~~' + t + '~~' : ''; } case 'CODE': return '`' + node.textContent.replace(/`/g, "'") + '`'; case 'A': { const href = node.getAttribute('href') || ''; const t = mdInlineAll(node).trim(); if (/^\s*javascript\s*:/i.test(href)) return t; // JS 伪链接(Copy 按钮等)不当链接处理 if (!href || href.charAt(0) === '#') return t; return '[' + (t || href) + '](' + absUrl(href) + ')'; } case 'IMG': { const src = absUrl(node.getAttribute('src') || ''); return src ? '' : ''; } case 'SUP': return '<sup>' + mdInlineAll(node) + '</sup>'; case 'SUB': return '<sub>' + mdInlineAll(node) + '</sub>'; case 'PRE': case 'SAMP': case 'TABLE': case 'UL': case 'OL': return mdBlock(node); default: { if (hasBlockChild(node)) return mdChildren(node); return mdInlineAll(node); } } }
function mdList(list, ordered, depth) { const lines = []; let idx = 1; for (const li of Array.from(list.children)) { if (li.tagName !== 'LI') continue; const marker = ordered ? (idx++) + '. ' : '- '; let inline = ''; const subs = []; for (const ch of Array.from(li.childNodes)) { if (ch.nodeType === Node.ELEMENT_NODE && (ch.tagName === 'UL' || ch.tagName === 'OL')) { subs.push(mdList(ch, ch.tagName === 'OL', depth + 1)); } else inline += mdBlock(ch); } const text = inline.replace(/\s*\n\s*/g, ' ').trim(); lines.push(' '.repeat(depth) + marker + text); for (const s of subs) if (s.trim()) lines.push(s); } return lines.join('\n'); }
function mdTable(table) { const trs = Array.from(table.querySelectorAll('tr')); if (!trs.length) return ''; const cells = tr => Array.from(tr.children).filter(c => c.tagName === 'TD' || c.tagName === 'TH'); const hasBlockContent = trs.some(tr => cells(tr).some(c => c.querySelector('pre,samp,ul,ol,table,h1,h2,h3,h4,h5,h6'))); if (hasBlockContent) { // 含块级内容(如样例表格)时平铺输出 let out = ''; trs.forEach(tr => cells(tr).forEach(c => { out += mdChildren(c); })); return out; } const rows = trs.map(tr => cells(tr).map(c => mdInlineAll(c).replace(/\|/g, '\\|').replace(/\s*\n\s*/g, ' ').trim())); const cols = Math.max.apply(null, rows.map(r => r.length)); rows.forEach(r => { while (r.length < cols) r.push(''); }); const head = rows.shift(); let out = '\n\n| ' + head.join(' | ') + ' |\n'; out += '|' + head.map(() => ' --- |').join('') + '\n'; rows.forEach(r => { out += '| ' + r.join(' | ') + ' |\n'; }); return out + '\n'; }
/* ================= LaTeX 转换 ================= */ const TEX_SECTION = ['section', 'subsection', 'subsubsection', 'paragraph', 'subparagraph', 'subparagraph'];
function texEscape(s) { const map = { '\\': '\\textbackslash{}', '&': '\\&', '%': '\\%', '$': '\\$', '#': '\\#', '_': '\\_', '{': '\\{', '}': '\\}', '~': '\\textasciitilde{}', '^': '\\textasciicircum{}' }; return String(s).replace(/[\\&%$#_{}~^]/g, ch => map[ch]); }
function texChildren(node) { return Array.from(node.childNodes).map(texBlock).join(''); } function texInlineAll(node) { return Array.from(node.childNodes).map(texInline).join(''); }
function texBlock(node) { if (node.nodeType === Node.TEXT_NODE) return texEscape(cleanInline(node.nodeValue)); if (node.nodeType !== Node.ELEMENT_NODE) return ''; const tag = node.tagName; if (/^H[1-6]$/.test(tag)) { const t = texInlineAll(node).trim(); return t ? '\n\n\\' + TEX_SECTION[+tag[1] - 1] + '*{' + t + '}\n\n' : ''; } switch (tag) { case 'BR': return '\n'; case 'HR': return '\n\n\\noindent\\rule{\\linewidth}{0.4pt}\n\n'; case 'P': return '\n\n' + texInlineAll(node).trim() + '\n\n'; case 'PRE': case 'SAMP': { const t = String(node.textContent).replace(/\s+$/, ''); return '\n\n\\begin{verbatim}\n' + t + '\n\\end{verbatim}\n\n'; } case 'UL': case 'OL': return '\n\n' + texList(node, tag === 'OL') + '\n\n'; case 'TABLE': return texTable(node); case 'BLOCKQUOTE': return '\n\n\\begin{quote}\n' + texChildren(node).trim() + '\n\\end{quote}\n\n'; default: { if (hasBlockChild(node)) return texChildren(node); const t = texInlineAll(node).trim(); return t ? '\n\n' + t + '\n\n' : ''; } } }
function texInline(node) { if (node.nodeType === Node.TEXT_NODE) return texEscape(cleanInline(node.nodeValue)); if (node.nodeType !== Node.ELEMENT_NODE) return ''; const tag = node.tagName; switch (tag) { case 'BR': return '\\\\\n'; case 'STRONG': case 'B': { const t = texInlineAll(node).trim(); return t ? '\\textbf{' + t + '}' : ''; } case 'EM': case 'I': { const t = texInlineAll(node).trim(); return t ? '\\textit{' + t + '}' : ''; } case 'DEL': case 'S': return texInlineAll(node).trim(); case 'CODE': return '\\texttt{' + texEscape(node.textContent) + '}'; case 'A': { const href = node.getAttribute('href') || ''; const t = texInlineAll(node).trim(); if (/^\s*javascript\s*:/i.test(href)) return t; // JS 伪链接(Copy 按钮等)不当链接处理 if (!href || href.charAt(0) === '#') return t; const u = absUrl(href).replace(/%/g, '\\%').replace(/#/g, '\\#'); return '\\href{' + u + '}{' + (t || u) + '}'; } case 'IMG': { const src = absUrl(node.getAttribute('src') || ''); return src ? '\n% [图片] ' + src + '\n' : ''; } case 'SUP': { const t = texInlineAll(node); return t ? '\\textsuperscript{' + t + '}' : ''; } case 'SUB': { const t = texInlineAll(node); return t ? '\\textsubscript{' + t + '}' : ''; } case 'PRE': case 'SAMP': case 'UL': case 'OL': case 'TABLE': return texBlock(node); default: { if (hasBlockChild(node)) return texChildren(node); return texInlineAll(node); } } }
function texList(list, ordered) { const env = ordered ? 'enumerate' : 'itemize'; let out = '\\begin{' + env + '}\n'; for (const li of Array.from(list.children)) { if (li.tagName !== 'LI') continue; let inline = ''; const subs = []; for (const ch of Array.from(li.childNodes)) { if (ch.nodeType === Node.ELEMENT_NODE && (ch.tagName === 'UL' || ch.tagName === 'OL')) { subs.push(texList(ch, ch.tagName === 'OL')); } else inline += texBlock(ch); } out += '\\item ' + inline.replace(/\s*\n\s*/g, ' ').trim() + '\n'; subs.forEach(s => { out += s; }); } return out + '\\end{' + env + '}\n'; }
function texTable(table) { const trs = Array.from(table.querySelectorAll('tr')); if (!trs.length) return ''; const cells = tr => Array.from(tr.children).filter(c => c.tagName === 'TD' || c.tagName === 'TH'); const hasBlockContent = trs.some(tr => cells(tr).some(c => c.querySelector('pre,samp,ul,ol,table,h1,h2,h3,h4,h5,h6'))); if (hasBlockContent) { let out = ''; trs.forEach(tr => cells(tr).forEach(c => { out += texChildren(c); })); return out; } const rows = trs.map(tr => cells(tr).map(c => texInlineAll(c).replace(/\s*\n\s*/g, ' ').trim())); const cols = Math.max.apply(null, rows.map(r => r.length)); rows.forEach(r => { while (r.length < cols) r.push(''); }); let out = '\n\n\\begin{center}\n\\begin{tabular}{' + Array(cols).fill('|l').join('') + '|}\n\\hline\n'; rows.forEach(r => { out += r.join(' & ') + ' \\\\\n\\hline\n'; }); return out + '\\end{tabular}\n\\end{center}\n\n'; }
/* ================= 构建输出 ================= */ function postProcess(s) { return s.replace(/\r/g, '').replace(/[ \t]+\n/g, '\n') .replace(/([^\n])\n(?=#+ )/g, '$1\n\n') .replace(/\n{3,}/g, '\n\n').trim(); }
function buildMarkdown() { const root = getContentRoot(); const clone = prepare(root); let md = restoreMath(postProcess(mdChildren(clone))); const title = findTitle(root); let head = ''; if (!/^#{1,3}\s/.test(md)) head += '# ' + title + '\n\n'; head += '> 来源: ' + location.href + '\n\n'; return head + md + '\n'; }
function buildLatex() { const root = getContentRoot(); const clone = prepare(root); let tex = restoreMath(postProcess(texChildren(clone))); const title = findTitle(root); let head = '% 题目: ' + title + '\n' + '% 来源: ' + location.href + '\n' + '% 公式已还原为 LaTeX;中文需 ctex 宏包,\\href 需 hyperref。\n\n'; if (!/^\\(section|subsection|subsubsection)/.test(tex.trim())) { head += '\\section*{' + texEscape(title) + '}\n\n'; } return head + tex + '\n'; }
/* ================= UI ================= */ function injectStyle() { const st = document.createElement('style'); st.textContent = [ '#ojcopy-panel{position:fixed;right:16px;bottom:16px;z-index:2147483647;width:200px;background:#20242e;color:#e8e8e8;border-radius:10px;box-shadow:0 6px 24px rgba(0,0,0,.35);font:12px/1.6 "Microsoft YaHei",system-ui,sans-serif;user-select:none}', '#ojcopy-panel .hd{display:flex;justify-content:space-between;align-items:center;padding:7px 10px;background:#2b3040;border-radius:10px 10px 0 0;cursor:move;font-weight:bold}', '#ojcopy-panel .hd .tog{cursor:pointer;padding:0 4px;color:#9aa0b0}', '#ojcopy-panel .bd{padding:10px;display:flex;flex-direction:column;gap:7px}', '#ojcopy-panel.collapsed .bd{display:none}', '#ojcopy-panel.collapsed{width:auto}', '#ojcopy-panel .info{color:#8f96a8;word-break:break-all}', '#ojcopy-panel .btn{border:0;border-radius:6px;padding:7px 10px;background:#3d7bfd;color:#fff;cursor:pointer;font-size:12px}', '#ojcopy-panel .btn:hover{background:#5b8ffd}', '#ojcopy-panel .btn.alt{background:#2f3542}', '#ojcopy-panel .btn.alt:hover{background:#3a4152}', '#ojcopy-panel .row{display:flex;gap:6px}', '#ojcopy-panel .row .btn{flex:1}', '.ojcp-hover{outline:3px solid #ff9f43!important;outline-offset:2px;cursor:crosshair}', '#ojcp-toast{position:fixed;top:18px;left:50%;transform:translateX(-50%);z-index:2147483647;background:#2ecc71;color:#fff;padding:8px 16px;border-radius:8px;font:13px/1.5 "Microsoft YaHei",sans-serif;opacity:0;pointer-events:none;transition:opacity .25s;box-shadow:0 4px 14px rgba(0,0,0,.25)}', '#ojcp-toast.show{opacity:.96}', '#ojcp-toast.err{background:#e74c3c}', ].join('\n'); document.head.appendChild(st); }
let toastTimer = null; function toast(msg, type) { let t = byId('ojcp-toast'); if (!t) { t = document.createElement('div'); t.id = 'ojcp-toast'; document.body.appendChild(t); } t.textContent = msg; t.className = 'show' + (type === 'err' ? ' err' : ''); clearTimeout(toastTimer); toastTimer = setTimeout(() => { t.className = ''; }, 2400); }
function describe(el) { if (!el) return '未找到'; let s = el.tagName.toLowerCase(); if (el.id) s += '#' + el.id; else if (el.classList && el.classList.length) s += '.' + Array.from(el.classList).slice(0, 2).join('.'); return s; }
function updateInfo() { const el = byId('ojcp-info'); if (!el) return; try { el.textContent = '当前区域:' + describe(getContentRoot()); } catch (e) { el.textContent = '检测失败'; } }
function cssPath(el) { if (el.id) return '#' + escCss(el.id); const parts = []; let cur = el; while (cur && cur.nodeType === Node.ELEMENT_NODE && parts.length < 4 && cur.tagName !== 'HTML') { let sel = cur.tagName.toLowerCase(); if (cur.id) { parts.unshift('#' + escCss(cur.id)); break; } if (cur.classList && cur.classList.length) sel += '.' + Array.from(cur.classList).slice(0, 2).map(escCss).join('.'); const parent = cur.parentElement; if (parent) { const same = Array.from(parent.children).filter(c => c.tagName === cur.tagName); if (same.length > 1) sel += ':nth-of-type(' + (same.indexOf(cur) + 1) + ')'; } parts.unshift(sel); cur = parent; } return parts.join(' > '); }
/* ---- 手动框选 ---- */ let picking = false, pickEl = null; function startPicker() { if (picking) return; picking = true; toast('🎯 移动鼠标到题目区域,点击确认;Esc 取消'); document.addEventListener('mousemove', onPickMove, true); document.addEventListener('mousedown', onPickDown, true); document.addEventListener('click', swallow, true); document.addEventListener('keydown', onPickKey, true); } function stopPicker() { picking = false; if (pickEl) { pickEl.classList.remove('ojcp-hover'); pickEl = null; } document.removeEventListener('mousemove', onPickMove, true); document.removeEventListener('mousedown', onPickDown, true); document.removeEventListener('click', swallow, true); document.removeEventListener('keydown', onPickKey, true); } function swallow(e) { if (picking) { e.preventDefault(); e.stopPropagation(); } } function onPickMove(e) { if (!picking) return; const panel = byId('ojcopy-panel'); const t = e.target; if (!t || (panel && panel.contains(t))) return; if (pickEl) pickEl.classList.remove('ojcp-hover'); pickEl = t.nodeType === Node.ELEMENT_NODE ? t : t.parentElement; if (pickEl) pickEl.classList.add('ojcp-hover'); } function onPickDown(e) { if (!picking) return; e.preventDefault(); e.stopPropagation(); const t = pickEl || e.target; stopPicker(); if (!t || t.nodeType !== Node.ELEMENT_NODE) return; manualRoot = t; try { GM_setValue('ojcp_selector', cssPath(t)); } catch (err) {} updateInfo(); toast('✅ 已记住该区域:' + describe(t)); } function onPickKey(e) { if (e.key === 'Escape') { stopPicker(); toast('已取消框选'); } }
/* ---- 面板 ---- */ async function copyMd() { try { const md = buildMarkdown(); await copyText(md); updateInfo(); toast('✅ 已复制 Markdown,共 ' + md.length + ' 字符'); } catch (e) { toast('❌ 失败:' + e.message, 'err'); } } async function copyTex() { try { const t = buildLatex(); await copyText(t); updateInfo(); toast('✅ 已复制 LaTeX,共 ' + t.length + ' 字符'); } catch (e) { toast('❌ 失败:' + e.message, 'err'); } }
function buildUI() { const panel = document.createElement('div'); panel.id = 'ojcopy-panel'; panel.innerHTML = [ '<div class="hd"><span>📋 题目复制助手</span><span class="tog" id="ojcp-tog">—</span></div>', '<div class="bd">', ' <div class="info" id="ojcp-info">未检测</div>', ' <button class="btn" id="ojcp-md">复制 Markdown</button>', ' <button class="btn alt" id="ojcp-tex">复制 LaTeX</button>', ' <div class="row">', ' <button class="btn alt" id="ojcp-dl">下载 .md</button>', ' <button class="btn alt" id="ojcp-auto">重新检测</button>', ' </div>', ' <button class="btn alt" id="ojcp-pick">🎯 手动框选区域</button>', '</div>', ].join(''); document.body.appendChild(panel);
byId('ojcp-md').addEventListener('click', copyMd); byId('ojcp-tex').addEventListener('click', copyTex); byId('ojcp-dl').addEventListener('click', () => { try { const md = buildMarkdown(); const name = (findTitle().replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 60) || 'problem') + '.md'; const blob = new Blob([md], { type: 'text/markdown;charset=utf-8' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); toast('✅ 已开始下载 ' + name); } catch (e) { toast('❌ 失败:' + e.message, 'err'); } }); byId('ojcp-auto').addEventListener('click', () => { manualRoot = null; try { GM_setValue('ojcp_selector', ''); } catch (e) {} updateInfo(); toast('已清除记忆并重新检测'); }); byId('ojcp-pick').addEventListener('click', startPicker); byId('ojcp-tog').addEventListener('click', () => { panel.classList.toggle('collapsed'); byId('ojcp-tog').textContent = panel.classList.contains('collapsed') ? '+' : '—'; });
// 拖动 const hd = panel.querySelector('.hd'); let drag = null; hd.addEventListener('mousedown', e => { if (e.target.id === 'ojcp-tog') return; const r = panel.getBoundingClientRect(); drag = { dx: e.clientX - r.left, dy: e.clientY - r.top }; e.preventDefault(); }); window.addEventListener('mousemove', e => { if (!drag) return; let x = Math.max(0, Math.min(window.innerWidth - panel.offsetWidth, e.clientX - drag.dx)); let y = Math.max(0, Math.min(window.innerHeight - panel.offsetHeight, e.clientY - drag.dy)); panel.style.left = x + 'px'; panel.style.top = y + 'px'; panel.style.right = 'auto'; panel.style.bottom = 'auto'; }); window.addEventListener('mouseup', () => { drag = null; });
// 快捷键:Alt+M 复制 Markdown,Alt+L 复制 LaTeX window.addEventListener('keydown', e => { if (e.altKey && !e.ctrlKey && !e.metaKey && !picking) { if (e.code === 'KeyM') { e.preventDefault(); copyMd(); } else if (e.code === 'KeyL') { e.preventDefault(); copyTex(); } } });
updateInfo(); }
function init() { injectStyle(); buildUI(); } if (document.body) init(); else document.addEventListener('DOMContentLoaded', init);})();```::::- [**Github汉化**](https://github.com/maboloshi/github-chinese/blob/gh-pages/main.user.js) - [洛谷屏蔽讨论与题解(保留犇犇)](https://github.com/GX6zm/luogu-blocker/blob/main/luogu-blocker.user.js)- [**洛谷emoji**](https://raw.githubusercontent.com/Kldxst/Luogu-Emoji/main/luogu-emoji.user.js) - [**篡改猴**](https://microsoftedge.microsoft.com/addons/detail/%E7%AF%A1%E6%94%B9%E7%8C%B4/iikmkjmpaadaobahmlepeloendndfphd?hl=zh-CN)- [**Edge new tab changer**](https://microsoftedge.microsoft.com/addons/detail/new-tab-changer/dlbnebcbaeajdpekcdhmcgdhoodcjpeg)