jax.js 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351
  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/jax/input/TeX/jax.js
  6. *
  7. * Implements the TeX InputJax that reads mathematics in
  8. * TeX and LaTeX format and converts it to the MML ElementJax
  9. * internal format.
  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. (function (TEX,HUB,AJAX) {
  28. var MML, NBSP = "\u00A0";
  29. var _ = function (id) {
  30. return MathJax.Localization._.apply(MathJax.Localization,
  31. [["TeX", id]].concat([].slice.call(arguments,1)));
  32. };
  33. var isArray = MathJax.Object.isArray;
  34. var STACK = MathJax.Object.Subclass({
  35. Init: function (env,inner) {
  36. this.global = {isInner: inner};
  37. this.data = [STACKITEM.start(this.global)];
  38. if (env) {this.data[0].env = env}
  39. this.env = this.data[0].env;
  40. },
  41. Push: function () {
  42. var i, m, item, top;
  43. for (i = 0, m = arguments.length; i < m; i++) {
  44. item = arguments[i]; if (!item) continue;
  45. if (item instanceof MML.mbase) {item = STACKITEM.mml(item)}
  46. item.global = this.global;
  47. top = (this.data.length ? this.Top().checkItem(item) : true);
  48. if (top instanceof Array) {this.Pop(); this.Push.apply(this,top)}
  49. else if (top instanceof STACKITEM) {this.Pop(); this.Push(top)}
  50. else if (top) {
  51. this.data.push(item);
  52. if (item.env) {
  53. if (item.copyEnv !== false) {
  54. for (var id in this.env)
  55. {if (this.env.hasOwnProperty(id)) {item.env[id] = this.env[id]}}
  56. }
  57. this.env = item.env;
  58. } else {item.env = this.env}
  59. }
  60. }
  61. },
  62. Pop: function () {
  63. var item = this.data.pop(); if (!item.isOpen) {delete item.env}
  64. this.env = (this.data.length ? this.Top().env : {});
  65. return item;
  66. },
  67. Top: function (n) {
  68. if (n == null) {n = 1}
  69. if (this.data.length < n) {return null}
  70. return this.data[this.data.length-n];
  71. },
  72. Prev: function (noPop) {
  73. var top = this.Top();
  74. if (noPop) {return top.data[top.data.length-1]}
  75. else {return top.Pop()}
  76. },
  77. toString: function () {return "stack[\n "+this.data.join("\n ")+"\n]"}
  78. });
  79. var STACKITEM = STACK.Item = MathJax.Object.Subclass({
  80. type: "base",
  81. endError: /*_()*/ ["ExtraOpenMissingClose","Extra open brace or missing close brace"],
  82. closeError: /*_()*/ ["ExtraCloseMissingOpen","Extra close brace or missing open brace"],
  83. rightError: /*_()*/ ["MissingLeftExtraRight","Missing \\left or extra \\right"],
  84. Init: function () {
  85. if (this.isOpen) {this.env = {}}
  86. this.data = [];
  87. this.Push.apply(this,arguments);
  88. },
  89. Push: function () {this.data.push.apply(this.data,arguments)},
  90. Pop: function () {return this.data.pop()},
  91. mmlData: function (inferred,forceRow) {
  92. if (inferred == null) {inferred = true}
  93. if (this.data.length === 1 && !forceRow) {return this.data[0]}
  94. return MML.mrow.apply(MML,this.data).With((inferred ? {inferred: true}: {}));
  95. },
  96. checkItem: function (item) {
  97. if (item.type === "over" && this.isOpen) {item.num = this.mmlData(false); this.data = []}
  98. if (item.type === "cell" && this.isOpen) {
  99. if (item.linebreak) {return false}
  100. TEX.Error(["Misplaced","Misplaced %1",item.name]);
  101. }
  102. if (item.isClose && this[item.type+"Error"]) {TEX.Error(this[item.type+"Error"])}
  103. if (!item.isNotStack) {return true}
  104. this.Push(item.data[0]); return false;
  105. },
  106. With: function (def) {
  107. for (var id in def) {if (def.hasOwnProperty(id)) {this[id] = def[id]}}
  108. return this;
  109. },
  110. toString: function () {return this.type+"["+this.data.join("; ")+"]"}
  111. });
  112. STACKITEM.start = STACKITEM.Subclass({
  113. type: "start", isOpen: true,
  114. Init: function (global) {
  115. this.SUPER(arguments).Init.call(this);
  116. this.global = global;
  117. },
  118. checkItem: function (item) {
  119. if (item.type === "stop") {return STACKITEM.mml(this.mmlData())}
  120. return this.SUPER(arguments).checkItem.call(this,item);
  121. }
  122. });
  123. STACKITEM.stop = STACKITEM.Subclass({
  124. type: "stop", isClose: true
  125. });
  126. STACKITEM.open = STACKITEM.Subclass({
  127. type: "open", isOpen: true,
  128. stopError: /*_()*/ ["ExtraOpenMissingClose","Extra open brace or missing close brace"],
  129. checkItem: function (item) {
  130. if (item.type === "close") {
  131. var mml = this.mmlData();
  132. return STACKITEM.mml(MML.TeXAtom(mml)); // TeXAtom make it an ORD to prevent spacing (FIXME: should be another way)
  133. }
  134. return this.SUPER(arguments).checkItem.call(this,item);
  135. }
  136. });
  137. STACKITEM.close = STACKITEM.Subclass({
  138. type: "close", isClose: true
  139. });
  140. STACKITEM.prime = STACKITEM.Subclass({
  141. type: "prime",
  142. checkItem: function (item) {
  143. if (this.data[0].type !== "msubsup")
  144. {return [MML.msup(this.data[0],this.data[1]),item]}
  145. this.data[0].SetData(this.data[0].sup,this.data[1]);
  146. return [this.data[0],item];
  147. }
  148. });
  149. STACKITEM.subsup = STACKITEM.Subclass({
  150. type: "subsup",
  151. stopError: /*_()*/ ["MissingScript","Missing superscript or subscript argument"],
  152. supError: /*_()*/ ["MissingOpenForSup","Missing open brace for superscript"],
  153. subError: /*_()*/ ["MissingOpenForSub","Missing open brace for subscript"],
  154. checkItem: function (item) {
  155. if (item.type === "open" || item.type === "left") {return true}
  156. if (item.type === "mml") {
  157. if (this.primes) {
  158. if (this.position !== 2) {this.data[0].SetData(2,this.primes)}
  159. else {item.data[0] = MML.mrow(this.primes.With({variantForm:true}),item.data[0])}
  160. }
  161. this.data[0].SetData(this.position,item.data[0]);
  162. if (this.movesupsub != null) {this.data[0].movesupsub = this.movesupsub}
  163. return STACKITEM.mml(this.data[0]);
  164. }
  165. if (this.SUPER(arguments).checkItem.call(this,item))
  166. {TEX.Error(this[["","subError","supError"][this.position]])}
  167. },
  168. Pop: function () {}
  169. });
  170. STACKITEM.over = STACKITEM.Subclass({
  171. type: "over", isClose: true, name: "\\over",
  172. checkItem: function (item,stack) {
  173. if (item.type === "over")
  174. {TEX.Error(["AmbiguousUseOf","Ambiguous use of %1",item.name])}
  175. if (item.isClose) {
  176. var mml = MML.mfrac(this.num,this.mmlData(false));
  177. if (this.thickness != null) {mml.linethickness = this.thickness}
  178. if (this.open || this.close) {
  179. mml.texWithDelims = true;
  180. mml = TEX.fixedFence(this.open,mml,this.close);
  181. }
  182. return [STACKITEM.mml(mml), item];
  183. }
  184. return this.SUPER(arguments).checkItem.call(this,item);
  185. },
  186. toString: function () {return "over["+this.num+" / "+this.data.join("; ")+"]"}
  187. });
  188. STACKITEM.left = STACKITEM.Subclass({
  189. type: "left", isOpen: true, delim: '(',
  190. stopError: /*_()*/ ["ExtraLeftMissingRight", "Extra \\left or missing \\right"],
  191. checkItem: function (item) {
  192. if (item.type === "right")
  193. {return STACKITEM.mml(TEX.fenced(this.delim,this.mmlData(),item.delim))}
  194. return this.SUPER(arguments).checkItem.call(this,item);
  195. }
  196. });
  197. STACKITEM.right = STACKITEM.Subclass({
  198. type: "right", isClose: true, delim: ')'
  199. });
  200. STACKITEM.begin = STACKITEM.Subclass({
  201. type: "begin", isOpen: true,
  202. checkItem: function (item) {
  203. if (item.type === "end") {
  204. if (item.name !== this.name)
  205. {TEX.Error(["EnvBadEnd","\\begin{%1} ended with \\end{%2}",this.name,item.name])}
  206. if (!this.end) {return STACKITEM.mml(this.mmlData())}
  207. return this.parse[this.end].call(this.parse,this,this.data);
  208. }
  209. if (item.type === "stop")
  210. {TEX.Error(["EnvMissingEnd","Missing \\end{%1}",this.name])}
  211. return this.SUPER(arguments).checkItem.call(this,item);
  212. }
  213. });
  214. STACKITEM.end = STACKITEM.Subclass({
  215. type: "end", isClose: true
  216. });
  217. STACKITEM.style = STACKITEM.Subclass({
  218. type: "style",
  219. checkItem: function (item) {
  220. if (!item.isClose) {return this.SUPER(arguments).checkItem.call(this,item)}
  221. var mml = MML.mstyle.apply(MML,this.data).With(this.styles);
  222. return [STACKITEM.mml(mml),item];
  223. }
  224. });
  225. STACKITEM.position = STACKITEM.Subclass({
  226. type: "position",
  227. checkItem: function (item) {
  228. if (item.isClose) {TEX.Error(["MissingBoxFor","Missing box for %1",this.name])}
  229. if (item.isNotStack) {
  230. var mml = item.mmlData();
  231. switch (this.move) {
  232. case 'vertical':
  233. mml = MML.mpadded(mml).With({height: this.dh, depth: this.dd, voffset: this.dh});
  234. return [STACKITEM.mml(mml)];
  235. case 'horizontal':
  236. return [STACKITEM.mml(this.left),item,STACKITEM.mml(this.right)];
  237. }
  238. }
  239. return this.SUPER(arguments).checkItem.call(this,item);
  240. }
  241. });
  242. STACKITEM.array = STACKITEM.Subclass({
  243. type: "array", isOpen: true, copyEnv: false, arraydef: {},
  244. Init: function () {
  245. this.table = []; this.row = []; this.frame = []; this.hfill = [];
  246. this.SUPER(arguments).Init.apply(this,arguments);
  247. },
  248. checkItem: function (item) {
  249. if (item.isClose && item.type !== "over") {
  250. if (item.isEntry) {this.EndEntry(); this.clearEnv(); return false}
  251. if (item.isCR) {this.EndEntry(); this.EndRow(); this.clearEnv(); return false}
  252. this.EndTable(); this.clearEnv();
  253. var scriptlevel = this.arraydef.scriptlevel; delete this.arraydef.scriptlevel;
  254. var mml = MML.mtable.apply(MML,this.table).With(this.arraydef);
  255. if (this.frame.length === 4) {
  256. mml.frame = (this.frame.dashed ? "dashed" : "solid");
  257. } else if (this.frame.length) {
  258. mml.hasFrame = true;
  259. if (this.arraydef.rowlines) {this.arraydef.rowlines = this.arraydef.rowlines.replace(/none( none)+$/,"none")}
  260. mml = MML.menclose(mml).With({notation: this.frame.join(" "), isFrame: true});
  261. if ((this.arraydef.columnlines||"none") != "none" ||
  262. (this.arraydef.rowlines||"none") != "none") {mml.padding = 0} // HTML-CSS jax implements this
  263. }
  264. if (scriptlevel) {mml = MML.mstyle(mml).With({scriptlevel: scriptlevel})}
  265. if (this.open || this.close) {mml = TEX.fenced(this.open,mml,this.close)}
  266. mml = STACKITEM.mml(mml);
  267. if (this.requireClose) {
  268. if (item.type === 'close') {return mml}
  269. TEX.Error(["MissingCloseBrace","Missing close brace"]);
  270. }
  271. return [mml,item];
  272. }
  273. return this.SUPER(arguments).checkItem.call(this,item);
  274. },
  275. EndEntry: function () {
  276. var mtd = MML.mtd.apply(MML,this.data);
  277. if (this.hfill.length) {
  278. if (this.hfill[0] === 0) mtd.columnalign = "right";
  279. if (this.hfill[this.hfill.length-1] === this.data.length)
  280. mtd.columnalign = (mtd.columnalign ? "center" : "left");
  281. }
  282. this.row.push(mtd); this.data = []; this.hfill = [];
  283. },
  284. EndRow: function () {
  285. var mtr = MML.mtr;
  286. if (this.isNumbered && this.row.length === 3) {
  287. this.row.unshift(this.row.pop()); // move equation number to first position
  288. mtr = MML.mlabeledtr;
  289. }
  290. this.table.push(mtr.apply(MML,this.row)); this.row = [];
  291. },
  292. EndTable: function () {
  293. if (this.data.length || this.row.length) {this.EndEntry(); this.EndRow()}
  294. this.checkLines();
  295. },
  296. checkLines: function () {
  297. if (this.arraydef.rowlines) {
  298. var lines = this.arraydef.rowlines.split(/ /);
  299. if (lines.length === this.table.length) {
  300. this.frame.push("bottom"); lines.pop();
  301. this.arraydef.rowlines = lines.join(' ');
  302. } else if (lines.length < this.table.length-1) {
  303. this.arraydef.rowlines += " none";
  304. }
  305. }
  306. if (this.rowspacing) {
  307. var rows = this.arraydef.rowspacing.split(/ /);
  308. while (rows.length < this.table.length) {rows.push(this.rowspacing+"em")}
  309. this.arraydef.rowspacing = rows.join(' ');
  310. }
  311. },
  312. clearEnv: function () {
  313. for (var id in this.env) {if (this.env.hasOwnProperty(id)) {delete this.env[id]}}
  314. }
  315. });
  316. STACKITEM.cell = STACKITEM.Subclass({
  317. type: "cell", isClose: true
  318. });
  319. STACKITEM.mml = STACKITEM.Subclass({
  320. type: "mml", isNotStack: true,
  321. Add: function () {this.data.push.apply(this.data,arguments); return this}
  322. });
  323. STACKITEM.fn = STACKITEM.Subclass({
  324. type: "fn",
  325. checkItem: function (item) {
  326. if (this.data[0]) {
  327. if (item.isOpen) {return true}
  328. if (item.type !== "fn") {
  329. if (item.type !== "mml" || !item.data[0]) {return [this.data[0],item]}
  330. if (item.data[0].isa(MML.mspace)) {return [this.data[0],item]}
  331. var mml = item.data[0]; if (mml.isEmbellished()) {mml = mml.CoreMO()}
  332. if ([0,0,1,1,0,1,1,0,0,0][mml.Get("texClass")]) {return [this.data[0],item]}
  333. }
  334. return [this.data[0],MML.mo(MML.entity("#x2061")).With({texClass:MML.TEXCLASS.NONE}),item];
  335. }
  336. return this.SUPER(arguments).checkItem.apply(this,arguments);
  337. }
  338. });
  339. STACKITEM.not = STACKITEM.Subclass({
  340. type: "not",
  341. checkItem: function (item) {
  342. var mml, c;
  343. if (item.type === "open" || item.type === "left") {return true}
  344. if (item.type === "mml" && item.data[0].type.match(/^(mo|mi|mtext)$/)) {
  345. mml = item.data[0], c = mml.data.join("");
  346. if (c.length === 1 && !mml.movesupsub && mml.data.length === 1) {
  347. c = STACKITEM.not.remap[c.charCodeAt(0)];
  348. if (c) {mml.SetData(0,MML.chars(String.fromCharCode(c)))}
  349. else {mml.Append(MML.chars("\u0338"))}
  350. return item;
  351. }
  352. }
  353. // \mathrel{\rlap{\notChar}}
  354. mml = MML.mpadded(MML.mtext("\u29F8")).With({width:0});
  355. mml = MML.TeXAtom(mml).With({texClass:MML.TEXCLASS.REL});
  356. return [mml,item];
  357. }
  358. });
  359. STACKITEM.not.remap = {
  360. 0x2190:0x219A, 0x2192:0x219B, 0x2194:0x21AE,
  361. 0x21D0:0x21CD, 0x21D2:0x21CF, 0x21D4:0x21CE,
  362. 0x2208:0x2209, 0x220B:0x220C, 0x2223:0x2224, 0x2225:0x2226,
  363. 0x223C:0x2241, 0x007E:0x2241, 0x2243:0x2244, 0x2245:0x2247,
  364. 0x2248:0x2249, 0x224D:0x226D, 0x003D:0x2260, 0x2261:0x2262,
  365. 0x003C:0x226E, 0x003E:0x226F, 0x2264:0x2270, 0x2265:0x2271,
  366. 0x2272:0x2274, 0x2273:0x2275, 0x2276:0x2278, 0x2277:0x2279,
  367. 0x227A:0x2280, 0x227B:0x2281, 0x2282:0x2284, 0x2283:0x2285,
  368. 0x2286:0x2288, 0x2287:0x2289, 0x22A2:0x22AC, 0x22A8:0x22AD,
  369. 0x22A9:0x22AE, 0x22AB:0x22AF, 0x227C:0x22E0, 0x227D:0x22E1,
  370. 0x2291:0x22E2, 0x2292:0x22E3, 0x22B2:0x22EA, 0x22B3:0x22EB,
  371. 0x22B4:0x22EC, 0x22B5:0x22ED, 0x2203:0x2204
  372. };
  373. STACKITEM.dots = STACKITEM.Subclass({
  374. type: "dots",
  375. checkItem: function (item) {
  376. if (item.type === "open" || item.type === "left") {return true}
  377. var dots = this.ldots;
  378. if (item.type === "mml" && item.data[0].isEmbellished()) {
  379. var tclass = item.data[0].CoreMO().Get("texClass");
  380. if (tclass === MML.TEXCLASS.BIN || tclass === MML.TEXCLASS.REL) {dots = this.cdots}
  381. }
  382. return [dots,item];
  383. }
  384. });
  385. var TEXDEF = {
  386. //
  387. // Add new definitions without overriding user-defined ones
  388. //
  389. Add: function (src,dst,nouser) {
  390. if (!dst) {dst = this}
  391. for (var id in src) {if (src.hasOwnProperty(id)) {
  392. if (typeof src[id] === 'object' && !isArray(src[id]) &&
  393. (typeof dst[id] === 'object' || typeof dst[id] === 'function'))
  394. {this.Add(src[id],dst[id],src[id],nouser)}
  395. else if (!dst[id] || !dst[id].isUser || !nouser) {dst[id] = src[id]}
  396. }}
  397. return dst;
  398. }
  399. };
  400. var STARTUP = function () {
  401. MML = MathJax.ElementJax.mml;
  402. HUB.Insert(TEXDEF,{
  403. // patterns for letters and numbers
  404. letter: /[a-z]/i,
  405. digit: /[0-9.]/,
  406. number: /^(?:[0-9]+(?:\{,\}[0-9]{3})*(?:\.[0-9]*)*|\.[0-9]+)/,
  407. special: {
  408. '\\': 'ControlSequence',
  409. '{': 'Open',
  410. '}': 'Close',
  411. '~': 'Tilde',
  412. '^': 'Superscript',
  413. '_': 'Subscript',
  414. ' ': 'Space',
  415. "\t": 'Space',
  416. "\r": 'Space',
  417. "\n": 'Space',
  418. "'": 'Prime',
  419. '%': 'Comment',
  420. '&': 'Entry',
  421. '#': 'Hash',
  422. '\u00A0': 'Space',
  423. '\u2019': 'Prime'
  424. },
  425. remap: {
  426. '-': '2212',
  427. '*': '2217',
  428. '`': '2018' // map ` to back quote
  429. },
  430. mathchar0mi: {
  431. // Lower-case greek
  432. alpha: '03B1',
  433. beta: '03B2',
  434. gamma: '03B3',
  435. delta: '03B4',
  436. epsilon: '03F5',
  437. zeta: '03B6',
  438. eta: '03B7',
  439. theta: '03B8',
  440. iota: '03B9',
  441. kappa: '03BA',
  442. lambda: '03BB',
  443. mu: '03BC',
  444. nu: '03BD',
  445. xi: '03BE',
  446. omicron: '03BF', // added for completeness
  447. pi: '03C0',
  448. rho: '03C1',
  449. sigma: '03C3',
  450. tau: '03C4',
  451. upsilon: '03C5',
  452. phi: '03D5',
  453. chi: '03C7',
  454. psi: '03C8',
  455. omega: '03C9',
  456. varepsilon: '03B5',
  457. vartheta: '03D1',
  458. varpi: '03D6',
  459. varrho: '03F1',
  460. varsigma: '03C2',
  461. varphi: '03C6',
  462. // Ord symbols
  463. S: ['00A7',{mathvariant: MML.VARIANT.NORMAL}],
  464. aleph: ['2135',{mathvariant: MML.VARIANT.NORMAL}],
  465. hbar: ['210F',{variantForm:true}],
  466. imath: '0131',
  467. jmath: '0237',
  468. ell: '2113',
  469. wp: ['2118',{mathvariant: MML.VARIANT.NORMAL}],
  470. Re: ['211C',{mathvariant: MML.VARIANT.NORMAL}],
  471. Im: ['2111',{mathvariant: MML.VARIANT.NORMAL}],
  472. partial: ['2202',{mathvariant: MML.VARIANT.NORMAL}],
  473. infty: ['221E',{mathvariant: MML.VARIANT.NORMAL}],
  474. prime: ['2032',{mathvariant: MML.VARIANT.NORMAL, variantForm:true}],
  475. emptyset: ['2205',{mathvariant: MML.VARIANT.NORMAL}],
  476. nabla: ['2207',{mathvariant: MML.VARIANT.NORMAL}],
  477. top: ['22A4',{mathvariant: MML.VARIANT.NORMAL}],
  478. bot: ['22A5',{mathvariant: MML.VARIANT.NORMAL}],
  479. angle: ['2220',{mathvariant: MML.VARIANT.NORMAL}],
  480. triangle: ['25B3',{mathvariant: MML.VARIANT.NORMAL}],
  481. backslash: ['2216',{mathvariant: MML.VARIANT.NORMAL, variantForm:true}],
  482. forall: ['2200',{mathvariant: MML.VARIANT.NORMAL}],
  483. exists: ['2203',{mathvariant: MML.VARIANT.NORMAL}],
  484. neg: ['00AC',{mathvariant: MML.VARIANT.NORMAL}],
  485. lnot: ['00AC',{mathvariant: MML.VARIANT.NORMAL}],
  486. flat: ['266D',{mathvariant: MML.VARIANT.NORMAL}],
  487. natural: ['266E',{mathvariant: MML.VARIANT.NORMAL}],
  488. sharp: ['266F',{mathvariant: MML.VARIANT.NORMAL}],
  489. clubsuit: ['2663',{mathvariant: MML.VARIANT.NORMAL}],
  490. diamondsuit: ['2662',{mathvariant: MML.VARIANT.NORMAL}],
  491. heartsuit: ['2661',{mathvariant: MML.VARIANT.NORMAL}],
  492. spadesuit: ['2660',{mathvariant: MML.VARIANT.NORMAL}]
  493. },
  494. mathchar0mo: {
  495. surd: '221A',
  496. // big ops
  497. coprod: ['2210',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  498. bigvee: ['22C1',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  499. bigwedge: ['22C0',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  500. biguplus: ['2A04',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  501. bigcap: ['22C2',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  502. bigcup: ['22C3',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  503. 'int': ['222B',{texClass: MML.TEXCLASS.OP}],
  504. intop: ['222B',{texClass: MML.TEXCLASS.OP, movesupsub:true, movablelimits:true}],
  505. iint: ['222C',{texClass: MML.TEXCLASS.OP}],
  506. iiint: ['222D',{texClass: MML.TEXCLASS.OP}],
  507. prod: ['220F',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  508. sum: ['2211',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  509. bigotimes: ['2A02',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  510. bigoplus: ['2A01',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  511. bigodot: ['2A00',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  512. oint: ['222E',{texClass: MML.TEXCLASS.OP}],
  513. bigsqcup: ['2A06',{texClass: MML.TEXCLASS.OP, movesupsub:true}],
  514. smallint: ['222B',{largeop:false}],
  515. // binary operations
  516. triangleleft: '25C3',
  517. triangleright: '25B9',
  518. bigtriangleup: '25B3',
  519. bigtriangledown: '25BD',
  520. wedge: '2227',
  521. land: '2227',
  522. vee: '2228',
  523. lor: '2228',
  524. cap: '2229',
  525. cup: '222A',
  526. ddagger: '2021',
  527. dagger: '2020',
  528. sqcap: '2293',
  529. sqcup: '2294',
  530. uplus: '228E',
  531. amalg: '2A3F',
  532. diamond: '22C4',
  533. bullet: '2219',
  534. wr: '2240',
  535. div: '00F7',
  536. odot: ['2299',{largeop: false}],
  537. oslash: ['2298',{largeop: false}],
  538. otimes: ['2297',{largeop: false}],
  539. ominus: ['2296',{largeop: false}],
  540. oplus: ['2295',{largeop: false}],
  541. mp: '2213',
  542. pm: '00B1',
  543. circ: '2218',
  544. bigcirc: '25EF',
  545. setminus: ['2216',{variantForm:true}],
  546. cdot: '22C5',
  547. ast: '2217',
  548. times: '00D7',
  549. star: '22C6',
  550. // Relations
  551. propto: '221D',
  552. sqsubseteq: '2291',
  553. sqsupseteq: '2292',
  554. parallel: '2225',
  555. mid: '2223',
  556. dashv: '22A3',
  557. vdash: '22A2',
  558. leq: '2264',
  559. le: '2264',
  560. geq: '2265',
  561. ge: '2265',
  562. lt: '003C',
  563. gt: '003E',
  564. succ: '227B',
  565. prec: '227A',
  566. approx: '2248',
  567. succeq: '2AB0', // or '227C',
  568. preceq: '2AAF', // or '227D',
  569. supset: '2283',
  570. subset: '2282',
  571. supseteq: '2287',
  572. subseteq: '2286',
  573. 'in': '2208',
  574. ni: '220B',
  575. notin: '2209',
  576. owns: '220B',
  577. gg: '226B',
  578. ll: '226A',
  579. sim: '223C',
  580. simeq: '2243',
  581. perp: '22A5',
  582. equiv: '2261',
  583. asymp: '224D',
  584. smile: '2323',
  585. frown: '2322',
  586. ne: '2260',
  587. neq: '2260',
  588. cong: '2245',
  589. doteq: '2250',
  590. bowtie: '22C8',
  591. models: '22A8',
  592. notChar: '29F8',
  593. // Arrows
  594. Leftrightarrow: '21D4',
  595. Leftarrow: '21D0',
  596. Rightarrow: '21D2',
  597. leftrightarrow: '2194',
  598. leftarrow: '2190',
  599. gets: '2190',
  600. rightarrow: '2192',
  601. to: '2192',
  602. mapsto: '21A6',
  603. leftharpoonup: '21BC',
  604. leftharpoondown: '21BD',
  605. rightharpoonup: '21C0',
  606. rightharpoondown: '21C1',
  607. nearrow: '2197',
  608. searrow: '2198',
  609. nwarrow: '2196',
  610. swarrow: '2199',
  611. rightleftharpoons: '21CC',
  612. hookrightarrow: '21AA',
  613. hookleftarrow: '21A9',
  614. longleftarrow: '27F5',
  615. Longleftarrow: '27F8',
  616. longrightarrow: '27F6',
  617. Longrightarrow: '27F9',
  618. Longleftrightarrow: '27FA',
  619. longleftrightarrow: '27F7',
  620. longmapsto: '27FC',
  621. // Misc.
  622. ldots: '2026',
  623. cdots: '22EF',
  624. vdots: '22EE',
  625. ddots: '22F1',
  626. dotsc: '2026', // dots with commas
  627. dotsb: '22EF', // dots with binary ops and relations
  628. dotsm: '22EF', // dots with multiplication
  629. dotsi: '22EF', // dots with integrals
  630. dotso: '2026', // other dots
  631. ldotp: ['002E', {texClass: MML.TEXCLASS.PUNCT}],
  632. cdotp: ['22C5', {texClass: MML.TEXCLASS.PUNCT}],
  633. colon: ['003A', {texClass: MML.TEXCLASS.PUNCT}]
  634. },
  635. mathchar7: {
  636. Gamma: '0393',
  637. Delta: '0394',
  638. Theta: '0398',
  639. Lambda: '039B',
  640. Xi: '039E',
  641. Pi: '03A0',
  642. Sigma: '03A3',
  643. Upsilon: '03A5',
  644. Phi: '03A6',
  645. Psi: '03A8',
  646. Omega: '03A9',
  647. '_': '005F',
  648. '#': '0023',
  649. '$': '0024',
  650. '%': '0025',
  651. '&': '0026',
  652. And: '0026'
  653. },
  654. delimiter: {
  655. '(': '(',
  656. ')': ')',
  657. '[': '[',
  658. ']': ']',
  659. '<': '27E8',
  660. '>': '27E9',
  661. '\\lt': '27E8',
  662. '\\gt': '27E9',
  663. '/': '/',
  664. '|': ['|',{texClass:MML.TEXCLASS.ORD}],
  665. '.': '',
  666. '\\\\': '\\',
  667. '\\lmoustache': '23B0', // non-standard
  668. '\\rmoustache': '23B1', // non-standard
  669. '\\lgroup': '27EE', // non-standard
  670. '\\rgroup': '27EF', // non-standard
  671. '\\arrowvert': '23D0',
  672. '\\Arrowvert': '2016',
  673. '\\bracevert': '23AA', // non-standard
  674. '\\Vert': ['2016',{texClass:MML.TEXCLASS.ORD}],
  675. '\\|': ['2016',{texClass:MML.TEXCLASS.ORD}],
  676. '\\vert': ['|',{texClass:MML.TEXCLASS.ORD}],
  677. '\\uparrow': '2191',
  678. '\\downarrow': '2193',
  679. '\\updownarrow': '2195',
  680. '\\Uparrow': '21D1',
  681. '\\Downarrow': '21D3',
  682. '\\Updownarrow': '21D5',
  683. '\\backslash': '\\',
  684. '\\rangle': '27E9',
  685. '\\langle': '27E8',
  686. '\\rbrace': '}',
  687. '\\lbrace': '{',
  688. '\\}': '}',
  689. '\\{': '{',
  690. '\\rceil': '2309',
  691. '\\lceil': '2308',
  692. '\\rfloor': '230B',
  693. '\\lfloor': '230A',
  694. '\\lbrack': '[',
  695. '\\rbrack': ']'
  696. },
  697. macros: {
  698. displaystyle: ['SetStyle','D',true,0],
  699. textstyle: ['SetStyle','T',false,0],
  700. scriptstyle: ['SetStyle','S',false,1],
  701. scriptscriptstyle: ['SetStyle','SS',false,2],
  702. rm: ['SetFont',MML.VARIANT.NORMAL],
  703. mit: ['SetFont',MML.VARIANT.ITALIC],
  704. oldstyle: ['SetFont',MML.VARIANT.OLDSTYLE],
  705. cal: ['SetFont',MML.VARIANT.CALIGRAPHIC],
  706. it: ['SetFont',"-tex-mathit"], // needs special handling
  707. bf: ['SetFont',MML.VARIANT.BOLD],
  708. bbFont: ['SetFont',MML.VARIANT.DOUBLESTRUCK],
  709. scr: ['SetFont',MML.VARIANT.SCRIPT],
  710. frak: ['SetFont',MML.VARIANT.FRAKTUR],
  711. sf: ['SetFont',MML.VARIANT.SANSSERIF],
  712. tt: ['SetFont',MML.VARIANT.MONOSPACE],
  713. // font:
  714. tiny: ['SetSize',0.5],
  715. Tiny: ['SetSize',0.6], // non-standard
  716. scriptsize: ['SetSize',0.7],
  717. small: ['SetSize',0.85],
  718. normalsize: ['SetSize',1.0],
  719. large: ['SetSize',1.2],
  720. Large: ['SetSize',1.44],
  721. LARGE: ['SetSize',1.73],
  722. huge: ['SetSize',2.07],
  723. Huge: ['SetSize',2.49],
  724. arcsin: ['NamedFn'],
  725. arccos: ['NamedFn'],
  726. arctan: ['NamedFn'],
  727. arg: ['NamedFn'],
  728. cos: ['NamedFn'],
  729. cosh: ['NamedFn'],
  730. cot: ['NamedFn'],
  731. coth: ['NamedFn'],
  732. csc: ['NamedFn'],
  733. deg: ['NamedFn'],
  734. det: 'NamedOp',
  735. dim: ['NamedFn'],
  736. exp: ['NamedFn'],
  737. gcd: 'NamedOp',
  738. hom: ['NamedFn'],
  739. inf: 'NamedOp',
  740. ker: ['NamedFn'],
  741. lg: ['NamedFn'],
  742. lim: 'NamedOp',
  743. liminf: ['NamedOp','lim&thinsp;inf'],
  744. limsup: ['NamedOp','lim&thinsp;sup'],
  745. ln: ['NamedFn'],
  746. log: ['NamedFn'],
  747. max: 'NamedOp',
  748. min: 'NamedOp',
  749. Pr: 'NamedOp',
  750. sec: ['NamedFn'],
  751. sin: ['NamedFn'],
  752. sinh: ['NamedFn'],
  753. sup: 'NamedOp',
  754. tan: ['NamedFn'],
  755. tanh: ['NamedFn'],
  756. limits: ['Limits',1],
  757. nolimits: ['Limits',0],
  758. overline: ['UnderOver','00AF',null,1],
  759. underline: ['UnderOver','005F'],
  760. overbrace: ['UnderOver','23DE',1],
  761. underbrace: ['UnderOver','23DF',1],
  762. overparen: ['UnderOver','23DC'],
  763. underparen: ['UnderOver','23DD'],
  764. overrightarrow: ['UnderOver','2192'],
  765. underrightarrow: ['UnderOver','2192'],
  766. overleftarrow: ['UnderOver','2190'],
  767. underleftarrow: ['UnderOver','2190'],
  768. overleftrightarrow: ['UnderOver','2194'],
  769. underleftrightarrow: ['UnderOver','2194'],
  770. overset: 'Overset',
  771. underset: 'Underset',
  772. stackrel: ['Macro','\\mathrel{\\mathop{#2}\\limits^{#1}}',2],
  773. over: 'Over',
  774. overwithdelims: 'Over',
  775. atop: 'Over',
  776. atopwithdelims: 'Over',
  777. above: 'Over',
  778. abovewithdelims: 'Over',
  779. brace: ['Over','{','}'],
  780. brack: ['Over','[',']'],
  781. choose: ['Over','(',')'],
  782. frac: 'Frac',
  783. sqrt: 'Sqrt',
  784. root: 'Root',
  785. uproot: ['MoveRoot','upRoot'],
  786. leftroot: ['MoveRoot','leftRoot'],
  787. left: 'LeftRight',
  788. right: 'LeftRight',
  789. middle: 'Middle',
  790. llap: 'Lap',
  791. rlap: 'Lap',
  792. raise: 'RaiseLower',
  793. lower: 'RaiseLower',
  794. moveleft: 'MoveLeftRight',
  795. moveright: 'MoveLeftRight',
  796. ',': ['Spacer',MML.LENGTH.THINMATHSPACE],
  797. ':': ['Spacer',MML.LENGTH.MEDIUMMATHSPACE], // for LaTeX
  798. '>': ['Spacer',MML.LENGTH.MEDIUMMATHSPACE],
  799. ';': ['Spacer',MML.LENGTH.THICKMATHSPACE],
  800. '!': ['Spacer',MML.LENGTH.NEGATIVETHINMATHSPACE],
  801. enspace: ['Spacer',".5em"],
  802. quad: ['Spacer',"1em"],
  803. qquad: ['Spacer',"2em"],
  804. thinspace: ['Spacer',MML.LENGTH.THINMATHSPACE],
  805. negthinspace: ['Spacer',MML.LENGTH.NEGATIVETHINMATHSPACE],
  806. hskip: 'Hskip',
  807. hspace: 'Hskip',
  808. kern: 'Hskip',
  809. mskip: 'Hskip',
  810. mspace: 'Hskip',
  811. mkern: 'Hskip',
  812. rule: 'rule',
  813. Rule: ['Rule'],
  814. Space: ['Rule','blank'],
  815. big: ['MakeBig',MML.TEXCLASS.ORD,0.85],
  816. Big: ['MakeBig',MML.TEXCLASS.ORD,1.15],
  817. bigg: ['MakeBig',MML.TEXCLASS.ORD,1.45],
  818. Bigg: ['MakeBig',MML.TEXCLASS.ORD,1.75],
  819. bigl: ['MakeBig',MML.TEXCLASS.OPEN,0.85],
  820. Bigl: ['MakeBig',MML.TEXCLASS.OPEN,1.15],
  821. biggl: ['MakeBig',MML.TEXCLASS.OPEN,1.45],
  822. Biggl: ['MakeBig',MML.TEXCLASS.OPEN,1.75],
  823. bigr: ['MakeBig',MML.TEXCLASS.CLOSE,0.85],
  824. Bigr: ['MakeBig',MML.TEXCLASS.CLOSE,1.15],
  825. biggr: ['MakeBig',MML.TEXCLASS.CLOSE,1.45],
  826. Biggr: ['MakeBig',MML.TEXCLASS.CLOSE,1.75],
  827. bigm: ['MakeBig',MML.TEXCLASS.REL,0.85],
  828. Bigm: ['MakeBig',MML.TEXCLASS.REL,1.15],
  829. biggm: ['MakeBig',MML.TEXCLASS.REL,1.45],
  830. Biggm: ['MakeBig',MML.TEXCLASS.REL,1.75],
  831. mathord: ['TeXAtom',MML.TEXCLASS.ORD],
  832. mathop: ['TeXAtom',MML.TEXCLASS.OP],
  833. mathopen: ['TeXAtom',MML.TEXCLASS.OPEN],
  834. mathclose: ['TeXAtom',MML.TEXCLASS.CLOSE],
  835. mathbin: ['TeXAtom',MML.TEXCLASS.BIN],
  836. mathrel: ['TeXAtom',MML.TEXCLASS.REL],
  837. mathpunct: ['TeXAtom',MML.TEXCLASS.PUNCT],
  838. mathinner: ['TeXAtom',MML.TEXCLASS.INNER],
  839. vcenter: ['TeXAtom',MML.TEXCLASS.VCENTER],
  840. mathchoice: ['Extension','mathchoice'],
  841. buildrel: 'BuildRel',
  842. hbox: ['HBox',0],
  843. text: 'HBox',
  844. mbox: ['HBox',0],
  845. fbox: 'FBox',
  846. strut: 'Strut',
  847. mathstrut: ['Macro','\\vphantom{(}'],
  848. phantom: 'Phantom',
  849. vphantom: ['Phantom',1,0],
  850. hphantom: ['Phantom',0,1],
  851. smash: 'Smash',
  852. acute: ['Accent', "00B4"], // or 0301 or 02CA
  853. grave: ['Accent', "0060"], // or 0300 or 02CB
  854. ddot: ['Accent', "00A8"], // or 0308
  855. tilde: ['Accent', "007E"], // or 0303 or 02DC
  856. bar: ['Accent', "00AF"], // or 0304 or 02C9
  857. breve: ['Accent', "02D8"], // or 0306
  858. check: ['Accent', "02C7"], // or 030C
  859. hat: ['Accent', "005E"], // or 0302 or 02C6
  860. vec: ['Accent', "2192"], // or 20D7
  861. dot: ['Accent', "02D9"], // or 0307
  862. widetilde: ['Accent', "007E",1], // or 0303 or 02DC
  863. widehat: ['Accent', "005E",1], // or 0302 or 02C6
  864. matrix: 'Matrix',
  865. array: 'Matrix',
  866. pmatrix: ['Matrix','(',')'],
  867. cases: ['Matrix','{','',"left left",null,".1em",null,true],
  868. eqalign: ['Matrix',null,null,"right left",MML.LENGTH.THICKMATHSPACE,".5em",'D'],
  869. displaylines: ['Matrix',null,null,"center",null,".5em",'D'],
  870. cr: 'Cr',
  871. '\\': 'CrLaTeX',
  872. newline: 'Cr',
  873. hline: ['HLine','solid'],
  874. hdashline: ['HLine','dashed'],
  875. // noalign: 'HandleNoAlign',
  876. eqalignno: ['Matrix',null,null,"right left",MML.LENGTH.THICKMATHSPACE,".5em",'D',null,"right"],
  877. leqalignno: ['Matrix',null,null,"right left",MML.LENGTH.THICKMATHSPACE,".5em",'D',null,"left"],
  878. hfill: 'HFill',
  879. hfil: 'HFill', // \hfil treated as \hfill for now
  880. hfilll: 'HFill', // \hfilll treated as \hfill for now
  881. // TeX substitution macros
  882. bmod: ['Macro','\\mmlToken{mo}[lspace="thickmathspace" rspace="thickmathspace"]{mod}'],
  883. pmod: ['Macro','\\pod{\\mmlToken{mi}{mod}\\kern 6mu #1}',1],
  884. mod: ['Macro','\\mathchoice{\\kern18mu}{\\kern12mu}{\\kern12mu}{\\kern12mu}\\mmlToken{mi}{mod}\\,\\,#1',1],
  885. pod: ['Macro','\\mathchoice{\\kern18mu}{\\kern8mu}{\\kern8mu}{\\kern8mu}(#1)',1],
  886. iff: ['Macro','\\;\\Longleftrightarrow\\;'],
  887. skew: ['Macro','{{#2{#3\\mkern#1mu}\\mkern-#1mu}{}}',3],
  888. mathcal: ['Macro','{\\cal #1}',1],
  889. mathscr: ['Macro','{\\scr #1}',1],
  890. mathrm: ['Macro','{\\rm #1}',1],
  891. mathbf: ['Macro','{\\bf #1}',1],
  892. mathbb: ['Macro','{\\bbFont #1}',1],
  893. Bbb: ['Macro','{\\bbFont #1}',1],
  894. mathit: ['Macro','{\\it #1}',1],
  895. mathfrak: ['Macro','{\\frak #1}',1],
  896. mathsf: ['Macro','{\\sf #1}',1],
  897. mathtt: ['Macro','{\\tt #1}',1],
  898. textrm: ['Macro','\\mathord{\\rm\\text{#1}}',1],
  899. textit: ['Macro','\\mathord{\\it\\text{#1}}',1],
  900. textbf: ['Macro','\\mathord{\\bf\\text{#1}}',1],
  901. textsf: ['Macro','\\mathord{\\sf\\text{#1}}',1],
  902. texttt: ['Macro','\\mathord{\\tt\\text{#1}}',1],
  903. pmb: ['Macro','\\rlap{#1}\\kern1px{#1}',1],
  904. TeX: ['Macro','T\\kern-.14em\\lower.5ex{E}\\kern-.115em X'],
  905. LaTeX: ['Macro','L\\kern-.325em\\raise.21em{\\scriptstyle{A}}\\kern-.17em\\TeX'],
  906. ' ': ['Macro','\\text{ }'],
  907. // Specially handled
  908. not: 'Not',
  909. dots: 'Dots',
  910. space: 'Tilde',
  911. '\u00A0': 'Tilde',
  912. // LaTeX
  913. begin: 'BeginEnd',
  914. end: 'BeginEnd',
  915. newcommand: ['Extension','newcommand'],
  916. renewcommand: ['Extension','newcommand'],
  917. newenvironment: ['Extension','newcommand'],
  918. renewenvironment: ['Extension','newcommand'],
  919. def: ['Extension','newcommand'],
  920. let: ['Extension','newcommand'],
  921. verb: ['Extension','verb'],
  922. boldsymbol: ['Extension','boldsymbol'],
  923. tag: ['Extension','AMSmath'],
  924. notag: ['Extension','AMSmath'],
  925. label: ['Extension','AMSmath'],
  926. ref: ['Extension','AMSmath'],
  927. eqref: ['Extension','AMSmath'],
  928. nonumber: ['Macro','\\notag'],
  929. // Extensions to TeX
  930. unicode: ['Extension','unicode'],
  931. color: 'Color',
  932. href: ['Extension','HTML'],
  933. 'class': ['Extension','HTML'],
  934. style: ['Extension','HTML'],
  935. cssId: ['Extension','HTML'],
  936. bbox: ['Extension','bbox'],
  937. mmlToken: 'MmlToken',
  938. require: 'Require'
  939. },
  940. environment: {
  941. array: ['AlignedArray'],
  942. matrix: ['Array',null,null,null,'c'],
  943. pmatrix: ['Array',null,'(',')','c'],
  944. bmatrix: ['Array',null,'[',']','c'],
  945. Bmatrix: ['Array',null,'\\{','\\}','c'],
  946. vmatrix: ['Array',null,'\\vert','\\vert','c'],
  947. Vmatrix: ['Array',null,'\\Vert','\\Vert','c'],
  948. cases: ['Array',null,'\\{','.','ll',null,".2em",'T'],
  949. equation: [null,'Equation'],
  950. 'equation*': [null,'Equation'],
  951. eqnarray: ['ExtensionEnv',null,'AMSmath'],
  952. 'eqnarray*': ['ExtensionEnv',null,'AMSmath'],
  953. align: ['ExtensionEnv',null,'AMSmath'],
  954. 'align*': ['ExtensionEnv',null,'AMSmath'],
  955. aligned: ['ExtensionEnv',null,'AMSmath'],
  956. multline: ['ExtensionEnv',null,'AMSmath'],
  957. 'multline*': ['ExtensionEnv',null,'AMSmath'],
  958. split: ['ExtensionEnv',null,'AMSmath'],
  959. gather: ['ExtensionEnv',null,'AMSmath'],
  960. 'gather*': ['ExtensionEnv',null,'AMSmath'],
  961. gathered: ['ExtensionEnv',null,'AMSmath'],
  962. alignat: ['ExtensionEnv',null,'AMSmath'],
  963. 'alignat*': ['ExtensionEnv',null,'AMSmath'],
  964. alignedat: ['ExtensionEnv',null,'AMSmath']
  965. },
  966. p_height: 1.2 / .85 // cmex10 height plus depth over .85
  967. });
  968. //
  969. // Add macros defined in the configuration
  970. //
  971. if (this.config.Macros) {
  972. var MACROS = this.config.Macros;
  973. for (var id in MACROS) {if (MACROS.hasOwnProperty(id)) {
  974. if (typeof(MACROS[id]) === "string") {TEXDEF.macros[id] = ['Macro',MACROS[id]]}
  975. else {TEXDEF.macros[id] = ["Macro"].concat(MACROS[id])}
  976. TEXDEF.macros[id].isUser = true;
  977. }}
  978. }
  979. };
  980. /************************************************************************/
  981. /*
  982. * The TeX Parser
  983. */
  984. var PARSE = MathJax.Object.Subclass({
  985. Init: function (string,env) {
  986. this.string = string; this.i = 0; this.macroCount = 0;
  987. var ENV; if (env) {ENV = {}; for (var id in env) {if (env.hasOwnProperty(id)) {ENV[id] = env[id]}}}
  988. this.stack = TEX.Stack(ENV,!!env);
  989. this.Parse(); this.Push(STACKITEM.stop());
  990. },
  991. Parse: function () {
  992. var c, n;
  993. while (this.i < this.string.length) {
  994. c = this.string.charAt(this.i++); n = c.charCodeAt(0);
  995. if (n >= 0xD800 && n < 0xDC00) {c += this.string.charAt(this.i++)}
  996. if (TEXDEF.special[c]) {this[TEXDEF.special[c]](c)}
  997. else if (TEXDEF.letter.test(c)) {this.Variable(c)}
  998. else if (TEXDEF.digit.test(c)) {this.Number(c)}
  999. else {this.Other(c)}
  1000. }
  1001. },
  1002. Push: function () {this.stack.Push.apply(this.stack,arguments)},
  1003. mml: function () {
  1004. if (this.stack.Top().type !== "mml") {return null}
  1005. return this.stack.Top().data[0];
  1006. },
  1007. mmlToken: function (token) {return token}, // used by boldsymbol extension
  1008. /************************************************************************/
  1009. /*
  1010. * Handle various token classes
  1011. */
  1012. /*
  1013. * Lookup a control-sequence and process it
  1014. */
  1015. ControlSequence: function (c) {
  1016. var name = this.GetCS(), macro = this.csFindMacro(name);
  1017. if (macro) {
  1018. if (!isArray(macro)) {macro = [macro]}
  1019. var fn = macro[0]; if (!(fn instanceof Function)) {fn = this[fn]}
  1020. fn.apply(this,[c+name].concat(macro.slice(1)));
  1021. } else if (TEXDEF.mathchar0mi[name]) {this.csMathchar0mi(name,TEXDEF.mathchar0mi[name])}
  1022. else if (TEXDEF.mathchar0mo[name]) {this.csMathchar0mo(name,TEXDEF.mathchar0mo[name])}
  1023. else if (TEXDEF.mathchar7[name]) {this.csMathchar7(name,TEXDEF.mathchar7[name])}
  1024. else if (TEXDEF.delimiter["\\"+name] != null) {this.csDelimiter(name,TEXDEF.delimiter["\\"+name])}
  1025. else {this.csUndefined(c+name)}
  1026. },
  1027. //
  1028. // Look up a macro in the macros list
  1029. // (overridden in begingroup extension)
  1030. //
  1031. csFindMacro: function (name) {return TEXDEF.macros[name]},
  1032. //
  1033. // Handle normal mathchar (as an mi)
  1034. //
  1035. csMathchar0mi: function (name,mchar) {
  1036. var def = {mathvariant: MML.VARIANT.ITALIC};
  1037. if (isArray(mchar)) {def = mchar[1]; mchar = mchar[0]}
  1038. this.Push(this.mmlToken(MML.mi(MML.entity("#x"+mchar)).With(def)));
  1039. },
  1040. //
  1041. // Handle normal mathchar (as an mo)
  1042. //
  1043. csMathchar0mo: function (name,mchar) {
  1044. var def = {stretchy: false};
  1045. if (isArray(mchar)) {def = mchar[1]; def.stretchy = false; mchar = mchar[0]}
  1046. this.Push(this.mmlToken(MML.mo(MML.entity("#x"+mchar)).With(def)));
  1047. },
  1048. //
  1049. // Handle mathchar in current family
  1050. //
  1051. csMathchar7: function (name,mchar) {
  1052. var def = {mathvariant: MML.VARIANT.NORMAL};
  1053. if (isArray(mchar)) {def = mchar[1]; mchar = mchar[0]}
  1054. if (this.stack.env.font) {def.mathvariant = this.stack.env.font}
  1055. this.Push(this.mmlToken(MML.mi(MML.entity("#x"+mchar)).With(def)));
  1056. },
  1057. //
  1058. // Handle delimiter
  1059. //
  1060. csDelimiter: function (name,delim) {
  1061. var def = {};
  1062. if (isArray(delim)) {def = delim[1]; delim = delim[0]}
  1063. if (delim.length === 4) {delim = MML.entity('#x'+delim)} else {delim = MML.chars(delim)}
  1064. this.Push(this.mmlToken(MML.mo(delim).With({fence: false, stretchy: false}).With(def)));
  1065. },
  1066. //
  1067. // Handle undefined control sequence
  1068. // (overridden in noUndefined extension)
  1069. //
  1070. csUndefined: function (name) {
  1071. TEX.Error(["UndefinedControlSequence","Undefined control sequence %1",name]);
  1072. },
  1073. /*
  1074. * Handle a variable (a single letter)
  1075. */
  1076. Variable: function (c) {
  1077. var def = {}; if (this.stack.env.font) {def.mathvariant = this.stack.env.font}
  1078. this.Push(this.mmlToken(MML.mi(MML.chars(c)).With(def)));
  1079. },
  1080. /*
  1081. * Determine the extent of a number (pattern may need work)
  1082. */
  1083. Number: function (c) {
  1084. var mml, n = this.string.slice(this.i-1).match(TEXDEF.number);
  1085. if (n) {mml = MML.mn(n[0].replace(/[{}]/g,"")); this.i += n[0].length - 1}
  1086. else {mml = MML.mo(MML.chars(c))}
  1087. if (this.stack.env.font) {mml.mathvariant = this.stack.env.font}
  1088. this.Push(this.mmlToken(mml));
  1089. },
  1090. /*
  1091. * Handle { and }
  1092. */
  1093. Open: function (c) {this.Push(STACKITEM.open())},
  1094. Close: function (c) {this.Push(STACKITEM.close())},
  1095. /*
  1096. * Handle tilde and spaces
  1097. */
  1098. Tilde: function (c) {this.Push(MML.mtext(MML.chars(NBSP)))},
  1099. Space: function (c) {},
  1100. /*
  1101. * Handle ^, _, and '
  1102. */
  1103. Superscript: function (c) {
  1104. if (this.GetNext().match(/\d/)) // don't treat numbers as a unit
  1105. {this.string = this.string.substr(0,this.i+1)+" "+this.string.substr(this.i+1)}
  1106. var primes, base, top = this.stack.Top();
  1107. if (top.type === "prime") {base = top.data[0]; primes = top.data[1]; this.stack.Pop()}
  1108. else {base = this.stack.Prev(); if (!base) {base = MML.mi("")}}
  1109. if (base.isEmbellishedWrapper) {base = base.data[0].data[0]}
  1110. var movesupsub = base.movesupsub, position = base.sup;
  1111. if ((base.type === "msubsup" && base.data[base.sup]) ||
  1112. (base.type === "munderover" && base.data[base.over] && !base.subsupOK))
  1113. {TEX.Error(["DoubleExponent","Double exponent: use braces to clarify"])}
  1114. if (base.type !== "msubsup") {
  1115. if (movesupsub) {
  1116. if (base.type !== "munderover" || base.data[base.over]) {
  1117. if (base.movablelimits && base.isa(MML.mi)) {base = this.mi2mo(base)}
  1118. base = MML.munderover(base,null,null).With({movesupsub:true})
  1119. }
  1120. position = base.over;
  1121. } else {
  1122. base = MML.msubsup(base,null,null);
  1123. position = base.sup;
  1124. }
  1125. }
  1126. this.Push(STACKITEM.subsup(base).With({
  1127. position: position, primes: primes, movesupsub: movesupsub
  1128. }));
  1129. },
  1130. Subscript: function (c) {
  1131. if (this.GetNext().match(/\d/)) // don't treat numbers as a unit
  1132. {this.string = this.string.substr(0,this.i+1)+" "+this.string.substr(this.i+1)}
  1133. var primes, base, top = this.stack.Top();
  1134. if (top.type === "prime") {base = top.data[0]; primes = top.data[1]; this.stack.Pop()}
  1135. else {base = this.stack.Prev(); if (!base) {base = MML.mi("")}}
  1136. if (base.isEmbellishedWrapper) {base = base.data[0].data[0]}
  1137. var movesupsub = base.movesupsub, position = base.sub;
  1138. if ((base.type === "msubsup" && base.data[base.sub]) ||
  1139. (base.type === "munderover" && base.data[base.under] && !base.subsupOK))
  1140. {TEX.Error(["DoubleSubscripts","Double subscripts: use braces to clarify"])}
  1141. if (base.type !== "msubsup") {
  1142. if (movesupsub) {
  1143. if (base.type !== "munderover" || base.data[base.under]) {
  1144. if (base.movablelimits && base.isa(MML.mi)) {base = this.mi2mo(base)}
  1145. base = MML.munderover(base,null,null).With({movesupsub:true})
  1146. }
  1147. position = base.under;
  1148. } else {
  1149. base = MML.msubsup(base,null,null);
  1150. position = base.sub;
  1151. }
  1152. }
  1153. this.Push(STACKITEM.subsup(base).With({
  1154. position: position, primes: primes, movesupsub: movesupsub
  1155. }));
  1156. },
  1157. PRIME: "\u2032", SMARTQUOTE: "\u2019",
  1158. Prime: function (c) {
  1159. var base = this.stack.Prev(); if (!base) {base = MML.mi()}
  1160. if (base.type === "msubsup" && base.data[base.sup]) {
  1161. TEX.Error(["DoubleExponentPrime",
  1162. "Prime causes double exponent: use braces to clarify"]);
  1163. }
  1164. var sup = ""; this.i--;
  1165. do {sup += this.PRIME; this.i++, c = this.GetNext()}
  1166. while (c === "'" || c === this.SMARTQUOTE);
  1167. sup = ["","\u2032","\u2033","\u2034","\u2057"][sup.length] || sup;
  1168. this.Push(STACKITEM.prime(base,this.mmlToken(MML.mo(sup))));
  1169. },
  1170. mi2mo: function (mi) {
  1171. var mo = MML.mo(); mo.Append.apply(mo,mi.data); var id;
  1172. for (id in mo.defaults)
  1173. {if (mo.defaults.hasOwnProperty(id) && mi[id] != null) {mo[id] = mi[id]}}
  1174. for (id in MML.copyAttributes)
  1175. {if (MML.copyAttributes.hasOwnProperty(id) && mi[id] != null) {mo[id] = mi[id]}}
  1176. mo.lspace = mo.rspace = "0"; // prevent mo from having space in NativeMML
  1177. mo.useMMLspacing &= ~(mo.SPACE_ATTR.lspace | mo.SPACE_ATTR.rspace); // don't count these explicit settings
  1178. return mo;
  1179. },
  1180. /*
  1181. * Handle comments
  1182. */
  1183. Comment: function (c) {
  1184. while (this.i < this.string.length && this.string.charAt(this.i) != "\n") {this.i++}
  1185. },
  1186. /*
  1187. * Handle hash marks outside of definitions
  1188. */
  1189. Hash: function (c) {
  1190. TEX.Error(["CantUseHash1",
  1191. "You can't use 'macro parameter character #' in math mode"]);
  1192. },
  1193. /*
  1194. * Handle other characters (as <mo> elements)
  1195. */
  1196. Other: function (c) {
  1197. var def, mo;
  1198. if (this.stack.env.font) {def = {mathvariant: this.stack.env.font}}
  1199. if (TEXDEF.remap[c]) {
  1200. c = TEXDEF.remap[c];
  1201. if (isArray(c)) {def = c[1]; c = c[0]}
  1202. mo = MML.mo(MML.entity('#x'+c)).With(def);
  1203. } else {
  1204. mo = MML.mo(c).With(def);
  1205. }
  1206. if (mo.autoDefault("stretchy",true)) {mo.stretchy = false}
  1207. if (mo.autoDefault("texClass",true) == "") {mo = MML.TeXAtom(mo)}
  1208. this.Push(this.mmlToken(mo));
  1209. },
  1210. /************************************************************************/
  1211. /*
  1212. * Macros
  1213. */
  1214. SetFont: function (name,font) {this.stack.env.font = font},
  1215. SetStyle: function (name,texStyle,style,level) {
  1216. this.stack.env.style = texStyle; this.stack.env.level = level;
  1217. this.Push(STACKITEM.style().With({styles: {displaystyle: style, scriptlevel: level}}));
  1218. },
  1219. SetSize: function (name,size) {
  1220. this.stack.env.size = size;
  1221. this.Push(STACKITEM.style().With({styles: {mathsize: size+"em"}})); // convert to absolute?
  1222. },
  1223. Color: function (name) {
  1224. var color = this.GetArgument(name);
  1225. var old = this.stack.env.color; this.stack.env.color = color;
  1226. var math = this.ParseArg(name);
  1227. if (old) {this.stack.env.color} else {delete this.stack.env.color}
  1228. this.Push(MML.mstyle(math).With({mathcolor: color}));
  1229. },
  1230. Spacer: function (name,space) {
  1231. this.Push(MML.mspace().With({width: space, mathsize: MML.SIZE.NORMAL, scriptlevel:0}));
  1232. },
  1233. LeftRight: function (name) {
  1234. this.Push(STACKITEM[name.substr(1)]().With({delim: this.GetDelimiter(name)}));
  1235. },
  1236. Middle: function (name) {
  1237. var delim = this.GetDelimiter(name);
  1238. this.Push(MML.TeXAtom().With({texClass:MML.TEXCLASS.CLOSE}));
  1239. if (this.stack.Top().type !== "left")
  1240. {TEX.Error(["MisplacedMiddle","%1 must be within \\left and \\right",name])}
  1241. this.Push(MML.mo(delim).With({stretchy:true}));
  1242. this.Push(MML.TeXAtom().With({texClass:MML.TEXCLASS.OPEN}));
  1243. },
  1244. NamedFn: function (name,id) {
  1245. if (!id) {id = name.substr(1)};
  1246. var mml = MML.mi(id).With({texClass: MML.TEXCLASS.OP});
  1247. this.Push(STACKITEM.fn(this.mmlToken(mml)));
  1248. },
  1249. NamedOp: function (name,id) {
  1250. if (!id) {id = name.substr(1)};
  1251. id = id.replace(/&thinsp;/,"\u2006");
  1252. var mml = MML.mo(id).With({
  1253. movablelimits: true,
  1254. movesupsub: true,
  1255. form: MML.FORM.PREFIX,
  1256. texClass: MML.TEXCLASS.OP
  1257. });
  1258. mml.useMMLspacing &= ~mml.SPACE_ATTR.form; // don't count this explicit form setting
  1259. this.Push(this.mmlToken(mml));
  1260. },
  1261. Limits: function (name,limits) {
  1262. var op = this.stack.Prev("nopop");
  1263. if (!op || (op.Get("texClass") !== MML.TEXCLASS.OP && op.movesupsub == null))
  1264. {TEX.Error(["MisplacedLimits","%1 is allowed only on operators",name])}
  1265. var top = this.stack.Top();
  1266. if (op.type === "munderover" && !limits) {
  1267. op = top.data[top.data.length-1] = MML.msubsup.apply(MML.subsup,op.data);
  1268. } else if (op.type === "msubsup" && limits) {
  1269. op = top.data[top.data.length-1] = MML.munderover.apply(MML.underover,op.data);
  1270. }
  1271. op.movesupsub = (limits ? true : false);
  1272. op.Core().movablelimits = false;
  1273. if (op.movablelimits) op.movablelimits = false;
  1274. },
  1275. Over: function (name,open,close) {
  1276. var mml = STACKITEM.over().With({name: name});
  1277. if (open || close) {
  1278. mml.open = open; mml.close = close;
  1279. } else if (name.match(/withdelims$/)) {
  1280. mml.open = this.GetDelimiter(name);
  1281. mml.close = this.GetDelimiter(name);
  1282. }
  1283. if (name.match(/^\\above/)) {mml.thickness = this.GetDimen(name)}
  1284. else if (name.match(/^\\atop/) || open || close) {mml.thickness = 0}
  1285. this.Push(mml);
  1286. },
  1287. Frac: function (name) {
  1288. var num = this.ParseArg(name);
  1289. var den = this.ParseArg(name);
  1290. this.Push(MML.mfrac(num,den));
  1291. },
  1292. Sqrt: function (name) {
  1293. var n = this.GetBrackets(name), arg = this.GetArgument(name);
  1294. if (arg === "\\frac") {arg += "{"+this.GetArgument(arg)+"}{"+this.GetArgument(arg)+"}"}
  1295. var mml = TEX.Parse(arg,this.stack.env).mml();
  1296. if (!n) {mml = MML.msqrt.apply(MML,mml.array())}
  1297. else {mml = MML.mroot(mml,this.parseRoot(n))}
  1298. this.Push(mml);
  1299. },
  1300. Root: function (name) {
  1301. var n = this.GetUpTo(name,"\\of");
  1302. var arg = this.ParseArg(name);
  1303. this.Push(MML.mroot(arg,this.parseRoot(n)));
  1304. },
  1305. parseRoot: function (n) {
  1306. var env = this.stack.env, inRoot = env.inRoot; env.inRoot = true;
  1307. var parser = TEX.Parse(n,env); n = parser.mml(); var global = parser.stack.global;
  1308. if (global.leftRoot || global.upRoot) {
  1309. n = MML.mpadded(n);
  1310. if (global.leftRoot) {n.width = global.leftRoot}
  1311. if (global.upRoot) {n.voffset = global.upRoot; n.height = global.upRoot}
  1312. }
  1313. env.inRoot = inRoot;
  1314. return n;
  1315. },
  1316. MoveRoot: function (name,id) {
  1317. if (!this.stack.env.inRoot)
  1318. {TEX.Error(["MisplacedMoveRoot","%1 can appear only within a root",name])}
  1319. if (this.stack.global[id])
  1320. {TEX.Error(["MultipleMoveRoot","Multiple use of %1",name])}
  1321. var n = this.GetArgument(name);
  1322. if (!n.match(/-?[0-9]+/))
  1323. {TEX.Error(["IntegerArg","The argument to %1 must be an integer",name])}
  1324. n = (n/15)+"em";
  1325. if (n.substr(0,1) !== "-") {n = "+"+n}
  1326. this.stack.global[id] = n;
  1327. },
  1328. Accent: function (name,accent,stretchy) {
  1329. var c = this.ParseArg(name);
  1330. var def = {accent: true}; if (this.stack.env.font) {def.mathvariant = this.stack.env.font}
  1331. var mml = this.mmlToken(MML.mo(MML.entity("#x"+accent)).With(def));
  1332. mml.stretchy = (stretchy ? true : false);
  1333. var mo = (c.isEmbellished() ? c.CoreMO() : c);
  1334. if (mo.isa(MML.mo)) mo.movablelimits = false;
  1335. this.Push(MML.TeXAtom(MML.munderover(c,null,mml).With({accent: true})));
  1336. },
  1337. UnderOver: function (name,c,stack,noaccent) {
  1338. var pos = {o: "over", u: "under"}[name.charAt(1)];
  1339. var base = this.ParseArg(name);
  1340. if (base.Get("movablelimits")) {base.movablelimits = false}
  1341. if (base.isa(MML.munderover) && base.isEmbellished()) {
  1342. base.Core().With({lspace:0,rspace:0}); // get spacing right for NativeMML
  1343. base = MML.mrow(MML.mo().With({rspace:0}),base); // add an empty <mi> so it's not embellished any more
  1344. }
  1345. var mml = MML.munderover(base,null,null);
  1346. mml.SetData(
  1347. mml[pos],
  1348. this.mmlToken(MML.mo(MML.entity("#x"+c)).With({stretchy:true, accent:!noaccent}))
  1349. );
  1350. if (stack) {mml = MML.TeXAtom(mml).With({texClass:MML.TEXCLASS.OP, movesupsub:true})}
  1351. this.Push(mml.With({subsupOK:true}));
  1352. },
  1353. Overset: function (name) {
  1354. var top = this.ParseArg(name), base = this.ParseArg(name);
  1355. if (base.movablelimits) base.movablelimits = false;
  1356. this.Push(MML.mover(base,top));
  1357. },
  1358. Underset: function (name) {
  1359. var bot = this.ParseArg(name), base = this.ParseArg(name);
  1360. if (base.movablelimits) base.movablelimits = false;
  1361. this.Push(MML.munder(base,bot));
  1362. },
  1363. TeXAtom: function (name,mclass) {
  1364. var def = {texClass: mclass}, mml;
  1365. if (mclass == MML.TEXCLASS.OP) {
  1366. def.movesupsub = def.movablelimits = true;
  1367. var arg = this.GetArgument(name);
  1368. var match = arg.match(/^\s*\\rm\s+([a-zA-Z0-9 ]+)$/);
  1369. if (match) {
  1370. def.mathvariant = MML.VARIANT.NORMAL;
  1371. mml = STACKITEM.fn(this.mmlToken(MML.mi(match[1]).With(def)));
  1372. } else {
  1373. mml = STACKITEM.fn(MML.TeXAtom(TEX.Parse(arg,this.stack.env).mml()).With(def));
  1374. }
  1375. } else {mml = MML.TeXAtom(this.ParseArg(name)).With(def)}
  1376. this.Push(mml);
  1377. },
  1378. MmlToken: function (name) {
  1379. var type = this.GetArgument(name),
  1380. attr = this.GetBrackets(name,"").replace(/^\s+/,""),
  1381. data = this.GetArgument(name),
  1382. def = {attrNames:[]}, match;
  1383. if (!MML[type] || !MML[type].prototype.isToken)
  1384. {TEX.Error(["NotMathMLToken","%1 is not a token element",type])}
  1385. while (attr !== "") {
  1386. match = attr.match(/^([a-z]+)\s*=\s*('[^']*'|"[^"]*"|[^ ,]*)\s*,?\s*/i);
  1387. if (!match)
  1388. {TEX.Error(["InvalidMathMLAttr","Invalid MathML attribute: %1",attr])}
  1389. if (MML[type].prototype.defaults[match[1]] == null && !this.MmlTokenAllow[match[1]]) {
  1390. TEX.Error(["UnknownAttrForElement",
  1391. "%1 is not a recognized attribute for %2",
  1392. match[1],type]);
  1393. }
  1394. var value = this.MmlFilterAttribute(match[1],match[2].replace(/^(['"])(.*)\1$/,"$2"));
  1395. if (value) {
  1396. if (value.toLowerCase() === "true") {value = true}
  1397. else if (value.toLowerCase() === "false") {value = false}
  1398. def[match[1]] = value;
  1399. def.attrNames.push(match[1]);
  1400. }
  1401. attr = attr.substr(match[0].length);
  1402. }
  1403. this.Push(this.mmlToken(MML[type](data).With(def)));
  1404. },
  1405. MmlFilterAttribute: function (name,value) {return value},
  1406. MmlTokenAllow: {
  1407. fontfamily:1, fontsize:1, fontweight:1, fontstyle:1,
  1408. color:1, background:1,
  1409. id:1, "class":1, href:1, style:1
  1410. },
  1411. Strut: function (name) {
  1412. this.Push(MML.mpadded(MML.mrow()).With({height: "8.6pt", depth: "3pt", width: 0}));
  1413. },
  1414. Phantom: function (name,v,h) {
  1415. var box = MML.mphantom(this.ParseArg(name));
  1416. if (v || h) {
  1417. box = MML.mpadded(box);
  1418. if (h) {box.height = box.depth = 0}
  1419. if (v) {box.width = 0}
  1420. }
  1421. this.Push(MML.TeXAtom(box));
  1422. },
  1423. Smash: function (name) {
  1424. var bt = this.trimSpaces(this.GetBrackets(name,""));
  1425. var smash = MML.mpadded(this.ParseArg(name));
  1426. switch (bt) {
  1427. case "b": smash.depth = 0; break;
  1428. case "t": smash.height = 0; break;
  1429. default: smash.height = smash.depth = 0;
  1430. }
  1431. this.Push(MML.TeXAtom(smash));
  1432. },
  1433. Lap: function (name) {
  1434. var mml = MML.mpadded(this.ParseArg(name)).With({width: 0});
  1435. if (name === "\\llap") {mml.lspace = "-1width"}
  1436. this.Push(MML.TeXAtom(mml));
  1437. },
  1438. RaiseLower: function (name) {
  1439. var h = this.GetDimen(name);
  1440. var item = STACKITEM.position().With({name: name, move: 'vertical'});
  1441. if (h.charAt(0) === '-') {h = h.slice(1); name = {raise: "\\lower", lower: "\\raise"}[name.substr(1)]}
  1442. if (name === "\\lower") {item.dh = '-'+h; item.dd = '+'+h} else {item.dh = '+'+h; item.dd = '-'+h}
  1443. this.Push(item);
  1444. },
  1445. MoveLeftRight: function (name) {
  1446. var h = this.GetDimen(name);
  1447. var nh = (h.charAt(0) === '-' ? h.slice(1) : '-'+h);
  1448. if (name === "\\moveleft") {var tmp = h; h = nh; nh = tmp}
  1449. this.Push(STACKITEM.position().With({
  1450. name: name, move: 'horizontal',
  1451. left: MML.mspace().With({width: h, mathsize: MML.SIZE.NORMAL}),
  1452. right: MML.mspace().With({width: nh, mathsize: MML.SIZE.NORMAL})
  1453. }));
  1454. },
  1455. Hskip: function (name) {
  1456. this.Push(MML.mspace().With({width: this.GetDimen(name), mathsize: MML.SIZE.NORMAL}));
  1457. },
  1458. Rule: function (name,style) {
  1459. var w = this.GetDimen(name),
  1460. h = this.GetDimen(name),
  1461. d = this.GetDimen(name);
  1462. var def = {width:w, height:h, depth:d};
  1463. if (style !== 'blank') {
  1464. def.mathbackground = (this.stack.env.color || "black");
  1465. }
  1466. this.Push(MML.mspace().With(def));
  1467. },
  1468. rule: function (name) {
  1469. var v = this.GetBrackets(name),
  1470. w = this.GetDimen(name),
  1471. h = this.GetDimen(name);
  1472. var mml = MML.mspace().With({
  1473. width: w, height:h,
  1474. mathbackground: (this.stack.env.color || "black")
  1475. });
  1476. if (v) {
  1477. mml = MML.mpadded(mml).With({voffset: v});
  1478. if (v.match(/^\-/)) {
  1479. mml.height = v;
  1480. mml.depth = '+' + v.substr(1);
  1481. } else {
  1482. mml.height = '+' + v;
  1483. }
  1484. }
  1485. this.Push(mml);
  1486. },
  1487. MakeBig: function (name,mclass,size) {
  1488. size *= TEXDEF.p_height;
  1489. size = String(size).replace(/(\.\d\d\d).+/,'$1')+"em";
  1490. var delim = this.GetDelimiter(name,true);
  1491. this.Push(MML.TeXAtom(MML.mo(delim).With({
  1492. minsize: size, maxsize: size,
  1493. fence: true, stretchy: true, symmetric: true
  1494. })).With({texClass: mclass}));
  1495. },
  1496. BuildRel: function (name) {
  1497. var top = this.ParseUpTo(name,"\\over");
  1498. var bot = this.ParseArg(name);
  1499. this.Push(MML.TeXAtom(MML.munderover(bot,null,top)).With({texClass: MML.TEXCLASS.REL}));
  1500. },
  1501. HBox: function (name,style) {
  1502. this.Push.apply(this,this.InternalMath(this.GetArgument(name),style));
  1503. },
  1504. FBox: function (name) {
  1505. this.Push(MML.menclose.apply(MML,this.InternalMath(this.GetArgument(name))).With({notation:"box"}));
  1506. },
  1507. Not: function (name) {
  1508. this.Push(STACKITEM.not());
  1509. },
  1510. Dots: function (name) {
  1511. this.Push(STACKITEM.dots().With({
  1512. ldots: this.mmlToken(MML.mo(MML.entity("#x2026")).With({stretchy:false})),
  1513. cdots: this.mmlToken(MML.mo(MML.entity("#x22EF")).With({stretchy:false}))
  1514. }));
  1515. },
  1516. Require: function (name) {
  1517. var file = this.GetArgument(name)
  1518. .replace(/.*\//,"") // remove any leading path
  1519. .replace(/[^a-z0-9_.-]/ig,""); // remove illegal characters
  1520. this.Extension(null,file);
  1521. },
  1522. Extension: function (name,file,array) {
  1523. if (name && !typeof(name) === "string") {name = name.name}
  1524. file = TEX.extensionDir+"/"+file;
  1525. if (!file.match(/\.js$/)) {file += ".js"}
  1526. if (!AJAX.loaded[AJAX.fileURL(file)]) {
  1527. if (name != null) {delete TEXDEF[array || 'macros'][name.replace(/^\\/,"")]}
  1528. HUB.RestartAfter(AJAX.Require(file));
  1529. }
  1530. },
  1531. Macro: function (name,macro,argcount,def) {
  1532. if (argcount) {
  1533. var args = [];
  1534. if (def != null) {
  1535. var optional = this.GetBrackets(name);
  1536. args.push(optional == null ? def : optional);
  1537. }
  1538. for (var i = args.length; i < argcount; i++) {args.push(this.GetArgument(name))}
  1539. macro = this.SubstituteArgs(args,macro);
  1540. }
  1541. this.string = this.AddArgs(macro,this.string.slice(this.i));
  1542. this.i = 0;
  1543. if (++this.macroCount > TEX.config.MAXMACROS) {
  1544. TEX.Error(["MaxMacroSub1",
  1545. "MathJax maximum macro substitution count exceeded; " +
  1546. "is there a recursive macro call?"]);
  1547. }
  1548. },
  1549. Matrix: function (name,open,close,align,spacing,vspacing,style,cases,numbered) {
  1550. var c = this.GetNext();
  1551. if (c === "")
  1552. {TEX.Error(["MissingArgFor","Missing argument for %1",name])}
  1553. if (c === "{") {this.i++} else {this.string = c+"}"+this.string.slice(this.i+1); this.i = 0}
  1554. var array = STACKITEM.array().With({
  1555. requireClose: true,
  1556. arraydef: {
  1557. rowspacing: (vspacing||"4pt"),
  1558. columnspacing: (spacing||"1em")
  1559. }
  1560. });
  1561. if (cases) {array.isCases = true}
  1562. if (numbered) {array.isNumbered = true; array.arraydef.side = numbered}
  1563. if (open || close) {array.open = open; array.close = close}
  1564. if (style === "D") {array.arraydef.displaystyle = true}
  1565. if (align != null) {array.arraydef.columnalign = align}
  1566. this.Push(array);
  1567. },
  1568. Entry: function (name) {
  1569. this.Push(STACKITEM.cell().With({isEntry: true, name: name}));
  1570. if (this.stack.Top().isCases) {
  1571. //
  1572. // Make second column be in \text{...} (unless it is already
  1573. // in a \text{...}, for backward compatibility).
  1574. //
  1575. var string = this.string;
  1576. var braces = 0, close = -1, i = this.i, m = string.length;
  1577. //
  1578. // Look through the string character by character...
  1579. //
  1580. while (i < m) {
  1581. var c = string.charAt(i);
  1582. if (c === "{") {
  1583. //
  1584. // Increase the nested brace count and go on
  1585. //
  1586. braces++;
  1587. i++;
  1588. } else if (c === "}") {
  1589. //
  1590. // If there are too many close braces, just end (we will get an
  1591. // error message later when the rest of the string is parsed)
  1592. // Otherwise
  1593. // decrease the nested brace count,
  1594. // if it is now zero and we haven't already marked the end of the
  1595. // first brace group, record the position (use to check for \text{} later)
  1596. // go on to the next character.
  1597. //
  1598. if (braces === 0) {
  1599. m = 0;
  1600. } else {
  1601. braces--;
  1602. if (braces === 0 && close < 0) {
  1603. close = i - this.i;
  1604. }
  1605. i++;
  1606. }
  1607. } else if (c === "&" && braces === 0) {
  1608. //
  1609. // Extra alignment tabs are not allowed in cases
  1610. //
  1611. TEX.Error(["ExtraAlignTab","Extra alignment tab in \\cases text"]);
  1612. } else if (c === "\\") {
  1613. //
  1614. // If the macro is \cr or \\, end the search, otherwise skip the macro
  1615. // (multi-letter names don't matter, as we will skip the rest of the
  1616. // characters in the main loop)
  1617. //
  1618. if (string.substr(i).match(/^((\\cr)[^a-zA-Z]|\\\\)/)) {m = 0} else {i += 2}
  1619. } else {
  1620. //
  1621. // Go on to the next character
  1622. //
  1623. i++;
  1624. }
  1625. }
  1626. //
  1627. // Check if the second column text is already in \text{},
  1628. // If not, process the second column as text and continue parsing from there,
  1629. // (otherwise process the second column as normal, since it is in \text{}
  1630. //
  1631. var text = string.substr(this.i,i-this.i);
  1632. if (!text.match(/^\s*\\text[^a-zA-Z]/) || close !== text.replace(/\s+$/,'').length - 1) {
  1633. this.Push.apply(this,this.InternalMath(text,0));
  1634. this.i = i;
  1635. }
  1636. }
  1637. },
  1638. Cr: function (name) {
  1639. this.Push(STACKITEM.cell().With({isCR: true, name: name}));
  1640. },
  1641. CrLaTeX: function (name) {
  1642. var n;
  1643. if (this.string.charAt(this.i) === "[") {
  1644. n = this.GetBrackets(name,"").replace(/ /g,"").replace(/,/,".");
  1645. if (n && !this.matchDimen(n)) {
  1646. TEX.Error(["BracketMustBeDimension",
  1647. "Bracket argument to %1 must be a dimension",name]);
  1648. }
  1649. }
  1650. this.Push(STACKITEM.cell().With({isCR: true, name: name, linebreak: true}));
  1651. var top = this.stack.Top();
  1652. if (top.isa(STACKITEM.array)) {
  1653. if (n && top.arraydef.rowspacing) {
  1654. var rows = top.arraydef.rowspacing.split(/ /);
  1655. if (!top.rowspacing) {top.rowspacing = this.dimen2em(rows[0])}
  1656. while (rows.length < top.table.length) {rows.push(this.Em(top.rowspacing))}
  1657. rows[top.table.length-1] = this.Em(Math.max(0,top.rowspacing+this.dimen2em(n)));
  1658. top.arraydef.rowspacing = rows.join(' ');
  1659. }
  1660. } else {
  1661. if (n) {this.Push(MML.mspace().With({depth:n}))}
  1662. this.Push(MML.mspace().With({linebreak:MML.LINEBREAK.NEWLINE}));
  1663. }
  1664. },
  1665. emPerInch: 7.2,
  1666. pxPerInch: 72,
  1667. matchDimen: function (dim) {
  1668. return dim.match(/^(-?(?:\.\d+|\d+(?:\.\d*)?))(px|pt|em|ex|mu|pc|in|mm|cm)$/);
  1669. },
  1670. dimen2em: function (dim) {
  1671. var match = this.matchDimen(dim);
  1672. var m = parseFloat(match[1]||"1"), unit = match[2];
  1673. if (unit === "em") {return m}
  1674. if (unit === "ex") {return m * .43}
  1675. if (unit === "pt") {return m / 10} // 10 pt to an em
  1676. if (unit === "pc") {return m * 1.2} // 12 pt to a pc
  1677. if (unit === "px") {return m * this.emPerInch / this.pxPerInch}
  1678. if (unit === "in") {return m * this.emPerInch}
  1679. if (unit === "cm") {return m * this.emPerInch / 2.54} // 2.54 cm to an inch
  1680. if (unit === "mm") {return m * this.emPerInch / 25.4} // 10 mm to a cm
  1681. if (unit === "mu") {return m / 18}
  1682. return 0;
  1683. },
  1684. Em: function (m) {
  1685. if (Math.abs(m) < .0006) {return "0em"}
  1686. return m.toFixed(3).replace(/\.?0+$/,"") + "em";
  1687. },
  1688. HLine: function (name,style) {
  1689. if (style == null) {style = "solid"}
  1690. var top = this.stack.Top();
  1691. if (!top.isa(STACKITEM.array) || top.data.length)
  1692. {TEX.Error(["Misplaced","Misplaced %1",name])}
  1693. if (top.table.length == 0) {
  1694. top.frame.push("top");
  1695. } else {
  1696. var lines = (top.arraydef.rowlines ? top.arraydef.rowlines.split(/ /) : []);
  1697. while (lines.length < top.table.length) {lines.push("none")}
  1698. lines[top.table.length-1] = style;
  1699. top.arraydef.rowlines = lines.join(' ');
  1700. }
  1701. },
  1702. HFill: function (name) {
  1703. var top = this.stack.Top();
  1704. if (top.isa(STACKITEM.array)) top.hfill.push(top.data.length);
  1705. else TEX.Error(["UnsupportedHFill","Unsupported use of %1",name]);
  1706. },
  1707. /************************************************************************/
  1708. /*
  1709. * LaTeX environments
  1710. */
  1711. BeginEnd: function (name) {
  1712. var env = this.GetArgument(name), isEnd = false;
  1713. if (env.match(/^\\end\\/)) {isEnd = true; env = env.substr(5)} // special \end{} for \newenvironment environments
  1714. if (env.match(/\\/i)) {TEX.Error(["InvalidEnv","Invalid environment name '%1'",env])}
  1715. var cmd = this.envFindName(env);
  1716. if (!cmd) {TEX.Error(["UnknownEnv","Unknown environment '%1'",env])}
  1717. if (!isArray(cmd)) {cmd = [cmd]}
  1718. var end = (isArray(cmd[1]) ? cmd[1][0] : cmd[1]);
  1719. var mml = STACKITEM.begin().With({name: env, end: end, parse:this});
  1720. if (name === "\\end") {
  1721. if (!isEnd && isArray(cmd[1]) && this[cmd[1][1]]) {
  1722. mml = this[cmd[1][1]].apply(this,[mml].concat(cmd.slice(2)));
  1723. } else {
  1724. mml = STACKITEM.end().With({name: env});
  1725. }
  1726. } else {
  1727. if (++this.macroCount > TEX.config.MAXMACROS) {
  1728. TEX.Error(["MaxMacroSub2",
  1729. "MathJax maximum substitution count exceeded; " +
  1730. "is there a recursive latex environment?"]);
  1731. }
  1732. if (cmd[0] && this[cmd[0]]) {mml = this[cmd[0]].apply(this,[mml].concat(cmd.slice(2)))}
  1733. }
  1734. this.Push(mml);
  1735. },
  1736. envFindName: function (name) {return TEXDEF.environment[name]},
  1737. Equation: function (begin,row) {return row},
  1738. ExtensionEnv: function (begin,file) {this.Extension(begin.name,file,"environment")},
  1739. Array: function (begin,open,close,align,spacing,vspacing,style,raggedHeight) {
  1740. if (!align) {align = this.GetArgument("\\begin{"+begin.name+"}")}
  1741. var lines = ("c"+align).replace(/[^clr|:]/g,'').replace(/[^|:]([|:])+/g,'$1');
  1742. align = align.replace(/[^clr]/g,'').split('').join(' ');
  1743. align = align.replace(/l/g,'left').replace(/r/g,'right').replace(/c/g,'center');
  1744. var array = STACKITEM.array().With({
  1745. arraydef: {
  1746. columnalign: align,
  1747. columnspacing: (spacing||"1em"),
  1748. rowspacing: (vspacing||"4pt")
  1749. }
  1750. });
  1751. if (lines.match(/[|:]/)) {
  1752. if (lines.charAt(0).match(/[|:]/)) {array.frame.push("left"); array.frame.dashed = lines.charAt(0) === ":"}
  1753. if (lines.charAt(lines.length-1).match(/[|:]/)) {array.frame.push("right")}
  1754. lines = lines.substr(1,lines.length-2);
  1755. array.arraydef.columnlines =
  1756. lines.split('').join(' ').replace(/[^|: ]/g,'none').replace(/\|/g,'solid').replace(/:/g,'dashed');
  1757. }
  1758. if (open) {array.open = this.convertDelimiter(open)}
  1759. if (close) {array.close = this.convertDelimiter(close)}
  1760. if (style === "D") {array.arraydef.displaystyle = true}
  1761. else if (style) {array.arraydef.displaystyle = false}
  1762. if (style === "S") {array.arraydef.scriptlevel = 1} // FIXME: should use mstyle?
  1763. if (raggedHeight) {array.arraydef.useHeight = false}
  1764. this.Push(begin);
  1765. return array;
  1766. },
  1767. AlignedArray: function (begin) {
  1768. var align = this.GetBrackets("\\begin{"+begin.name+"}");
  1769. return this.setArrayAlign(this.Array.apply(this,arguments),align);
  1770. },
  1771. setArrayAlign: function (array,align) {
  1772. align = this.trimSpaces(align||"");
  1773. if (align === "t") {array.arraydef.align = "baseline 1"}
  1774. else if (align === "b") {array.arraydef.align = "baseline -1"}
  1775. else if (align === "c") {array.arraydef.align = "center"}
  1776. else if (align) {array.arraydef.align = align} // FIXME: should be an error?
  1777. return array;
  1778. },
  1779. /************************************************************************/
  1780. /*
  1781. * String handling routines
  1782. */
  1783. /*
  1784. * Convert delimiter to character
  1785. */
  1786. convertDelimiter: function (c) {
  1787. if (c) {c = TEXDEF.delimiter[c]}
  1788. if (c == null) {return null}
  1789. if (isArray(c)) {c = c[0]}
  1790. if (c.length === 4) {c = String.fromCharCode(parseInt(c,16))}
  1791. return c;
  1792. },
  1793. /*
  1794. * Trim spaces from a string
  1795. */
  1796. trimSpaces: function (text) {
  1797. if (typeof(text) != 'string') {return text}
  1798. var TEXT = text.replace(/^\s+|\s+$/g,'');
  1799. if (TEXT.match(/\\$/) && text.match(/ $/)) TEXT += " ";
  1800. return TEXT;
  1801. },
  1802. /*
  1803. * Check if the next character is a space
  1804. */
  1805. nextIsSpace: function () {
  1806. return this.string.charAt(this.i).match(/\s/);
  1807. },
  1808. /*
  1809. * Get the next non-space character
  1810. */
  1811. GetNext: function () {
  1812. while (this.nextIsSpace()) {this.i++}
  1813. return this.string.charAt(this.i);
  1814. },
  1815. /*
  1816. * Get and return a control-sequence name
  1817. */
  1818. GetCS: function () {
  1819. var CS = this.string.slice(this.i).match(/^([a-z]+|.) ?/i);
  1820. if (CS) {this.i += CS[1].length; return CS[1]} else {this.i++; return " "}
  1821. },
  1822. /*
  1823. * Get and return a TeX argument (either a single character or control sequence,
  1824. * or the contents of the next set of braces).
  1825. */
  1826. GetArgument: function (name,noneOK) {
  1827. switch (this.GetNext()) {
  1828. case "":
  1829. if (!noneOK) {TEX.Error(["MissingArgFor","Missing argument for %1",name])}
  1830. return null;
  1831. case '}':
  1832. if (!noneOK) {
  1833. TEX.Error(["ExtraCloseMissingOpen",
  1834. "Extra close brace or missing open brace"]);
  1835. }
  1836. return null;
  1837. case '\\':
  1838. this.i++; return "\\"+this.GetCS();
  1839. case '{':
  1840. var j = ++this.i, parens = 1;
  1841. while (this.i < this.string.length) {
  1842. switch (this.string.charAt(this.i++)) {
  1843. case '\\': this.i++; break;
  1844. case '{': parens++; break;
  1845. case '}':
  1846. if (--parens == 0) {return this.string.slice(j,this.i-1)}
  1847. break;
  1848. }
  1849. }
  1850. TEX.Error(["MissingCloseBrace","Missing close brace"]);
  1851. break;
  1852. }
  1853. return this.string.charAt(this.i++);
  1854. },
  1855. /*
  1856. * Get an optional LaTeX argument in brackets
  1857. */
  1858. GetBrackets: function (name,def) {
  1859. if (this.GetNext() != '[') {return def};
  1860. var j = ++this.i, parens = 0;
  1861. while (this.i < this.string.length) {
  1862. switch (this.string.charAt(this.i++)) {
  1863. case '{': parens++; break;
  1864. case '\\': this.i++; break;
  1865. case '}':
  1866. if (parens-- <= 0) {
  1867. TEX.Error(["ExtraCloseLooking",
  1868. "Extra close brace while looking for %1","']'"]);
  1869. }
  1870. break;
  1871. case ']':
  1872. if (parens == 0) {return this.string.slice(j,this.i-1)}
  1873. break;
  1874. }
  1875. }
  1876. TEX.Error(["MissingCloseBracket",
  1877. "Couldn't find closing ']' for argument to %1",name]);
  1878. },
  1879. /*
  1880. * Get the name of a delimiter (check it in the delimiter list).
  1881. */
  1882. GetDelimiter: function (name,braceOK) {
  1883. while (this.nextIsSpace()) {this.i++}
  1884. var c = this.string.charAt(this.i); this.i++;
  1885. if (this.i <= this.string.length) {
  1886. if (c == "\\") {c += this.GetCS(name)}
  1887. else if (c === "{" && braceOK) {this.i--; c = this.GetArgument(name)}
  1888. if (TEXDEF.delimiter[c] != null) {return this.convertDelimiter(c)}
  1889. }
  1890. TEX.Error(["MissingOrUnrecognizedDelim",
  1891. "Missing or unrecognized delimiter for %1",name]);
  1892. },
  1893. /*
  1894. * Get a dimension (including its units).
  1895. */
  1896. GetDimen: function (name) {
  1897. var dimen;
  1898. if (this.nextIsSpace()) {this.i++}
  1899. if (this.string.charAt(this.i) == '{') {
  1900. dimen = this.GetArgument(name);
  1901. if (dimen.match(/^\s*([-+]?([.,]\d+|\d+([.,]\d*)?))\s*(pt|em|ex|mu|px|mm|cm|in|pc)\s*$/))
  1902. {return dimen.replace(/ /g,"").replace(/,/,".")}
  1903. } else {
  1904. dimen = this.string.slice(this.i);
  1905. var match = dimen.match(/^\s*(([-+]?([.,]\d+|\d+([.,]\d*)?))\s*(pt|em|ex|mu|px|mm|cm|in|pc)) ?/);
  1906. if (match) {
  1907. this.i += match[0].length;
  1908. return match[1].replace(/ /g,"").replace(/,/,".");
  1909. }
  1910. }
  1911. TEX.Error(["MissingDimOrUnits",
  1912. "Missing dimension or its units for %1",name]);
  1913. },
  1914. /*
  1915. * Get everything up to the given control sequence (token)
  1916. */
  1917. GetUpTo: function (name,token) {
  1918. while (this.nextIsSpace()) {this.i++}
  1919. var j = this.i, k, c, parens = 0;
  1920. while (this.i < this.string.length) {
  1921. k = this.i; c = this.string.charAt(this.i++);
  1922. switch (c) {
  1923. case '\\': c += this.GetCS(); break;
  1924. case '{': parens++; break;
  1925. case '}':
  1926. if (parens == 0) {
  1927. TEX.Error(["ExtraCloseLooking",
  1928. "Extra close brace while looking for %1",token])
  1929. }
  1930. parens--;
  1931. break;
  1932. }
  1933. if (parens == 0 && c == token) {return this.string.slice(j,k)}
  1934. }
  1935. TEX.Error(["TokenNotFoundForCommand",
  1936. "Couldn't find %1 for %2",token,name]);
  1937. },
  1938. /*
  1939. * Parse various substrings
  1940. */
  1941. ParseArg: function (name) {return TEX.Parse(this.GetArgument(name),this.stack.env).mml()},
  1942. ParseUpTo: function (name,token) {return TEX.Parse(this.GetUpTo(name,token),this.stack.env).mml()},
  1943. /*
  1944. * Break up a string into text and math blocks
  1945. */
  1946. InternalMath: function (text,level) {
  1947. var def = (this.stack.env.font ? {mathvariant: this.stack.env.font} : {});
  1948. var mml = [], i = 0, k = 0, c, match = '', braces = 0;
  1949. if (text.match(/\\?[${}\\]|\\\(|\\(eq)?ref\s*\{/)) {
  1950. while (i < text.length) {
  1951. c = text.charAt(i++);
  1952. if (c === '$') {
  1953. if (match === '$' && braces === 0) {
  1954. mml.push(MML.TeXAtom(TEX.Parse(text.slice(k,i-1),{}).mml()));
  1955. match = ''; k = i;
  1956. } else if (match === '') {
  1957. if (k < i-1) mml.push(this.InternalText(text.slice(k,i-1),def));
  1958. match = '$'; k = i;
  1959. }
  1960. } else if (c === '{' && match !== '') {
  1961. braces++;
  1962. } else if (c === '}') {
  1963. if (match === '}' && braces === 0) {
  1964. mml.push(MML.TeXAtom(TEX.Parse(text.slice(k,i),{}).mml().With(def)));
  1965. match = ''; k = i;
  1966. } else if (match !== '') {
  1967. if (braces) braces--;
  1968. }
  1969. } else if (c === '\\') {
  1970. if (match === '' && text.substr(i).match(/^(eq)?ref\s*\{/)) {
  1971. var len = RegExp["$&"].length;
  1972. if (k < i-1) mml.push(this.InternalText(text.slice(k,i-1),def));
  1973. match = '}'; k = i-1; i += len;
  1974. } else {
  1975. c = text.charAt(i++);
  1976. if (c === '(' && match === '') {
  1977. if (k < i-2) mml.push(this.InternalText(text.slice(k,i-2),def));
  1978. match = ')'; k = i;
  1979. } else if (c === ')' && match === ')' && braces === 0) {
  1980. mml.push(MML.TeXAtom(TEX.Parse(text.slice(k,i-2),{}).mml()));
  1981. match = ''; k = i;
  1982. } else if (c.match(/[${}\\]/) && match === '') {
  1983. i--; text = text.substr(0,i-1) + text.substr(i); // remove \ from \$, \{, \}, or \\
  1984. }
  1985. }
  1986. }
  1987. }
  1988. if (match !== '') TEX.Error(["MathNotTerminated","Math not terminated in text box"]);
  1989. }
  1990. if (k < text.length) mml.push(this.InternalText(text.slice(k),def));
  1991. if (level != null) {
  1992. mml = [MML.mstyle.apply(MML,mml).With({displaystyle:false,scriptlevel:level})];
  1993. } else if (mml.length > 1) {
  1994. mml = [MML.mrow.apply(MML,mml)];
  1995. }
  1996. return mml;
  1997. },
  1998. InternalText: function (text,def) {
  1999. text = text.replace(/^\s+/,NBSP).replace(/\s+$/,NBSP);
  2000. return MML.mtext(MML.chars(text)).With(def);
  2001. },
  2002. /*
  2003. * Replace macro paramters with their values
  2004. */
  2005. SubstituteArgs: function (args,string) {
  2006. var text = ''; var newstring = ''; var c; var i = 0;
  2007. while (i < string.length) {
  2008. c = string.charAt(i++);
  2009. if (c === "\\") {text += c + string.charAt(i++)}
  2010. else if (c === '#') {
  2011. c = string.charAt(i++);
  2012. if (c === '#') {text += c} else {
  2013. if (!c.match(/[1-9]/) || c > args.length) {
  2014. TEX.Error(["IllegalMacroParam",
  2015. "Illegal macro parameter reference"]);
  2016. }
  2017. newstring = this.AddArgs(this.AddArgs(newstring,text),args[c-1]);
  2018. text = '';
  2019. }
  2020. } else {text += c}
  2021. }
  2022. return this.AddArgs(newstring,text);
  2023. },
  2024. /*
  2025. * Make sure that macros are followed by a space if their names
  2026. * could accidentally be continued into the following text.
  2027. */
  2028. AddArgs: function (s1,s2) {
  2029. if (s2.match(/^[a-z]/i) && s1.match(/(^|[^\\])(\\\\)*\\[a-z]+$/i)) {s1 += ' '}
  2030. if (s1.length + s2.length > TEX.config.MAXBUFFER) {
  2031. TEX.Error(["MaxBufferSize",
  2032. "MathJax internal buffer size exceeded; is there a recursive macro call?"]);
  2033. }
  2034. return s1+s2;
  2035. }
  2036. });
  2037. /************************************************************************/
  2038. TEX.Augment({
  2039. Stack: STACK, Parse: PARSE, Definitions: TEXDEF, Startup: STARTUP,
  2040. config: {
  2041. MAXMACROS: 10000, // maximum number of macro substitutions per equation
  2042. MAXBUFFER: 5*1024 // maximum size of TeX string to process
  2043. },
  2044. sourceMenuTitle: /*_(MathMenu)*/ ["TeXCommands","TeX Commands"],
  2045. annotationEncoding: "application/x-tex",
  2046. prefilterHooks: MathJax.Callback.Hooks(true), // hooks to run before processing TeX
  2047. postfilterHooks: MathJax.Callback.Hooks(true), // hooks to run after processing TeX
  2048. //
  2049. // Check if AMSmath extension must be loaded and push
  2050. // it on the extensions array, if needed
  2051. //
  2052. Config: function () {
  2053. this.SUPER(arguments).Config.apply(this,arguments);
  2054. if (this.config.equationNumbers.autoNumber !== "none") {
  2055. if (!this.config.extensions) {this.config.extensions = []}
  2056. this.config.extensions.push("AMSmath.js");
  2057. }
  2058. },
  2059. //
  2060. // Convert TeX to ElementJax
  2061. //
  2062. Translate: function (script) {
  2063. var mml, isError = false, math = MathJax.HTML.getScript(script);
  2064. var display = (script.type.replace(/\n/g," ").match(/(;|\s|\n)mode\s*=\s*display(;|\s|\n|$)/) != null);
  2065. var data = {math:math, display:display, script:script};
  2066. var callback = this.prefilterHooks.Execute(data); if (callback) return callback;
  2067. math = data.math;
  2068. try {
  2069. mml = TEX.Parse(math).mml();
  2070. } catch(err) {
  2071. if (!err.texError) {throw err}
  2072. mml = this.formatError(err,math,display,script);
  2073. isError = true;
  2074. }
  2075. if (mml.isa(MML.mtable) && mml.displaystyle === "inherit") mml.displaystyle = display; // for tagged equations
  2076. if (mml.inferred) {mml = MML.apply(MathJax.ElementJax,mml.data)} else {mml = MML(mml)}
  2077. if (display) {mml.root.display = "block"}
  2078. if (isError) {mml.texError = true}
  2079. data.math = mml;
  2080. return this.postfilterHooks.Execute(data) || data.math;
  2081. },
  2082. prefilterMath: function (math,displaystyle,script) {
  2083. return math;
  2084. },
  2085. postfilterMath: function (math,displaystyle,script) {
  2086. this.combineRelations(math.root);
  2087. return math;
  2088. },
  2089. formatError: function (err,math,display,script) {
  2090. var message = err.message.replace(/\n.*/,"");
  2091. HUB.signal.Post(["TeX Jax - parse error",message,math,display,script]);
  2092. return MML.Error(message);
  2093. },
  2094. //
  2095. // Produce an error and stop processing this equation
  2096. //
  2097. Error: function (message) {
  2098. //
  2099. // Translate message if it is ["id","message",args]
  2100. //
  2101. if (isArray(message)) {message = _.apply(_,message)}
  2102. throw HUB.Insert(Error(message),{texError: true});
  2103. },
  2104. //
  2105. // Add a user-defined macro to the macro list
  2106. //
  2107. Macro: function (name,def,argn) {
  2108. TEXDEF.macros[name] = ['Macro'].concat([].slice.call(arguments,1));
  2109. TEXDEF.macros[name].isUser = true;
  2110. },
  2111. /*
  2112. * Create an mrow that has stretchy delimiters at either end, as needed
  2113. */
  2114. fenced: function (open,mml,close) {
  2115. var mrow = MML.mrow().With({open:open, close:close, texClass:MML.TEXCLASS.INNER});
  2116. mrow.Append(
  2117. MML.mo(open).With({fence:true, stretchy:true, symmetric:true, texClass:MML.TEXCLASS.OPEN}),
  2118. mml,
  2119. MML.mo(close).With({fence:true, stretchy:true, symmetric:true, texClass:MML.TEXCLASS.CLOSE})
  2120. );
  2121. return mrow;
  2122. },
  2123. /*
  2124. * Create an mrow that has \mathchoice using \bigg and \big for the delimiters
  2125. */
  2126. fixedFence: function (open,mml,close) {
  2127. var mrow = MML.mrow().With({open:open, close:close, texClass:MML.TEXCLASS.ORD});
  2128. if (open) {mrow.Append(this.mathPalette(open,"l"))}
  2129. if (mml.type === "mrow") {mrow.Append.apply(mrow,mml.data)} else {mrow.Append(mml)}
  2130. if (close) {mrow.Append(this.mathPalette(close,"r"))}
  2131. return mrow;
  2132. },
  2133. mathPalette: function (fence,side) {
  2134. if (fence === '{' || fence === '}') {fence = "\\"+fence}
  2135. var D = '{\\bigg'+side+' '+fence+'}', T = '{\\big'+side+' '+fence+'}';
  2136. return TEX.Parse('\\mathchoice'+D+T+T+T,{}).mml();
  2137. },
  2138. //
  2139. // Combine adjacent <mo> elements that are relations
  2140. // (since MathML treats the spacing very differently)
  2141. //
  2142. combineRelations: function (mml) {
  2143. var i, m, m1, m2;
  2144. for (i = 0, m = mml.data.length; i < m; i++) {
  2145. if (mml.data[i]) {
  2146. if (mml.isa(MML.mrow)) {
  2147. while (i+1 < m && (m1 = mml.data[i]) && (m2 = mml.data[i+1]) &&
  2148. m1.isa(MML.mo) && m2.isa(MML.mo) &&
  2149. m1.Get("texClass") === MML.TEXCLASS.REL &&
  2150. m2.Get("texClass") === MML.TEXCLASS.REL) {
  2151. if (m1.variantForm == m2.variantForm &&
  2152. m1.Get("mathvariant") == m2.Get("mathvariant") && m1.style == m2.style &&
  2153. m1["class"] == m2["class"] && !m1.id && !m2.id) {
  2154. m1.Append.apply(m1,m2.data);
  2155. mml.data.splice(i+1,1); m--;
  2156. } else {
  2157. m1.rspace = m2.lspace = "0pt"; i++;
  2158. }
  2159. }
  2160. }
  2161. if (!mml.data[i].isToken) {this.combineRelations(mml.data[i])}
  2162. }
  2163. }
  2164. }
  2165. });
  2166. //
  2167. // Add the default filters
  2168. //
  2169. TEX.prefilterHooks.Add(function (data) {
  2170. data.math = TEX.prefilterMath(data.math,data.display,data.script);
  2171. });
  2172. TEX.postfilterHooks.Add(function (data) {
  2173. data.math = TEX.postfilterMath(data.math,data.display,data.script);
  2174. });
  2175. TEX.loadComplete("jax.js");
  2176. })(MathJax.InputJax.TeX,MathJax.Hub,MathJax.Ajax);