asciimath2jax.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
  2. /* vim: set ts=2 et sw=2 tw=80: */
  3. /*************************************************************
  4. *
  5. * MathJax/extensions/asciimath2jax.js
  6. *
  7. * Implements the AsciiMath to Jax preprocessor that locates AsciiMath
  8. * code within the text of a document and replaces it with SCRIPT tags for
  9. * processing by MathJax.
  10. *
  11. * Modified by David Lippman, based on tex2jax.js.
  12. * Additional work by Davide P. Cervone.
  13. *
  14. * ---------------------------------------------------------------------
  15. *
  16. * Copyright (c) 2012-2017 The MathJax Consortium
  17. *
  18. * Licensed under the Apache License, Version 2.0 (the "License");
  19. * you may not use this file except in compliance with the License.
  20. * You may obtain a copy of the License at
  21. *
  22. * http://www.apache.org/licenses/LICENSE-2.0
  23. *
  24. * Unless required by applicable law or agreed to in writing, software
  25. * distributed under the License is distributed on an "AS IS" BASIS,
  26. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27. * See the License for the specific language governing permissions and
  28. * limitations under the License.
  29. */
  30. MathJax.Extension.asciimath2jax = {
  31. version: "2.7.2",
  32. config: {
  33. delimiters: [['`','`']], // The star/stop delimiter pairs for asciimath code
  34. skipTags: ["script","noscript","style","textarea","pre","code","annotation","annotation-xml"],
  35. // The names of the tags whose contents will not be
  36. // scanned for math delimiters
  37. ignoreClass: "asciimath2jax_ignore", // the class name of elements whose contents should
  38. // NOT be processed by asciimath2jax. Note that this
  39. // is a regular expression, so be sure to quote any
  40. // regexp special characters
  41. processClass: "asciimath2jax_process", // the class name of elements whose contents SHOULD
  42. // be processed when they appear inside ones that
  43. // are ignored. Note that this is a regular expression,
  44. // so be sure to quote any regexp special characters
  45. preview: "AsciiMath" // set to "none" to not insert MathJax_Preview spans
  46. // or set to an array specifying an HTML snippet
  47. // to use the same preview for every equation.
  48. },
  49. //
  50. // Tags to ignore when searching for AsciiMath in the page
  51. //
  52. ignoreTags: {
  53. br: (MathJax.Hub.Browser.isMSIE && document.documentMode < 9 ? "\n" : " "),
  54. wbr: "",
  55. "#comment": ""
  56. },
  57. PreProcess: function (element) {
  58. if (!this.configured) {
  59. this.config = MathJax.Hub.CombineConfig("asciimath2jax",this.config);
  60. if (this.config.Augment) {MathJax.Hub.Insert(this,this.config.Augment)}
  61. this.configured = true;
  62. }
  63. if (typeof(element) === "string") {element = document.getElementById(element)}
  64. if (!element) {element = document.body}
  65. if (this.createPatterns()) {this.scanElement(element,element.nextSibling)}
  66. },
  67. createPatterns: function () {
  68. var starts = [], i, m, config = this.config; this.match = {};
  69. if (config.delimiters.length === 0) {return false}
  70. for (i = 0, m = config.delimiters.length; i < m; i++) {
  71. starts.push(this.patternQuote(config.delimiters[i][0]));
  72. this.match[config.delimiters[i][0]] = {
  73. mode: "",
  74. end: config.delimiters[i][1],
  75. pattern: this.endPattern(config.delimiters[i][1])
  76. };
  77. }
  78. this.start = new RegExp(starts.sort(this.sortLength).join("|"),"g");
  79. this.skipTags = new RegExp("^("+config.skipTags.join("|")+")$","i");
  80. var ignore = [];
  81. if (MathJax.Hub.config.preRemoveClass) {ignore.push(MathJax.Hub.config.preRemoveClass)}
  82. if (config.ignoreClass) {ignore.push(config.ignoreClass)}
  83. this.ignoreClass = (ignore.length ? new RegExp("(^| )("+ignore.join("|")+")( |$)") : /^$/);
  84. this.processClass = new RegExp("(^| )("+config.processClass+")( |$)");
  85. return true;
  86. },
  87. patternQuote: function (s) {return s.replace(/([\^$(){}+*?\-|\[\]\:\\])/g,'\\$1')},
  88. endPattern: function (end) {
  89. return new RegExp(this.patternQuote(end)+"|\\\\.","g");
  90. },
  91. sortLength: function (a,b) {
  92. if (a.length !== b.length) {return b.length - a.length}
  93. return (a == b ? 0 : (a < b ? -1 : 1));
  94. },
  95. scanElement: function (element,stop,ignore) {
  96. var cname, tname, ignoreChild, process;
  97. while (element && element != stop) {
  98. if (element.nodeName.toLowerCase() === '#text') {
  99. if (!ignore) {element = this.scanText(element)}
  100. } else {
  101. cname = (typeof(element.className) === "undefined" ? "" : element.className);
  102. tname = (typeof(element.tagName) === "undefined" ? "" : element.tagName);
  103. if (typeof(cname) !== "string") {cname = String(cname)} // jsxgraph uses non-string class names!
  104. process = this.processClass.exec(cname);
  105. if (element.firstChild && !cname.match(/(^| )MathJax/) &&
  106. (process || !this.skipTags.exec(tname))) {
  107. ignoreChild = (ignore || this.ignoreClass.exec(cname)) && !process;
  108. this.scanElement(element.firstChild,stop,ignoreChild);
  109. }
  110. }
  111. if (element) {element = element.nextSibling}
  112. }
  113. },
  114. scanText: function (element) {
  115. if (element.nodeValue.replace(/\s+/,'') == '') {return element}
  116. var match, prev;
  117. this.search = {start: true};
  118. this.pattern = this.start;
  119. while (element) {
  120. this.pattern.lastIndex = 0;
  121. while (element && element.nodeName.toLowerCase() === '#text' &&
  122. (match = this.pattern.exec(element.nodeValue))) {
  123. if (this.search.start) {element = this.startMatch(match,element)}
  124. else {element = this.endMatch(match,element)}
  125. }
  126. if (this.search.matched) {element = this.encloseMath(element)}
  127. if (element) {
  128. do {prev = element; element = element.nextSibling}
  129. while (element && this.ignoreTags[element.nodeName.toLowerCase()] != null);
  130. if (!element || element.nodeName !== '#text') {return prev}
  131. }
  132. }
  133. return element;
  134. },
  135. startMatch: function (match,element) {
  136. var delim = this.match[match[0]];
  137. if (delim != null) {
  138. this.search = {
  139. end: delim.end, mode: delim.mode,
  140. open: element, olen: match[0].length,
  141. opos: this.pattern.lastIndex - match[0].length
  142. };
  143. this.switchPattern(delim.pattern);
  144. }
  145. return element;
  146. },
  147. endMatch: function (match,element) {
  148. if (match[0] == this.search.end) {
  149. this.search.close = element;
  150. this.search.cpos = this.pattern.lastIndex;
  151. this.search.clen = (this.search.isBeginEnd ? 0 : match[0].length);
  152. this.search.matched = true;
  153. element = this.encloseMath(element);
  154. this.switchPattern(this.start);
  155. }
  156. return element;
  157. },
  158. switchPattern: function (pattern) {
  159. pattern.lastIndex = this.pattern.lastIndex;
  160. this.pattern = pattern;
  161. this.search.start = (pattern === this.start);
  162. },
  163. encloseMath: function (element) {
  164. var search = this.search, close = search.close, CLOSE, math, next;
  165. if (search.cpos === close.length) {close = close.nextSibling}
  166. else {close = close.splitText(search.cpos)}
  167. if (!close) {CLOSE = close = MathJax.HTML.addText(search.close.parentNode,"")}
  168. search.close = close;
  169. math = (search.opos ? search.open.splitText(search.opos) : search.open);
  170. while ((next = math.nextSibling) && next !== close) {
  171. if (next.nodeValue !== null) {
  172. if (next.nodeName === "#comment") {
  173. math.nodeValue += next.nodeValue.replace(/^\[CDATA\[((.|\n|\r)*)\]\]$/,"$1");
  174. } else {
  175. math.nodeValue += math.nextSibling.nodeValue;
  176. }
  177. } else {
  178. var ignore = this.ignoreTags[next.nodeName.toLowerCase()];
  179. math.nodeValue += (ignore == null ? " " : ignore);
  180. }
  181. math.parentNode.removeChild(next);
  182. }
  183. var AM = math.nodeValue.substr(search.olen,math.nodeValue.length-search.olen-search.clen);
  184. math.parentNode.removeChild(math);
  185. if (this.config.preview !== "none") {this.createPreview(search.mode,AM)}
  186. math = this.createMathTag(search.mode,AM);
  187. this.search = {}; this.pattern.lastIndex = 0;
  188. if (CLOSE) {CLOSE.parentNode.removeChild(CLOSE)}
  189. return math;
  190. },
  191. insertNode: function (node) {
  192. var search = this.search;
  193. search.close.parentNode.insertBefore(node,search.close);
  194. },
  195. createPreview: function (mode,asciimath) {
  196. var previewClass = MathJax.Hub.config.preRemoveClass;
  197. var preview = this.config.preview;
  198. if (preview === "none") return;
  199. if ((this.search.close.previousSibling||{}).className === previewClass) return;
  200. if (preview === "AsciiMath") {preview = [this.filterPreview(asciimath)]}
  201. if (preview) {
  202. preview = MathJax.HTML.Element("span",{className:previewClass},preview);
  203. this.insertNode(preview);
  204. }
  205. },
  206. createMathTag: function (mode,asciimath) {
  207. var script = document.createElement("script");
  208. script.type = "math/asciimath" + mode;
  209. MathJax.HTML.setScript(script,asciimath);
  210. this.insertNode(script);
  211. return script;
  212. },
  213. filterPreview: function (asciimath) {return asciimath}
  214. };
  215. // We register the preprocessors with the following priorities:
  216. // - mml2jax.js: 5
  217. // - jsMath2jax.js: 8
  218. // - asciimath2jax.js, tex2jax.js: 10 (default)
  219. // See issues 18 and 484 and the other *2jax.js files.
  220. MathJax.Hub.Register.PreProcessor(["PreProcess",MathJax.Extension.asciimath2jax]);
  221. MathJax.Ajax.loadComplete("[MathJax]/extensions/asciimath2jax.js");