jax.js 82 KB

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