toMathML.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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-2015 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.5.0";
  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 || !this.attr.xmlns))
  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) {CLASS.push("MJX-TeXAtom-"+TEXCLASS)}
  75. }
  76. if (this.mathvariant && this.toMathMLvariants[this.mathvariant])
  77. {CLASS.push("MJX"+this.mathvariant)}
  78. if (this.variantForm) {CLASS.push("MJX-variant")}
  79. if (CLASS.length) {attr.unshift('class="'+CLASS.join(" ")+'"')}
  80. },
  81. toMathMLattribute: function (value) {
  82. if (typeof(value) === "string" &&
  83. value.replace(/ /g,"").match(/^(([-+])?(\d+(\.\d*)?|\.\d+))mu$/)) {
  84. // FIXME: should take scriptlevel into account
  85. return (RegExp.$2||"")+((1/18)*RegExp.$3).toFixed(3).replace(/\.?0+$/,"")+"em";
  86. }
  87. else if (this.toMathMLvariants[value]) {return this.toMathMLvariants[value]}
  88. return this.toMathMLquote(value);
  89. },
  90. toMathMLvariants: {
  91. "-tex-caligraphic": MML.VARIANT.SCRIPT,
  92. "-tex-caligraphic-bold": MML.VARIANT.BOLDSCRIPT,
  93. "-tex-oldstyle": MML.VARIANT.NORMAL,
  94. "-tex-oldstyle-bold": MML.VARIANT.BOLD,
  95. "-tex-mathit": MML.VARIANT.ITALIC
  96. },
  97. toMathMLquote: function (string) {
  98. string = String(string).split("");
  99. for (var i = 0, m = string.length; i < m; i++) {
  100. var n = string[i].charCodeAt(0);
  101. if (n <= 0xD7FF || 0xE000 <= n) {
  102. // Code points U+0000 to U+D7FF and U+E000 to U+FFFF.
  103. // They are directly represented by n.
  104. if (n > 0x7E || (n < 0x20 && n !== 0x0A && n !== 0x0D && n !== 0x09)) {
  105. string[i] = "&#x"+n.toString(16).toUpperCase()+";";
  106. } else {
  107. var c =
  108. {'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;'}[string[i]];
  109. if (c) {string[i] = c}
  110. }
  111. } else if (i+1 < m) {
  112. // Code points U+10000 to U+10FFFF.
  113. // n is the lead surrogate, let's read the trail surrogate.
  114. var trailSurrogate = string[i+1].charCodeAt(0);
  115. var codePoint = (((n-0xD800)<<10)+(trailSurrogate-0xDC00)+0x10000);
  116. string[i] = "&#x"+codePoint.toString(16).toUpperCase()+";";
  117. string[i+1] = "";
  118. i++;
  119. } else {
  120. // n is a lead surrogate without corresponding trail surrogate:
  121. // remove that character.
  122. string[i] = "";
  123. }
  124. }
  125. return string.join("");
  126. }
  127. });
  128. //
  129. // Override math.toMathML in order to add semantics tag
  130. // for the input format, if the user requests that in the
  131. // Show As menu.
  132. //
  133. MML.math.Augment({
  134. toMathML: function (space,jax) {
  135. var annotation;
  136. if (space == null) {space = ""}
  137. if (jax && jax.originalText && SETTINGS.semantics)
  138. {annotation = MathJax.InputJax[jax.inputJax].annotationEncoding}
  139. var nested = (this.data[0] && this.data[0].data.length > 1);
  140. var tag = this.type, attr = this.toMathMLattributes();
  141. var data = [], SPACE = space + (annotation ? " " + (nested ? " " : "") : "") + " ";
  142. for (var i = 0, m = this.data.length; i < m; i++) {
  143. if (this.data[i]) {data.push(this.data[i].toMathML(SPACE))}
  144. else {data.push(SPACE+"<mrow />")}
  145. }
  146. if (data.length === 0 || (data.length === 1 && data[0] === "")) {
  147. if (!annotation) {return "<"+tag+attr+" />"}
  148. data.push(SPACE+"<mrow />");
  149. }
  150. if (annotation) {
  151. if (nested) {data.unshift(space+" <mrow>"); data.push(space+" </mrow>")}
  152. data.unshift(space+" <semantics>");
  153. var xmlEscapedTex = jax.originalText.replace(/[&<>]/g, function(item) {
  154. return { '>': '&gt;', '<': '&lt;','&': '&amp;' }[item]
  155. });
  156. data.push(space+' <annotation encoding="'+annotation+'">'+xmlEscapedTex+"</annotation>");
  157. data.push(space+" </semantics>");
  158. }
  159. return space+"<"+tag+attr+">\n"+data.join("\n")+"\n"+space+"</"+tag+">";
  160. }
  161. });
  162. MML.msubsup.Augment({
  163. toMathML: function (space) {
  164. var tag = this.type;
  165. if (this.data[this.sup] == null) {tag = "msub"}
  166. if (this.data[this.sub] == null) {tag = "msup"}
  167. var attr = this.toMathMLattributes();
  168. delete this.data[0].inferred;
  169. var data = [];
  170. for (var i = 0, m = this.data.length; i < m; i++)
  171. {if (this.data[i]) {data.push(this.data[i].toMathML(space+" "))}}
  172. return space + "<"+tag+attr+">\n" + data.join("\n") + "\n" + space + "</"+tag+">";
  173. }
  174. });
  175. MML.munderover.Augment({
  176. toMathML: function (space) {
  177. var tag = this.type;
  178. if (this.data[this.under] == null) {tag = "mover"}
  179. if (this.data[this.over] == null) {tag = "munder"}
  180. var attr = this.toMathMLattributes();
  181. delete this.data[0].inferred;
  182. var data = [];
  183. for (var i = 0, m = this.data.length; i < m; i++)
  184. {if (this.data[i]) {data.push(this.data[i].toMathML(space+" "))}}
  185. return space + "<"+tag+attr+">\n" + data.join("\n") + "\n" + space + "</"+tag+">";
  186. }
  187. });
  188. MML.TeXAtom.Augment({
  189. toMathML: function (space) {
  190. // FIXME: Handle spacing using mpadded?
  191. var attr = this.toMathMLattributes();
  192. if (!attr && this.data[0].data.length === 1) {return space.substr(2) + this.data[0].toMathML(space)}
  193. return space+"<mrow"+attr+">\n" + this.data[0].toMathML(space+" ")+"\n"+space+"</mrow>";
  194. }
  195. });
  196. MML.chars.Augment({
  197. toMathML: function (space) {return (space||"") + this.toMathMLquote(this.toString())}
  198. });
  199. MML.entity.Augment({
  200. toMathML: function (space) {return (space||"") + "&"+this.data[0]+";<!-- "+this.toString()+" -->"}
  201. });
  202. MML.xml.Augment({
  203. toMathML: function (space) {return (space||"") + this.toString()}
  204. });
  205. MathJax.Hub.Register.StartupHook("TeX mathchoice Ready",function () {
  206. MML.TeXmathchoice.Augment({
  207. toMathML: function (space) {return this.Core().toMathML(space)}
  208. });
  209. });
  210. MathJax.Hub.Startup.signal.Post("toMathML Ready");
  211. });
  212. MathJax.Ajax.loadComplete("[MathJax]/extensions/toMathML.js");