-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpycon_copy.js
More file actions
193 lines (168 loc) · 6.29 KB
/
pycon_copy.js
File metadata and controls
193 lines (168 loc) · 6.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/**
* Custom copy handler for Python console (pycon) code blocks.
* Strips >>> and ... prompts when copying code examples.
*/
document.addEventListener("DOMContentLoaded", function () {
const COPY_BUTTON_SELECTOR = ".md-clipboard, .md-code__button";
function handleCopyButtonClick(event) {
const copyButton = event.target.closest(COPY_BUTTON_SELECTOR);
if (!copyButton) return;
const codeBlock = findCodeBlockForCopyButton(copyButton);
if (!codeBlock) return;
const rawText = codeBlock.textContent || "";
if (!shouldStripPrompts(codeBlock, rawText)) return;
const strippedText = stripPythonPrompts(rawText);
primeClipboardButton(copyButton, strippedText);
}
function handleCopyButtonPointerDown(event) {
const copyButton = event.target.closest(COPY_BUTTON_SELECTOR);
if (!copyButton) return;
const codeBlock = findCodeBlockForCopyButton(copyButton);
if (!codeBlock) return;
const rawText = codeBlock.textContent || "";
if (!shouldStripPrompts(codeBlock, rawText)) return;
const strippedText = stripPythonPrompts(rawText);
primeClipboardButton(copyButton, strippedText);
}
function handleSelectionCopy(event) {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return;
const range = selection.getRangeAt(0);
const anchorNode = range.commonAncestorContainer;
const codeBlock =
anchorNode.nodeType === Node.ELEMENT_NODE
? anchorNode.closest("code")
: anchorNode.parentElement?.closest("code");
if (!codeBlock) return;
const rawText = selection.toString();
if (!shouldStripPrompts(codeBlock, rawText)) return;
event.preventDefault();
event.stopPropagation();
const strippedText = stripPythonPrompts(rawText);
event.clipboardData?.setData("text/plain", strippedText);
}
function bindCopyButtons(root) {
root.querySelectorAll(COPY_BUTTON_SELECTOR).forEach((button) => {
button.removeEventListener("click", handleCopyButtonClick, true);
button.addEventListener("click", handleCopyButtonClick, true);
button.removeEventListener(
"pointerdown",
handleCopyButtonPointerDown,
true
);
button.addEventListener(
"pointerdown",
handleCopyButtonPointerDown,
true
);
});
}
function observeDynamicCopyButtons() {
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type !== "childList") continue;
mutation.addedNodes.forEach((node) => {
if (node.nodeType !== Node.ELEMENT_NODE) return;
if (node.matches?.(COPY_BUTTON_SELECTOR)) {
bindCopyButtons(node.parentElement || document);
return;
}
if (node.querySelectorAll) {
const hasButtons = node.querySelectorAll(COPY_BUTTON_SELECTOR);
if (hasButtons.length > 0) {
bindCopyButtons(node);
}
}
});
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
document.addEventListener("click", handleCopyButtonClick, true);
document.addEventListener("pointerdown", handleCopyButtonPointerDown, true);
document.addEventListener("copy", handleSelectionCopy, true);
bindCopyButtons(document);
observeDynamicCopyButtons();
});
function primeClipboardButton(copyButton, strippedText) {
copyButton.setAttribute("data-clipboard-text", strippedText);
copyButton.removeAttribute("data-clipboard-target");
copyButton.setAttribute("data-md-clipboard", "true");
}
function shouldStripPrompts(codeBlock, rawText) {
const hasReplPrompts = /(^|\n)[ \t]*(>>>|\.\.\.)/.test(rawText);
return (
hasReplPrompts ||
codeBlock.classList.contains("language-pycon") ||
codeBlock.closest("pre")?.classList.contains("pycon") ||
codeBlock.closest(".pycon") !== null ||
codeBlock.closest(".highlight")?.classList.contains("pycon")
);
}
function findCodeBlockForCopyButton(copyButton) {
const targetSelector = copyButton.getAttribute("data-clipboard-target");
if (targetSelector) {
const target = document.querySelector(targetSelector);
const targetCode = target?.querySelector?.("code") || target;
if (targetCode?.tagName?.toLowerCase() === "code") {
return targetCode;
}
}
return (
copyButton.closest("pre")?.querySelector("code") ||
copyButton.parentElement?.querySelector("pre code") ||
copyButton
.closest(".highlight, .codehilite, .md-typeset__scrollwrap, .md-typeset")
?.querySelector("pre code") ||
copyButton
.closest(".highlight, .codehilite, .md-typeset__scrollwrap, .md-typeset")
?.querySelector("code")
);
}
/**
* Strips Python REPL prompts (>>> and ...) from code text.
* Also removes output lines (lines that don't start with >>> or ...).
*
* NOTE: This is a best-effort parser. It preserves unprompted lines inside
* triple-quoted strings, but it does not fully model Python's tokenizer.
*/
function stripPythonPrompts(text) {
const lines = text.split("\n");
const codeLines = [];
let inTripleQuotedString = false;
function toggleTripleQuoteState(sourceLine) {
const tripleQuotePattern = /("""|''')/g;
const matches = sourceLine.match(tripleQuotePattern);
if (!matches) return;
if (matches.length % 2 === 1) {
inTripleQuotedString = !inTripleQuotedString;
}
}
for (const line of lines) {
const trimmedLine = line.trimEnd();
// Primary prompt: ">>> "
if (trimmedLine.startsWith(">>> ")) {
const stripped = trimmedLine.slice(4);
codeLines.push(stripped);
toggleTripleQuoteState(stripped);
}
// Continuation prompt: "... "
else if (trimmedLine.startsWith("... ")) {
const stripped = trimmedLine.slice(4);
codeLines.push(stripped);
toggleTripleQuoteState(stripped);
}
// Handle prompts without space after (edge case)
else if (trimmedLine === ">>>") {
codeLines.push("");
} else if (trimmedLine === "...") {
codeLines.push("");
} else if (inTripleQuotedString) {
codeLines.push(trimmedLine);
toggleTripleQuoteState(trimmedLine);
}
// Skip output lines (lines that don't start with prompts)
// This intentionally excludes output like "1.0" from the copied text
}
return codeLines.join("\n").trim();
}