tex2jax.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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/tex2jax.js
  6. *
  7. * Implements the TeX to Jax preprocessor that locates TeX code
  8. * within the text of a document and replaces it with SCRIPT tags
  9. * for processing by MathJax.
  10. *
  11. * ---------------------------------------------------------------------
  12. *
  13. * Copyright (c) 2009-2017 The MathJax Consortium
  14. *
  15. * Licensed under the Apache License, Version 2.0 (the "License");
  16. * you may not use this file except in compliance with the License.
  17. * You may obtain a copy of the License at
  18. *
  19. * http://www.apache.org/licenses/LICENSE-2.0
  20. *
  21. * Unless required by applicable law or agreed to in writing, software
  22. * distributed under the License is distributed on an "AS IS" BASIS,
  23. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. * See the License for the specific language governing permissions and
  25. * limitations under the License.
  26. */
  27. MathJax.Extension.tex2jax = {
  28. version: "2.7.2",
  29. config: {
  30. inlineMath: [ // The start/stop pairs for in-line math
  31. // ['$','$'], // (comment out any you don't want, or add your own, but
  32. ['\\(','\\)'] // be sure that you don't have an extra comma at the end)
  33. ],
  34. displayMath: [ // The start/stop pairs for display math
  35. ['$$','$$'], // (comment out any you don't want, or add your own, but
  36. ['\\[','\\]'] // be sure that you don't have an extra comma at the end)
  37. ],
  38. balanceBraces: true, // determines whether tex2jax requires braces to be
  39. // balanced within math delimiters (allows for nested
  40. // dollar signs). Set to false to get pre-v2.0 compatibility.
  41. skipTags: ["script","noscript","style","textarea","pre","code","annotation","annotation-xml"],
  42. // The names of the tags whose contents will not be
  43. // scanned for math delimiters
  44. ignoreClass: "tex2jax_ignore", // the class name of elements whose contents should
  45. // NOT be processed by tex2jax. Note that this
  46. // is a regular expression, so be sure to quote any
  47. // regexp special characters
  48. processClass: "tex2jax_process", // the class name of elements whose contents SHOULD
  49. // be processed when they appear inside ones that
  50. // are ignored. Note that this is a regular expression,
  51. // so be sure to quote any regexp special characters
  52. processEscapes: false, // set to true to allow \$ to produce a dollar without
  53. // starting in-line math mode
  54. processEnvironments: true, // set to true to process \begin{xxx}...\end{xxx} outside
  55. // of math mode, false to prevent that
  56. processRefs: true, // set to true to process \ref{...} outside of math mode
  57. preview: "TeX" // set to "none" to not insert MathJax_Preview spans
  58. // or set to an array specifying an HTML snippet
  59. // to use the same preview for every equation.
  60. },
  61. //
  62. // Tags to ignore when searching for TeX in the page
  63. //
  64. ignoreTags: {
  65. br: (MathJax.Hub.Browser.isMSIE && document.documentMode < 9 ? "\n" : " "),
  66. wbr: "",
  67. "#comment": ""
  68. },
  69. PreProcess: function (element) {
  70. if (!this.configured) {
  71. this.config = MathJax.Hub.CombineConfig("tex2jax",this.config);
  72. if (this.config.Augment) {MathJax.Hub.Insert(this,this.config.Augment)}
  73. if (typeof(this.config.previewTeX) !== "undefined" && !this.config.previewTeX)
  74. {this.config.preview = "none"} // backward compatibility for previewTeX parameter
  75. this.configured = true;
  76. }
  77. if (typeof(element) === "string") {element = document.getElementById(element)}
  78. if (!element) {element = document.body}
  79. if (this.createPatterns()) {this.scanElement(element,element.nextSibling)}
  80. },
  81. createPatterns: function () {
  82. var starts = [], parts = [], i, m, config = this.config;
  83. this.match = {};
  84. for (i = 0, m = config.inlineMath.length; i < m; i++) {
  85. starts.push(this.patternQuote(config.inlineMath[i][0]));
  86. this.match[config.inlineMath[i][0]] = {
  87. mode: "",
  88. end: config.inlineMath[i][1],
  89. pattern: this.endPattern(config.inlineMath[i][1])
  90. };
  91. }
  92. for (i = 0, m = config.displayMath.length; i < m; i++) {
  93. starts.push(this.patternQuote(config.displayMath[i][0]));
  94. this.match[config.displayMath[i][0]] = {
  95. mode: "; mode=display",
  96. end: config.displayMath[i][1],
  97. pattern: this.endPattern(config.displayMath[i][1])
  98. };
  99. }
  100. if (starts.length) {parts.push(starts.sort(this.sortLength).join("|"))}
  101. if (config.processEnvironments) {parts.push("\\\\begin\\{([^}]*)\\}")}
  102. if (config.processEscapes) {parts.push("\\\\*\\\\\\\$")}
  103. if (config.processRefs) {parts.push("\\\\(eq)?ref\\{[^}]*\\}")}
  104. this.start = new RegExp(parts.join("|"),"g");
  105. this.skipTags = new RegExp("^("+config.skipTags.join("|")+")$","i");
  106. var ignore = [];
  107. if (MathJax.Hub.config.preRemoveClass) {ignore.push(MathJax.Hub.config.preRemoveClass)};
  108. if (config.ignoreClass) {ignore.push(config.ignoreClass)}
  109. this.ignoreClass = (ignore.length ? new RegExp("(^| )("+ignore.join("|")+")( |$)") : /^$/);
  110. this.processClass = new RegExp("(^| )("+config.processClass+")( |$)");
  111. return (parts.length > 0);
  112. },
  113. patternQuote: function (s) {return s.replace(/([\^$(){}+*?\-|\[\]\:\\])/g,'\\$1')},
  114. endPattern: function (end) {
  115. return new RegExp(this.patternQuote(end)+"|\\\\.|[{}]","g");
  116. },
  117. sortLength: function (a,b) {
  118. if (a.length !== b.length) {return b.length - a.length}
  119. return (a == b ? 0 : (a < b ? -1 : 1));
  120. },
  121. scanElement: function (element,stop,ignore) {
  122. var cname, tname, ignoreChild, process;
  123. while (element && element != stop) {
  124. if (element.nodeName.toLowerCase() === '#text') {
  125. if (!ignore) {element = this.scanText(element)}
  126. } else {
  127. cname = (typeof(element.className) === "undefined" ? "" : element.className);
  128. tname = (typeof(element.tagName) === "undefined" ? "" : element.tagName);
  129. if (typeof(cname) !== "string") {cname = String(cname)} // jsxgraph uses non-string class names!
  130. process = this.processClass.exec(cname);
  131. if (element.firstChild && !cname.match(/(^| )MathJax/) &&
  132. (process || !this.skipTags.exec(tname))) {
  133. ignoreChild = (ignore || this.ignoreClass.exec(cname)) && !process;
  134. this.scanElement(element.firstChild,stop,ignoreChild);
  135. }
  136. }
  137. if (element) {element = element.nextSibling}
  138. }
  139. },
  140. scanText: function (element) {
  141. if (element.nodeValue.replace(/\s+/,'') == '') {return element}
  142. var match, prev;
  143. this.search = {start: true};
  144. this.pattern = this.start;
  145. while (element) {
  146. this.pattern.lastIndex = 0;
  147. while (element && element.nodeName.toLowerCase() === '#text' &&
  148. (match = this.pattern.exec(element.nodeValue))) {
  149. if (this.search.start) {element = this.startMatch(match,element)}
  150. else {element = this.endMatch(match,element)}
  151. }
  152. if (this.search.matched) {element = this.encloseMath(element)}
  153. if (element) {
  154. do {prev = element; element = element.nextSibling}
  155. while (element && this.ignoreTags[element.nodeName.toLowerCase()] != null);
  156. if (!element || element.nodeName !== '#text')
  157. {return (this.search.close ? this.prevEndMatch() : prev)}
  158. }
  159. }
  160. return element;
  161. },
  162. startMatch: function (match,element) {
  163. var delim = this.match[match[0]];
  164. if (delim != null) { // a start delimiter
  165. this.search = {
  166. end: delim.end, mode: delim.mode, pcount: 0,
  167. open: element, olen: match[0].length, opos: this.pattern.lastIndex - match[0].length
  168. };
  169. this.switchPattern(delim.pattern);
  170. } else if (match[0].substr(0,6) === "\\begin") { // \begin{...}
  171. this.search = {
  172. end: "\\end{"+match[1]+"}", mode: "; mode=display", pcount: 0,
  173. open: element, olen: 0, opos: this.pattern.lastIndex - match[0].length,
  174. isBeginEnd: true
  175. };
  176. this.switchPattern(this.endPattern(this.search.end));
  177. } else if (match[0].substr(0,4) === "\\ref" || match[0].substr(0,6) === "\\eqref") {
  178. this.search = {
  179. mode: "", end: "", open: element, pcount: 0,
  180. olen: 0, opos: this.pattern.lastIndex - match[0].length
  181. }
  182. return this.endMatch([""],element);
  183. } else { // escaped dollar signs
  184. // put $ in a span so it doesn't get processed again
  185. // split off backslashes so they don't get removed later
  186. var slashes = match[0].substr(0,match[0].length-1), n, span;
  187. if (slashes.length % 2 === 0) {span = [slashes.replace(/\\\\/g,"\\")]; n = 1}
  188. else {span = [slashes.substr(1).replace(/\\\\/g,"\\"),"$"]; n = 0}
  189. span = MathJax.HTML.Element("span",null,span);
  190. var text = MathJax.HTML.TextNode(element.nodeValue.substr(0,match.index));
  191. element.nodeValue = element.nodeValue.substr(match.index + match[0].length - n);
  192. element.parentNode.insertBefore(span,element);
  193. element.parentNode.insertBefore(text,span);
  194. this.pattern.lastIndex = n;
  195. }
  196. return element;
  197. },
  198. endMatch: function (match,element) {
  199. var search = this.search;
  200. if (match[0] == search.end) {
  201. if (!search.close || search.pcount === 0) {
  202. search.close = element;
  203. search.cpos = this.pattern.lastIndex;
  204. search.clen = (search.isBeginEnd ? 0 : match[0].length);
  205. }
  206. if (search.pcount === 0) {
  207. search.matched = true;
  208. element = this.encloseMath(element);
  209. this.switchPattern(this.start);
  210. }
  211. }
  212. else if (match[0] === "{") {search.pcount++}
  213. else if (match[0] === "}" && search.pcount) {search.pcount--}
  214. return element;
  215. },
  216. prevEndMatch: function () {
  217. this.search.matched = true;
  218. var element = this.encloseMath(this.search.close);
  219. this.switchPattern(this.start);
  220. return element;
  221. },
  222. switchPattern: function (pattern) {
  223. pattern.lastIndex = this.pattern.lastIndex;
  224. this.pattern = pattern;
  225. this.search.start = (pattern === this.start);
  226. },
  227. encloseMath: function (element) {
  228. var search = this.search, close = search.close, CLOSE, math, next;
  229. if (search.cpos === close.length) {close = close.nextSibling}
  230. else {close = close.splitText(search.cpos)}
  231. if (!close) {CLOSE = close = MathJax.HTML.addText(search.close.parentNode,"")}
  232. search.close = close;
  233. math = (search.opos ? search.open.splitText(search.opos) : search.open);
  234. while ((next = math.nextSibling) && next !== close) {
  235. if (next.nodeValue !== null) {
  236. if (next.nodeName === "#comment") {
  237. math.nodeValue += next.nodeValue.replace(/^\[CDATA\[((.|\n|\r)*)\]\]$/,"$1");
  238. } else {
  239. math.nodeValue += next.nodeValue;
  240. }
  241. } else {
  242. var ignore = this.ignoreTags[next.nodeName.toLowerCase()];
  243. math.nodeValue += (ignore == null ? " " : ignore);
  244. }
  245. math.parentNode.removeChild(next);
  246. }
  247. var TeX = math.nodeValue.substr(search.olen,math.nodeValue.length-search.olen-search.clen);
  248. math.parentNode.removeChild(math);
  249. if (this.config.preview !== "none") {this.createPreview(search.mode,TeX)}
  250. math = this.createMathTag(search.mode,TeX);
  251. this.search = {}; this.pattern.lastIndex = 0;
  252. if (CLOSE) {CLOSE.parentNode.removeChild(CLOSE)}
  253. return math;
  254. },
  255. insertNode: function (node) {
  256. var search = this.search;
  257. search.close.parentNode.insertBefore(node,search.close);
  258. },
  259. createPreview: function (mode,tex) {
  260. var previewClass = MathJax.Hub.config.preRemoveClass;
  261. var preview = this.config.preview;
  262. if (preview === "none") return;
  263. if ((this.search.close.previousSibling||{}).className === previewClass) return;
  264. if (preview === "TeX") {preview = [this.filterPreview(tex)]}
  265. if (preview) {
  266. preview = MathJax.HTML.Element("span",{className:previewClass},preview);
  267. this.insertNode(preview);
  268. }
  269. },
  270. createMathTag: function (mode,tex) {
  271. var script = document.createElement("script");
  272. script.type = "math/tex" + mode;
  273. MathJax.HTML.setScript(script,tex);
  274. this.insertNode(script);
  275. return script;
  276. },
  277. filterPreview: function (tex) {return tex}
  278. };
  279. // We register the preprocessors with the following priorities:
  280. // - mml2jax.js: 5
  281. // - jsMath2jax.js: 8
  282. // - asciimath2jax.js, tex2jax.js: 10 (default)
  283. // See issues 18 and 484 and the other *2jax.js files.
  284. MathJax.Hub.Register.PreProcessor(["PreProcess",MathJax.Extension.tex2jax]);
  285. MathJax.Ajax.loadComplete("[MathJax]/extensions/tex2jax.js");