MathJax.js 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228
  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.js
  6. *
  7. * The main support code for the MathJax Hub, including the
  8. * Ajax, Callback, Messaging, and Object-Oriented Programming
  9. * libraries, as well as the base Jax classes, and startup
  10. * processing code.
  11. *
  12. * ---------------------------------------------------------------------
  13. *
  14. * Copyright (c) 2009-2015 The MathJax Consortium
  15. *
  16. * Licensed under the Apache License, Version 2.0 (the "License");
  17. * you may not use this file except in compliance with the License.
  18. * You may obtain a copy of the License at
  19. *
  20. * http://www.apache.org/licenses/LICENSE-2.0
  21. *
  22. * Unless required by applicable law or agreed to in writing, software
  23. * distributed under the License is distributed on an "AS IS" BASIS,
  24. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25. * See the License for the specific language governing permissions and
  26. * limitations under the License.
  27. */
  28. //
  29. // Check if browser can support MathJax (no one fails this nowadays)
  30. //
  31. if (document.getElementById && document.childNodes && document.createElement) {
  32. //
  33. // Skip if MathJax is already loaded
  34. //
  35. if (!(window.MathJax && MathJax.Hub)) {
  36. //
  37. // Get author configuration from MathJax variable, if any
  38. //
  39. if (window.MathJax) {window.MathJax = {AuthorConfig: window.MathJax}}
  40. else {window.MathJax = {}}
  41. // MathJax.isPacked = true; // This line is uncommented by the packer.
  42. MathJax.version = "2.5";
  43. MathJax.fileversion = "2.5.3";
  44. MathJax.cdnVersion = "2.5.3"; // specifies a revision to break caching
  45. MathJax.cdnFileVersions = {}; // can be used to specify revisions for individual files
  46. /**********************************************************/
  47. (function (BASENAME) {
  48. var BASE = window[BASENAME];
  49. if (!BASE) {BASE = window[BASENAME] = {}}
  50. var PROTO = []; // a static object used to indicate when a prototype is being created
  51. var OBJECT = function (def) {
  52. var obj = def.constructor; if (!obj) {obj = function () {}}
  53. for (var id in def) {if (id !== 'constructor' && def.hasOwnProperty(id)) {obj[id] = def[id]}}
  54. return obj;
  55. };
  56. var CONSTRUCTOR = function () {
  57. return function () {return arguments.callee.Init.call(this,arguments)};
  58. };
  59. BASE.Object = OBJECT({
  60. constructor: CONSTRUCTOR(),
  61. Subclass: function (def,classdef) {
  62. var obj = CONSTRUCTOR();
  63. obj.SUPER = this; obj.Init = this.Init;
  64. obj.Subclass = this.Subclass; obj.Augment = this.Augment;
  65. obj.protoFunction = this.protoFunction;
  66. obj.can = this.can; obj.has = this.has; obj.isa = this.isa;
  67. obj.prototype = new this(PROTO);
  68. obj.prototype.constructor = obj; // the real constructor
  69. obj.Augment(def,classdef);
  70. return obj;
  71. },
  72. Init: function (args) {
  73. var obj = this;
  74. if (args.length === 1 && args[0] === PROTO) {return obj}
  75. if (!(obj instanceof args.callee)) {obj = new args.callee(PROTO)}
  76. return obj.Init.apply(obj,args) || obj;
  77. },
  78. Augment: function (def,classdef) {
  79. var id;
  80. if (def != null) {
  81. for (id in def) {if (def.hasOwnProperty(id)) {this.protoFunction(id,def[id])}}
  82. // MSIE doesn't list toString even if it is not native so handle it separately
  83. if (def.toString !== this.prototype.toString && def.toString !== {}.toString)
  84. {this.protoFunction('toString',def.toString)}
  85. }
  86. if (classdef != null) {
  87. for (id in classdef) {if (classdef.hasOwnProperty(id)) {this[id] = classdef[id]}}
  88. }
  89. return this;
  90. },
  91. protoFunction: function (id,def) {
  92. this.prototype[id] = def;
  93. if (typeof def === "function") {def.SUPER = this.SUPER.prototype}
  94. },
  95. prototype: {
  96. Init: function () {},
  97. SUPER: function (fn) {return fn.callee.SUPER},
  98. can: function (method) {return typeof(this[method]) === "function"},
  99. has: function (property) {return typeof(this[property]) !== "undefined"},
  100. isa: function (obj) {return (obj instanceof Object) && (this instanceof obj)}
  101. },
  102. can: function (method) {return this.prototype.can.call(this,method)},
  103. has: function (property) {return this.prototype.has.call(this,property)},
  104. isa: function (obj) {
  105. var constructor = this;
  106. while (constructor) {
  107. if (constructor === obj) {return true} else {constructor = constructor.SUPER}
  108. }
  109. return false;
  110. },
  111. SimpleSUPER: OBJECT({
  112. constructor: function (def) {return this.SimpleSUPER.define(def)},
  113. define: function (src) {
  114. var dst = {};
  115. if (src != null) {
  116. for (var id in src) {if (src.hasOwnProperty(id)) {dst[id] = this.wrap(id,src[id])}}
  117. // MSIE doesn't list toString even if it is not native so handle it separately
  118. if (src.toString !== this.prototype.toString && src.toString !== {}.toString)
  119. {dst.toString = this.wrap('toString',src.toString)}
  120. }
  121. return dst;
  122. },
  123. wrap: function (id,f) {
  124. if (typeof(f) !== 'function' || !f.toString().match(/\.\s*SUPER\s*\(/)) {return f}
  125. var fn = function () {
  126. this.SUPER = fn.SUPER[id];
  127. try {var result = f.apply(this,arguments)} catch (err) {delete this.SUPER; throw err}
  128. delete this.SUPER;
  129. return result;
  130. }
  131. fn.toString = function () {return f.toString.apply(f,arguments)}
  132. return fn;
  133. }
  134. })
  135. });
  136. })("MathJax");
  137. /**********************************************************/
  138. /*
  139. * Create a callback function from various forms of data:
  140. *
  141. * MathJax.Callback(fn) -- callback to a function
  142. *
  143. * MathJax.Callback([fn]) -- callback to function
  144. * MathJax.Callback([fn,data...])
  145. * -- callback to function with given data as arguments
  146. * MathJax.Callback([object,fn])
  147. * -- call fn with object as "this"
  148. * MathJax.Callback([object,fn,data...])
  149. * -- call fn with object as "this" and data as arguments
  150. * MathJax.Callback(["method",object])
  151. * -- call method of object wth object as "this"
  152. * MathJax.Callback(["method",object,data...])
  153. * -- as above, but with data as arguments to method
  154. *
  155. * MathJax.Callback({hook: fn, data: [...], object: this})
  156. * -- give function, data, and object to act as "this" explicitly
  157. *
  158. * MathJax.Callback("code") -- callback that compiles and executes a string
  159. *
  160. * MathJax.Callback([...],i)
  161. * -- use slice of array starting at i and interpret
  162. * result as above. (Used for passing "arguments" array
  163. * and trimming initial arguments, if any.)
  164. */
  165. /*
  166. * MathJax.Callback.After([...],cb1,cb2,...)
  167. * -- make a callback that isn't called until all the other
  168. * ones are called first. I.e., wait for a union of
  169. * callbacks to occur before making the given callback.
  170. */
  171. /*
  172. * MathJax.Callback.Queue([callback,...])
  173. * -- make a synchronized queue of commands that process
  174. * sequentially, waiting for those that return uncalled
  175. * callbacks.
  176. */
  177. /*
  178. * MathJax.Callback.Signal(name)
  179. * -- finds or creates a names signal, to which listeners
  180. * can be attached and are signaled by messages posted
  181. * to the signal. Responses can be asynchronous.
  182. */
  183. (function (BASENAME) {
  184. var BASE = window[BASENAME];
  185. if (!BASE) {BASE = window[BASENAME] = {}}
  186. //
  187. // Create a callback from an associative array
  188. //
  189. var CALLBACK = function (data) {
  190. var cb = function () {return arguments.callee.execute.apply(arguments.callee,arguments)};
  191. for (var id in CALLBACK.prototype) {
  192. if (CALLBACK.prototype.hasOwnProperty(id)) {
  193. if (typeof(data[id]) !== 'undefined') {cb[id] = data[id]}
  194. else {cb[id] = CALLBACK.prototype[id]}
  195. }
  196. }
  197. cb.toString = CALLBACK.prototype.toString;
  198. return cb;
  199. };
  200. CALLBACK.prototype = {
  201. isCallback: true,
  202. hook: function () {},
  203. data: [],
  204. object: window,
  205. execute: function () {
  206. if (!this.called || this.autoReset) {
  207. this.called = !this.autoReset;
  208. return this.hook.apply(this.object,this.data.concat([].slice.call(arguments,0)));
  209. }
  210. },
  211. reset: function () {delete this.called},
  212. toString: function () {return this.hook.toString.apply(this.hook,arguments)}
  213. };
  214. var ISCALLBACK = function (f) {
  215. return (typeof(f) === "function" && f.isCallback);
  216. }
  217. //
  218. // Evaluate a string in global context
  219. //
  220. var EVAL = function (code) {return eval.call(window,code)}
  221. var TESTEVAL = function () {
  222. EVAL("var __TeSt_VaR__ = 1"); // check if it works in global context
  223. if (window.__TeSt_VaR__) {
  224. try { delete window.__TeSt_VaR__; } // NOTE IE9 throws when in IE7 mode
  225. catch (error) { window.__TeSt_VaR__ = null; }
  226. } else {
  227. if (window.execScript) {
  228. // IE
  229. EVAL = function (code) {
  230. BASE.__code = code;
  231. code = "try {"+BASENAME+".__result = eval("+BASENAME+".__code)} catch(err) {"+BASENAME+".__result = err}";
  232. window.execScript(code);
  233. var result = BASE.__result; delete BASE.__result; delete BASE.__code;
  234. if (result instanceof Error) {throw result}
  235. return result;
  236. }
  237. } else {
  238. // Safari2
  239. EVAL = function (code) {
  240. BASE.__code = code;
  241. code = "try {"+BASENAME+".__result = eval("+BASENAME+".__code)} catch(err) {"+BASENAME+".__result = err}";
  242. var head = (document.getElementsByTagName("head"))[0]; if (!head) {head = document.body}
  243. var script = document.createElement("script");
  244. script.appendChild(document.createTextNode(code));
  245. head.appendChild(script); head.removeChild(script);
  246. var result = BASE.__result; delete BASE.__result; delete BASE.__code;
  247. if (result instanceof Error) {throw result}
  248. return result;
  249. }
  250. }
  251. }
  252. TESTEVAL = null;
  253. }
  254. //
  255. // Create a callback from various types of data
  256. //
  257. var USING = function (args,i) {
  258. if (arguments.length > 1) {
  259. if (arguments.length === 2 && !(typeof arguments[0] === 'function') &&
  260. arguments[0] instanceof Object && typeof arguments[1] === 'number')
  261. {args = [].slice.call(args,i)}
  262. else {args = [].slice.call(arguments,0)}
  263. }
  264. if (args instanceof Array && args.length === 1) {args = args[0]}
  265. if (typeof args === 'function') {
  266. if (args.execute === CALLBACK.prototype.execute) {return args}
  267. return CALLBACK({hook: args});
  268. } else if (args instanceof Array) {
  269. if (typeof(args[0]) === 'string' && args[1] instanceof Object &&
  270. typeof args[1][args[0]] === 'function') {
  271. return CALLBACK({hook: args[1][args[0]], object: args[1], data: args.slice(2)});
  272. } else if (typeof args[0] === 'function') {
  273. return CALLBACK({hook: args[0], data: args.slice(1)});
  274. } else if (typeof args[1] === 'function') {
  275. return CALLBACK({hook: args[1], object: args[0], data: args.slice(2)});
  276. }
  277. } else if (typeof(args) === 'string') {
  278. if (TESTEVAL) TESTEVAL();
  279. return CALLBACK({hook: EVAL, data: [args]});
  280. } else if (args instanceof Object) {
  281. return CALLBACK(args);
  282. } else if (typeof(args) === 'undefined') {
  283. return CALLBACK({});
  284. }
  285. throw Error("Can't make callback from given data");
  286. };
  287. //
  288. // Wait for a given time to elapse and then perform the callback
  289. //
  290. var DELAY = function (time,callback) {
  291. callback = USING(callback);
  292. callback.timeout = setTimeout(callback,time);
  293. return callback;
  294. };
  295. //
  296. // Callback used by AFTER, QUEUE, and SIGNAL to check if calls have completed
  297. //
  298. var WAITFOR = function (callback,signal) {
  299. callback = USING(callback);
  300. if (!callback.called) {WAITSIGNAL(callback,signal); signal.pending++}
  301. };
  302. var WAITEXECUTE = function () {
  303. var signals = this.signal; delete this.signal;
  304. this.execute = this.oldExecute; delete this.oldExecute;
  305. var result = this.execute.apply(this,arguments);
  306. if (ISCALLBACK(result) && !result.called) {WAITSIGNAL(result,signals)} else {
  307. for (var i = 0, m = signals.length; i < m; i++) {
  308. signals[i].pending--;
  309. if (signals[i].pending <= 0) {signals[i].call()}
  310. }
  311. }
  312. };
  313. var WAITSIGNAL = function (callback,signals) {
  314. if (!(signals instanceof Array)) {signals = [signals]}
  315. if (!callback.signal) {
  316. callback.oldExecute = callback.execute;
  317. callback.execute = WAITEXECUTE;
  318. callback.signal = signals;
  319. } else if (signals.length === 1) {callback.signal.push(signals[0])}
  320. else {callback.signal = callback.signal.concat(signals)}
  321. };
  322. //
  323. // Create a callback that is called when a collection of other callbacks have
  324. // all been executed. If the callback gets called immediately (i.e., the
  325. // others are all already called), check if it returns another callback
  326. // and return that instead.
  327. //
  328. var AFTER = function (callback) {
  329. callback = USING(callback);
  330. callback.pending = 0;
  331. for (var i = 1, m = arguments.length; i < m; i++)
  332. {if (arguments[i]) {WAITFOR(arguments[i],callback)}}
  333. if (callback.pending === 0) {
  334. var result = callback();
  335. if (ISCALLBACK(result)) {callback = result}
  336. }
  337. return callback;
  338. };
  339. //
  340. // An array of prioritized hooks that are executed sequentially
  341. // with a given set of data.
  342. //
  343. var HOOKS = MathJax.Object.Subclass({
  344. //
  345. // Initialize the array and the auto-reset status
  346. //
  347. Init: function (reset) {
  348. this.hooks = [];
  349. this.remove = []; // used when hooks are removed during execution of list
  350. this.reset = reset;
  351. this.running = false;
  352. },
  353. //
  354. // Add a callback to the list, in priority order (default priority is 10)
  355. //
  356. Add: function (hook,priority) {
  357. if (priority == null) {priority = 10}
  358. if (!ISCALLBACK(hook)) {hook = USING(hook)}
  359. hook.priority = priority;
  360. var i = this.hooks.length;
  361. while (i > 0 && priority < this.hooks[i-1].priority) {i--}
  362. this.hooks.splice(i,0,hook);
  363. return hook;
  364. },
  365. Remove: function (hook) {
  366. for (var i = 0, m = this.hooks.length; i < m; i++) {
  367. if (this.hooks[i] === hook) {
  368. if (this.running) {this.remove.push(i)}
  369. else {this.hooks.splice(i,1)}
  370. return;
  371. }
  372. }
  373. },
  374. //
  375. // Execute the list of callbacks, resetting them if requested.
  376. // If any return callbacks, return a callback that will be
  377. // executed when they all have completed.
  378. // Remove any hooks that requested being removed during processing.
  379. //
  380. Execute: function () {
  381. var callbacks = [{}];
  382. this.running = true;
  383. for (var i = 0, m = this.hooks.length; i < m; i++) {
  384. if (this.reset) {this.hooks[i].reset()}
  385. var result = this.hooks[i].apply(window,arguments);
  386. if (ISCALLBACK(result) && !result.called) {callbacks.push(result)}
  387. }
  388. this.running = false;
  389. if (this.remove.length) {this.RemovePending()}
  390. if (callbacks.length === 1) {return null}
  391. if (callbacks.length === 2) {return callbacks[1]}
  392. return AFTER.apply({},callbacks);
  393. },
  394. //
  395. // Remove hooks that asked to be removed during execution of list
  396. //
  397. RemovePending: function () {
  398. this.remove = this.remove.sort();
  399. for (var i = this.remove.length-1; i >= 0; i--) {this.hooks.splice(i,1)}
  400. this.remove = [];
  401. }
  402. });
  403. //
  404. // Run an array of callbacks passing them the given data.
  405. // (Legacy function, since this has been replaced by the HOOKS object).
  406. //
  407. var EXECUTEHOOKS = function (hooks,data,reset) {
  408. if (!hooks) {return null}
  409. if (!(hooks instanceof Array)) {hooks = [hooks]}
  410. if (!(data instanceof Array)) {data = (data == null ? [] : [data])}
  411. var handler = HOOKS(reset);
  412. for (var i = 0, m = hooks.length; i < m; i++) {handler.Add(hooks[i])}
  413. return handler.Execute.apply(handler,data);
  414. };
  415. //
  416. // Command queue that performs commands in order, waiting when
  417. // necessary for commands to complete asynchronousely
  418. //
  419. var QUEUE = BASE.Object.Subclass({
  420. //
  421. // Create the queue and push any commands that are specified
  422. //
  423. Init: function () {
  424. this.pending = this.running = 0;
  425. this.queue = [];
  426. this.Push.apply(this,arguments);
  427. },
  428. //
  429. // Add commands to the queue and run them. Adding a callback object
  430. // (rather than a callback specification) queues a wait for that callback.
  431. // Return the final callback for synchronization purposes.
  432. //
  433. Push: function () {
  434. var callback;
  435. for (var i = 0, m = arguments.length; i < m; i++) {
  436. callback = USING(arguments[i]);
  437. if (callback === arguments[i] && !callback.called)
  438. {callback = USING(["wait",this,callback])}
  439. this.queue.push(callback);
  440. }
  441. if (!this.running && !this.pending) {this.Process()}
  442. return callback;
  443. },
  444. //
  445. // Process the command queue if we aren't waiting on another command
  446. //
  447. Process: function (queue) {
  448. while (!this.running && !this.pending && this.queue.length) {
  449. var callback = this.queue[0];
  450. queue = this.queue.slice(1); this.queue = [];
  451. this.Suspend(); var result = callback(); this.Resume();
  452. if (queue.length) {this.queue = queue.concat(this.queue)}
  453. if (ISCALLBACK(result) && !result.called) {WAITFOR(result,this)}
  454. }
  455. },
  456. //
  457. // Suspend/Resume command processing on this queue
  458. //
  459. Suspend: function () {this.running++},
  460. Resume: function () {if (this.running) {this.running--}},
  461. //
  462. // Used by WAITFOR to restart the queue when an action completes
  463. //
  464. call: function () {this.Process.apply(this,arguments)},
  465. wait: function (callback) {return callback}
  466. });
  467. //
  468. // Create a named signal that listeners can attach to, to be signaled by
  469. // postings made to the signal. Posts are queued if they occur while one
  470. // is already in process.
  471. //
  472. var SIGNAL = QUEUE.Subclass({
  473. Init: function (name) {
  474. QUEUE.prototype.Init.call(this);
  475. this.name = name;
  476. this.posted = []; // the messages posted so far
  477. this.listeners = HOOKS(true); // those with interest in this signal
  478. this.posting = false;
  479. this.callback = null;
  480. },
  481. //
  482. // Post a message to the signal listeners, with callback for when complete
  483. //
  484. Post: function (message,callback,forget) {
  485. callback = USING(callback);
  486. if (this.posting || this.pending) {
  487. this.Push(["Post",this,message,callback,forget]);
  488. } else {
  489. this.callback = callback; callback.reset();
  490. if (!forget) {this.posted.push(message)}
  491. this.Suspend(); this.posting = true;
  492. var result = this.listeners.Execute(message);
  493. if (ISCALLBACK(result) && !result.called) {WAITFOR(result,this)}
  494. this.Resume(); this.posting = false;
  495. if (!this.pending) {this.call()}
  496. }
  497. return callback;
  498. },
  499. //
  500. // Clear the post history (so new listeners won't get old messages)
  501. //
  502. Clear: function (callback) {
  503. callback = USING(callback);
  504. if (this.posting || this.pending) {
  505. callback = this.Push(["Clear",this,callback]);
  506. } else {
  507. this.posted = [];
  508. callback();
  509. }
  510. return callback;
  511. },
  512. //
  513. // Call the callback (all replies are in) and process the command queue
  514. //
  515. call: function () {this.callback(this); this.Process()},
  516. //
  517. // A listener calls this to register interest in the signal (so it will be called
  518. // when posts occur). If ignorePast is true, it will not be sent the post history.
  519. //
  520. Interest: function (callback,ignorePast,priority) {
  521. callback = USING(callback);
  522. this.listeners.Add(callback,priority);
  523. if (!ignorePast) {
  524. for (var i = 0, m = this.posted.length; i < m; i++) {
  525. callback.reset();
  526. var result = callback(this.posted[i]);
  527. if (ISCALLBACK(result) && i === this.posted.length-1) {WAITFOR(result,this)}
  528. }
  529. }
  530. return callback;
  531. },
  532. //
  533. // A listener calls this to remove itself from a signal
  534. //
  535. NoInterest: function (callback) {
  536. this.listeners.Remove(callback);
  537. },
  538. //
  539. // Hook a callback to a particular message on this signal
  540. //
  541. MessageHook: function (msg,callback,priority) {
  542. callback = USING(callback);
  543. if (!this.hooks) {this.hooks = {}; this.Interest(["ExecuteHooks",this])}
  544. if (!this.hooks[msg]) {this.hooks[msg] = HOOKS(true)}
  545. this.hooks[msg].Add(callback,priority);
  546. for (var i = 0, m = this.posted.length; i < m; i++)
  547. {if (this.posted[i] == msg) {callback.reset(); callback(this.posted[i])}}
  548. callback.msg = msg; // keep track so we can remove it
  549. return callback;
  550. },
  551. //
  552. // Execute the message hooks for the given message
  553. //
  554. ExecuteHooks: function (msg) {
  555. var type = ((msg instanceof Array) ? msg[0] : msg);
  556. if (!this.hooks[type]) {return null}
  557. return this.hooks[type].Execute(msg);
  558. },
  559. //
  560. // Remove a hook safely
  561. //
  562. RemoveHook: function (hook) {
  563. this.hooks[hook.msg].Remove(hook);
  564. }
  565. },{
  566. signals: {}, // the named signals
  567. find: function (name) {
  568. if (!SIGNAL.signals[name]) {SIGNAL.signals[name] = new SIGNAL(name)}
  569. return SIGNAL.signals[name];
  570. }
  571. });
  572. //
  573. // The main entry-points
  574. //
  575. BASE.Callback = BASE.CallBack = USING;
  576. BASE.Callback.Delay = DELAY;
  577. BASE.Callback.After = AFTER;
  578. BASE.Callback.Queue = QUEUE;
  579. BASE.Callback.Signal = SIGNAL.find;
  580. BASE.Callback.Hooks = HOOKS;
  581. BASE.Callback.ExecuteHooks = EXECUTEHOOKS;
  582. })("MathJax");
  583. /**********************************************************/
  584. (function (BASENAME) {
  585. var BASE = window[BASENAME];
  586. if (!BASE) {BASE = window[BASENAME] = {}}
  587. var isSafari2 = (navigator.vendor === "Apple Computer, Inc." &&
  588. typeof navigator.vendorSub === "undefined");
  589. var sheets = 0; // used by Safari2
  590. //
  591. // Update sheets count and look up the head object
  592. //
  593. var HEAD = function (head) {
  594. if (document.styleSheets && document.styleSheets.length > sheets)
  595. {sheets = document.styleSheets.length}
  596. if (!head) {
  597. head = document.head || ((document.getElementsByTagName("head"))[0]);
  598. if (!head) {head = document.body}
  599. }
  600. return head;
  601. };
  602. //
  603. // Remove scripts that are completed so they don't clutter up the HEAD.
  604. // This runs via setTimeout since IE7 can't remove the script while it is running.
  605. //
  606. var SCRIPTS = []; // stores scripts to be removed after a delay
  607. var REMOVESCRIPTS = function () {
  608. for (var i = 0, m = SCRIPTS.length; i < m; i++) {BASE.Ajax.head.removeChild(SCRIPTS[i])}
  609. SCRIPTS = [];
  610. };
  611. var PATH = {};
  612. PATH[BASENAME] = ""; // empty path gets the root URL
  613. BASE.Ajax = {
  614. loaded: {}, // files already loaded
  615. loading: {}, // files currently in process of loading
  616. loadHooks: {}, // hooks to call when files are loaded
  617. timeout: 15*1000, // timeout for loading of files (15 seconds)
  618. styleDelay: 1, // delay to use before styles are available
  619. config: {
  620. root: "", // URL of root directory to load from
  621. path: PATH // paths to named URL's (e.g., [MathJax]/...)
  622. },
  623. STATUS: {
  624. OK: 1, // file is loading or did load OK
  625. ERROR: -1 // file timed out during load
  626. },
  627. //
  628. // Return a complete URL to a file (replacing any root names)
  629. //
  630. fileURL: function (file) {
  631. var match = file.match(/^\[([-._a-z0-9]+)\]/i);
  632. if (match && match[1] in PATH)
  633. {file = (PATH[match[1]]||this.config.root) + file.substr(match[1].length+2)}
  634. return file;
  635. },
  636. //
  637. // Replace root names if URL includes one
  638. //
  639. fileName: function (url) {
  640. var root = this.config.root;
  641. if (url.substr(0,root.length) === root) {url = "["+BASENAME+"]"+url.substr(root.length)}
  642. else {
  643. for (var id in PATH) {if (PATH.hasOwnProperty(id) && PATH[id]) {
  644. if (url.substr(0,PATH[id].length) === PATH[id])
  645. {url = "["+id+"]"+url.substr(PATH[id].length); break}
  646. }}
  647. }
  648. return url;
  649. },
  650. //
  651. // Cache-breaking revision number for file
  652. //
  653. fileRev: function (file) {
  654. var rev = BASE.cdnFileVersions[name] || BASE.cdnVersion;
  655. if (rev) {rev = "?rev="+rev}
  656. return rev;
  657. },
  658. urlRev: function (file) {return this.fileURL(file)+this.fileRev(file)},
  659. //
  660. // Load a file if it hasn't been already.
  661. // Make sure the file URL is "safe"?
  662. //
  663. Require: function (file,callback) {
  664. callback = BASE.Callback(callback); var type;
  665. if (file instanceof Object) {
  666. for (var i in file)
  667. {if (file.hasOwnProperty(i)) {type = i.toUpperCase(); file = file[i]}}
  668. } else {type = file.split(/\./).pop().toUpperCase()}
  669. file = this.fileURL(file);
  670. // FIXME: check that URL is OK
  671. if (this.loaded[file]) {
  672. callback(this.loaded[file]);
  673. } else {
  674. var FILE = {}; FILE[type] = file;
  675. this.Load(FILE,callback);
  676. }
  677. return callback;
  678. },
  679. //
  680. // Load a file regardless of where it is and whether it has
  681. // already been loaded.
  682. //
  683. Load: function (file,callback) {
  684. callback = BASE.Callback(callback); var type;
  685. if (file instanceof Object) {
  686. for (var i in file)
  687. {if (file.hasOwnProperty(i)) {type = i.toUpperCase(); file = file[i]}}
  688. } else {type = file.split(/\./).pop().toUpperCase()}
  689. file = this.fileURL(file);
  690. if (this.loading[file]) {
  691. this.addHook(file,callback);
  692. } else {
  693. this.head = HEAD(this.head);
  694. if (this.loader[type]) {this.loader[type].call(this,file,callback)}
  695. else {throw Error("Can't load files of type "+type)}
  696. }
  697. return callback;
  698. },
  699. //
  700. // Register a load hook for a particular file (it will be called when
  701. // loadComplete() is called for that file)
  702. //
  703. LoadHook: function (file,callback,priority) {
  704. callback = BASE.Callback(callback);
  705. if (file instanceof Object)
  706. {for (var i in file) {if (file.hasOwnProperty(i)) {file = file[i]}}}
  707. file = this.fileURL(file);
  708. if (this.loaded[file]) {callback(this.loaded[file])}
  709. else {this.addHook(file,callback,priority)}
  710. return callback;
  711. },
  712. addHook: function (file,callback,priority) {
  713. if (!this.loadHooks[file]) {this.loadHooks[file] = MathJax.Callback.Hooks()}
  714. this.loadHooks[file].Add(callback,priority);
  715. callback.file = file;
  716. },
  717. removeHook: function (hook) {
  718. if (this.loadHooks[hook.file]) {
  719. this.loadHooks[hook.file].Remove(hook);
  720. if (!this.loadHooks[hook.file].hooks.length) {delete this.loadHooks[hook.file]}
  721. }
  722. },
  723. //
  724. // Used when files are combined in a preloading configuration file
  725. //
  726. Preloading: function () {
  727. for (var i = 0, m = arguments.length; i < m; i++) {
  728. var file = this.fileURL(arguments[i]);
  729. if (!this.loading[file]) {this.loading[file] = {preloaded: true}}
  730. }
  731. },
  732. //
  733. // Code used to load the various types of files
  734. // (JS for JavaScript, CSS for style sheets)
  735. //
  736. loader: {
  737. //
  738. // Create a SCRIPT tag to load the file
  739. //
  740. JS: function (file,callback) {
  741. var name = this.fileName(file);
  742. var script = document.createElement("script");
  743. var timeout = BASE.Callback(["loadTimeout",this,file]);
  744. this.loading[file] = {
  745. callback: callback,
  746. timeout: setTimeout(timeout,this.timeout),
  747. status: this.STATUS.OK,
  748. script: script
  749. };
  750. //
  751. // Add this to the structure above after it is created to prevent recursion
  752. // when loading the initial localization file (before loading messsage is available)
  753. //
  754. this.loading[file].message = BASE.Message.File(name);
  755. script.onerror = timeout; // doesn't work in IE and no apparent substitute
  756. script.type = "text/javascript";
  757. script.src = file+this.fileRev(name);
  758. this.head.appendChild(script);
  759. },
  760. //
  761. // Create a LINK tag to load the style sheet
  762. //
  763. CSS: function (file,callback) {
  764. var name = this.fileName(file);
  765. var link = document.createElement("link");
  766. link.rel = "stylesheet"; link.type = "text/css";
  767. link.href = file+this.fileRev(name);
  768. this.loading[file] = {
  769. callback: callback,
  770. message: BASE.Message.File(name),
  771. status: this.STATUS.OK
  772. };
  773. this.head.appendChild(link);
  774. this.timer.create.call(this,[this.timer.file,file],link);
  775. }
  776. },
  777. //
  778. // Timing code for checking when style sheets are available.
  779. //
  780. timer: {
  781. //
  782. // Create the timing callback and start the timing loop.
  783. // We use a delay because some browsers need it to allow the styles
  784. // to be processed.
  785. //
  786. create: function (callback,node) {
  787. callback = BASE.Callback(callback);
  788. if (node.nodeName === "STYLE" && node.styleSheet &&
  789. typeof(node.styleSheet.cssText) !== 'undefined') {
  790. callback(this.STATUS.OK); // MSIE processes style immediately, but doesn't set its styleSheet!
  791. } else if (window.chrome && node.nodeName === "LINK") {
  792. callback(this.STATUS.OK); // Chrome doesn't give access to cssRules for stylesheet in
  793. // a link node, so we can't detect when it is loaded.
  794. } else if (isSafari2) {
  795. this.timer.start(this,[this.timer.checkSafari2,sheets++,callback],this.styleDelay);
  796. } else {
  797. this.timer.start(this,[this.timer.checkLength,node,callback],this.styleDelay);
  798. }
  799. return callback;
  800. },
  801. //
  802. // Start the timer for the given callback checker
  803. //
  804. start: function (AJAX,check,delay,timeout) {
  805. check = BASE.Callback(check);
  806. check.execute = this.execute; check.time = this.time;
  807. check.STATUS = AJAX.STATUS; check.timeout = timeout || AJAX.timeout;
  808. check.delay = check.total = delay || 0;
  809. if (delay) {setTimeout(check,delay)} else {check()}
  810. },
  811. //
  812. // Increment the time total, increase the delay
  813. // and test if we are past the timeout time.
  814. //
  815. time: function (callback) {
  816. this.total += this.delay;
  817. this.delay = Math.floor(this.delay * 1.05 + 5);
  818. if (this.total >= this.timeout) {callback(this.STATUS.ERROR); return 1}
  819. return 0;
  820. },
  821. //
  822. // For JS file loads, call the proper routine according to status
  823. //
  824. file: function (file,status) {
  825. if (status < 0) {BASE.Ajax.loadTimeout(file)} else {BASE.Ajax.loadComplete(file)}
  826. },
  827. //
  828. // Call the hook with the required data
  829. //
  830. execute: function () {this.hook.call(this.object,this,this.data[0],this.data[1])},
  831. //
  832. // Safari2 doesn't set the link's stylesheet, so we need to look in the
  833. // document.styleSheets array for the new sheet when it is created
  834. //
  835. checkSafari2: function (check,length,callback) {
  836. if (check.time(callback)) return;
  837. if (document.styleSheets.length > length &&
  838. document.styleSheets[length].cssRules &&
  839. document.styleSheets[length].cssRules.length)
  840. {callback(check.STATUS.OK)} else {setTimeout(check,check.delay)}
  841. },
  842. //
  843. // Look for the stylesheets rules and check when they are defined
  844. // and no longer of length zero. (This assumes there actually ARE
  845. // some rules in the stylesheet.)
  846. //
  847. checkLength: function (check,node,callback) {
  848. if (check.time(callback)) return;
  849. var isStyle = 0; var sheet = (node.sheet || node.styleSheet);
  850. try {if ((sheet.cssRules||sheet.rules||[]).length > 0) {isStyle = 1}} catch(err) {
  851. if (err.message.match(/protected variable|restricted URI/)) {isStyle = 1}
  852. else if (err.message.match(/Security error/)) {
  853. // Firefox3 gives "Security error" for missing files, so
  854. // can't distinguish that from OK files on remote servers.
  855. // or OK files in different directory from local files.
  856. isStyle = 1; // just say it is OK (can't really tell)
  857. }
  858. }
  859. if (isStyle) {
  860. // Opera 9.6 requires this setTimeout
  861. setTimeout(BASE.Callback([callback,check.STATUS.OK]),0);
  862. } else {
  863. setTimeout(check,check.delay);
  864. }
  865. }
  866. },
  867. //
  868. // JavaScript code must call this when they are completely initialized
  869. // (this allows them to perform asynchronous actions before indicating
  870. // that they are complete).
  871. //
  872. loadComplete: function (file) {
  873. file = this.fileURL(file);
  874. var loading = this.loading[file];
  875. if (loading && !loading.preloaded) {
  876. BASE.Message.Clear(loading.message);
  877. clearTimeout(loading.timeout);
  878. if (loading.script) {
  879. if (SCRIPTS.length === 0) {setTimeout(REMOVESCRIPTS,0)}
  880. SCRIPTS.push(loading.script);
  881. }
  882. this.loaded[file] = loading.status; delete this.loading[file];
  883. this.addHook(file,loading.callback);
  884. } else {
  885. if (loading) {delete this.loading[file]}
  886. this.loaded[file] = this.STATUS.OK;
  887. loading = {status: this.STATUS.OK}
  888. }
  889. if (!this.loadHooks[file]) {return null}
  890. return this.loadHooks[file].Execute(loading.status);
  891. },
  892. //
  893. // If a file fails to load within the timeout period (or the onerror handler
  894. // is called), this routine runs to signal the error condition.
  895. //
  896. loadTimeout: function (file) {
  897. if (this.loading[file].timeout) {clearTimeout(this.loading[file].timeout)}
  898. this.loading[file].status = this.STATUS.ERROR;
  899. this.loadError(file);
  900. this.loadComplete(file);
  901. },
  902. //
  903. // The default error hook for file load failures
  904. //
  905. loadError: function (file) {
  906. BASE.Message.Set(["LoadFailed","File failed to load: %1",file],null,2000);
  907. BASE.Hub.signal.Post(["file load error",file]);
  908. },
  909. //
  910. // Defines a style sheet from a hash of style declarations (key:value pairs
  911. // where the key is the style selector and the value is a hash of CSS attributes
  912. // and values).
  913. //
  914. Styles: function (styles,callback) {
  915. var styleString = this.StyleString(styles);
  916. if (styleString === "") {
  917. callback = BASE.Callback(callback);
  918. callback();
  919. } else {
  920. var style = document.createElement("style"); style.type = "text/css";
  921. this.head = HEAD(this.head);
  922. this.head.appendChild(style);
  923. if (style.styleSheet && typeof(style.styleSheet.cssText) !== 'undefined') {
  924. style.styleSheet.cssText = styleString;
  925. } else {
  926. style.appendChild(document.createTextNode(styleString));
  927. }
  928. callback = this.timer.create.call(this,callback,style);
  929. }
  930. return callback;
  931. },
  932. //
  933. // Create a stylesheet string from a style declaration object
  934. //
  935. StyleString: function (styles) {
  936. if (typeof(styles) === 'string') {return styles}
  937. var string = "", id, style;
  938. for (id in styles) {if (styles.hasOwnProperty(id)) {
  939. if (typeof styles[id] === 'string') {
  940. string += id + " {"+styles[id]+"}\n";
  941. } else if (styles[id] instanceof Array) {
  942. for (var i = 0; i < styles[id].length; i++) {
  943. style = {}; style[id] = styles[id][i];
  944. string += this.StyleString(style);
  945. }
  946. } else if (id.substr(0,6) === '@media') {
  947. string += id + " {"+this.StyleString(styles[id])+"}\n";
  948. } else if (styles[id] != null) {
  949. style = [];
  950. for (var name in styles[id]) {if (styles[id].hasOwnProperty(name)) {
  951. if (styles[id][name] != null)
  952. {style[style.length] = name + ': ' + styles[id][name]}
  953. }}
  954. string += id +" {"+style.join('; ')+"}\n";
  955. }
  956. }}
  957. return string;
  958. }
  959. };
  960. })("MathJax");
  961. /**********************************************************/
  962. MathJax.HTML = {
  963. //
  964. // Create an HTML element with given attributes and content.
  965. // The def parameter is an (optional) object containing key:value pairs
  966. // of the attributes and their values, and contents is an (optional)
  967. // array of strings to be inserted as text, or arrays of the form
  968. // [type,def,contents] that describes an HTML element to be inserted
  969. // into the current element. Thus the contents can describe a complete
  970. // HTML snippet of arbitrary complexity. E.g.:
  971. //
  972. // MathJax.HTML.Element("span",{id:"mySpan",style{"font-style":"italic"}},[
  973. // "(See the ",["a",{href:"http://www.mathjax.org"},["MathJax home page"]],
  974. // " for more details.)"]);
  975. //
  976. Element: function (type,def,contents) {
  977. var obj = document.createElement(type);
  978. if (def) {
  979. if (def.style) {
  980. var style = def.style; def.style = {};
  981. for (var id in style) {if (style.hasOwnProperty(id))
  982. {def.style[id.replace(/-([a-z])/g,this.ucMatch)] = style[id]}}
  983. }
  984. MathJax.Hub.Insert(obj,def);
  985. }
  986. if (contents) {
  987. if (!(contents instanceof Array)) {contents = [contents]}
  988. for (var i = 0; i < contents.length; i++) {
  989. if (contents[i] instanceof Array) {
  990. obj.appendChild(this.Element(contents[i][0],contents[i][1],contents[i][2]));
  991. } else if (type === "script") { // IE throws an error if script is added as a text node
  992. this.setScript(obj, contents[i]);
  993. } else {
  994. obj.appendChild(document.createTextNode(contents[i]));
  995. }
  996. }
  997. }
  998. return obj;
  999. },
  1000. ucMatch: function (match,c) {return c.toUpperCase()},
  1001. addElement: function (span,type,def,contents) {return span.appendChild(this.Element(type,def,contents))},
  1002. TextNode: function (text) {return document.createTextNode(text)},
  1003. addText: function (span,text) {return span.appendChild(this.TextNode(text))},
  1004. //
  1005. // Set and get the text of a script
  1006. //
  1007. setScript: function (script,text) {
  1008. if (this.setScriptBug) {script.text = text} else {
  1009. while (script.firstChild) {script.removeChild(script.firstChild)}
  1010. this.addText(script,text);
  1011. }
  1012. },
  1013. getScript: function (script) {
  1014. var text = (script.text === "" ? script.innerHTML : script.text);
  1015. return text.replace(/^\s+/,"").replace(/\s+$/,"");
  1016. },
  1017. //
  1018. // Manage cookies
  1019. //
  1020. Cookie: {
  1021. prefix: "mjx",
  1022. expires: 365,
  1023. //
  1024. // Save an object as a named cookie
  1025. //
  1026. Set: function (name,def) {
  1027. var keys = [];
  1028. if (def) {
  1029. for (var id in def) {if (def.hasOwnProperty(id)) {
  1030. keys.push(id+":"+def[id].toString().replace(/&/g,"&&"));
  1031. }}
  1032. }
  1033. var cookie = this.prefix+"."+name+"="+escape(keys.join('&;'));
  1034. if (this.expires) {
  1035. var time = new Date(); time.setDate(time.getDate() + this.expires);
  1036. cookie += '; expires='+time.toGMTString();
  1037. }
  1038. try {document.cookie = cookie+"; path=/"} catch (err) {} // ignore errors saving cookies
  1039. },
  1040. //
  1041. // Get the contents of a named cookie and incorporate
  1042. // it into the given object (or return a fresh one)
  1043. //
  1044. Get: function (name,obj) {
  1045. if (!obj) {obj = {}}
  1046. var pattern = new RegExp("(?:^|;\\s*)"+this.prefix+"\\."+name+"=([^;]*)(?:;|$)");
  1047. var match;
  1048. try {match = pattern.exec(document.cookie)} catch (err) {}; // ignore errors reading cookies
  1049. if (match && match[1] !== "") {
  1050. var keys = unescape(match[1]).split('&;');
  1051. for (var i = 0, m = keys.length; i < m; i++) {
  1052. match = keys[i].match(/([^:]+):(.*)/);
  1053. var value = match[2].replace(/&&/g,'&');
  1054. if (value === "true") {value = true} else if (value === "false") {value = false}
  1055. else if (value.match(/^-?(\d+(\.\d+)?|\.\d+)$/)) {value = parseFloat(value)}
  1056. obj[match[1]] = value;
  1057. }
  1058. }
  1059. return obj;
  1060. }
  1061. }
  1062. };
  1063. /**********************************************************/
  1064. MathJax.Localization = {
  1065. locale: "en",
  1066. directory: "[MathJax]/localization",
  1067. strings: {
  1068. // Currently, this list is not modified by the MathJax-i18n script. You can
  1069. // run the following command in MathJax/unpacked/localization to update it:
  1070. //
  1071. // find . -name "*.js" | xargs grep menuTitle\: | grep -v qqq | sed 's/^\.\/\(.*\)\/.*\.js\: / "\1"\: \{/' | sed 's/,$/\},/' | sed 's/"English"/"English", isLoaded: true/' > tmp ; sort tmp > tmp2 ; sed '$ s/,$//' tmp2 ; rm tmp*
  1072. //
  1073. // This only takes languages with localization data so you must also add
  1074. // the languages that use a remap but are not translated at all.
  1075. //
  1076. "ast": {menuTitle: "asturianu"},
  1077. "bcc": {menuTitle: "\u0628\u0644\u0648\u0686\u06CC"},
  1078. "br": {menuTitle: "brezhoneg"},
  1079. "ca": {menuTitle: "catal\u00E0"},
  1080. "cdo": {menuTitle: "M\u00ECng-d\u0115\u0324ng-ng\u1E73\u0304"},
  1081. "cs": {menuTitle: "\u010De\u0161tina"},
  1082. "da": {menuTitle: "dansk"},
  1083. "de": {menuTitle: "Deutsch"},
  1084. "en": {menuTitle: "English", isLoaded: true},
  1085. "eo": {menuTitle: "Esperanto"},
  1086. "es": {menuTitle: "espa\u00F1ol"},
  1087. "fa": {menuTitle: "\u0641\u0627\u0631\u0633\u06CC"},
  1088. "fi": {menuTitle: "suomi"},
  1089. "fr": {menuTitle: "fran\u00E7ais"},
  1090. "gl": {menuTitle: "galego"},
  1091. "he": {menuTitle: "\u05E2\u05D1\u05E8\u05D9\u05EA"},
  1092. "ia": {menuTitle: "interlingua"},
  1093. "it": {menuTitle: "italiano"},
  1094. "ja": {menuTitle: "\u65E5\u672C\u8A9E"},
  1095. "kn": {menuTitle: "\u0C95\u0CA8\u0CCD\u0CA8\u0CA1"},
  1096. "ko": {menuTitle: "\uD55C\uAD6D\uC5B4"},
  1097. "lb": {menuTitle: "L\u00EBtzebuergesch"},
  1098. "mk": {menuTitle: "\u043C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438"},
  1099. "nl": {menuTitle: "Nederlands"},
  1100. "oc": {menuTitle: "occitan"},
  1101. "pl": {menuTitle: "polski"},
  1102. "pt": {menuTitle: "portugus\u00EA"},
  1103. "pt-br": {menuTitle: "portugu\u00EAs do Brasil"},
  1104. "ru": {menuTitle: "\u0440\u0443\u0441\u0441\u043A\u0438\u0439"},
  1105. "sco": {menuTitle: "Scots"},
  1106. "sl": {menuTitle: "sloven\u0161\u010Dina"},
  1107. "sv": {menuTitle: "svenska"},
  1108. "tr": {menuTitle: "T\u00FCrk\u00E7e"},
  1109. "uk": {menuTitle: "\u0443\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430"},
  1110. "vi": {menuTitle: "Ti\u1EBFng Vi\u1EC7t"},
  1111. "zh-hans": {menuTitle: "\u4E2D\u6587\uFF08\u7B80\u4F53\uFF09"}
  1112. },
  1113. //
  1114. // The pattern for substitution escapes:
  1115. // %n or %{n} or %{plural:%n|option1|option1|...} or %c
  1116. //
  1117. pattern: /%(\d+|\{\d+\}|\{[a-z]+:\%\d+(?:\|(?:%\{\d+\}|%.|[^\}])*)+\}|.)/g,
  1118. SPLIT: ("axb".split(/(x)/).length === 3 ?
  1119. function (string,regex) {return string.split(regex)} :
  1120. //
  1121. // IE8 and below don't do split() correctly when the pattern includes
  1122. // parentheses (the split should include the matched exrepssions).
  1123. // So implement it by hand here.
  1124. //
  1125. function (string,regex) {
  1126. var result = [], match, last = 0;
  1127. regex.lastIndex = 0;
  1128. while (match = regex.exec(string)) {
  1129. result.push(string.substr(last,match.index-last));
  1130. result.push.apply(result,match.slice(1));
  1131. last = match.index + match[0].length;
  1132. }
  1133. result.push(string.substr(last));
  1134. return result;
  1135. }),
  1136. _: function (id,phrase) {
  1137. if (phrase instanceof Array) {return this.processSnippet(id,phrase)}
  1138. return this.processString(this.lookupPhrase(id,phrase),[].slice.call(arguments,2));
  1139. },
  1140. processString: function (string,args,domain) {
  1141. //
  1142. // Process arguments for substitution
  1143. // If the argument is a snippet (and we are processing snippets) do so,
  1144. // Otherwise, if it is a number, convert it for the lacale
  1145. //
  1146. var i, m;
  1147. for (i = 0, m = args.length; i < m; i++) {
  1148. if (domain && args[i] instanceof Array) {args[i] = this.processSnippet(domain,args[i])}
  1149. }
  1150. //
  1151. // Split string at escapes and process them individually
  1152. //
  1153. var parts = this.SPLIT(string,this.pattern);
  1154. for (i = 1, m = parts.length; i < m; i += 2) {
  1155. var c = parts[i].charAt(0); // first char will be { or \d or a char to be kept literally
  1156. if (c >= "0" && c <= "9") { // %n
  1157. parts[i] = args[parts[i]-1];
  1158. if (typeof parts[i] === "number") parts[i] = this.number(parts[i]);
  1159. } else if (c === "{") { // %{n} or %{plural:%n|...}
  1160. c = parts[i].substr(1);
  1161. if (c >= "0" && c <= "9") { // %{n}
  1162. parts[i] = args[parts[i].substr(1,parts[i].length-2)-1];
  1163. if (typeof parts[i] === "number") parts[i] = this.number(parts[i]);
  1164. } else { // %{plural:%n|...}
  1165. var match = parts[i].match(/^\{([a-z]+):%(\d+)\|(.*)\}$/);
  1166. if (match) {
  1167. if (match[1] === "plural") {
  1168. var n = args[match[2]-1];
  1169. if (typeof n === "undefined") {
  1170. parts[i] = "???"; // argument doesn't exist
  1171. } else {
  1172. n = this.plural(n) - 1; // index of the form to use
  1173. var plurals = match[3].replace(/(^|[^%])(%%)*%\|/g,"$1$2%\uEFEF").split(/\|/); // the parts (replacing %| with a special character)
  1174. if (n >= 0 && n < plurals.length) {
  1175. parts[i] = this.processString(plurals[n].replace(/\uEFEF/g,"|"),args,domain);
  1176. } else {
  1177. parts[i] = "???"; // no string for this index
  1178. }
  1179. }
  1180. } else {parts[i] = "%"+parts[i]} // not "plural", put back the % and leave unchanged
  1181. }
  1182. }
  1183. }
  1184. if (parts[i] == null) {parts[i] = "???"}
  1185. }
  1186. //
  1187. // If we are not forming a snippet, return the completed string
  1188. //
  1189. if (!domain) {return parts.join("")}
  1190. //
  1191. // We need to return an HTML snippet, so buld it from the
  1192. // broken up string with inserted parts (that could be snippets)
  1193. //
  1194. var snippet = [], part = "";
  1195. for (i = 0; i < m; i++) {
  1196. part += parts[i]; i++; // add the string and move on to substitution result
  1197. if (i < m) {
  1198. if (parts[i] instanceof Array) { // substitution was a snippet
  1199. snippet.push(part); // add the accumulated string
  1200. snippet = snippet.concat(parts[i]); // concatenate the substution snippet
  1201. part = ""; // start accumulating a new string
  1202. } else { // substitution was a string
  1203. part += parts[i]; // add to accumulating string
  1204. }
  1205. }
  1206. }
  1207. if (part !== "") {snippet.push(part)} // add final string
  1208. return snippet;
  1209. },
  1210. processSnippet: function (domain,snippet) {
  1211. var result = []; // the new snippet
  1212. //
  1213. // Look through the original snippet for
  1214. // strings or snippets to translate
  1215. //
  1216. for (var i = 0, m = snippet.length; i < m; i++) {
  1217. if (snippet[i] instanceof Array) {
  1218. //
  1219. // This could be a sub-snippet:
  1220. // ["tag"] or ["tag",{properties}] or ["tag",{properties},snippet]
  1221. // Or it could be something to translate:
  1222. // [id,string,args] or [domain,snippet]
  1223. var data = snippet[i];
  1224. if (typeof data[1] === "string") { // [id,string,args]
  1225. var id = data[0]; if (!(id instanceof Array)) {id = [domain,id]}
  1226. var phrase = this.lookupPhrase(id,data[1]);
  1227. result = result.concat(this.processMarkdown(phrase,data.slice(2),domain));
  1228. } else if (data[1] instanceof Array) { // [domain,snippet]
  1229. result = result.concat(this.processSnippet.apply(this,data));
  1230. } else if (data.length >= 3) { // ["tag",{properties},snippet]
  1231. result.push([data[0],data[1],this.processSnippet(domain,data[2])]);
  1232. } else { // ["tag"] or ["tag",{properties}]
  1233. result.push(snippet[i]);
  1234. }
  1235. } else { // a string
  1236. result.push(snippet[i]);
  1237. }
  1238. }
  1239. return result;
  1240. },
  1241. markdownPattern: /(%.)|(\*{1,3})((?:%.|.)+?)\2|(`+)((?:%.|.)+?)\4|\[((?:%.|.)+?)\]\(([^\s\)]+)\)/,
  1242. // %c or *bold*, **italics**, ***bold-italics***, or `code`, or [link](url)
  1243. processMarkdown: function (phrase,args,domain) {
  1244. var result = [], data;
  1245. //
  1246. // Split the string by the Markdown pattern
  1247. // (the text blocks are separated by
  1248. // c,stars,star-text,backtics,code-text,link-text,URL).
  1249. // Start with teh first text string from the split.
  1250. //
  1251. var parts = phrase.split(this.markdownPattern);
  1252. var string = parts[0];
  1253. //
  1254. // Loop through the matches and process them
  1255. //
  1256. for (var i = 1, m = parts.length; i < m; i += 8) {
  1257. if (parts[i+1]) { // stars (for bold/italic)
  1258. //
  1259. // Select the tag to use by number of stars (three stars requires two tags)
  1260. //
  1261. data = this.processString(parts[i+2],args,domain);
  1262. if (!(data instanceof Array)) {data = [data]}
  1263. data = [["b","i","i"][parts[i+1].length-1],{},data]; // number of stars determines type
  1264. if (parts[i+1].length === 3) {data = ["b",{},data]} // bold-italic
  1265. } else if (parts[i+3]) { // backtics (for code)
  1266. //
  1267. // Remove one leading or trailing space, and process substitutions
  1268. // Make a <code> tag
  1269. //
  1270. data = this.processString(parts[i+4].replace(/^\s/,"").replace(/\s$/,""),args,domain);
  1271. if (!(data instanceof Array)) {data = [data]}
  1272. data = ["code",{},data];
  1273. } else if (parts[i+5]) { // hyperlink
  1274. //
  1275. // Process the link text, and make an <a> tag with the URL
  1276. //
  1277. data = this.processString(parts[i+5],args,domain);
  1278. if (!(data instanceof Array)) {data = [data]}
  1279. data = ["a",{href:this.processString(parts[i+6],args),target:"_blank"},data];
  1280. } else {
  1281. //
  1282. // Escaped character (%c) gets added into the string.
  1283. //
  1284. string += parts[i]; data = null;
  1285. }
  1286. //
  1287. // If there is a tag to insert,
  1288. // Add any pending string, then push the tag
  1289. //
  1290. if (data) {
  1291. result = this.concatString(result,string,args,domain);
  1292. result.push(data); string = "";
  1293. }
  1294. //
  1295. // Process the string that follows matches pattern
  1296. //
  1297. if (parts[i+7] !== "") {string += parts[i+7]}
  1298. };
  1299. //
  1300. // Add any pending string and return the resulting snippet
  1301. //
  1302. result = this.concatString(result,string,args,domain);
  1303. return result;
  1304. },
  1305. concatString: function (result,string,args,domain) {
  1306. if (string != "") {
  1307. //
  1308. // Process the substutions.
  1309. // If the result is not a snippet, turn it into one.
  1310. // Then concatenate the snippet to the current one
  1311. //
  1312. string = this.processString(string,args,domain);
  1313. if (!(string instanceof Array)) {string = [string]}
  1314. result = result.concat(string);
  1315. }
  1316. return result;
  1317. },
  1318. lookupPhrase: function (id,phrase,domain) {
  1319. //
  1320. // Get the domain and messageID
  1321. //
  1322. if (!domain) {domain = "_"}
  1323. if (id instanceof Array) {domain = (id[0] || "_"); id = (id[1] || "")}
  1324. //
  1325. // Check if the data is available and if not,
  1326. // load it and throw a restart error so the calling
  1327. // code can wait for the load and try again.
  1328. //
  1329. var load = this.loadDomain(domain);
  1330. if (load) {MathJax.Hub.RestartAfter(load)}
  1331. //
  1332. // Look up the message in the localization data
  1333. // (if not found, the original English is used)
  1334. //
  1335. var localeData = this.strings[this.locale];
  1336. if (localeData) {
  1337. if (localeData.domains && domain in localeData.domains) {
  1338. var domainData = localeData.domains[domain];
  1339. if (domainData.strings && id in domainData.strings)
  1340. {phrase = domainData.strings[id]}
  1341. }
  1342. }
  1343. //
  1344. // return the translated phrase
  1345. //
  1346. return phrase;
  1347. },
  1348. //
  1349. // Load a langauge data file from the proper
  1350. // directory and file.
  1351. //
  1352. loadFile: function (file,data,callback) {
  1353. callback = MathJax.Callback(callback);
  1354. file = (data.file || file); // the data's file name or the default name
  1355. if (!file.match(/\.js$/)) {file += ".js"} // add .js if needed
  1356. //
  1357. // Add the directory if the file doesn't
  1358. // contain a full URL already.
  1359. //
  1360. if (!file.match(/^([a-z]+:|\[MathJax\])/)) {
  1361. var dir = (this.strings[this.locale].directory ||
  1362. this.directory + "/" + this.locale ||
  1363. "[MathJax]/localization/" + this.locale);
  1364. file = dir + "/" + file;
  1365. }
  1366. //
  1367. // Load the file and mark the data as loaded (even if it
  1368. // failed to load, so we don't continue to try to load it
  1369. // over and over).
  1370. //
  1371. var load = MathJax.Ajax.Require(file,function () {data.isLoaded = true; return callback()});
  1372. //
  1373. // Return the callback if needed, otherwise null.
  1374. //
  1375. return (load.called ? null : load);
  1376. },
  1377. //
  1378. // Check to see if the localization data are loaded
  1379. // for the given domain; if not, load the data file,
  1380. // and return a callback for the loading operation.
  1381. // Otherwise return null (data are loaded).
  1382. //
  1383. loadDomain: function (domain,callback) {
  1384. var load, localeData = this.strings[this.locale];
  1385. if (localeData) {
  1386. if (!localeData.isLoaded) {
  1387. load = this.loadFile(this.locale,localeData);
  1388. if (load) {
  1389. return MathJax.Callback.Queue(
  1390. load,["loadDomain",this,domain] // call again to load domain
  1391. ).Push(callback||{});
  1392. }
  1393. }
  1394. if (localeData.domains && domain in localeData.domains) {
  1395. var domainData = localeData.domains[domain];
  1396. if (!domainData.isLoaded) {
  1397. load = this.loadFile(domain,domainData);
  1398. if (load) {return MathJax.Callback.Queue(load).Push(callback)}
  1399. }
  1400. }
  1401. }
  1402. // localization data are loaded, so just do the callback
  1403. return MathJax.Callback(callback)();
  1404. },
  1405. //
  1406. // Perform a function, properly handling
  1407. // restarts due to localization file loads.
  1408. //
  1409. // Note that this may return before the function
  1410. // has been called successfully, so you should
  1411. // consider fn as running asynchronously. (Callbacks
  1412. // can be used to synchronize it with other actions.)
  1413. //
  1414. Try: function (fn) {
  1415. fn = MathJax.Callback(fn); fn.autoReset = true;
  1416. try {fn()} catch (err) {
  1417. if (!err.restart) {throw err}
  1418. MathJax.Callback.After(["Try",this,fn],err.restart);
  1419. }
  1420. },
  1421. //
  1422. // Reset the current language
  1423. //
  1424. resetLocale: function(locale) {
  1425. // Selection algorithm:
  1426. // 1) Downcase locale name (e.g. "en-US" => "en-us")
  1427. // 2) Try a parent language (e.g. "en-us" => "en")
  1428. // 3) Try the fallback specified in the data (e.g. "pt" => "pt-br")
  1429. // 4) Otherwise don't change the locale.
  1430. if (!locale) return;
  1431. locale = locale.toLowerCase();
  1432. while (!this.strings[locale]) {
  1433. var dashPos = locale.lastIndexOf("-");
  1434. if (dashPos === -1) return;
  1435. locale = locale.substring(0, dashPos);
  1436. }
  1437. var remap = this.strings[locale].remap;
  1438. this.locale = remap ? remap : locale;
  1439. },
  1440. //
  1441. // Set the current language
  1442. //
  1443. setLocale: function(locale) {
  1444. this.resetLocale(locale);
  1445. if (MathJax.Menu) {this.loadDomain("MathMenu")}
  1446. },
  1447. //
  1448. // Add or update a language or domain
  1449. //
  1450. addTranslation: function (locale,domain,definition) {
  1451. var data = this.strings[locale], isNew = false;
  1452. if (!data) {data = this.strings[locale] = {}; isNew = true}
  1453. if (!data.domains) {data.domains = {}}
  1454. if (domain) {
  1455. if (!data.domains[domain]) {data.domains[domain] = {}}
  1456. data = data.domains[domain];
  1457. }
  1458. MathJax.Hub.Insert(data,definition);
  1459. if (isNew && MathJax.Menu.menu) {MathJax.Menu.CreateLocaleMenu()}
  1460. },
  1461. //
  1462. // Set CSS for an element based on font requirements
  1463. //
  1464. setCSS: function (div) {
  1465. var locale = this.strings[this.locale];
  1466. if (locale) {
  1467. if (locale.fontFamily) {div.style.fontFamily = locale.fontFamily}
  1468. if (locale.fontDirection) {
  1469. div.style.direction = locale.fontDirection;
  1470. if (locale.fontDirection === "rtl") {div.style.textAlign = "right"}
  1471. }
  1472. }
  1473. return div;
  1474. },
  1475. //
  1476. // Get the language's font family or direction
  1477. //
  1478. fontFamily: function () {
  1479. var locale = this.strings[this.locale];
  1480. return (locale ? locale.fontFamily : null);
  1481. },
  1482. fontDirection: function () {
  1483. var locale = this.strings[this.locale];
  1484. return (locale ? locale.fontDirection : null);
  1485. },
  1486. //
  1487. // Get the language's plural index for a number
  1488. //
  1489. plural: function (n) {
  1490. var locale = this.strings[this.locale];
  1491. if (locale && locale.plural) {return locale.plural(n)}
  1492. // default
  1493. if (n == 1) {return 1} // one
  1494. return 2; // other
  1495. },
  1496. //
  1497. // Convert a number to language-specific form
  1498. //
  1499. number: function(n) {
  1500. var locale = this.strings[this.locale];
  1501. if (locale && locale.number) {return locale.number(n)}
  1502. // default
  1503. return n;
  1504. }
  1505. };
  1506. /**********************************************************/
  1507. MathJax.Message = {
  1508. ready: false, // used to tell when the styles are available
  1509. log: [{}], current: null,
  1510. textNodeBug: (navigator.vendor === "Apple Computer, Inc." &&
  1511. typeof navigator.vendorSub === "undefined") ||
  1512. (window.hasOwnProperty && window.hasOwnProperty("konqueror")), // Konqueror displays some gibberish with text.nodeValue = "..."
  1513. styles: {
  1514. "#MathJax_Message": {
  1515. position: "fixed", left: "1px", bottom: "2px",
  1516. 'background-color': "#E6E6E6", border: "1px solid #959595",
  1517. margin: "0px", padding: "2px 8px",
  1518. 'z-index': "102", color: "black", 'font-size': "80%",
  1519. width: "auto", 'white-space': "nowrap"
  1520. },
  1521. "#MathJax_MSIE_Frame": {
  1522. position: "absolute",
  1523. top:0, left: 0, width: "0px", 'z-index': 101,
  1524. border: "0px", margin: "0px", padding: "0px"
  1525. }
  1526. },
  1527. browsers: {
  1528. MSIE: function (browser) {
  1529. MathJax.Message.msieFixedPositionBug = ((document.documentMode||0) < 7);
  1530. if (MathJax.Message.msieFixedPositionBug)
  1531. {MathJax.Hub.config.styles["#MathJax_Message"].position = "absolute"}
  1532. MathJax.Message.quirks = (document.compatMode === "BackCompat");
  1533. },
  1534. Chrome: function (browser) {
  1535. MathJax.Hub.config.styles["#MathJax_Message"].bottom = "1.5em";
  1536. MathJax.Hub.config.styles["#MathJax_Message"].left = "1em";
  1537. }
  1538. },
  1539. Init: function (styles) {
  1540. if (styles) {this.ready = true}
  1541. if (!document.body || !this.ready) {return false}
  1542. //
  1543. // ASCIIMathML replaces the entire page with a copy of itself (@#!#%@!!)
  1544. // so check that this.div is still part of the page, otherwise look up
  1545. // the copy and use that.
  1546. //
  1547. if (this.div && this.div.parentNode == null) {
  1548. this.div = document.getElementById("MathJax_Message");
  1549. if (this.div) {this.text = this.div.firstChild}
  1550. }
  1551. if (!this.div) {
  1552. var frame = document.body;
  1553. if (this.msieFixedPositionBug && window.attachEvent) {
  1554. frame = this.frame = this.addDiv(document.body); frame.removeAttribute("id");
  1555. frame.style.position = "absolute";
  1556. frame.style.border = frame.style.margin = frame.style.padding = "0px";
  1557. frame.style.zIndex = "101"; frame.style.height = "0px";
  1558. frame = this.addDiv(frame);
  1559. frame.id = "MathJax_MSIE_Frame";
  1560. window.attachEvent("onscroll",this.MoveFrame);
  1561. window.attachEvent("onresize",this.MoveFrame);
  1562. this.MoveFrame();
  1563. }
  1564. this.div = this.addDiv(frame); this.div.style.display = "none";
  1565. this.text = this.div.appendChild(document.createTextNode(""));
  1566. }
  1567. return true;
  1568. },
  1569. addDiv: function (parent) {
  1570. var div = document.createElement("div");
  1571. div.id = "MathJax_Message";
  1572. if (parent.firstChild) {parent.insertBefore(div,parent.firstChild)}
  1573. else {parent.appendChild(div)}
  1574. return div;
  1575. },
  1576. MoveFrame: function () {
  1577. var body = (MathJax.Message.quirks ? document.body : document.documentElement);
  1578. var frame = MathJax.Message.frame;
  1579. frame.style.left = body.scrollLeft + 'px';
  1580. frame.style.top = body.scrollTop + 'px';
  1581. frame.style.width = body.clientWidth + 'px';
  1582. frame = frame.firstChild;
  1583. frame.style.height = body.clientHeight + 'px';
  1584. },
  1585. localize: function (message) {
  1586. return MathJax.Localization._(message,message);
  1587. },
  1588. filterText: function (text,n,id) {
  1589. if (MathJax.Hub.config.messageStyle === "simple") {
  1590. if (id === "LoadFile") {
  1591. if (!this.loading) {this.loading = this.localize("Loading") + " "}
  1592. text = this.loading; this.loading += ".";
  1593. } else if (id === "ProcessMath") {
  1594. if (!this.processing) {this.processing = this.localize("Processing") + " "}
  1595. text = this.processing; this.processing += ".";
  1596. } else if (id === "TypesetMath") {
  1597. if (!this.typesetting) {this.typesetting = this.localize("Typesetting") + " "}
  1598. text = this.typesetting; this.typesetting += ".";
  1599. }
  1600. }
  1601. return text;
  1602. },
  1603. Set: function (text,n,clearDelay) {
  1604. if (n == null) {n = this.log.length; this.log[n] = {}}
  1605. //
  1606. // Translate message if it is [id,message,arguments]
  1607. //
  1608. var id = "";
  1609. if (text instanceof Array) {
  1610. id = text[0]; if (id instanceof Array) {id = id[1]}
  1611. //
  1612. // Localization._() will throw a restart error if a localization file
  1613. // needs to be loaded, so trap that and redo the Set() call
  1614. // after it is loaded.
  1615. //
  1616. try {
  1617. text = MathJax.Localization._.apply(MathJax.Localization,text);
  1618. } catch (err) {
  1619. if (!err.restart) {throw err}
  1620. if (!err.restart.called) {
  1621. //
  1622. // Mark it so we can tell if the Clear() comes before the message is displayed
  1623. //
  1624. if (this.log[n].restarted == null) {this.log[n].restarted = 0}
  1625. this.log[n].restarted++; delete this.log[n].cleared;
  1626. MathJax.Callback.After(["Set",this,text,n,clearDelay],err.restart);
  1627. return n;
  1628. }
  1629. }
  1630. }
  1631. //
  1632. // Clear the timout timer.
  1633. //
  1634. if (this.timer) {clearTimeout(this.timer); delete this.timer}
  1635. //
  1636. // Save the message and filtered message.
  1637. //
  1638. this.log[n].text = text; this.log[n].filteredText = text = this.filterText(text,n,id);
  1639. //
  1640. // Hook the message into the message list so we can tell
  1641. // what message to put up when this one is removed.
  1642. //
  1643. if (typeof(this.log[n].next) === "undefined") {
  1644. this.log[n].next = this.current;
  1645. if (this.current != null) {this.log[this.current].prev = n}
  1646. this.current = n;
  1647. }
  1648. //
  1649. // Show the message if it is the currently active one.
  1650. //
  1651. if (this.current === n && MathJax.Hub.config.messageStyle !== "none") {
  1652. if (this.Init()) {
  1653. if (this.textNodeBug) {this.div.innerHTML = text} else {this.text.nodeValue = text}
  1654. this.div.style.display = "";
  1655. if (this.status) {window.status = ""; delete this.status}
  1656. } else {
  1657. window.status = text;
  1658. this.status = true;
  1659. }
  1660. }
  1661. //
  1662. // Check if the message was resetarted to load a localization file
  1663. // and if it has been cleared in the meanwhile.
  1664. //
  1665. if (this.log[n].restarted) {
  1666. if (this.log[n].cleared) {clearDelay = 0}
  1667. if (--this.log[n].restarted === 0) {delete this.log[n].cleared}
  1668. }
  1669. //
  1670. // Check if we need to clear the message automatically.
  1671. //
  1672. if (clearDelay) {setTimeout(MathJax.Callback(["Clear",this,n]),clearDelay)}
  1673. else if (clearDelay == 0) {this.Clear(n,0)}
  1674. //
  1675. // Return the message number.
  1676. //
  1677. return n;
  1678. },
  1679. Clear: function (n,delay) {
  1680. //
  1681. // Detatch the message from the active list.
  1682. //
  1683. if (this.log[n].prev != null) {this.log[this.log[n].prev].next = this.log[n].next}
  1684. if (this.log[n].next != null) {this.log[this.log[n].next].prev = this.log[n].prev}
  1685. //
  1686. // If it is the current message, get the next one to show.
  1687. //
  1688. if (this.current === n) {
  1689. this.current = this.log[n].next;
  1690. if (this.text) {
  1691. if (this.div.parentNode == null) {this.Init()} // see ASCIIMathML comments above
  1692. if (this.current == null) {
  1693. //
  1694. // If there are no more messages, remove the message box.
  1695. //
  1696. if (this.timer) {clearTimeout(this.timer); delete this.timer}
  1697. if (delay == null) {delay = 600}
  1698. if (delay === 0) {this.Remove()}
  1699. else {this.timer = setTimeout(MathJax.Callback(["Remove",this]),delay)}
  1700. } else if (MathJax.Hub.config.messageStyle !== "none") {
  1701. //
  1702. // If there is an old message, put it in place
  1703. //
  1704. if (this.textNodeBug) {this.div.innerHTML = this.log[this.current].filteredText}
  1705. else {this.text.nodeValue = this.log[this.current].filteredText}
  1706. }
  1707. if (this.status) {window.status = ""; delete this.status}
  1708. } else if (this.status) {
  1709. window.status = (this.current == null ? "" : this.log[this.current].text);
  1710. }
  1711. }
  1712. //
  1713. // Clean up the log data no longer needed
  1714. //
  1715. delete this.log[n].next; delete this.log[n].prev;
  1716. delete this.log[n].filteredText;
  1717. //
  1718. // If this is a restarted localization message, mark that it has been cleared
  1719. // while waiting for the file to load.
  1720. //
  1721. if (this.log[n].restarted) {this.log[n].cleared = true}
  1722. },
  1723. Remove: function () {
  1724. // FIXME: do a fade out or something else interesting?
  1725. this.text.nodeValue = "";
  1726. this.div.style.display = "none";
  1727. },
  1728. File: function (file) {
  1729. return this.Set(["LoadFile","Loading %1",file],null,null);
  1730. },
  1731. Log: function () {
  1732. var strings = [];
  1733. for (var i = 1, m = this.log.length; i < m; i++) {strings[i] = this.log[i].text}
  1734. return strings.join("\n");
  1735. }
  1736. };
  1737. /**********************************************************/
  1738. MathJax.Hub = {
  1739. config: {
  1740. root: "",
  1741. config: [], // list of configuration files to load
  1742. styleSheets: [], // list of CSS files to load
  1743. styles: { // styles to generate in-line
  1744. ".MathJax_Preview": {color: "#888"}
  1745. },
  1746. jax: [], // list of input and output jax to load
  1747. extensions: [], // list of extensions to load
  1748. preJax: null, // pattern to remove from before math script tag
  1749. postJax: null, // pattern to remove from after math script tag
  1750. displayAlign: 'center', // how to align displayed equations (left, center, right)
  1751. displayIndent: '0', // indentation for displayed equations (when not centered)
  1752. preRemoveClass: 'MathJax_Preview', // class of objects to remove preceeding math script
  1753. showProcessingMessages: true, // display "Processing math: nn%" messages or not
  1754. messageStyle: "normal", // set to "none" or "simple" (for "Loading..." and "Processing...")
  1755. delayStartupUntil: "none", // set to "onload" to delay setup until the onload handler runs
  1756. // set to "configured" to delay startup until MathJax.Hub.Configured() is called
  1757. // set to a Callback to wait for before continuing with the startup
  1758. skipStartupTypeset: false, // set to true to skip PreProcess and Process during startup
  1759. elements: [], // array of elements to process when none is given explicitly
  1760. positionToHash: true, // after initial typeset pass, position to #hash location?
  1761. showMathMenu: true, // attach math context menu to typeset math?
  1762. showMathMenuMSIE: true, // separtely determine if MSIE should have math menu
  1763. // (since the code for that is a bit delicate)
  1764. menuSettings: {
  1765. zoom: "None", // when to do MathZoom
  1766. CTRL: false, // require CTRL for MathZoom?
  1767. ALT: false, // require Alt or Option?
  1768. CMD: false, // require CMD?
  1769. Shift: false, // require Shift?
  1770. discoverable: false, // make math menu discoverable on hover?
  1771. zscale: "200%", // the scaling factor for MathZoom
  1772. renderer: "", // set when Jax are loaded
  1773. font: "Auto", // what font HTML-CSS should use
  1774. context: "MathJax", // or "Browser" for pass-through to browser menu
  1775. locale: "en", // the language to use for messages
  1776. mpContext: false, // true means pass menu events to MathPlayer in IE
  1777. mpMouse: false, // true means pass mouse events to MathPlayer in IE
  1778. texHints: true, // include class names for TeXAtom elements
  1779. semantics: false // add semantics tag with original form in MathML output
  1780. },
  1781. errorSettings: {
  1782. // localized HTML snippet structure for message to use
  1783. message: ["[",["MathProcessingError","Math Processing Error"],"]"],
  1784. style: {color: "#CC0000", "font-style":"italic"} // style for message
  1785. },
  1786. ignoreMMLattributes: {} // attributes not to copy to HTML-CSS or SVG output
  1787. // from MathML input (in addition to the ones in MML.nocopyAttributes).
  1788. // An id set to true will be ignored, one set to false will
  1789. // be allowed (even if other criteria normally would prevent
  1790. // it from being copied); use false carefully!
  1791. },
  1792. preProcessors: MathJax.Callback.Hooks(true), // list of callbacks for preprocessing (initialized by extensions)
  1793. inputJax: {}, // mime-type mapped to input jax (by registration)
  1794. outputJax: {order:{}}, // mime-type mapped to output jax list (by registration)
  1795. processSectionDelay: 50, // pause between input and output phases of processing
  1796. processUpdateTime: 250, // time between screen updates when processing math (milliseconds)
  1797. processUpdateDelay: 10, // pause between screen updates to allow other processing (milliseconds)
  1798. signal: MathJax.Callback.Signal("Hub"), // Signal used for Hub events
  1799. Config: function (def) {
  1800. this.Insert(this.config,def);
  1801. if (this.config.Augment) {this.Augment(this.config.Augment)}
  1802. },
  1803. CombineConfig: function (name,def) {
  1804. var config = this.config, id, parent; name = name.split(/\./);
  1805. for (var i = 0, m = name.length; i < m; i++) {
  1806. id = name[i]; if (!config[id]) {config[id] = {}}
  1807. parent = config; config = config[id];
  1808. }
  1809. parent[id] = config = this.Insert(def,config);
  1810. return config;
  1811. },
  1812. Register: {
  1813. PreProcessor: function () {return MathJax.Hub.preProcessors.Add.apply(MathJax.Hub.preProcessors,arguments)},
  1814. MessageHook: function () {return MathJax.Hub.signal.MessageHook.apply(MathJax.Hub.signal,arguments)},
  1815. StartupHook: function () {return MathJax.Hub.Startup.signal.MessageHook.apply(MathJax.Hub.Startup.signal,arguments)},
  1816. LoadHook: function () {return MathJax.Ajax.LoadHook.apply(MathJax.Ajax,arguments)}
  1817. },
  1818. UnRegister: {
  1819. PreProcessor: function (hook) {MathJax.Hub.preProcessors.Remove(hook)},
  1820. MessageHook: function (hook) {MathJax.Hub.signal.RemoveHook(hook)},
  1821. StartupHook: function (hook) {MathJax.Hub.Startup.signal.RemoveHook(hook)},
  1822. LoadHook: function (hook) {MathJax.Ajax.removeHook(hook)}
  1823. },
  1824. getAllJax: function (element) {
  1825. var jax = [], scripts = this.elementScripts(element);
  1826. for (var i = 0, m = scripts.length; i < m; i++) {
  1827. if (scripts[i].MathJax && scripts[i].MathJax.elementJax)
  1828. {jax.push(scripts[i].MathJax.elementJax)}
  1829. }
  1830. return jax;
  1831. },
  1832. getJaxByType: function (type,element) {
  1833. var jax = [], scripts = this.elementScripts(element);
  1834. for (var i = 0, m = scripts.length; i < m; i++) {
  1835. if (scripts[i].MathJax && scripts[i].MathJax.elementJax &&
  1836. scripts[i].MathJax.elementJax.mimeType === type)
  1837. {jax.push(scripts[i].MathJax.elementJax)}
  1838. }
  1839. return jax;
  1840. },
  1841. getJaxByInputType: function (type,element) {
  1842. var jax = [], scripts = this.elementScripts(element);
  1843. for (var i = 0, m = scripts.length; i < m; i++) {
  1844. if (scripts[i].MathJax && scripts[i].MathJax.elementJax &&
  1845. scripts[i].type && scripts[i].type.replace(/ *;(.|\s)*/,"") === type)
  1846. {jax.push(scripts[i].MathJax.elementJax)}
  1847. }
  1848. return jax;
  1849. },
  1850. getJaxFor: function (element) {
  1851. if (typeof(element) === 'string') {element = document.getElementById(element)}
  1852. if (element && element.MathJax) {return element.MathJax.elementJax}
  1853. if (element && element.isMathJax) {
  1854. while (element && !element.jaxID) {element = element.parentNode}
  1855. if (element) {return MathJax.OutputJax[element.jaxID].getJaxFromMath(element)}
  1856. }
  1857. return null;
  1858. },
  1859. isJax: function (element) {
  1860. if (typeof(element) === 'string') {element = document.getElementById(element)}
  1861. if (element && element.isMathJax) {return 1}
  1862. if (element && element.tagName != null && element.tagName.toLowerCase() === 'script') {
  1863. if (element.MathJax)
  1864. {return (element.MathJax.state === MathJax.ElementJax.STATE.PROCESSED ? 1 : -1)}
  1865. if (element.type && this.inputJax[element.type.replace(/ *;(.|\s)*/,"")]) {return -1}
  1866. }
  1867. return 0;
  1868. },
  1869. setRenderer: function (renderer,type) {
  1870. if (!renderer) return;
  1871. if (!MathJax.OutputJax[renderer]) {
  1872. this.config.menuSettings.renderer = "";
  1873. var file = "[MathJax]/jax/output/"+renderer+"/config.js";
  1874. return MathJax.Ajax.Require(file,["setRenderer",this,renderer,type]);
  1875. } else {
  1876. this.config.menuSettings.renderer = renderer;
  1877. if (type == null) {type = "jax/mml"}
  1878. var jax = this.outputJax;
  1879. if (jax[type] && jax[type].length) {
  1880. if (renderer !== jax[type][0].id) {
  1881. jax[type].unshift(MathJax.OutputJax[renderer]);
  1882. return this.signal.Post(["Renderer Selected",renderer]);
  1883. }
  1884. }
  1885. return null;
  1886. }
  1887. },
  1888. Queue: function () {
  1889. return this.queue.Push.apply(this.queue,arguments);
  1890. },
  1891. Typeset: function (element,callback) {
  1892. if (!MathJax.isReady) return null;
  1893. var ec = this.elementCallback(element,callback);
  1894. if (ec.count) {
  1895. var queue = MathJax.Callback.Queue(
  1896. ["PreProcess",this,ec.elements],
  1897. ["Process",this,ec.elements]
  1898. );
  1899. }
  1900. return queue.Push(ec.callback);
  1901. },
  1902. PreProcess: function (element,callback) {
  1903. var ec = this.elementCallback(element,callback);
  1904. var queue = MathJax.Callback.Queue();
  1905. if (ec.count) {
  1906. var elements = (ec.count === 1 ? [ec.elements] : ec.elements);
  1907. queue.Push(["Post",this.signal,["Begin PreProcess",ec.elements]]);
  1908. for (var i = 0, m = elements.length; i < m; i++) {
  1909. if (elements[i]) {queue.Push(["Execute",this.preProcessors,elements[i]])}
  1910. }
  1911. queue.Push(["Post",this.signal,["End PreProcess",ec.elements]]);
  1912. }
  1913. return queue.Push(ec.callback);
  1914. },
  1915. Process: function (element,callback) {return this.takeAction("Process",element,callback)},
  1916. Update: function (element,callback) {return this.takeAction("Update",element,callback)},
  1917. Reprocess: function (element,callback) {return this.takeAction("Reprocess",element,callback)},
  1918. Rerender: function (element,callback) {return this.takeAction("Rerender",element,callback)},
  1919. takeAction: function (action,element,callback) {
  1920. var ec = this.elementCallback(element,callback);
  1921. var elements = ec.elements;
  1922. var queue = MathJax.Callback.Queue(["Clear",this.signal]);
  1923. var state = {
  1924. scripts: [], // filled in by prepareScripts
  1925. start: new Date().getTime(), // timer for processing messages
  1926. i: 0, j: 0, // current script, current jax
  1927. jax: {}, // scripts grouped by output jax
  1928. jaxIDs: [] // id's of jax used
  1929. };
  1930. if (ec.count) {
  1931. var delay = ["Delay",MathJax.Callback,this.processSectionDelay];
  1932. if (!delay[2]) {delay = {}}
  1933. queue.Push(
  1934. ["Post",this.signal,["Begin "+action,elements]],
  1935. ["Post",this.signal,["Begin Math",elements,action]],
  1936. ["prepareScripts",this,action,elements,state],
  1937. ["Post",this.signal,["Begin Math Input",elements,action]],
  1938. ["processInput",this,state],
  1939. ["Post",this.signal,["End Math Input",elements,action]],
  1940. delay,
  1941. ["prepareOutput",this,state,"preProcess"],
  1942. delay,
  1943. ["Post",this.signal,["Begin Math Output",elements,action]],
  1944. ["processOutput",this,state],
  1945. ["Post",this.signal,["End Math Output",elements,action]],
  1946. delay,
  1947. ["prepareOutput",this,state,"postProcess"],
  1948. delay,
  1949. ["Post",this.signal,["End Math",elements,action]],
  1950. ["Post",this.signal,["End "+action,elements]]
  1951. );
  1952. }
  1953. return queue.Push(ec.callback);
  1954. },
  1955. scriptAction: {
  1956. Process: function (script) {},
  1957. Update: function (script) {
  1958. var jax = script.MathJax.elementJax;
  1959. if (jax && jax.needsUpdate()) {jax.Remove(true); script.MathJax.state = jax.STATE.UPDATE}
  1960. else {script.MathJax.state = jax.STATE.PROCESSED}
  1961. },
  1962. Reprocess: function (script) {
  1963. var jax = script.MathJax.elementJax;
  1964. if (jax) {jax.Remove(true); script.MathJax.state = jax.STATE.UPDATE}
  1965. },
  1966. Rerender: function (script) {
  1967. var jax = script.MathJax.elementJax;
  1968. if (jax) {jax.Remove(true); script.MathJax.state = jax.STATE.OUTPUT}
  1969. }
  1970. },
  1971. prepareScripts: function (action,element,state) {
  1972. if (arguments.callee.disabled) return;
  1973. var scripts = this.elementScripts(element);
  1974. var STATE = MathJax.ElementJax.STATE;
  1975. for (var i = 0, m = scripts.length; i < m; i++) {
  1976. var script = scripts[i];
  1977. if (script.type && this.inputJax[script.type.replace(/ *;(.|\n)*/,"")]) {
  1978. if (script.MathJax) {
  1979. if (script.MathJax.elementJax && script.MathJax.elementJax.hover) {
  1980. MathJax.Extension.MathEvents.Hover.ClearHover(script.MathJax.elementJax);
  1981. }
  1982. if (script.MathJax.state !== STATE.PENDING) {this.scriptAction[action](script)}
  1983. }
  1984. if (!script.MathJax) {script.MathJax = {state: STATE.PENDING}}
  1985. if (script.MathJax.state !== STATE.PROCESSED) {state.scripts.push(script)}
  1986. }
  1987. }
  1988. },
  1989. checkScriptSiblings: function (script) {
  1990. if (script.MathJax.checked) return;
  1991. var config = this.config, pre = script.previousSibling;
  1992. if (pre && pre.nodeName === "#text") {
  1993. var preJax,postJax, post = script.nextSibling;
  1994. if (post && post.nodeName !== "#text") {post = null}
  1995. if (config.preJax) {
  1996. if (typeof(config.preJax) === "string") {config.preJax = new RegExp(config.preJax+"$")}
  1997. preJax = pre.nodeValue.match(config.preJax);
  1998. }
  1999. if (config.postJax && post) {
  2000. if (typeof(config.postJax) === "string") {config.postJax = new RegExp("^"+config.postJax)}
  2001. postJax = post.nodeValue.match(config.postJax);
  2002. }
  2003. if (preJax && (!config.postJax || postJax)) {
  2004. pre.nodeValue = pre.nodeValue.replace
  2005. (config.preJax,(preJax.length > 1? preJax[1] : ""));
  2006. pre = null;
  2007. }
  2008. if (postJax && (!config.preJax || preJax)) {
  2009. post.nodeValue = post.nodeValue.replace
  2010. (config.postJax,(postJax.length > 1? postJax[1] : ""));
  2011. }
  2012. if (pre && !pre.nodeValue.match(/\S/)) {pre = pre.previousSibling}
  2013. }
  2014. if (config.preRemoveClass && pre && pre.className === config.preRemoveClass)
  2015. {script.MathJax.preview = pre}
  2016. script.MathJax.checked = 1;
  2017. },
  2018. processInput: function (state) {
  2019. var jax, STATE = MathJax.ElementJax.STATE;
  2020. var script, prev, m = state.scripts.length;
  2021. try {
  2022. //
  2023. // Loop through the scripts
  2024. //
  2025. while (state.i < m) {
  2026. script = state.scripts[state.i]; if (!script) {state.i++; continue}
  2027. //
  2028. // Remove previous error marker, if any
  2029. //
  2030. prev = script.previousSibling;
  2031. if (prev && prev.className === "MathJax_Error") {prev.parentNode.removeChild(prev)}
  2032. //
  2033. // Check if already processed or needs processing
  2034. //
  2035. if (!script.MathJax || script.MathJax.state === STATE.PROCESSED) {state.i++; continue};
  2036. if (!script.MathJax.elementJax || script.MathJax.state === STATE.UPDATE) {
  2037. this.checkScriptSiblings(script); // remove preJax/postJax etc.
  2038. var type = script.type.replace(/ *;(.|\s)*/,""); // the input jax type
  2039. jax = this.inputJax[type].Process(script,state); // run the input jax
  2040. if (typeof jax === 'function') { // if a callback was returned
  2041. if (jax.called) continue; // go back and call Process() again
  2042. this.RestartAfter(jax); // wait for the callback
  2043. }
  2044. jax.Attach(script,this.inputJax[type].id); // register the jax on the script
  2045. this.saveScript(jax,state,script,STATE); // add script to state
  2046. } else if (script.MathJax.state === STATE.OUTPUT) {
  2047. this.saveScript(script.MathJax.elementJax,state,script,STATE); // add script to state
  2048. }
  2049. //
  2050. // Go on to the next script, and check if we need to update the processing message
  2051. //
  2052. state.i++; var now = new Date().getTime();
  2053. if (now - state.start > this.processUpdateTime && state.i < state.scripts.length)
  2054. {state.start = now; this.RestartAfter(MathJax.Callback.Delay(1))}
  2055. }
  2056. } catch (err) {return this.processError(err,state,"Input")}
  2057. //
  2058. // Put up final message, reset the state and return
  2059. //
  2060. if (state.scripts.length && this.config.showProcessingMessages)
  2061. {MathJax.Message.Set(["ProcessMath","Processing math: %1%%",100],0)}
  2062. state.start = new Date().getTime(); state.i = state.j = 0;
  2063. return null;
  2064. },
  2065. saveScript: function (jax,state,script,STATE) {
  2066. //
  2067. // Check that output jax exists
  2068. //
  2069. if (!this.outputJax[jax.mimeType]) {
  2070. script.MathJax.state = STATE.UPDATE;
  2071. throw Error("No output jax registered for "+jax.mimeType);
  2072. }
  2073. //
  2074. // Record the output jax
  2075. // and put this script in the queue for that jax
  2076. //
  2077. jax.outputJax = this.outputJax[jax.mimeType][0].id;
  2078. if (!state.jax[jax.outputJax]) {
  2079. if (state.jaxIDs.length === 0) {
  2080. // use original array until we know there are more (rather than two copies)
  2081. state.jax[jax.outputJax] = state.scripts;
  2082. } else {
  2083. if (state.jaxIDs.length === 1) // get the script so far for the existing jax
  2084. {state.jax[state.jaxIDs[0]] = state.scripts.slice(0,state.i)}
  2085. state.jax[jax.outputJax] = []; // start a new array for the new jax
  2086. }
  2087. state.jaxIDs.push(jax.outputJax); // save the ID of the jax
  2088. }
  2089. if (state.jaxIDs.length > 1) {state.jax[jax.outputJax].push(script)}
  2090. //
  2091. // Mark script as needing output
  2092. //
  2093. script.MathJax.state = STATE.OUTPUT;
  2094. },
  2095. //
  2096. // Pre- and post-process scripts by jax
  2097. // (to get scaling factors, hide/show output, and so on)
  2098. // Since this can cause the jax to load, we need to trap restarts
  2099. //
  2100. prepareOutput: function (state,method) {
  2101. while (state.j < state.jaxIDs.length) {
  2102. var id = state.jaxIDs[state.j], JAX = MathJax.OutputJax[id];
  2103. if (JAX[method]) {
  2104. try {
  2105. var result = JAX[method](state);
  2106. if (typeof result === 'function') {
  2107. if (result.called) continue; // go back and try again
  2108. this.RestartAfter(result);
  2109. }
  2110. } catch (err) {
  2111. if (!err.restart) {
  2112. MathJax.Message.Set(["PrepError","Error preparing %1 output (%2)",id,method],null,600);
  2113. MathJax.Hub.lastPrepError = err;
  2114. state.j++;
  2115. }
  2116. return MathJax.Callback.After(["prepareOutput",this,state,method],err.restart);
  2117. }
  2118. }
  2119. state.j++;
  2120. }
  2121. return null;
  2122. },
  2123. processOutput: function (state) {
  2124. var result, STATE = MathJax.ElementJax.STATE, script, m = state.scripts.length;
  2125. try {
  2126. //
  2127. // Loop through the scripts
  2128. //
  2129. while (state.i < m) {
  2130. //
  2131. // Check that there is an element jax
  2132. //
  2133. script = state.scripts[state.i];
  2134. if (!script || !script.MathJax || script.MathJax.error) {state.i++; continue}
  2135. var jax = script.MathJax.elementJax; if (!jax) {state.i++; continue}
  2136. //
  2137. // Call the output Jax's Process method (which will be its Translate()
  2138. // method once loaded). Mark it as complete and remove the preview unless
  2139. // the Process() call returns an explicit false value (in which case, it will
  2140. // handle this later during the postProcess phase, as HTML-CSS does).
  2141. //
  2142. result = MathJax.OutputJax[jax.outputJax].Process(script,state);
  2143. if (result !== false) {
  2144. script.MathJax.state = STATE.PROCESSED;
  2145. if (script.MathJax.preview) {script.MathJax.preview.innerHTML = ""}
  2146. //
  2147. // Signal that new math is available
  2148. //
  2149. this.signal.Post(["New Math",jax.inputID]); // FIXME: wait for this? (i.e., restart if returns uncalled callback)
  2150. }
  2151. //
  2152. // Go on to next math expression
  2153. //
  2154. state.i++;
  2155. //
  2156. // Update the processing message, if needed
  2157. //
  2158. var now = new Date().getTime();
  2159. if (now - state.start > this.processUpdateTime && state.i < state.scripts.length)
  2160. {state.start = now; this.RestartAfter(MathJax.Callback.Delay(this.processUpdateDelay))}
  2161. }
  2162. } catch (err) {return this.processError(err,state,"Output")}
  2163. //
  2164. // Put up the typesetting-complete message
  2165. //
  2166. if (state.scripts.length && this.config.showProcessingMessages) {
  2167. MathJax.Message.Set(["TypesetMath","Typesetting math: %1%%",100],0);
  2168. MathJax.Message.Clear(0);
  2169. }
  2170. state.i = state.j = 0;
  2171. return null;
  2172. },
  2173. processMessage: function (state,type) {
  2174. var m = Math.floor(state.i/(state.scripts.length)*100);
  2175. var message = (type === "Output" ? ["TypesetMath","Typesetting math: %1%%"] :
  2176. ["ProcessMath","Processing math: %1%%"]);
  2177. if (this.config.showProcessingMessages) {MathJax.Message.Set(message.concat(m),0)}
  2178. },
  2179. processError: function (err,state,type) {
  2180. if (!err.restart) {
  2181. if (!this.config.errorSettings.message) {throw err}
  2182. this.formatError(state.scripts[state.i],err); state.i++;
  2183. }
  2184. this.processMessage(state,type);
  2185. return MathJax.Callback.After(["process"+type,this,state],err.restart);
  2186. },
  2187. formatError: function (script,err) {
  2188. //
  2189. // Get the error message, URL, and line, and save it for
  2190. // reporting in the Show Math As Error menu
  2191. //
  2192. var message = "Error: "+err.message+"\n";
  2193. if (err.sourceURL) {message += "\nfile: "+err.sourceURL}
  2194. if (err.line) {message += "\nline: "+err.line}
  2195. script.MathJax.error = MathJax.OutputJax.Error.Jax(message,script);
  2196. //
  2197. // Create the [Math Processing Error] span
  2198. //
  2199. var errorSettings = this.config.errorSettings;
  2200. var errorText = MathJax.Localization._(errorSettings.messageId,errorSettings.message);
  2201. var error = MathJax.HTML.Element("span",
  2202. {className:"MathJax_Error", jaxID:"Error", isMathJax:true},errorText);
  2203. //
  2204. // Attach the menu events
  2205. //
  2206. if (MathJax.Extension.MathEvents) {
  2207. error.oncontextmenu = MathJax.Extension.MathEvents.Event.Menu;
  2208. error.onmousedown = MathJax.Extension.MathEvents.Event.Mousedown;
  2209. } else {
  2210. MathJax.Ajax.Require("[MathJax]/extensions/MathEvents.js",function () {
  2211. error.oncontextmenu = MathJax.Extension.MathEvents.Event.Menu;
  2212. error.onmousedown = MathJax.Extension.MathEvents.Event.Mousedown;
  2213. });
  2214. }
  2215. //
  2216. // Insert the error into the page and remove any preview
  2217. //
  2218. script.parentNode.insertBefore(error,script);
  2219. if (script.MathJax.preview) {script.MathJax.preview.innerHTML = ""}
  2220. //
  2221. // Save the error for debugging purposes
  2222. // Report the error as a signal
  2223. //
  2224. this.lastError = err;
  2225. this.signal.Post(["Math Processing Error",script,err]);
  2226. },
  2227. RestartAfter: function (callback) {
  2228. throw this.Insert(Error("restart"),{restart: MathJax.Callback(callback)});
  2229. },
  2230. elementCallback: function (element,callback) {
  2231. if (callback == null && (element instanceof Array || typeof element === 'function'))
  2232. {try {MathJax.Callback(element); callback = element; element = null} catch(e) {}}
  2233. if (element == null) {element = this.config.elements || []}
  2234. if (this.isHTMLCollection(element)) {element = this.HTMLCollection2Array(element)}
  2235. if (!(element instanceof Array)) {element = [element]}
  2236. element = [].concat(element); // make a copy so the original isn't changed
  2237. for (var i = 0, m = element.length; i < m; i++)
  2238. {if (typeof(element[i]) === 'string') {element[i] = document.getElementById(element[i])}}
  2239. if (!document.body) {document.body = document.getElementsByTagName("body")[0]}
  2240. if (element.length == 0) {element.push(document.body)}
  2241. if (!callback) {callback = {}}
  2242. return {
  2243. count: element.length,
  2244. elements: (element.length === 1 ? element[0] : element),
  2245. callback: callback
  2246. };
  2247. },
  2248. elementScripts: function (element) {
  2249. var scripts = [];
  2250. if (element instanceof Array || this.isHTMLCollection(element)) {
  2251. for (var i = 0, m = element.length; i < m; i++) {
  2252. var alreadyDone = 0;
  2253. for (var j = 0; j < i && !alreadyDone; j++)
  2254. {alreadyDone = element[j].contains(element[i])}
  2255. if (!alreadyDone) scripts.push.apply(scripts,this.elementScripts(element[i]));
  2256. }
  2257. return scripts;
  2258. }
  2259. if (typeof(element) === 'string') {element = document.getElementById(element)}
  2260. if (!document.body) {document.body = document.getElementsByTagName("body")[0]}
  2261. if (element == null) {element = document.body}
  2262. if (element.tagName != null && element.tagName.toLowerCase() === "script") {return [element]}
  2263. scripts = element.getElementsByTagName("script");
  2264. if (this.msieHTMLCollectionBug) {scripts = this.HTMLCollection2Array(scripts)}
  2265. return scripts;
  2266. },
  2267. //
  2268. // IE8 fails to check "obj instanceof HTMLCollection" for some values of obj.
  2269. //
  2270. isHTMLCollection: function (obj) {
  2271. return ("HTMLCollection" in window && typeof(obj) === "object" && obj instanceof HTMLCollection);
  2272. },
  2273. //
  2274. // IE8 doesn't deal with HTMLCollection as an array, so convert to array
  2275. //
  2276. HTMLCollection2Array: function (nodes) {
  2277. if (!this.msieHTMLCollectionBug) {return [].slice.call(nodes)}
  2278. var NODES = [];
  2279. for (var i = 0, m = nodes.length; i < m; i++) {NODES[i] = nodes[i]}
  2280. return NODES;
  2281. },
  2282. Insert: function (dst,src) {
  2283. for (var id in src) {if (src.hasOwnProperty(id)) {
  2284. // allow for concatenation of arrays?
  2285. if (typeof src[id] === 'object' && !(src[id] instanceof Array) &&
  2286. (typeof dst[id] === 'object' || typeof dst[id] === 'function')) {
  2287. this.Insert(dst[id],src[id]);
  2288. } else {
  2289. dst[id] = src[id];
  2290. }
  2291. }}
  2292. return dst;
  2293. },
  2294. // Old browsers (e.g. Internet Explorer <= 8) do not support trim().
  2295. SplitList: ("trim" in String.prototype ?
  2296. function (list) {return list.trim().split(/\s+/)} :
  2297. function (list) {return list.replace(/^\s+/,'').
  2298. replace(/\s+$/,'').split(/\s+/)})
  2299. };
  2300. MathJax.Hub.Insert(MathJax.Hub.config.styles,MathJax.Message.styles);
  2301. MathJax.Hub.Insert(MathJax.Hub.config.styles,{".MathJax_Error":MathJax.Hub.config.errorSettings.style});
  2302. //
  2303. // Storage area for extensions and preprocessors
  2304. //
  2305. MathJax.Extension = {};
  2306. //
  2307. // Hub Startup code
  2308. //
  2309. MathJax.Hub.Configured = MathJax.Callback({}); // called when configuration is complete
  2310. MathJax.Hub.Startup = {
  2311. script: "", // the startup script from the SCRIPT call that loads MathJax.js
  2312. queue: MathJax.Callback.Queue(), // Queue used for startup actions
  2313. signal: MathJax.Callback.Signal("Startup"), // Signal used for startup events
  2314. params: {},
  2315. //
  2316. // Load the configuration files
  2317. //
  2318. Config: function () {
  2319. this.queue.Push(["Post",this.signal,"Begin Config"]);
  2320. //
  2321. // If a locale is given as a parameter,
  2322. // set the locale and the default menu value for the locale
  2323. //
  2324. if (this.params.locale) {
  2325. MathJax.Localization.resetLocale(this.params.locale);
  2326. MathJax.Hub.config.menuSettings.locale = this.params.locale;
  2327. }
  2328. //
  2329. // Run the config files, if any are given in the parameter list
  2330. //
  2331. if (this.params.config) {
  2332. var files = this.params.config.split(/,/);
  2333. for (var i = 0, m = files.length; i < m; i++) {
  2334. if (!files[i].match(/\.js$/)) {files[i] += ".js"}
  2335. this.queue.Push(["Require",MathJax.Ajax,this.URL("config",files[i])]);
  2336. }
  2337. }
  2338. //
  2339. // Perform author configuration from in-line MathJax = {...}
  2340. //
  2341. this.queue.Push(["Config",MathJax.Hub,MathJax.AuthorConfig]);
  2342. //
  2343. // Run the deprecated configuration script, if any (ignoring return value)
  2344. // Wait for the startup delay signal
  2345. // Run the mathjax-config blocks
  2346. // Load the files in the configuration's config array
  2347. //
  2348. if (this.script.match(/\S/)) {this.queue.Push(this.script+";\n1;")}
  2349. this.queue.Push(
  2350. ["ConfigDelay",this],
  2351. ["ConfigBlocks",this],
  2352. [function (THIS) {return THIS.loadArray(MathJax.Hub.config.config,"config",null,true)},this],
  2353. ["Post",this.signal,"End Config"]
  2354. );
  2355. },
  2356. //
  2357. // Return the delay callback
  2358. //
  2359. ConfigDelay: function () {
  2360. var delay = this.params.delayStartupUntil || MathJax.Hub.config.delayStartupUntil;
  2361. if (delay === "onload") {return this.onload}
  2362. if (delay === "configured") {return MathJax.Hub.Configured}
  2363. return delay;
  2364. },
  2365. //
  2366. // Run the scripts of type=text/x-mathjax-config
  2367. //
  2368. ConfigBlocks: function () {
  2369. var scripts = document.getElementsByTagName("script");
  2370. var last = null, queue = MathJax.Callback.Queue();
  2371. for (var i = 0, m = scripts.length; i < m; i++) {
  2372. var type = String(scripts[i].type).replace(/ /g,"");
  2373. if (type.match(/^text\/x-mathjax-config(;.*)?$/) && !type.match(/;executed=true/)) {
  2374. scripts[i].type += ";executed=true";
  2375. last = queue.Push(scripts[i].innerHTML+";\n1;");
  2376. }
  2377. }
  2378. return last;
  2379. },
  2380. //
  2381. // Read cookie and set up menu defaults
  2382. // (set the locale according to the cookie)
  2383. // (adjust the jax to accommodate renderer preferences)
  2384. //
  2385. Cookie: function () {
  2386. return this.queue.Push(
  2387. ["Post",this.signal,"Begin Cookie"],
  2388. ["Get",MathJax.HTML.Cookie,"menu",MathJax.Hub.config.menuSettings],
  2389. [function (config) {
  2390. if (config.menuSettings.locale)
  2391. {MathJax.Localization.resetLocale(config.menuSettings.locale)}
  2392. var renderer = config.menuSettings.renderer, jax = config.jax;
  2393. if (renderer) {
  2394. var name = "output/"+renderer; jax.sort();
  2395. for (var i = 0, m = jax.length; i < m; i++) {
  2396. if (jax[i].substr(0,7) === "output/") break;
  2397. }
  2398. if (i == m-1) {jax.pop()} else {
  2399. while (i < m) {if (jax[i] === name) {jax.splice(i,1); break}; i++}
  2400. }
  2401. jax.unshift(name);
  2402. }
  2403. if (config.menuSettings.CHTMLpreview && !MathJax.Extension["CHTML-preview"])
  2404. {MathJax.Hub.config.extensions.push("CHTML-preview.js")}
  2405. },MathJax.Hub.config],
  2406. ["Post",this.signal,"End Cookie"]
  2407. );
  2408. },
  2409. //
  2410. // Setup stylesheets and extra styles
  2411. //
  2412. Styles: function () {
  2413. return this.queue.Push(
  2414. ["Post",this.signal,"Begin Styles"],
  2415. ["loadArray",this,MathJax.Hub.config.styleSheets,"config"],
  2416. ["Styles",MathJax.Ajax,MathJax.Hub.config.styles],
  2417. ["Post",this.signal,"End Styles"]
  2418. );
  2419. },
  2420. //
  2421. // Load the input and output jax
  2422. //
  2423. Jax: function () {
  2424. var config = MathJax.Hub.config, jax = MathJax.Hub.outputJax;
  2425. // Save the order of the output jax since they are loading asynchronously
  2426. for (var i = 0, m = config.jax.length, k = 0; i < m; i++) {
  2427. var name = config.jax[i].substr(7);
  2428. if (config.jax[i].substr(0,7) === "output/" && jax.order[name] == null)
  2429. {jax.order[name] = k; k++}
  2430. }
  2431. var queue = MathJax.Callback.Queue();
  2432. return queue.Push(
  2433. ["Post",this.signal,"Begin Jax"],
  2434. ["loadArray",this,config.jax,"jax","config.js"],
  2435. ["Post",this.signal,"End Jax"]
  2436. );
  2437. },
  2438. //
  2439. // Load the extensions
  2440. //
  2441. Extensions: function () {
  2442. var queue = MathJax.Callback.Queue();
  2443. return queue.Push(
  2444. ["Post",this.signal,"Begin Extensions"],
  2445. ["loadArray",this,MathJax.Hub.config.extensions,"extensions"],
  2446. ["Post",this.signal,"End Extensions"]
  2447. );
  2448. },
  2449. //
  2450. // Initialize the Message system
  2451. //
  2452. Message: function () {
  2453. MathJax.Message.Init(true);
  2454. },
  2455. //
  2456. // Set the math menu renderer, if it isn't already
  2457. // (this must come after the jax are loaded)
  2458. //
  2459. Menu: function () {
  2460. var menu = MathJax.Hub.config.menuSettings, jax = MathJax.Hub.outputJax, registered;
  2461. for (var id in jax) {if (jax.hasOwnProperty(id)) {
  2462. if (jax[id].length) {registered = jax[id]; break}
  2463. }}
  2464. if (registered && registered.length) {
  2465. if (menu.renderer && menu.renderer !== registered[0].id)
  2466. {registered.unshift(MathJax.OutputJax[menu.renderer])}
  2467. menu.renderer = registered[0].id;
  2468. }
  2469. },
  2470. //
  2471. // Set the location to the designated hash position
  2472. //
  2473. Hash: function () {
  2474. if (MathJax.Hub.config.positionToHash && document.location.hash &&
  2475. document.body && document.body.scrollIntoView) {
  2476. var name = document.location.hash.substr(1);
  2477. var target = document.getElementById(name);
  2478. if (!target) {
  2479. var a = document.getElementsByTagName("a");
  2480. for (var i = 0, m = a.length; i < m; i++)
  2481. {if (a[i].name === name) {target = a[i]; break}}
  2482. }
  2483. if (target) {
  2484. while (!target.scrollIntoView) {target = target.parentNode}
  2485. target = this.HashCheck(target);
  2486. if (target && target.scrollIntoView)
  2487. {setTimeout(function () {target.scrollIntoView(true)},1)}
  2488. }
  2489. }
  2490. },
  2491. HashCheck: function (target) {
  2492. if (target.isMathJax) {
  2493. var jax = MathJax.Hub.getJaxFor(target);
  2494. if (jax && MathJax.OutputJax[jax.outputJax].hashCheck)
  2495. {target = MathJax.OutputJax[jax.outputJax].hashCheck(target)}
  2496. }
  2497. return target;
  2498. },
  2499. //
  2500. // Load the Menu and Zoom code, if it hasn't already been loaded.
  2501. // This is called after the initial typeset, so should no longer be
  2502. // competing with other page loads, but will make these available
  2503. // if needed later on.
  2504. //
  2505. MenuZoom: function () {
  2506. if (MathJax.Hub.config.showMathMenu) {
  2507. if (!MathJax.Extension.MathMenu) {
  2508. setTimeout(
  2509. function () {
  2510. MathJax.Callback.Queue(
  2511. ["Require",MathJax.Ajax,"[MathJax]/extensions/MathMenu.js",{}],
  2512. ["loadDomain",MathJax.Localization,"MathMenu"]
  2513. )
  2514. },1000
  2515. );
  2516. } else {
  2517. setTimeout(
  2518. MathJax.Callback(["loadDomain",MathJax.Localization,"MathMenu"]),
  2519. 1000
  2520. );
  2521. }
  2522. if (!MathJax.Extension.MathZoom) {
  2523. setTimeout(
  2524. MathJax.Callback(["Require",MathJax.Ajax,"[MathJax]/extensions/MathZoom.js",{}]),
  2525. 2000
  2526. );
  2527. }
  2528. }
  2529. },
  2530. //
  2531. // Setup the onload callback
  2532. //
  2533. onLoad: function () {
  2534. var onload = this.onload =
  2535. MathJax.Callback(function () {MathJax.Hub.Startup.signal.Post("onLoad")});
  2536. if (document.body && document.readyState)
  2537. if (MathJax.Hub.Browser.isMSIE) {
  2538. // IE can change from loading to interactive before
  2539. // full page is ready, so go with complete (even though
  2540. // that means we may have to wait longer).
  2541. if (document.readyState === "complete") {return [onload]}
  2542. } else if (document.readyState !== "loading") {return [onload]}
  2543. if (window.addEventListener) {
  2544. window.addEventListener("load",onload,false);
  2545. if (!this.params.noDOMContentEvent)
  2546. {window.addEventListener("DOMContentLoaded",onload,false)}
  2547. }
  2548. else if (window.attachEvent) {window.attachEvent("onload",onload)}
  2549. else {window.onload = onload}
  2550. return onload;
  2551. },
  2552. //
  2553. // Perform the initial typesetting (or skip if configuration says to)
  2554. //
  2555. Typeset: function (element,callback) {
  2556. if (MathJax.Hub.config.skipStartupTypeset) {return function () {}}
  2557. return this.queue.Push(
  2558. ["Post",this.signal,"Begin Typeset"],
  2559. ["Typeset",MathJax.Hub,element,callback],
  2560. ["Post",this.signal,"End Typeset"]
  2561. );
  2562. },
  2563. //
  2564. // Create a URL in the MathJax hierarchy
  2565. //
  2566. URL: function (dir,name) {
  2567. if (!name.match(/^([a-z]+:\/\/|\[|\/)/)) {name = "[MathJax]/"+dir+"/"+name}
  2568. return name;
  2569. },
  2570. //
  2571. // Load an array of files, waiting for all of them
  2572. // to be loaded before going on
  2573. //
  2574. loadArray: function (files,dir,name,synchronous) {
  2575. if (files) {
  2576. if (!(files instanceof Array)) {files = [files]}
  2577. if (files.length) {
  2578. var queue = MathJax.Callback.Queue(), callback = {}, file;
  2579. for (var i = 0, m = files.length; i < m; i++) {
  2580. file = this.URL(dir,files[i]);
  2581. if (name) {file += "/" + name}
  2582. if (synchronous) {queue.Push(["Require",MathJax.Ajax,file,callback])}
  2583. else {queue.Push(MathJax.Ajax.Require(file,callback))}
  2584. }
  2585. return queue.Push({}); // wait for everything to finish
  2586. }
  2587. }
  2588. return null;
  2589. }
  2590. };
  2591. /**********************************************************/
  2592. (function (BASENAME) {
  2593. var BASE = window[BASENAME], ROOT = "["+BASENAME+"]";
  2594. var HUB = BASE.Hub, AJAX = BASE.Ajax, CALLBACK = BASE.Callback;
  2595. var JAX = MathJax.Object.Subclass({
  2596. JAXFILE: "jax.js",
  2597. require: null, // array of files to load before jax.js is complete
  2598. config: {},
  2599. //
  2600. // Make a subclass and return an instance of it.
  2601. // (FIXME: should we replace config with a copy of the constructor's
  2602. // config? Otherwise all subclasses share the same config structure.)
  2603. //
  2604. Init: function (def,cdef) {
  2605. if (arguments.length === 0) {return this}
  2606. return (this.constructor.Subclass(def,cdef))();
  2607. },
  2608. //
  2609. // Augment by merging with class definition (not replacing)
  2610. //
  2611. Augment: function (def,cdef) {
  2612. var cObject = this.constructor, ndef = {};
  2613. if (def != null) {
  2614. for (var id in def) {if (def.hasOwnProperty(id)) {
  2615. if (typeof def[id] === "function")
  2616. {cObject.protoFunction(id,def[id])} else {ndef[id] = def[id]}
  2617. }}
  2618. // MSIE doesn't list toString even if it is not native so handle it separately
  2619. if (def.toString !== cObject.prototype.toString && def.toString !== {}.toString)
  2620. {cObject.protoFunction('toString',def.toString)}
  2621. }
  2622. HUB.Insert(cObject.prototype,ndef);
  2623. cObject.Augment(null,cdef);
  2624. return this;
  2625. },
  2626. Translate: function (script,state) {
  2627. throw Error(this.directory+"/"+this.JAXFILE+" failed to define the Translate() method");
  2628. },
  2629. Register: function (mimetype) {},
  2630. Config: function () {
  2631. this.config = HUB.CombineConfig(this.id,this.config);
  2632. if (this.config.Augment) {this.Augment(this.config.Augment)}
  2633. },
  2634. Startup: function () {},
  2635. loadComplete: function (file) {
  2636. if (file === "config.js") {
  2637. return AJAX.loadComplete(this.directory+"/"+file);
  2638. } else {
  2639. var queue = CALLBACK.Queue();
  2640. queue.Push(
  2641. HUB.Register.StartupHook("End Config",{}), // wait until config complete
  2642. ["Post",HUB.Startup.signal,this.id+" Jax Config"],
  2643. ["Config",this],
  2644. ["Post",HUB.Startup.signal,this.id+" Jax Require"],
  2645. // Config may set the required and extensions array,
  2646. // so use functions to delay making the reference until needed
  2647. [function (THIS) {return MathJax.Hub.Startup.loadArray(THIS.require,this.directory)},this],
  2648. [function (config,id) {return MathJax.Hub.Startup.loadArray(config.extensions,"extensions/"+id)},this.config||{},this.id],
  2649. ["Post",HUB.Startup.signal,this.id+" Jax Startup"],
  2650. ["Startup",this],
  2651. ["Post",HUB.Startup.signal,this.id+" Jax Ready"]
  2652. );
  2653. if (this.copyTranslate) {
  2654. queue.Push(
  2655. [function (THIS) {
  2656. THIS.preProcess = THIS.preTranslate;
  2657. THIS.Process = THIS.Translate;
  2658. THIS.postProcess = THIS.postTranslate;
  2659. },this.constructor.prototype]
  2660. );
  2661. }
  2662. return queue.Push(["loadComplete",AJAX,this.directory+"/"+file]);
  2663. }
  2664. }
  2665. },{
  2666. id: "Jax",
  2667. version: "2.5.0",
  2668. directory: ROOT+"/jax",
  2669. extensionDir: ROOT+"/extensions"
  2670. });
  2671. /***********************************/
  2672. BASE.InputJax = JAX.Subclass({
  2673. elementJax: "mml", // the element jax to load for this input jax
  2674. sourceMenuTitle: /*_(MathMenu)*/ ["Original","Original Form"],
  2675. copyTranslate: true,
  2676. Process: function (script,state) {
  2677. var queue = CALLBACK.Queue(), file;
  2678. // Load any needed element jax
  2679. var jax = this.elementJax; if (!(jax instanceof Array)) {jax = [jax]}
  2680. for (var i = 0, m = jax.length; i < m; i++) {
  2681. file = BASE.ElementJax.directory+"/"+jax[i]+"/"+this.JAXFILE;
  2682. if (!this.require) {this.require = []}
  2683. else if (!(this.require instanceof Array)) {this.require = [this.require]};
  2684. this.require.push(file); // so Startup will wait for it to be loaded
  2685. queue.Push(AJAX.Require(file));
  2686. }
  2687. // Load the input jax
  2688. file = this.directory+"/"+this.JAXFILE;
  2689. var load = queue.Push(AJAX.Require(file));
  2690. if (!load.called) {
  2691. this.constructor.prototype.Process = function () {
  2692. if (!load.called) {return load}
  2693. throw Error(file+" failed to load properly");
  2694. }
  2695. }
  2696. // Load the associated output jax
  2697. jax = HUB.outputJax["jax/"+jax[0]];
  2698. if (jax) {queue.Push(AJAX.Require(jax[0].directory+"/"+this.JAXFILE))}
  2699. return queue.Push({});
  2700. },
  2701. needsUpdate: function (jax) {
  2702. var script = jax.SourceElement();
  2703. return (jax.originalText !== BASE.HTML.getScript(script));
  2704. },
  2705. Register: function (mimetype) {
  2706. if (!HUB.inputJax) {HUB.inputJax = {}}
  2707. HUB.inputJax[mimetype] = this;
  2708. }
  2709. },{
  2710. id: "InputJax",
  2711. version: "2.5.0",
  2712. directory: JAX.directory+"/input",
  2713. extensionDir: JAX.extensionDir
  2714. });
  2715. /***********************************/
  2716. BASE.OutputJax = JAX.Subclass({
  2717. copyTranslate: true,
  2718. preProcess: function (state) {
  2719. var load, file = this.directory+"/"+this.JAXFILE;
  2720. this.constructor.prototype.preProcess = function (state) {
  2721. if (!load.called) {return load}
  2722. throw Error(file+" failed to load properly");
  2723. }
  2724. load = AJAX.Require(file);
  2725. return load;
  2726. },
  2727. Register: function (mimetype) {
  2728. var jax = HUB.outputJax;
  2729. if (!jax[mimetype]) {jax[mimetype] = []}
  2730. // If the output jax is earlier in the original configuration list, put it first here
  2731. if (jax[mimetype].length && (this.id === HUB.config.menuSettings.renderer ||
  2732. (jax.order[this.id]||0) < (jax.order[jax[mimetype][0].id]||0)))
  2733. {jax[mimetype].unshift(this)} else {jax[mimetype].push(this)}
  2734. // Make sure the element jax is loaded before Startup is called
  2735. if (!this.require) {this.require = []}
  2736. else if (!(this.require instanceof Array)) {this.require = [this.require]};
  2737. this.require.push(BASE.ElementJax.directory+"/"+(mimetype.split(/\//)[1])+"/"+this.JAXFILE);
  2738. },
  2739. Remove: function (jax) {}
  2740. },{
  2741. id: "OutputJax",
  2742. version: "2.5.0",
  2743. directory: JAX.directory+"/output",
  2744. extensionDir: JAX.extensionDir,
  2745. fontDir: ROOT+(BASE.isPacked?"":"/..")+"/fonts",
  2746. imageDir: ROOT+(BASE.isPacked?"":"/..")+"/images"
  2747. });
  2748. /***********************************/
  2749. BASE.ElementJax = JAX.Subclass({
  2750. // make a subclass, not an instance
  2751. Init: function (def,cdef) {return this.constructor.Subclass(def,cdef)},
  2752. inputJax: null,
  2753. outputJax: null,
  2754. inputID: null,
  2755. originalText: "",
  2756. mimeType: "",
  2757. sourceMenuTitle: /*_(MathMenu)*/ ["MathMLcode","MathML Code"],
  2758. Text: function (text,callback) {
  2759. var script = this.SourceElement();
  2760. BASE.HTML.setScript(script,text);
  2761. script.MathJax.state = this.STATE.UPDATE;
  2762. return HUB.Update(script,callback);
  2763. },
  2764. Reprocess: function (callback) {
  2765. var script = this.SourceElement();
  2766. script.MathJax.state = this.STATE.UPDATE;
  2767. return HUB.Reprocess(script,callback);
  2768. },
  2769. Update: function (callback) {return this.Rerender(callback)},
  2770. Rerender: function (callback) {
  2771. var script = this.SourceElement();
  2772. script.MathJax.state = this.STATE.OUTPUT;
  2773. return HUB.Process(script,callback);
  2774. },
  2775. Remove: function (keep) {
  2776. if (this.hover) {this.hover.clear(this)}
  2777. BASE.OutputJax[this.outputJax].Remove(this);
  2778. if (!keep) {
  2779. HUB.signal.Post(["Remove Math",this.inputID]); // wait for this to finish?
  2780. this.Detach();
  2781. }
  2782. },
  2783. needsUpdate: function () {
  2784. return BASE.InputJax[this.inputJax].needsUpdate(this);
  2785. },
  2786. SourceElement: function () {return document.getElementById(this.inputID)},
  2787. Attach: function (script,inputJax) {
  2788. var jax = script.MathJax.elementJax;
  2789. if (script.MathJax.state === this.STATE.UPDATE) {
  2790. jax.Clone(this);
  2791. } else {
  2792. jax = script.MathJax.elementJax = this;
  2793. if (script.id) {this.inputID = script.id}
  2794. else {script.id = this.inputID = BASE.ElementJax.GetID(); this.newID = 1}
  2795. }
  2796. jax.originalText = BASE.HTML.getScript(script);
  2797. jax.inputJax = inputJax;
  2798. if (jax.root) {jax.root.inputID = jax.inputID}
  2799. return jax;
  2800. },
  2801. Detach: function () {
  2802. var script = this.SourceElement(); if (!script) return;
  2803. try {delete script.MathJax} catch(err) {script.MathJax = null}
  2804. if (this.newID) {script.id = ""}
  2805. },
  2806. Clone: function (jax) {
  2807. var id;
  2808. for (id in this) {
  2809. if (!this.hasOwnProperty(id)) continue;
  2810. if (typeof(jax[id]) === 'undefined' && id !== 'newID') {delete this[id]}
  2811. }
  2812. for (id in jax) {
  2813. if (!jax.hasOwnProperty(id)) continue;
  2814. if (typeof(this[id]) === 'undefined' || (this[id] !== jax[id] && id !== 'inputID'))
  2815. {this[id] = jax[id]}
  2816. }
  2817. }
  2818. },{
  2819. id: "ElementJax",
  2820. version: "2.5.0",
  2821. directory: JAX.directory+"/element",
  2822. extensionDir: JAX.extensionDir,
  2823. ID: 0, // jax counter (for IDs)
  2824. STATE: {
  2825. PENDING: 1, // script is identified as math but not yet processed
  2826. PROCESSED: 2, // script has been processed
  2827. UPDATE: 3, // elementJax should be updated
  2828. OUTPUT: 4 // output should be updated (input is OK)
  2829. },
  2830. GetID: function () {this.ID++; return "MathJax-Element-"+this.ID},
  2831. Subclass: function () {
  2832. var obj = JAX.Subclass.apply(this,arguments);
  2833. obj.loadComplete = this.prototype.loadComplete;
  2834. return obj;
  2835. }
  2836. });
  2837. BASE.ElementJax.prototype.STATE = BASE.ElementJax.STATE;
  2838. //
  2839. // Some "Fake" jax used to allow menu access for "Math Processing Error" messages
  2840. //
  2841. BASE.OutputJax.Error = {
  2842. id: "Error", version: "2.5.0", config: {},
  2843. ContextMenu: function () {return BASE.Extension.MathEvents.Event.ContextMenu.apply(BASE.Extension.MathEvents.Event,arguments)},
  2844. Mousedown: function () {return BASE.Extension.MathEvents.Event.AltContextMenu.apply(BASE.Extension.MathEvents.Event,arguments)},
  2845. getJaxFromMath: function (math) {return (math.nextSibling.MathJax||{}).error},
  2846. Jax: function (text,script) {
  2847. var jax = MathJax.Hub.inputJax[script.type.replace(/ *;(.|\s)*/,"")];
  2848. return {
  2849. inputJax: (jax||{id:"Error"}).id, // Use Error InputJax as fallback
  2850. outputJax: "Error",
  2851. sourceMenuTitle: /*_(MathMenu)*/ ["ErrorMessage","Error Message"],
  2852. sourceMenuFormat: "Error",
  2853. originalText: MathJax.HTML.getScript(script),
  2854. errorText: text
  2855. }
  2856. }
  2857. };
  2858. BASE.InputJax.Error = {
  2859. id: "Error", version: "2.5.0", config: {},
  2860. sourceMenuTitle: /*_(MathMenu)*/ ["Original","Original Form"]
  2861. };
  2862. })("MathJax");
  2863. /**********************************************************/
  2864. (function (BASENAME) {
  2865. var BASE = window[BASENAME];
  2866. if (!BASE) {BASE = window[BASENAME] = {}}
  2867. var HUB = BASE.Hub; var STARTUP = HUB.Startup; var CONFIG = HUB.config;
  2868. var HEAD = document.head || (document.getElementsByTagName("head")[0]);
  2869. if (!HEAD) {HEAD = document.childNodes[0]};
  2870. var scripts = (document.documentElement || document).getElementsByTagName("script");
  2871. if (scripts.length === 0 && HEAD.namespaceURI)
  2872. scripts = document.getElementsByTagNameNS(HEAD.namespaceURI,"script");
  2873. var namePattern = new RegExp("(^|/)"+BASENAME+"\\.js(\\?.*)?$");
  2874. for (var i = scripts.length-1; i >= 0; i--) {
  2875. if ((scripts[i].src||"").match(namePattern)) {
  2876. STARTUP.script = scripts[i].innerHTML;
  2877. if (RegExp.$2) {
  2878. var params = RegExp.$2.substr(1).split(/\&/);
  2879. for (var j = 0, m = params.length; j < m; j++) {
  2880. var KV = params[j].match(/(.*)=(.*)/);
  2881. if (KV) {STARTUP.params[unescape(KV[1])] = unescape(KV[2])}
  2882. }
  2883. }
  2884. CONFIG.root = scripts[i].src.replace(/(^|\/)[^\/]*(\?.*)?$/,'')
  2885. // convert rackspace to cdn.mathjax.org now that it supports https protocol
  2886. .replace(/^(https?:)\/\/[0-9a-f]+(-[0-9a-f]+)?.ssl.cf1.rackcdn.com\//,"$1//cdn.mathjax.org/");
  2887. BASE.Ajax.config.root = CONFIG.root;
  2888. break;
  2889. }
  2890. }
  2891. var AGENT = navigator.userAgent;
  2892. var BROWSERS = {
  2893. isMac: (navigator.platform.substr(0,3) === "Mac"),
  2894. isPC: (navigator.platform.substr(0,3) === "Win"),
  2895. isMSIE: ("ActiveXObject" in window && "clipboardData" in window),
  2896. isFirefox: (AGENT.match(/Gecko\//) && !AGENT.match(/like Gecko/)),
  2897. isSafari: (AGENT.match(/ (Apple)?WebKit\//) != null &&
  2898. (!window.chrome || window.chrome.loadTimes == null)),
  2899. isChrome: (window.chrome != null && window.chrome.loadTimes != null),
  2900. isOpera: (window.opera != null && window.opera.version != null),
  2901. isKonqueror: ("konqueror" in window && navigator.vendor == "KDE"),
  2902. versionAtLeast: function (v) {
  2903. var bv = (this.version).split('.'); v = (new String(v)).split('.');
  2904. for (var i = 0, m = v.length; i < m; i++)
  2905. {if (bv[i] != v[i]) {return parseInt(bv[i]||"0") >= parseInt(v[i])}}
  2906. return true;
  2907. },
  2908. Select: function (choices) {
  2909. var browser = choices[HUB.Browser];
  2910. if (browser) {return browser(HUB.Browser)}
  2911. return null;
  2912. }
  2913. };
  2914. var xAGENT = AGENT
  2915. .replace(/^Mozilla\/(\d+\.)+\d+ /,"") // remove initial Mozilla, which is never right
  2916. .replace(/[a-z][-a-z0-9._: ]+\/\d+[^ ]*-[^ ]*\.([a-z][a-z])?\d+ /i,"") // remove linux version
  2917. .replace(/Gentoo |Ubuntu\/(\d+\.)*\d+ (\([^)]*\) )?/,""); // special case for these
  2918. HUB.Browser = HUB.Insert(HUB.Insert(new String("Unknown"),{version: "0.0"}),BROWSERS);
  2919. for (var browser in BROWSERS) {if (BROWSERS.hasOwnProperty(browser)) {
  2920. if (BROWSERS[browser] && browser.substr(0,2) === "is") {
  2921. browser = browser.slice(2);
  2922. if (browser === "Mac" || browser === "PC") continue;
  2923. HUB.Browser = HUB.Insert(new String(browser),BROWSERS);
  2924. var VERSION = new RegExp(
  2925. ".*(Version/| Trident/.*; rv:)((?:\\d+\\.)+\\d+)|" + // for Safari, Opera10, and IE11+
  2926. ".*("+browser+")"+(browser == "MSIE" ? " " : "/")+"((?:\\d+\\.)*\\d+)|"+ // for one of the main browser
  2927. "(?:^|\\(| )([a-z][-a-z0-9._: ]+|(?:Apple)?WebKit)/((?:\\d+\\.)+\\d+)"); // for unrecognized browser
  2928. var MATCH = VERSION.exec(xAGENT) || ["","","","unknown","0.0"];
  2929. HUB.Browser.name = (MATCH[1] != "" ? browser : (MATCH[3] || MATCH[5]));
  2930. HUB.Browser.version = MATCH[2] || MATCH[4] || MATCH[6];
  2931. break;
  2932. }
  2933. }};
  2934. //
  2935. // Initial browser-specific info (e.g., touch up version or name)
  2936. //
  2937. HUB.Browser.Select({
  2938. Safari: function (browser) {
  2939. var v = parseInt((String(browser.version).split("."))[0]);
  2940. if (v > 85) {browser.webkit = browser.version}
  2941. if (v >= 538) {browser.version = "8.0"}
  2942. else if (v >= 537) {browser.version = "7.0"}
  2943. else if (v >= 536) {browser.version = "6.0"}
  2944. else if (v >= 534) {browser.version = "5.1"}
  2945. else if (v >= 533) {browser.version = "5.0"}
  2946. else if (v >= 526) {browser.version = "4.0"}
  2947. else if (v >= 525) {browser.version = "3.1"}
  2948. else if (v > 500) {browser.version = "3.0"}
  2949. else if (v > 400) {browser.version = "2.0"}
  2950. else if (v > 85) {browser.version = "1.0"}
  2951. browser.webkit = (navigator.appVersion.match(/WebKit\/(\d+)\./))[1];
  2952. browser.isMobile = (navigator.appVersion.match(/Mobile/i) != null);
  2953. browser.noContextMenu = browser.isMobile;
  2954. },
  2955. Firefox: function (browser) {
  2956. if ((browser.version === "0.0" || AGENT.match(/Firefox/) == null) &&
  2957. navigator.product === "Gecko") {
  2958. var rv = AGENT.match(/[\/ ]rv:(\d+\.\d.*?)[\) ]/);
  2959. if (rv) {browser.version = rv[1]}
  2960. else {
  2961. var date = (navigator.buildID||navigator.productSub||"0").substr(0,8);
  2962. if (date >= "20111220") {browser.version = "9.0"}
  2963. else if (date >= "20111120") {browser.version = "8.0"}
  2964. else if (date >= "20110927") {browser.version = "7.0"}
  2965. else if (date >= "20110816") {browser.version = "6.0"}
  2966. else if (date >= "20110621") {browser.version = "5.0"}
  2967. else if (date >= "20110320") {browser.version = "4.0"}
  2968. else if (date >= "20100121") {browser.version = "3.6"}
  2969. else if (date >= "20090630") {browser.version = "3.5"}
  2970. else if (date >= "20080617") {browser.version = "3.0"}
  2971. else if (date >= "20061024") {browser.version = "2.0"}
  2972. }
  2973. }
  2974. browser.isMobile = (navigator.appVersion.match(/Android/i) != null ||
  2975. AGENT.match(/ Fennec\//) != null ||
  2976. AGENT.match(/Mobile/) != null);
  2977. },
  2978. Opera: function (browser) {browser.version = opera.version()},
  2979. MSIE: function (browser) {
  2980. browser.isIE9 = !!(document.documentMode && (window.performance || window.msPerformance));
  2981. MathJax.HTML.setScriptBug = !browser.isIE9 || document.documentMode < 9;
  2982. MathJax.Hub.msieHTMLCollectionBug = (document.documentMode < 9);
  2983. //
  2984. // MathPlayer doesn't function properly in IE10, and not at all in IE11,
  2985. // so don't even try to load it.
  2986. //
  2987. if (document.documentMode < 10 && !STARTUP.params.NoMathPlayer) {
  2988. try {
  2989. new ActiveXObject("MathPlayer.Factory.1");
  2990. browser.hasMathPlayer = true;
  2991. } catch (err) {}
  2992. try {
  2993. if (browser.hasMathPlayer) {
  2994. var mathplayer = document.createElement("object");
  2995. mathplayer.id = "mathplayer"; mathplayer.classid = "clsid:32F66A20-7614-11D4-BD11-00104BD3F987";
  2996. HEAD.appendChild(mathplayer);
  2997. document.namespaces.add("m","http://www.w3.org/1998/Math/MathML");
  2998. browser.mpNamespace = true;
  2999. if (document.readyState && (document.readyState === "loading" ||
  3000. document.readyState === "interactive")) {
  3001. document.write('<?import namespace="m" implementation="#MathPlayer">');
  3002. browser.mpImported = true;
  3003. }
  3004. } else {
  3005. // Adding any namespace avoids a crash in IE9 in IE9-standards mode
  3006. // (any reference to document.namespaces before document.readyState is
  3007. // "complete" causes an "unspecified error" to be thrown)
  3008. document.namespaces.add("mjx_IE_fix","http://www.w3.org/1999/xlink");
  3009. }
  3010. } catch (err) {}
  3011. }
  3012. }
  3013. });
  3014. HUB.Browser.Select(MathJax.Message.browsers);
  3015. if (BASE.AuthorConfig && typeof BASE.AuthorConfig.AuthorInit === "function") {BASE.AuthorConfig.AuthorInit()}
  3016. HUB.queue = BASE.Callback.Queue();
  3017. HUB.queue.Push(
  3018. ["Post",STARTUP.signal,"Begin"],
  3019. ["Config",STARTUP],
  3020. ["Cookie",STARTUP],
  3021. ["Styles",STARTUP],
  3022. ["Message",STARTUP],
  3023. function () {
  3024. // Do Jax and Extensions in parallel, but wait for them all to complete
  3025. var queue = BASE.Callback.Queue(
  3026. STARTUP.Jax(),
  3027. STARTUP.Extensions()
  3028. );
  3029. return queue.Push({});
  3030. },
  3031. ["Menu",STARTUP],
  3032. STARTUP.onLoad(),
  3033. function () {MathJax.isReady = true}, // indicates that MathJax is ready to process math
  3034. ["Typeset",STARTUP],
  3035. ["Hash",STARTUP],
  3036. ["MenuZoom",STARTUP],
  3037. ["Post",STARTUP.signal,"End"]
  3038. );
  3039. })("MathJax");
  3040. }}