MathJax compiler and decompiler

Ctrl-m compiles LaTeX code with inline math delimiters $ ... $ and [; ... ;], and display math delimiters $$ ... $$ and [(; ... ;)]. Ctrl-, decompiles.

  1. // ==UserScript==
  2. // @name MathJax compiler and decompiler
  3. // @namespace
  4. // @author Marcelo Silvarolla
  5. // @version 0.2
  6. // @description Ctrl-m compiles LaTeX code with inline math delimiters $ ... $ and [; ... ;], and display math delimiters $$ ... $$ and [(; ... ;)]. Ctrl-, decompiles.
  7. // @match *://*/*
  8. // @copyright
  9. // @namespace https://greasyfork.org/users/196485
  10. // ==/UserScript==
  11.  
  12. function removeTypeset() {
  13. var HTML = MathJax.HTML,
  14. jax = MathJax.Hub.getAllJax();
  15. for (var i = 0, m = jax.length; i < m; i++) {
  16. var script = jax[i].SourceElement(),
  17. tex = jax[i].originalText;
  18. if (script.type.match(/display/)) {
  19. tex = "$$" + tex + "$$";
  20. } else {
  21. tex = "$" + tex + "$";
  22. }
  23. jax[i].Remove();
  24. var preview = script.previousSibling;
  25. if (preview && preview.className === "MathJax_Preview") {
  26. preview.parentNode.removeChild(preview);
  27. }
  28. preview = HTML.Element("span", { className: "MathJax_Preview" }, [tex]);
  29. script.parentNode.insertBefore(preview, script);
  30. }
  31. }
  32.  
  33. function showTypeset(e) {
  34. // ctrl-m
  35. if (e.ctrlKey && e.keyCode == 77) {
  36. var script = document.createElement("script");
  37. script.type = "text/javascript";
  38. script.src =
  39. "//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML";
  40. var config =
  41. "MathJax.Hub.Config({ " +
  42. 'extensions: ["tex2jax.js"], ' +
  43. 'tex2jax: { skipTags: ["script","noscript","style","textarea"],inlineMath: [ ["$", "$"], ["[;", ";]"] ], displayMath: [ ["$$", "$$"], ["[(;",";)]"]], processEscapes: true }, ' +
  44. 'jax: ["input/TeX", "output/HTML-CSS"] ' +
  45. " }); " +
  46. "MathJax.Hub.Startup.onload(); ";
  47. if (window.opera) {
  48. script.innerHTML = config;
  49. } else {
  50. script.text = config;
  51. }
  52. document.getElementsByTagName("head")[0].appendChild(script);
  53. MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
  54. $(".MathJax")
  55. .parent()
  56. .css("border", "none")
  57. .css("background", "none");
  58. }
  59. // ctrl-,
  60. if (e.ctrlKey && e.keyCode == 188) {
  61. removeTypeset();
  62. }
  63. }
  64.  
  65. window.addEventListener("keyup", showTypeset);
  66.