copy-tex.js 943 B

12345678910111213141516171819202122232425
  1. import katexReplaceWithTex from './katex2tex';
  2. // Global copy handler to modify behavior on .katex elements.
  3. document.addEventListener('copy', function(event) {
  4. const selection = window.getSelection();
  5. if (selection.isCollapsed) {
  6. return; // default action OK if selection is empty
  7. }
  8. const fragment = selection.getRangeAt(0).cloneContents();
  9. if (!fragment.querySelector('.katex-mathml')) {
  10. return; // default action OK if no .katex-mathml elements
  11. }
  12. // Preserve usual HTML copy/paste behavior.
  13. const html = [];
  14. for (let i = 0; i < fragment.childNodes.length; i++) {
  15. html.push(fragment.childNodes[i].outerHTML);
  16. }
  17. event.clipboardData.setData('text/html', html.join(''));
  18. // Rewrite plain-text version.
  19. event.clipboardData.setData('text/plain',
  20. katexReplaceWithTex(fragment).textContent);
  21. // Prevent normal copy handling.
  22. event.preventDefault();
  23. });