tex2jax.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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-2013 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.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"],
  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. PreProcess: function (element) {
  62. if (!this.configured) {
  63. this.config = MathJax.Hub.CombineConfig("tex2jax",this.config);
  64. if (this.config.Augment) {MathJax.Hub.Insert(this,this.config.Augment)}
  65. if (typeof(this.config.previewTeX) !== "undefined" && !this.config.previewTeX)
  66. {this.config.preview = "none"} // backward compatibility for previewTeX parameter
  67. this.configured = true;
  68. }
  69. if (typeof(element) === "string") {element = document.getElementById(element)}
  70. if (!element) {element = document.body}
  71. if (this.createPatterns()) {this.scanElement(element,element.nextSibling)}
  72. },
  73. createPatterns: function () {
  74. var starts = [], parts = [], i, m, config = this.config;
  75. this.match = {};
  76. for (i = 0, m = config.inlineMath.length; i < m; i++) {
  77. starts.push(this.patternQuote(config.inlineMath[i][0]));
  78. this.match[config.inlineMath[i][0]] = {
  79. mode: "",
  80. end: config.inlineMath[i][1],
  81. pattern: this.endPattern(config.inlineMath[i][1])
  82. };
  83. }
  84. for (i = 0, m = config.displayMath.length; i < m; i++) {
  85. starts.push(this.patternQuote(config.displayMath[i][0]));
  86. this.match[config.displayMath[i][0]] = {
  87. mode: "; mode=display",
  88. end: config.displayMath[i][1],
  89. pattern: this.endPattern(config.displayMath[i][1])
  90. };
  91. }
  92. if (starts.length) {parts.push(starts.sort(this.sortLength).join("|"))}
  93. if (config.processEnvironments) {parts.push("\\\\begin\\{([^}]*)\\}")}
  94. if (config.processEscapes) {parts.push("\\\\*\\\\\\\$")}
  95. if (config.processRefs) {parts.push("\\\\(eq)?ref\\{[^}]*\\}")}
  96. this.start = new RegExp(parts.join("|"),"g");
  97. this.skipTags = new RegExp("^("+config.skipTags.join("|")+")$","i");
  98. var ignore = [];
  99. if (MathJax.Hub.config.preRemoveClass) {ignore.push(MathJax.Hub.config.preRemoveClass)};
  100. if (config.ignoreClass) {ignore.push(config.ignoreClass)}
  101. this.ignoreClass = (ignore.length ? new RegExp("(^| )("+ignore.join("|")+")( |$)") : /^$/);
  102. this.processClass = new RegExp("(^| )("+config.processClass+")( |$)");
  103. return (parts.length > 0);
  104. },
  105. patternQuote: function (s) {return s.replace(/([\^$(){}+*?\-|\[\]\:\\])/g,'\\$1')},
  106. endPattern: function (end) {
  107. return new RegExp(this.patternQuote(end)+"|\\\\.|[{}]","g");
  108. },
  109. sortLength: function (a,b) {
  110. if (a.length !== b.length) {return b.length - a.length}
  111. return (a == b ? 0 : (a < b ? -1 : 1));
  112. },
  113. scanElement: function (element,stop,ignore) {
  114. var cname, tname, ignoreChild, process;
  115. while (element && element != stop) {
  116. if (element.nodeName.toLowerCase() === '#text') {
  117. if (!ignore) {element = this.scanText(element)}
  118. } else {
  119. cname = (typeof(element.className) === "undefined" ? "" : element.className);
  120. tname = (typeof(element.tagName) === "undefined" ? "" : element.tagName);
  121. if (typeof(cname) !== "string") {cname = String(cname)} // jsxgraph uses non-string class names!
  122. process = this.processClass.exec(cname);
  123. if (element.firstChild && !cname.match(/(^| )MathJax/) &&
  124. (process || !this.skipTags.exec(tname))) {
  125. ignoreChild = (ignore || this.ignoreClass.exec(cname)) && !process;
  126. this.scanElement(element.firstChild,stop,ignoreChild);
  127. }
  128. }
  129. if (element) {element = element.nextSibling}
  130. }
  131. },
  132. scanText: function (element) {
  133. if (element.nodeValue.replace(/\s+/,'') == '') {return element}
  134. var match, prev;
  135. this.search = {start: true};
  136. this.pattern = this.start;
  137. while (element) {
  138. this.pattern.lastIndex = 0;
  139. while (element && element.nodeName.toLowerCase() === '#text' &&
  140. (match = this.pattern.exec(element.nodeValue))) {
  141. if (this.search.start) {element = this.startMatch(match,element)}
  142. else {element = this.endMatch(match,element)}
  143. }
  144. if (this.search.matched) {element = this.encloseMath(element)}
  145. if (element) {
  146. do {prev = element; element = element.nextSibling}
  147. while (element && (element.nodeName.toLowerCase() === 'br' ||
  148. element.nodeName.toLowerCase() === '#comment'));
  149. if (!element || element.nodeName !== '#text')
  150. {return (this.search.close ? this.prevEndMatch() : prev)}
  151. }
  152. }
  153. return element;
  154. },
  155. startMatch: function (match,element) {
  156. var delim = this.match[match[0]];
  157. if (delim != null) { // a start delimiter
  158. this.search = {
  159. end: delim.end, mode: delim.mode, pcount: 0,
  160. open: element, olen: match[0].length, opos: this.pattern.lastIndex - match[0].length
  161. };
  162. this.switchPattern(delim.pattern);
  163. } else if (match[0].substr(0,6) === "\\begin") { // \begin{...}
  164. this.search = {
  165. end: "\\end{"+match[1]+"}", mode: "; mode=display", pcount: 0,
  166. open: element, olen: 0, opos: this.pattern.lastIndex - match[0].length,
  167. isBeginEnd: true
  168. };
  169. this.switchPattern(this.endPattern(this.search.end));
  170. } else if (match[0].substr(0,4) === "\\ref" || match[0].substr(0,6) === "\\eqref") {
  171. this.search = {
  172. mode: "", end: "", open: element, pcount: 0,
  173. olen: 0, opos: this.pattern.lastIndex - match[0].length
  174. }
  175. return this.endMatch([""],element);
  176. } else { // escaped dollar signs
  177. // put $ in a span so it doesn't get processed again
  178. // split off backslashes so they don't get removed later
  179. var slashes = match[0].substr(0,match[0].length-1), n, span;
  180. if (slashes.length % 2 === 0) {span = [slashes.replace(/\\\\/g,"\\")]; n = 1}
  181. else {span = [slashes.substr(1).replace(/\\\\/g,"\\"),"$"]; n = 0}
  182. span = MathJax.HTML.Element("span",null,span);
  183. var text = MathJax.HTML.TextNode(element.nodeValue.substr(0,match.index));
  184. element.nodeValue = element.nodeValue.substr(match.index + match[0].length - n);
  185. element.parentNode.insertBefore(span,element);
  186. element.parentNode.insertBefore(text,span);
  187. this.pattern.lastIndex = n;
  188. }
  189. return element;
  190. },
  191. endMatch: function (match,element) {
  192. var search = this.search;
  193. if (match[0] == search.end) {
  194. if (!search.close || search.pcount === 0) {
  195. search.close = element;
  196. search.cpos = this.pattern.lastIndex;
  197. search.clen = (search.isBeginEnd ? 0 : match[0].length);
  198. }
  199. if (search.pcount === 0) {
  200. search.matched = true;
  201. element = this.encloseMath(element);
  202. this.switchPattern(this.start);
  203. }
  204. }
  205. else if (match[0] === "{") {search.pcount++}
  206. else if (match[0] === "}" && search.pcount) {search.pcount--}
  207. return element;
  208. },
  209. prevEndMatch: function () {
  210. this.search.matched = true;
  211. var element = this.encloseMath(this.search.close);
  212. this.switchPattern(this.start);
  213. return element;
  214. },
  215. switchPattern: function (pattern) {
  216. pattern.lastIndex = this.pattern.lastIndex;
  217. this.pattern = pattern;
  218. this.search.start = (pattern === this.start);
  219. },
  220. encloseMath: function (element) {
  221. var search = this.search, close = search.close, CLOSE, math;
  222. if (search.cpos === close.length) {close = close.nextSibling}
  223. else {close = close.splitText(search.cpos)}
  224. if (!close) {CLOSE = close = MathJax.HTML.addText(search.close.parentNode,"")}
  225. search.close = close;
  226. math = (search.opos ? search.open.splitText(search.opos) : search.open);
  227. while (math.nextSibling && math.nextSibling !== close) {
  228. if (math.nextSibling.nodeValue !== null) {
  229. if (math.nextSibling.nodeName === "#comment") {
  230. math.nodeValue += math.nextSibling.nodeValue.replace(/^\[CDATA\[((.|\n|\r)*)\]\]$/,"$1");
  231. } else {
  232. math.nodeValue += math.nextSibling.nodeValue;
  233. }
  234. } else if (this.msieNewlineBug) {
  235. math.nodeValue += (math.nextSibling.nodeName.toLowerCase() === "br" ? "\n" : " ");
  236. } else {
  237. math.nodeValue += " ";
  238. }
  239. math.parentNode.removeChild(math.nextSibling);
  240. }
  241. var TeX = math.nodeValue.substr(search.olen,math.nodeValue.length-search.olen-search.clen);
  242. math.parentNode.removeChild(math);
  243. if (this.config.preview !== "none") {this.createPreview(search.mode,TeX)}
  244. math = this.createMathTag(search.mode,TeX);
  245. this.search = {}; this.pattern.lastIndex = 0;
  246. if (CLOSE) {CLOSE.parentNode.removeChild(CLOSE)}
  247. return math;
  248. },
  249. insertNode: function (node) {
  250. var search = this.search;
  251. search.close.parentNode.insertBefore(node,search.close);
  252. },
  253. createPreview: function (mode,tex) {
  254. var preview = this.config.preview;
  255. if (preview === "none") return;
  256. if (preview === "TeX") {preview = [this.filterPreview(tex)]}
  257. if (preview) {
  258. preview = MathJax.HTML.Element("span",{className:MathJax.Hub.config.preRemoveClass},preview);
  259. this.insertNode(preview);
  260. }
  261. },
  262. createMathTag: function (mode,tex) {
  263. var script = document.createElement("script");
  264. script.type = "math/tex" + mode;
  265. MathJax.HTML.setScript(script,tex);
  266. this.insertNode(script);
  267. return script;
  268. },
  269. filterPreview: function (tex) {return tex},
  270. msieNewlineBug: (MathJax.Hub.Browser.isMSIE && document.documentMode < 9)
  271. };
  272. MathJax.Hub.Register.PreProcessor(["PreProcess",MathJax.Extension.tex2jax]);
  273. MathJax.Ajax.loadComplete("[MathJax]/extensions/tex2jax.js");