toMathML.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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/toMathML.js
  6. *
  7. * Implements a toMathML() method for the mml Element Jax that returns
  8. * a MathML string from a given math expression.
  9. *
  10. * ---------------------------------------------------------------------
  11. *
  12. * Copyright (c) 2010-2018 The MathJax Consortium
  13. *
  14. * Licensed under the Apache License, Version 2.0 (the "License");
  15. * you may not use this file except in compliance with the License.
  16. * You may obtain a copy of the License at
  17. *
  18. * http://www.apache.org/licenses/LICENSE-2.0
  19. *
  20. * Unless required by applicable law or agreed to in writing, software
  21. * distributed under the License is distributed on an "AS IS" BASIS,
  22. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. * See the License for the specific language governing permissions and
  24. * limitations under the License.
  25. */
  26. MathJax.Hub.Register.LoadHook("[MathJax]/jax/element/mml/jax.js",function () {
  27. var VERSION = "2.7.5";
  28. var MML = MathJax.ElementJax.mml,
  29. SETTINGS = MathJax.Hub.config.menuSettings;
  30. MML.mbase.Augment({
  31. toMathML: function (space) {
  32. var inferred = (this.inferred && this.parent.inferRow);
  33. if (space == null) {space = ""}
  34. var tag = this.type, attr = this.toMathMLattributes();
  35. if (tag === "mspace") {return space + "<"+tag+attr+" />"}
  36. var data = [], SPACE = (this.isToken ? "" : space+(inferred ? "" : " "));
  37. for (var i = 0, m = this.data.length; i < m; i++) {
  38. if (this.data[i]) {data.push(this.data[i].toMathML(SPACE))}
  39. else if (!this.isToken && !this.isChars) {data.push(SPACE+"<mrow />")}
  40. }
  41. if (this.isToken || this.isChars) {return space + "<"+tag+attr+">"+data.join("")+"</"+tag+">"}
  42. if (inferred) {return data.join("\n")}
  43. if (data.length === 0 || (data.length === 1 && data[0] === ""))
  44. {return space + "<"+tag+attr+" />"}
  45. return space + "<"+tag+attr+">\n"+data.join("\n")+"\n"+ space +"</"+tag+">";
  46. },
  47. toMathMLattributes: function () {
  48. var defaults = (this.type === "mstyle" ? MML.math.prototype.defaults : this.defaults);
  49. var names = (this.attrNames||MML.copyAttributeNames),
  50. skip = MML.skipAttributes, copy = MML.copyAttributes;
  51. var attr = [];
  52. if (this.type === "math" && (!this.attr || !('xmlns' in this.attr)))
  53. {attr.push('xmlns="http://www.w3.org/1998/Math/MathML"')}
  54. if (!this.attrNames) {
  55. for (var id in defaults) {if (!skip[id] && !copy[id] && defaults.hasOwnProperty(id)) {
  56. if (this[id] != null && this[id] !== defaults[id]) {
  57. if (this.Get(id,null,1) !== this[id])
  58. attr.push(id+'="'+this.toMathMLattribute(this[id])+'"');
  59. }
  60. }}
  61. }
  62. for (var i = 0, m = names.length; i < m; i++) {
  63. if (copy[names[i]] === 1 && !defaults.hasOwnProperty(names[i])) continue;
  64. value = (this.attr||{})[names[i]]; if (value == null) {value = this[names[i]]}
  65. if (value != null) {attr.push(names[i]+'="'+this.toMathMLquote(value)+'"')}
  66. }
  67. this.toMathMLclass(attr);
  68. if (attr.length) {return " "+attr.join(" ")} else {return ""}
  69. },
  70. toMathMLclass: function (attr) {
  71. var CLASS = []; if (this["class"]) {CLASS.push(this["class"])}
  72. if (this.isa(MML.TeXAtom) && SETTINGS.texHints) {
  73. var TEXCLASS = ["ORD","OP","BIN","REL","OPEN","CLOSE","PUNCT","INNER","VCENTER"][this.texClass];
  74. if (TEXCLASS) {
  75. CLASS.push("MJX-TeXAtom-"+TEXCLASS)
  76. if (TEXCLASS === "OP" && !this.movablelimits) CLASS.push("MJX-fixedlimits");
  77. }
  78. }
  79. if (this.mathvariant && this.toMathMLvariants[this.mathvariant])
  80. {CLASS.push("MJX"+this.mathvariant)}
  81. if (this.variantForm) {CLASS.push("MJX-variant")}
  82. if (CLASS.length) {attr.unshift('class="'+this.toMathMLquote(CLASS.join(" "))+'"')}
  83. },
  84. toMathMLattribute: function (value) {
  85. if (typeof(value) === "string" &&
  86. value.replace(/ /g,"").match(/^(([-+])?(\d+(\.\d*)?|\.\d+))mu$/)) {
  87. // FIXME: should take scriptlevel into account
  88. return (RegExp.$2||"")+((1/18)*RegExp.$3).toFixed(3).replace(/\.?0+$/,"")+"em";
  89. }
  90. else if (this.toMathMLvariants[value]) {return this.toMathMLvariants[value]}
  91. return this.toMathMLquote(value);
  92. },
  93. toMathMLvariants: {
  94. "-tex-caligraphic": MML.VARIANT.SCRIPT,
  95. "-tex-caligraphic-bold": MML.VARIANT.BOLDSCRIPT,
  96. "-tex-oldstyle": MML.VARIANT.NORMAL,
  97. "-tex-oldstyle-bold": MML.VARIANT.BOLD,
  98. "-tex-mathit": MML.VARIANT.ITALIC
  99. },
  100. toMathMLquote: function (string) {
  101. string = String(string).split("");
  102. for (var i = 0, m = string.length; i < m; i++) {
  103. var n = string[i].charCodeAt(0);
  104. if (n <= 0xD7FF || 0xE000 <= n) {
  105. // Code points U+0000 to U+D7FF and U+E000 to U+FFFF.
  106. // They are directly represented by n.
  107. if (n > 0x7E || (n < 0x20 && n !== 0x0A && n !== 0x0D && n !== 0x09)) {
  108. string[i] = "&#x"+n.toString(16).toUpperCase()+";";
  109. } else {
  110. var c =
  111. {'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;'}[string[i]];
  112. if (c) {string[i] = c}
  113. }
  114. } else if (i+1 < m) {
  115. // Code points U+10000 to U+10FFFF.
  116. // n is the lead surrogate, let's read the trail surrogate.
  117. var trailSurrogate = string[i+1].charCodeAt(0);
  118. var codePoint = (((n-0xD800)<<10)+(trailSurrogate-0xDC00)+0x10000);
  119. string[i] = "&#x"+codePoint.toString(16).toUpperCase()+";";
  120. string[i+1] = "";
  121. i++;
  122. } else {
  123. // n is a lead surrogate without corresponding trail surrogate:
  124. // remove that character.
  125. string[i] = "";
  126. }
  127. }
  128. return string.join("");
  129. }
  130. });
  131. //
  132. // Override math.toMathML in order to add semantics tag
  133. // for the input format, if the user requests that in the
  134. // Show As menu.
  135. //
  136. MML.math.Augment({
  137. toMathML: function (space,jax) {
  138. var annotation;
  139. if (space == null) {space = ""}
  140. if (jax && jax.originalText && SETTINGS.semantics)
  141. {annotation = MathJax.InputJax[jax.inputJax].annotationEncoding}
  142. var nested = (this.data[0] && this.data[0].data.length > 1);
  143. var tag = this.type, attr = this.toMathMLattributes();
  144. var data = [], SPACE = space + (annotation ? " " + (nested ? " " : "") : "") + " ";
  145. for (var i = 0, m = this.data.length; i < m; i++) {
  146. if (this.data[i]) {data.push(this.data[i].toMathML(SPACE))}
  147. else {data.push(SPACE+"<mrow />")}
  148. }
  149. if (data.length === 0 || (data.length === 1 && data[0] === "")) {
  150. if (!annotation) {return "<"+tag+attr+" />"}
  151. data.push(SPACE+"<mrow />");
  152. }
  153. if (annotation) {
  154. if (nested) {data.unshift(space+" <mrow>"); data.push(space+" </mrow>")}
  155. data.unshift(space+" <semantics>");
  156. var xmlEscapedTex = jax.originalText.replace(/[&<>]/g, function(item) {
  157. return { '>': '&gt;', '<': '&lt;','&': '&amp;' }[item]
  158. });
  159. data.push(space+' <annotation encoding="'+this.toMathMLquote(annotation)+'">'+xmlEscapedTex+"</annotation>");
  160. data.push(space+" </semantics>");
  161. }
  162. return space+"<"+tag+attr+">\n"+data.join("\n")+"\n"+space+"</"+tag+">";
  163. }
  164. });
  165. MML.msubsup.Augment({
  166. toMathML: function (space) {
  167. var tag = this.type;
  168. if (this.data[this.sup] == null) {tag = "msub"}
  169. if (this.data[this.sub] == null) {tag = "msup"}
  170. var attr = this.toMathMLattributes();
  171. delete this.data[0].inferred;
  172. var data = [];
  173. for (var i = 0, m = this.data.length; i < m; i++)
  174. {if (this.data[i]) {data.push(this.data[i].toMathML(space+" "))}}
  175. return space + "<"+tag+attr+">\n" + data.join("\n") + "\n" + space + "</"+tag+">";
  176. }
  177. });
  178. MML.munderover.Augment({
  179. toMathML: function (space) {
  180. var tag = this.type;
  181. var base = this.data[this.base];
  182. if (base && base.isa(MML.TeXAtom) && base.movablelimits && !base.Get("displaystyle")) {
  183. type = "msubsup";
  184. if (this.data[this.under] == null) {tag = "msup"}
  185. if (this.data[this.over] == null) {tag = "msub"}
  186. } else {
  187. if (this.data[this.under] == null) {tag = "mover"}
  188. if (this.data[this.over] == null) {tag = "munder"}
  189. }
  190. var attr = this.toMathMLattributes();
  191. delete this.data[0].inferred;
  192. var data = [];
  193. for (var i = 0, m = this.data.length; i < m; i++)
  194. {if (this.data[i]) {data.push(this.data[i].toMathML(space+" "))}}
  195. return space + "<"+tag+attr+">\n" + data.join("\n") + "\n" + space + "</"+tag+">";
  196. }
  197. });
  198. MML.TeXAtom.Augment({
  199. toMathML: function (space) {
  200. // FIXME: Handle spacing using mpadded?
  201. var attr = this.toMathMLattributes();
  202. if (!attr && this.data[0].data.length === 1) {return space.substr(2) + this.data[0].toMathML(space)}
  203. return space+"<mrow"+attr+">\n" + this.data[0].toMathML(space+" ")+"\n"+space+"</mrow>";
  204. }
  205. });
  206. MML.chars.Augment({
  207. toMathML: function (space) {return (space||"") + this.toMathMLquote(this.toString())}
  208. });
  209. MML.entity.Augment({
  210. toMathML: function (space) {return (space||"") + "&"+this.toMathMLquote(this.data[0])+";<!-- "+this.toString()+" -->"}
  211. });
  212. MML.xml.Augment({
  213. toMathML: function (space) {return (space||"") + this.toString()}
  214. });
  215. MathJax.Hub.Register.StartupHook("TeX mathchoice Ready",function () {
  216. MML.TeXmathchoice.Augment({
  217. toMathML: function (space) {return this.Core().toMathML(space)}
  218. });
  219. });
  220. MathJax.Hub.Startup.signal.Post("toMathML Ready");
  221. });
  222. MathJax.Ajax.loadComplete("[MathJax]/extensions/toMathML.js");