Debian Codegraph @

sphinx_copybutton/_static/copybutton_funcs.js

raw
1 function escapeRegExp(string) {
2 return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
3 }
4
5 /**
6 * Removes excluded text from a Node.
7 *
8 * @param {Node} target Node to filter.
9 * @param {string} exclude CSS selector of nodes to exclude.
10 * @returns {DOMString} Text from `target` with text removed.
11 */
12 export function filterText(target, exclude) {
13 const clone = target.cloneNode(true); // clone as to not modify the live DOM
14 if (exclude) {
15 // remove excluded nodes
16 clone.querySelectorAll(exclude).forEach(node => node.remove());
17 }
18 return clone.innerText;
19 }
20
21 // Callback when a copy button is clicked. Will be passed the node that was clicked
22 // should then grab the text and replace pieces of text that shouldn't be used in output
23 export function formatCopyText(textContent, copybuttonPromptText, isRegexp = false, onlyCopyPromptLines = true, removePrompts = true, copyEmptyLines = true, lineContinuationChar = "", hereDocDelim = "") {
24 var regexp;
25 var match;
26
27 // Do we check for line continuation characters and "HERE-documents"?
28 var useLineCont = !!lineContinuationChar
29 var useHereDoc = !!hereDocDelim
30
31 // create regexp to capture prompt and remaining line
32 if (isRegexp) {
33 regexp = new RegExp('^(' + copybuttonPromptText + ')(.*)')
34 } else {
35 regexp = new RegExp('^(' + escapeRegExp(copybuttonPromptText) + ')(.*)')
36 }
37
38 const outputLines = [];
39 var promptFound = false;
40 var gotLineCont = false;
41 var gotHereDoc = false;
42 const lineGotPrompt = [];
43 for (const line of textContent.split('\n')) {
44 match = line.match(regexp)
45 if (match || gotLineCont || gotHereDoc) {
46 promptFound = regexp.test(line)
47 lineGotPrompt.push(promptFound)
48 if (removePrompts && promptFound) {
49 outputLines.push(match[2])
50 } else {
51 outputLines.push(line)
52 }
53 gotLineCont = line.endsWith(lineContinuationChar) & useLineCont
54 if (line.includes(hereDocDelim) & useHereDoc)
55 gotHereDoc = !gotHereDoc
56 } else if (!onlyCopyPromptLines) {
57 outputLines.push(line)
58 } else if (copyEmptyLines && line.trim() === '') {
59 outputLines.push(line)
60 }
61 }
62
63 // If no lines with the prompt were found then just use original lines
64 if (lineGotPrompt.some(v => v === true)) {
65 textContent = outputLines.join('\n');
66 }
67
68 // Remove a trailing newline to avoid auto-running when pasting
69 if (textContent.endsWith("\n")) {
70 textContent = textContent.slice(0, -1)
71 }
72 return textContent
73 }