-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathconsole-copy.js
More file actions
executable file
·70 lines (61 loc) · 2.76 KB
/
console-copy.js
File metadata and controls
executable file
·70 lines (61 loc) · 2.76 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
/* global document$:readonly */
document$.subscribe(() => {
document.querySelectorAll("pre > code").forEach((code) => {
const wrapper = code.closest("div.language-console");
if (!wrapper) return;
const button = wrapper.querySelector("button.md-clipboard");
if (!button) return;
button.addEventListener(
"mouseenter",
() => {
// Only set data-copy once
if (code.hasAttribute("data-copy")) return;
const text = code.textContent.trimEnd();
// Merge continuation lines that end with '\', and remove '$'
// from prompts
let lines = [];
let mergeNext = false;
text.split("\n").forEach((line) => {
// If we need to merge the current line with the next one
if (mergeNext) {
// Merge the line with the previous one and reset the
// flag
lines[lines.length - 1] += " " + line.trimStart();
if (lines[lines.length - 1].endsWith(" \\")) {
lines[lines.length - 1] = lines[
lines.length - 1
].slice(0, -2);
} else if (lines[lines.length - 1].endsWith("\\")) {
lines[lines.length - 1] = lines[
lines.length - 1
].slice(0, -1);
} else {
mergeNext = false;
}
}
// If the line starts with '$' and ends with '\'
// (continuation line)
if (line.startsWith("$ ")) {
if (line.endsWith(" \\")) {
// Remove "$ " and the trailing "\"
lines.push(line.slice(2, -2));
// Mark that we need to merge with the next line
mergeNext = true;
} else if (line.endsWith("\\")) {
// Remove "$ " and the trailing " \"
lines.push(line.slice(2, -1));
mergeNext = true;
} else {
// If it's a prompt line without continuation, just
// remove the '$'
lines.push(line.slice(2));
}
}
});
const cleaned = lines.join("\n");
code.setAttribute("data-copy", cleaned);
},
{ once: true },
);
});
});