Skip to content
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
db5a460
fix: preserve TeX and line breaks when copying contest Markdown
boomzero Oct 2, 2026
2174975
3.7.2
github-actions[bot] Oct 2, 2026
32945a4
Update version info to 3.7.2
github-actions[bot] Oct 2, 2026
ddad45a
Update time and description of 3.7.2
github-actions[bot] Oct 2, 2026
01e8c72
Update time and description of 3.7.2
github-actions[bot] Oct 2, 2026
29f2988
fix: address Markdown copy review feedback and automate browser tests
boomzero Oct 2, 2026
697e3e4
Update time and description of 3.7.2
github-actions[bot] Oct 2, 2026
9001a95
Update time and description of 3.7.2
github-actions[bot] Oct 2, 2026
58f4f59
feat: add titled section, sample and full problem Markdown copying
boomzero Oct 2, 2026
d1b0fd1
Update time and description of 3.7.2
github-actions[bot] Oct 2, 2026
097d9ed
Update time and description of 3.7.2
github-actions[bot] Oct 2, 2026
92c2766
fix: retain table cell formatting and portable test invocation
boomzero Oct 2, 2026
c7274c3
Update time and description of 3.7.2
github-actions[bot] Oct 2, 2026
bda3723
Update time and description of 3.7.2
github-actions[bot] Oct 2, 2026
61368be
fix: preserve wrapped samples and test language-aware copying
boomzero Oct 3, 2026
c4a4ed4
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
bef6b35
fix: add spacing before classic problem copy buttons
boomzero Oct 3, 2026
04b204b
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
4ddc11d
test: share the classic English statement expectation
boomzero Oct 3, 2026
bd5da91
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
e37be7b
fix: retain explanation code blocks and normalize prose whitespace
boomzero Oct 3, 2026
e14342c
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
ae1fcb3
fix: detect code language across pre and code classes
boomzero Oct 3, 2026
ff06d97
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
9dd0add
fix: preserve rendered tables in copied problem Markdown
boomzero Oct 3, 2026
998b795
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
e3cdc23
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
83b5852
fix: preserve links in copied header tables
boomzero Oct 3, 2026
6b6f425
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
461e353
Update time and description of 3.7.2
github-actions[bot] Oct 3, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/Test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm install --ignore-scripts
- run: npx playwright install --with-deps chromium
- run: npm test
11 changes: 11 additions & 0 deletions Update.json
Original file line number Diff line number Diff line change
Expand Up @@ -3791,6 +3791,17 @@
}
],
"Notes": "No release notes were provided for this release."
},
"3.7.2": {
"UpdateDate": 1791004704591,
"Prerelease": true,
"UpdateContents": [
{
"PR": 1031,
"Description": "fix: preserve problem Markdown and add full-statement copying"
}
],
"Notes": "No release notes were provided for this release."
}
}
}
263 changes: 219 additions & 44 deletions XMOJ.user.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// ==UserScript==
// @name XMOJ
// @version 3.7.1
// @version 3.7.2
// @description XMOJ增强脚本
// @author @XMOJ-Script-dev, @langningchen and the community
// @namespace https://github/langningchen
Expand Down Expand Up @@ -2653,13 +2653,7 @@ async function InitializeContestWebApp() {
}
// Sample boxes are cards, as on the legacy page.
for (const pre of root.querySelectorAll(".xmoj-problem-body .in-out pre")) pre.classList.add("card");
if (UtilityEnabled("CopyMD")) {
for (const section of root.querySelectorAll(".xmoj-problem-body .cnt-row")) {
const heading = section.querySelector(".cnt-row-head");
const body = section.querySelector(".cnt-row-body");
if (heading && body && !body.querySelector(".sampledata")) AddCopy(heading, "copy-section", () => GetMDText(body).trim());
}
}
if (UtilityEnabled("CopyMD")) InitializeProblemMarkdownCopy(root, root, AddCopy);
// Built from this page's API response rather than a cached copy.
if (UtilityEnabled("ProblemSwitcher") && Array.isArray(routeData?.problems) && !document.querySelector(`[${owned}="problem-switcher"]`)) {
const list = routeData.problems.map(item => ({title: item.problemTitle || item.title || item.num, url: new URL(GetContestProblemURL(route.cid, item.num), location.origin).href}));
Expand Down Expand Up @@ -3887,25 +3881,8 @@ async function main() {
return Response.text();
}).then((Response) => {
let ParsedDocument = new DOMParser().parseFromString(Response, "text/html");
let Temp = ParsedDocument.querySelectorAll(".cnt-row-body");
if (UtilityEnabled("DebugMode")) console.log(Temp);
for (let i = 0; i < Temp.length; i++) {
if (Temp[i].children[0].className === "content lang_cn") {
let CopyMDButton = document.createElement("button");
CopyMDButton.className = "btn btn-sm btn-outline-secondary copy-btn";
CopyMDButton.innerText = "复制";
CopyMDButton.style.marginLeft = "10px";
CopyMDButton.type = "button";
document.querySelectorAll(".cnt-row-head.title")[i].appendChild(CopyMDButton);
CopyMDButton.addEventListener("click", () => {
GM_setClipboard(GetMDText(Temp[i].children[0]).trim().replaceAll("\n\t", "\n").replaceAll("\n\n", "\n"));
CopyMDButton.innerText = "复制成功";
setTimeout(() => {
CopyMDButton.innerText = "复制";
}, 1000);
});
}
}
InitializeProblemMarkdownCopy(document.querySelector(".mt-3") || document,
ParsedDocument.querySelector(".jumbotron") || ParsedDocument);
});
}

