copybutton_funcs.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. function escapeRegExp(string) {
  2. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  3. }
  4. // Callback when a copy button is clicked. Will be passed the node that was clicked
  5. // should then grab the text and replace pieces of text that shouldn't be used in output
  6. export function formatCopyText(textContent, copybuttonPromptText, isRegexp = false, onlyCopyPromptLines = true, removePrompts = true, copyEmptyLines = true, lineContinuationChar = "", hereDocDelim = "") {
  7. var regexp;
  8. var match;
  9. // Do we check for line continuation characters and "HERE-documents"?
  10. var useLineCont = !!lineContinuationChar
  11. var useHereDoc = !!hereDocDelim
  12. // create regexp to capture prompt and remaining line
  13. if (isRegexp) {
  14. regexp = new RegExp('^(' + copybuttonPromptText + ')(.*)')
  15. } else {
  16. regexp = new RegExp('^(' + escapeRegExp(copybuttonPromptText) + ')(.*)')
  17. }
  18. const outputLines = [];
  19. var promptFound = false;
  20. var gotLineCont = false;
  21. var gotHereDoc = false;
  22. const lineGotPrompt = [];
  23. for (const line of textContent.split('\n')) {
  24. match = line.match(regexp)
  25. if (match || gotLineCont || gotHereDoc) {
  26. promptFound = regexp.test(line)
  27. lineGotPrompt.push(promptFound)
  28. if (removePrompts && promptFound) {
  29. outputLines.push(match[2])
  30. } else {
  31. outputLines.push(line)
  32. }
  33. gotLineCont = line.endsWith(lineContinuationChar) & useLineCont
  34. if (line.includes(hereDocDelim) & useHereDoc)
  35. gotHereDoc = !gotHereDoc
  36. } else if (!onlyCopyPromptLines) {
  37. outputLines.push(line)
  38. } else if (copyEmptyLines && line.trim() === '') {
  39. outputLines.push(line)
  40. }
  41. }
  42. // If no lines with the prompt were found then just use original lines
  43. if (lineGotPrompt.some(v => v === true)) {
  44. textContent = outputLines.join('\n');
  45. }
  46. // Remove a trailing newline to avoid auto-running when pasting
  47. if (textContent.endsWith("\n")) {
  48. textContent = textContent.slice(0, -1)
  49. }
  50. return textContent
  51. }