katex2tex.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Set these to how you want inline and display math to be delimited.
  2. export const defaultCopyDelimiters = {
  3. inline: ['$', '$'], // alternative: ['\(', '\)']
  4. display: ['$$', '$$'], // alternative: ['\[', '\]']
  5. };
  6. // Replace .katex elements with their TeX source (<annotation> element).
  7. // Modifies fragment in-place. Useful for writing your own 'copy' handler,
  8. // as in copy-tex.js.
  9. export const katexReplaceWithTex = function(fragment,
  10. copyDelimiters = defaultCopyDelimiters) {
  11. // Remove .katex-html blocks that are preceded by .katex-mathml blocks
  12. // (which will get replaced below).
  13. const katexHtml = fragment.querySelectorAll('.katex-mathml + .katex-html');
  14. for (let i = 0; i < katexHtml.length; i++) {
  15. const element = katexHtml[i];
  16. if (element.remove) {
  17. element.remove(null);
  18. } else {
  19. element.parentNode.removeChild(element);
  20. }
  21. }
  22. // Replace .katex-mathml elements with their annotation (TeX source)
  23. // descendant, with inline delimiters.
  24. const katexMathml = fragment.querySelectorAll('.katex-mathml');
  25. for (let i = 0; i < katexMathml.length; i++) {
  26. const element = katexMathml[i];
  27. const texSource = element.querySelector('annotation');
  28. if (texSource) {
  29. if (element.replaceWith) {
  30. element.replaceWith(texSource);
  31. } else {
  32. element.parentNode.replaceChild(texSource, element);
  33. }
  34. texSource.innerHTML = copyDelimiters.inline[0] +
  35. texSource.innerHTML + copyDelimiters.inline[1];
  36. }
  37. }
  38. // Switch display math to display delimiters.
  39. const displays = fragment.querySelectorAll('.katex-display annotation');
  40. for (let i = 0; i < displays.length; i++) {
  41. const element = displays[i];
  42. element.innerHTML = copyDelimiters.display[0] +
  43. element.innerHTML.substr(copyDelimiters.inline[0].length,
  44. element.innerHTML.length - copyDelimiters.inline[0].length
  45. - copyDelimiters.inline[1].length)
  46. + copyDelimiters.display[1];
  47. }
  48. return fragment;
  49. };
  50. export default katexReplaceWithTex;