Expand Down Expand Up @@ -7683,10 +7660,53 @@ function GetMDText(element) {
'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'
]);
const cellTags = new Set(['TD', 'TH']);
const mathItems = new Map();
const mathDocument = (typeof unsafeWindow === 'undefined' ? window : unsafeWindow).MathJax?.startup?.document;
// XMOJ also serves MathJax 3.0, before getMathItemsWithin was available.
const items = typeof mathDocument?.getMathItemsWithin === 'function' ?
mathDocument.getMathItemsWithin([element]) : mathDocument?.math || [];
for (const math of items) {
if (math.typesetRoot && element.contains(math.typesetRoot) && typeof math.math === 'string') {
mathItems.set(math.typesetRoot, math);
}
}

function AppendBreak(count) {
if (!result) return;
const trailing = result.match(/\n*$/)[0].length;
if (trailing < count) result += '\n'.repeat(count - trailing);
}

function AppendContent(content, cell) {
if (cell?.breakPending) {
AppendBreak(1);
cell.breakPending = false;
}
result += content;
}

function AppendMath(tex, display, inCell) {
// Keep a table cell on its row, including its trailing tab separator.
if (display && !inCell) AppendBreak(2);
AppendContent(display ? (inCell ? '$$' + tex + '$$' : '$$\n' + tex + '\n$$') : '$' + tex + '$', inCell);
if (display && !inCell) AppendBreak(2);
}

