jax.js 86 KB

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