jax.js 90 KB

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