function traverse(node) {
function Traverse(node, inPre = false, inCell = false) {
if (node.nodeType === Node.TEXT_NODE) {
result += node.textContent;
// Serialized HTML often has indentation between blocks and cells.
// Keep inline spaces and all preformatted text.
const boundary = node => blockTags.has(node?.nodeName) || cellTags.has(node?.nodeName);
const before = boundary(node.previousSibling) || (boundary(node.parentElement) && !node.previousSibling);
const after = boundary(node.nextSibling) || (boundary(node.parentElement) && !node.nextSibling);
let text = node.textContent;
if (!inPre && /^[ \t\r\n]*$/.test(text) && (before || after)) return;
if (!inPre) {
text = text.replace(/[ \t\r\n]+/g, ' ');
if (before) text = text.replace(/^ +/, '');
if (after) text = text.replace(/ +$/, '');
}
AppendContent(text, inCell);
return;
}

Expand All @@ -7696,9 +7716,47 @@ function GetMDText(element) {

const tag = node.nodeName.toUpperCase();

if (tag === 'PRE' && !inPre) {
// Read literal code (including highlighted spans) without converting math
// or collapsing its indentation. BR is also used by older editors.
function ReadCode(child) {
if (child.nodeType === Node.TEXT_NODE) return child.textContent;
if (child.nodeName === 'BR') return '\n';
return [...child.childNodes].map(ReadCode).join('');
}
const code = ReadCode(node);
if (inCell) {
inCell.breakPending = true;
AppendContent(code, inCell);
inCell.breakPending = true;
} else {
const classes = node.querySelector('code')?.className || node.className;
Comment thread
boomzero marked this conversation as resolved.
Resolved
const language = classes.match(/(?:^|\s)(?:language|lang)-([\w+-]+)(?=\s|$)/)?.[1] || 'plain';
AppendBreak(2);
AppendContent(GetMarkdownCodeBlock(code, language));
AppendBreak(2);
}
return;
}

// Copy the source once, rather than the visual and accessibility trees.
const math = mathItems.get(node);
if (math) {
AppendMath(math.math, math.display, inCell);
return;
}
if (node.classList.contains('katex') || node.classList.contains('katex-display') || tag === 'MATH') {
const annotation = node.querySelector('annotation[encoding="application/x-tex"]');
if (annotation) {
AppendMath(annotation.textContent, node.classList.contains('katex-display') ||
node.parentElement?.classList.contains('katex-display') || node.getAttribute('display') === 'block', inCell);
return;
}
}

// Preserve line breaks for <br>
if (tag === 'BR') {
result += '\n';
AppendContent(inPre ? '\n' : ' \n', inCell);
return;
}

Expand All @@ -7712,40 +7770,157 @@ function GetMDText(element) {
} catch (e) {
// Fallback to the raw src if URL construction fails
}
result += `![](${resolvedSrc})`;
AppendContent(`![](${resolvedSrc})`, inCell);
}
return;
}

const isBlock = blockTags.has(tag);
const isCell = cellTags.has(tag);

if (isBlock && !result.endsWith('\n')) {
result += '\n';
const breaks = tag === 'TR' ? 1 : 2;

// Each cell has its own buffer. Defer block breaks until its next content
// so nested paragraphs separate without leading/trailing row breaks.
if (isCell) {
const previous = result;
result = '';
const cell = {breakPending: false};
for (const child of node.childNodes) Traverse(child, inPre, cell);
result = previous + result + '\t';
return;
}

// Keep table cells visually separated when copied as plain text.
if (isCell && result.length > 0 && !result.endsWith('\n') && !result.endsWith('\t') && !result.endsWith(' ')) {
result += '\t';
if (isBlock && !inPre) {
if (inCell) inCell.breakPending = true;
else AppendBreak(breaks);
}

for (let child of node.childNodes) {
traverse(child);
Traverse(child, inPre || tag === 'PRE', inCell);
}

if (isCell && !result.endsWith('\n') && !result.endsWith('\t')) {
result += '\t';
if (isBlock && !inPre) {
if (inCell) inCell.breakPending = true;
else AppendBreak(breaks);
}
}

if (isBlock && !result.endsWith('\n')) {
result += '\n';
Traverse(element);
return result;
}

function GetMarkdownCodeBlock(code, language = "plain") {
// A backtick run in the source must not terminate the copied code block.
const runs = [...code.matchAll(/`+/g)].map(match => match[0].length + 1);
const fence = "`".repeat(Math.max(3, ...runs));
return fence + language + "\n" + code + (code.endsWith("\n") ? "" : "\n") + fence;
}

// Use the displayed section labels, excluding copy controls and alternate languages.
function GetProblemCopyHeading(element, language = "zh") {
if (!element) return "";
const copy = element.cloneNode(true);
const otherLanguage = language === "en" ? ".lang_cn" : ".lang_en";
for (const node of copy.querySelectorAll("button, .copy-btn, [data-xmoj-script], " + otherLanguage)) node.remove();
return copy.textContent.replace(/\s+/g, " ").trim();
}

function GetProblemCopyLanguage(root) {
const english = root.querySelector(".content.lang_en");
return english?.isConnected && !english.closest("[hidden], .hidden, .d-none") &&
getComputedStyle(english).display !== "none" ? "en" : "zh";
}

function GetProblemSectionMarkdown(section, language = "zh") {
const heading = GetProblemCopyHeading(section.querySelector(".cnt-row-head"), language);
const body = section.querySelector(".cnt-row-body");
if (!heading || !body) return "";
let content;
if (body.querySelector(".sampledata, .data-sample, .in-out-item")) {
const parts = [];
const samples = [...body.querySelectorAll(".data-sample")];
const groups = samples.length ? samples : [...body.querySelectorAll(".in-out")];
function Visit(node) {
if (node.nodeType !== Node.ELEMENT_NODE ||
node.classList.contains(language === "en" ? "lang_cn" : "lang_en")) return;
if (node.classList.contains("in-out-item")) {
const sample = node.querySelector(".sampledata");
if (!sample || sample.textContent === "") return;
let label = GetProblemCopyHeading(node.querySelector(".title"), language);
const group = node.closest(samples.length ? ".data-sample" : ".in-out");
if (!/#\s*\d+/.test(label)) label += " #" + (Math.max(0, groups.indexOf(group)) + 1);
const code = sample.textContent;
parts.push("### " + label + "\n\n" + GetMarkdownCodeBlock(code));
return;
}
if (node.classList.contains("title")) {
const label = GetProblemCopyHeading(node, language);
if (label) parts.push("### " + label);
return;
}
// Legacy pages wrap the complete sample section in .content.
if (node.classList.contains("content") && !node.querySelector(".sampledata, .data-sample, .in-out-item")) {
const text = GetMDText(node).trim();
if (text) parts.push(text);
return;
}
for (const child of node.children) Visit(child);
}
for (const child of body.children) Visit(child);
content = parts.join("\n\n");
} else {
const translated = body.querySelector(language === "en" ? ".content.lang_en" : ".content.lang_cn");
const fallback = body.querySelector(".content.lang_cn") || body.querySelector(".content");
content = GetMDText(translated || fallback || body).trim();
}
return content ? "## " + heading + "\n\n" + content : "";
}

traverse(element);
return result;
function GetProblemStatementMarkdown(root, language = "zh") {
const title = root.querySelector(".xmoj-problem-head h2") ||
root.querySelector(language === "en" ? "h2.lang_en" : "h2.lang_cn") || root.querySelector("h2");
const name = GetProblemCopyHeading(title, language)
.replace(/^(?:(?:问题|Problem)\s+[^::]+|\d+)\s*[::]\s*/i, "");
const body = root.querySelector(".xmoj-problem-body") || root;
const sections = [...body.querySelectorAll(".cnt-row")]
.map(section => GetProblemSectionMarkdown(section, language)).filter(Boolean);
return (name ? ["# " + name, ...sections] : sections).join("\n\n");
}

function InitializeProblemMarkdownCopy(root, sourceRoot = root, addCopy = null) {
if (!addCopy) addCopy = (parent, name, readText) => {
if (parent.querySelector('[data-xmoj-script="' + name + '"]')) return;
const button = document.createElement("button");
button.type = "button";
button.className = "btn btn-sm btn-outline-secondary copy-btn";
button.style.marginLeft = "10px";
button.setAttribute("data-xmoj-script", name);
button.textContent = "复制";
button.addEventListener("click", () => {
GM_setClipboard(readText());
button.textContent = "复制成功";
setTimeout(() => { button.textContent = "复制"; }, 1000);
});
parent.appendChild(button);
};
const titles = [...root.querySelectorAll(".xmoj-problem-head h2, h2.lang_cn, h2.lang_en")];
if (!titles.length && root.querySelector("h2")) titles.push(root.querySelector("h2"));
for (const title of titles) {
addCopy(title, "copy-problem", () => GetProblemStatementMarkdown(sourceRoot, GetProblemCopyLanguage(root)));
}
const body = root.querySelector(".xmoj-problem-body") || root;
const sourceBody = sourceRoot.querySelector(".xmoj-problem-body") || sourceRoot;
const sourceSections = [...sourceBody.querySelectorAll(".cnt-row")];
for (const [index, section] of [...body.querySelectorAll(".cnt-row")].entries()) {
const heading = section.querySelector(".cnt-row-head");
if (heading && section.querySelector(".cnt-row-body")) {
addCopy(heading, "copy-section", () =>
GetProblemSectionMarkdown(sourceSections[index] || section, GetProblemCopyLanguage(root)));
}
}
}


function InitializeImageEnlarger() {
// Image Enlargement Feature
if (UtilityEnabled("ImageEnlarger")) {
Expand Down
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
{
"name": "xmoj-script",
"version": "3.7.1",
"version": "3.7.2",
"description": "an improvement script for xmoj.tech",
"main": "AddonScript.js",
"scripts": {
"test": "node --test tests/contest-web.test.cjs"
"test": "node --test tests/contest-web.test.cjs tests/markdown-copy.test.cjs"
},
"devDependencies": {
"playwright": "1.59.1"
},
"repository": {
"type": "git",
Expand Down
Loading
Loading