mathquill.js 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888
  1. /**
  2. * Copyleft 2010-2011 Jay and Han (laughinghan@gmail.com)
  3. * under the GNU Lesser General Public License
  4. * http://www.gnu.org/licenses/lgpl.html
  5. * Project Website: http://mathquill.com
  6. */
  7. (function() {
  8. var jQuery = window.jQuery,
  9. undefined,
  10. _, //temp variable of prototypes
  11. mqCmdId = 'mathquill-command-id',
  12. mqBlockId = 'mathquill-block-id',
  13. min = Math.min,
  14. max = Math.max;
  15. var __slice = [].slice;
  16. function noop() {}
  17. /**
  18. * sugar to make defining lots of commands easier.
  19. * TODO: rethink this.
  20. */
  21. function bind(cons /*, args... */) {
  22. var args = __slice.call(arguments, 1);
  23. return function() {
  24. return cons.apply(this, args);
  25. };
  26. }
  27. /**
  28. * a development-only debug method. This definition and all
  29. * calls to `pray` will be stripped from the minified
  30. * build of mathquill.
  31. *
  32. * This function must be called by name to be removed
  33. * at compile time. Do not define another function
  34. * with the same name, and only call this function by
  35. * name.
  36. */
  37. function pray(message, cond) {
  38. if (!cond) throw new Error('prayer failed: '+message);
  39. }
  40. var P = (function(prototype, ownProperty, undefined) {
  41. // helper functions that also help minification
  42. function isObject(o) { return typeof o === 'object'; }
  43. function isFunction(f) { return typeof f === 'function'; }
  44. // a function that gets reused to make uninitialized objects
  45. function BareConstructor() {}
  46. function P(_superclass /* = Object */, definition) {
  47. // handle the case where no superclass is given
  48. if (definition === undefined) {
  49. definition = _superclass;
  50. _superclass = Object;
  51. }
  52. // C is the class to be returned.
  53. //
  54. // It delegates to instantiating an instance of `Bare`, so that it
  55. // will always return a new instance regardless of the calling
  56. // context.
  57. //
  58. // TODO: the Chrome inspector shows all created objects as `C`
  59. // rather than `Object`. Setting the .name property seems to
  60. // have no effect. Is there a way to override this behavior?
  61. function C() {
  62. var self = new Bare;
  63. if (isFunction(self.init)) self.init.apply(self, arguments);
  64. return self;
  65. }
  66. // C.Bare is a class with a noop constructor. Its prototype is the
  67. // same as C, so that instances of C.Bare are also instances of C.
  68. // New objects can be allocated without initialization by calling
  69. // `new MyClass.Bare`.
  70. function Bare() {}
  71. C.Bare = Bare;
  72. // Set up the prototype of the new class.
  73. var _super = BareConstructor[prototype] = _superclass[prototype];
  74. var proto = Bare[prototype] = C[prototype] = new BareConstructor;
  75. // other variables, as a minifier optimization
  76. var extensions;
  77. // set the constructor property on the prototype, for convenience
  78. proto.constructor = C;
  79. C.mixin = function(def) {
  80. Bare[prototype] = C[prototype] = P(C, def)[prototype];
  81. return C;
  82. }
  83. return (C.open = function(def) {
  84. extensions = {};
  85. if (isFunction(def)) {
  86. // call the defining function with all the arguments you need
  87. // extensions captures the return value.
  88. extensions = def.call(C, proto, _super, C, _superclass);
  89. }
  90. else if (isObject(def)) {
  91. // if you passed an object instead, we'll take it
  92. extensions = def;
  93. }
  94. // ...and extend it
  95. if (isObject(extensions)) {
  96. for (var ext in extensions) {
  97. if (ownProperty.call(extensions, ext)) {
  98. proto[ext] = extensions[ext];
  99. }
  100. }
  101. }
  102. // if there's no init, we assume we're inheriting a non-pjs class, so
  103. // we default to applying the superclass's constructor.
  104. if (!isFunction(proto.init)) {
  105. proto.init = _superclass;
  106. }
  107. return C;
  108. })(definition);
  109. }
  110. // ship it
  111. return P;
  112. // as a minifier optimization, we've closured in a few helper functions
  113. // and the string 'prototype' (C[p] is much shorter than C.prototype)
  114. })('prototype', ({}).hasOwnProperty);
  115. /*************************************************
  116. * Textarea Manager
  117. *
  118. * An abstraction layer wrapping the textarea in
  119. * an object with methods to manipulate and listen
  120. * to events on, that hides all the nasty cross-
  121. * browser incompatibilities behind a uniform API.
  122. *
  123. * Design goal: This is a *HARD* internal
  124. * abstraction barrier. Cross-browser
  125. * inconsistencies are not allowed to leak through
  126. * and be dealt with by event handlers. All future
  127. * cross-browser issues that arise must be dealt
  128. * with here, and if necessary, the API updated.
  129. *
  130. * Organization:
  131. * - key values map and stringify()
  132. * - manageTextarea()
  133. * + defer() and flush()
  134. * + event handler logic
  135. * + attach event handlers and export methods
  136. ************************************************/
  137. var manageTextarea = (function() {
  138. // The following [key values][1] map was compiled from the
  139. // [DOM3 Events appendix section on key codes][2] and
  140. // [a widely cited report on cross-browser tests of key codes][3],
  141. // except for 10: 'Enter', which I've empirically observed in Safari on iOS
  142. // and doesn't appear to conflict with any other known key codes.
  143. //
  144. // [1]: http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#keys-keyvalues
  145. // [2]: http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#fixed-virtual-key-codes
  146. // [3]: http://unixpapa.com/js/key.html
  147. var KEY_VALUES = {
  148. 8: 'Backspace',
  149. 9: 'Tab',
  150. 10: 'Enter', // for Safari on iOS
  151. 13: 'Enter',
  152. 16: 'Shift',
  153. 17: 'Control',
  154. 18: 'Alt',
  155. 20: 'CapsLock',
  156. 27: 'Esc',
  157. 32: 'Spacebar',
  158. 33: 'PageUp',
  159. 34: 'PageDown',
  160. 35: 'End',
  161. 36: 'Home',
  162. 37: 'Left',
  163. 38: 'Up',
  164. 39: 'Right',
  165. 40: 'Down',
  166. 45: 'Insert',
  167. 46: 'Del',
  168. 144: 'NumLock'
  169. };
  170. // To the extent possible, create a normalized string representation
  171. // of the key combo (i.e., key code and modifier keys).
  172. function stringify(evt) {
  173. var which = evt.which || evt.keyCode;
  174. var keyVal = KEY_VALUES[which];
  175. var key;
  176. var modifiers = [];
  177. if (evt.ctrlKey) modifiers.push('Ctrl');
  178. if (evt.originalEvent && evt.originalEvent.metaKey) modifiers.push('Meta');
  179. if (evt.altKey) modifiers.push('Alt');
  180. if (evt.shiftKey) modifiers.push('Shift');
  181. key = keyVal || String.fromCharCode(which);
  182. if (!modifiers.length && !keyVal) return key;
  183. modifiers.push(key);
  184. return modifiers.join('-');
  185. }
  186. // create a textarea manager that calls callbacks at useful times
  187. // and exports useful public methods
  188. return function manageTextarea(el, opts) {
  189. var keydown = null;
  190. var keypress = null;
  191. if (!opts) opts = {};
  192. var textCallback = opts.text || noop;
  193. var keyCallback = opts.key || noop;
  194. var pasteCallback = opts.paste || noop;
  195. var onCut = opts.cut || noop;
  196. var textarea = jQuery(el);
  197. var target = jQuery(opts.container || textarea);
  198. // checkTextareaFor() is called after keypress or paste events to
  199. // say "Hey, I think something was just typed" or "pasted" (resp.),
  200. // so that at all subsequent opportune times (next event or timeout),
  201. // will check for expected typed or pasted text.
  202. // Need to check repeatedly because #135: in Safari 5.1 (at least),
  203. // after selecting something and then typing, the textarea is
  204. // incorrectly reported as selected during the input event (but not
  205. // subsequently).
  206. var checkTextarea = noop, timeoutId;
  207. function checkTextareaFor(checker) {
  208. checkTextarea = checker;
  209. clearTimeout(timeoutId);
  210. timeoutId = setTimeout(checker);
  211. }
  212. target.bind('keydown keypress input keyup focusout paste', function() { checkTextarea(); });
  213. // -*- public methods -*- //
  214. function select(text) {
  215. // check textarea at least once/one last time before munging (so
  216. // no race condition if selection happens after keypress/paste but
  217. // before checkTextarea), then never again ('cos it's been munged)
  218. checkTextarea();
  219. checkTextarea = noop;
  220. clearTimeout(timeoutId);
  221. textarea.val(text);
  222. if (text) textarea[0].select();
  223. }
  224. // -*- helper subroutines -*- //
  225. // Determine whether there's a selection in the textarea.
  226. // This will always return false in IE < 9, which don't support
  227. // HTMLTextareaElement::selection{Start,End}.
  228. function hasSelection() {
  229. var dom = textarea[0];
  230. if (!('selectionStart' in dom)) return false;
  231. return dom.selectionStart !== dom.selectionEnd;
  232. }
  233. function popText(callback) {
  234. var text = textarea.val();
  235. textarea.val('');
  236. if (text) callback(text);
  237. }
  238. function handleKey() {
  239. keyCallback(stringify(keydown), keydown);
  240. }
  241. // -*- event handlers -*- //
  242. function onKeydown(e) {
  243. keydown = e;
  244. keypress = null;
  245. handleKey();
  246. }
  247. function onKeypress(e) {
  248. // call the key handler for repeated keypresses.
  249. // This excludes keypresses that happen directly
  250. // after keydown. In that case, there will be
  251. // no previous keypress, so we skip it here
  252. if (keydown && keypress) handleKey();
  253. keypress = e;
  254. checkTextareaFor(typedText);
  255. }
  256. function typedText() {
  257. // If there is a selection, the contents of the textarea couldn't
  258. // possibly have just been typed in.
  259. // This happens in browsers like Firefox and Opera that fire
  260. // keypress for keystrokes that are not text entry and leave the
  261. // selection in the textarea alone, such as Ctrl-C.
  262. // Note: we assume that browsers that don't support hasSelection()
  263. // also never fire keypress on keystrokes that are not text entry.
  264. // This seems reasonably safe because:
  265. // - all modern browsers including IE 9+ support hasSelection(),
  266. // making it extremely unlikely any browser besides IE < 9 won't
  267. // - as far as we know IE < 9 never fires keypress on keystrokes
  268. // that aren't text entry, which is only as reliable as our
  269. // tests are comprehensive, but the IE < 9 way to do
  270. // hasSelection() is poorly documented and is also only as
  271. // reliable as our tests are comprehensive
  272. // If anything like #40 or #71 is reported in IE < 9, see
  273. // b1318e5349160b665003e36d4eedd64101ceacd8
  274. if (hasSelection()) return;
  275. popText(textCallback);
  276. }
  277. function onBlur() { keydown = keypress = null; }
  278. function onPaste(e) {
  279. // browsers are dumb.
  280. //
  281. // In Linux, middle-click pasting causes onPaste to be called,
  282. // when the textarea is not necessarily focused. We focus it
  283. // here to ensure that the pasted text actually ends up in the
  284. // textarea.
  285. //
  286. // It's pretty nifty that by changing focus in this handler,
  287. // we can change the target of the default action. (This works
  288. // on keydown too, FWIW).
  289. //
  290. // And by nifty, we mean dumb (but useful sometimes).
  291. textarea.focus();
  292. checkTextareaFor(pastedText);
  293. }
  294. function pastedText() {
  295. popText(pasteCallback);
  296. }
  297. // -*- attach event handlers -*- //
  298. target.bind({
  299. keydown: onKeydown,
  300. keypress: onKeypress,
  301. focusout: onBlur,
  302. cut: onCut,
  303. paste: onPaste
  304. });
  305. // -*- export public methods -*- //
  306. return {
  307. select: select
  308. };
  309. };
  310. }());
  311. var Parser = P(function(_, _super, Parser) {
  312. // The Parser object is a wrapper for a parser function.
  313. // Externally, you use one to parse a string by calling
  314. // var result = SomeParser.parse('Me Me Me! Parse Me!');
  315. // You should never call the constructor, rather you should
  316. // construct your Parser from the base parsers and the
  317. // parser combinator methods.
  318. function parseError(stream, message) {
  319. if (stream) {
  320. stream = "'"+stream+"'";
  321. }
  322. else {
  323. stream = 'EOF';
  324. }
  325. throw 'Parse Error: '+message+' at '+stream;
  326. }
  327. _.init = function(body) { this._ = body; };
  328. _.parse = function(stream) {
  329. return this.skip(eof)._(stream, success, parseError);
  330. function success(stream, result) { return result; }
  331. };
  332. // -*- primitive combinators -*- //
  333. _.or = function(alternative) {
  334. pray('or is passed a parser', alternative instanceof Parser);
  335. var self = this;
  336. return Parser(function(stream, onSuccess, onFailure) {
  337. return self._(stream, onSuccess, failure);
  338. function failure(newStream) {
  339. return alternative._(stream, onSuccess, onFailure);
  340. }
  341. });
  342. };
  343. _.then = function(next) {
  344. var self = this;
  345. return Parser(function(stream, onSuccess, onFailure) {
  346. return self._(stream, success, onFailure);
  347. function success(newStream, result) {
  348. var nextParser = (next instanceof Parser ? next : next(result));
  349. pray('a parser is returned', nextParser instanceof Parser);
  350. return nextParser._(newStream, onSuccess, onFailure);
  351. }
  352. });
  353. };
  354. // -*- optimized iterative combinators -*- //
  355. _.many = function() {
  356. var self = this;
  357. return Parser(function(stream, onSuccess, onFailure) {
  358. var xs = [];
  359. while (self._(stream, success, failure));
  360. return onSuccess(stream, xs);
  361. function success(newStream, x) {
  362. stream = newStream;
  363. xs.push(x);
  364. return true;
  365. }
  366. function failure() {
  367. return false;
  368. }
  369. });
  370. };
  371. _.times = function(min, max) {
  372. if (arguments.length < 2) max = min;
  373. var self = this;
  374. return Parser(function(stream, onSuccess, onFailure) {
  375. var xs = [];
  376. var result = true;
  377. var failure;
  378. for (var i = 0; i < min; i += 1) {
  379. result = self._(stream, success, firstFailure);
  380. if (!result) return onFailure(stream, failure);
  381. }
  382. for (; i < max && result; i += 1) {
  383. result = self._(stream, success, secondFailure);
  384. }
  385. return onSuccess(stream, xs);
  386. function success(newStream, x) {
  387. xs.push(x);
  388. stream = newStream;
  389. return true;
  390. }
  391. function firstFailure(newStream, msg) {
  392. failure = msg;
  393. stream = newStream;
  394. return false;
  395. }
  396. function secondFailure(newStream, msg) {
  397. return false;
  398. }
  399. });
  400. };
  401. // -*- higher-level combinators -*- //
  402. _.result = function(res) { return this.then(succeed(res)); };
  403. _.atMost = function(n) { return this.times(0, n); };
  404. _.atLeast = function(n) {
  405. var self = this;
  406. return self.times(n).then(function(start) {
  407. return self.many().map(function(end) {
  408. return start.concat(end);
  409. });
  410. });
  411. };
  412. _.map = function(fn) {
  413. return this.then(function(result) { return succeed(fn(result)); });
  414. };
  415. _.skip = function(two) {
  416. return this.then(function(result) { return two.result(result); });
  417. };
  418. // -*- primitive parsers -*- //
  419. var string = this.string = function(str) {
  420. var len = str.length;
  421. var expected = "expected '"+str+"'";
  422. return Parser(function(stream, onSuccess, onFailure) {
  423. var head = stream.slice(0, len);
  424. if (head === str) {
  425. return onSuccess(stream.slice(len), head);
  426. }
  427. else {
  428. return onFailure(stream, expected);
  429. }
  430. });
  431. };
  432. var regex = this.regex = function(re) {
  433. pray('regexp parser is anchored', re.toString().charAt(1) === '^');
  434. var expected = 'expected '+re;
  435. return Parser(function(stream, onSuccess, onFailure) {
  436. var match = re.exec(stream);
  437. if (match) {
  438. var result = match[0];
  439. return onSuccess(stream.slice(result.length), result);
  440. }
  441. else {
  442. return onFailure(stream, expected);
  443. }
  444. });
  445. };
  446. var succeed = Parser.succeed = function(result) {
  447. return Parser(function(stream, onSuccess) {
  448. return onSuccess(stream, result);
  449. });
  450. };
  451. var fail = Parser.fail = function(msg) {
  452. return Parser(function(stream, _, onFailure) {
  453. return onFailure(stream, msg);
  454. });
  455. };
  456. var letter = Parser.letter = regex(/^[a-z]/i);
  457. var letters = Parser.letters = regex(/^[a-z]*/i);
  458. var digit = Parser.digit = regex(/^[0-9]/);
  459. var digits = Parser.digits = regex(/^[0-9]*/);
  460. var whitespace = Parser.whitespace = regex(/^\s+/);
  461. var optWhitespace = Parser.optWhitespace = regex(/^\s*/);
  462. var any = Parser.any = Parser(function(stream, onSuccess, onFailure) {
  463. if (!stream) return onFailure(stream, 'expected any character');
  464. return onSuccess(stream.slice(1), stream.charAt(0));
  465. });
  466. var all = Parser.all = Parser(function(stream, onSuccess, onFailure) {
  467. return onSuccess('', stream);
  468. });
  469. var eof = Parser.eof = Parser(function(stream, onSuccess, onFailure) {
  470. if (stream) return onFailure(stream, 'expected EOF');
  471. return onSuccess(stream, stream);
  472. });
  473. });
  474. /*************************************************
  475. * Base classes of the MathQuill virtual DOM tree
  476. *
  477. * Only doing tree node manipulation via these
  478. * adopt/ disown methods guarantees well-formedness
  479. * of the tree.
  480. ************************************************/
  481. // L = 'left'
  482. // R = 'right'
  483. //
  484. // the contract is that they can be used as object properties
  485. // and (-L) === R, and (-R) === L.
  486. var L = -1;
  487. var R = 1;
  488. function prayDirection(dir) {
  489. pray('a direction was passed', dir === L || dir === R);
  490. }
  491. /**
  492. * Tiny extension of jQuery adding directionalized DOM manipulation methods.
  493. *
  494. * Funny how Pjs v3 almost just works with `jQuery.fn.init`.
  495. *
  496. * jQuery features that don't work on $:
  497. * - jQuery.*, like jQuery.ajax, obviously (Pjs doesn't and shouldn't
  498. * copy constructor properties)
  499. *
  500. * - jQuery(function), the shortcut for `jQuery(document).ready(function)`,
  501. * because `jQuery.fn.init` is idiosyncratic and Pjs doing, essentially,
  502. * `jQuery.fn.init.apply(this, arguments)` isn't quite right, you need:
  503. *
  504. * _.init = function(s, c) { jQuery.fn.init.call(this, s, c, $(document)); };
  505. *
  506. * if you actually give a shit (really, don't bother),
  507. * see https://github.com/jquery/jquery/blob/1.7.2/src/core.js#L889
  508. *
  509. * - jQuery(selector), because jQuery translates that to
  510. * `jQuery(document).find(selector)`, but Pjs doesn't (should it?) let
  511. * you override the result of a constructor call
  512. * + note that because of the jQuery(document) shortcut-ness, there's also
  513. * the 3rd-argument-needs-to-be-`$(document)` thing above, but the fix
  514. * for that (as can be seen above) is really easy. This problem requires
  515. * a way more intrusive fix
  516. *
  517. * And that's it! Everything else just magically works because jQuery internally
  518. * uses `this.constructor()` everywhere (hence calling `$`), but never ever does
  519. * `this.constructor.find` or anything like that, always doing `jQuery.find`.
  520. */
  521. var $ = P(jQuery, function(_) {
  522. _.insDirOf = function(dir, el) {
  523. return dir === L ?
  524. this.insertBefore(el.first()) : this.insertAfter(el.last());
  525. };
  526. _.insAtDirEnd = function(dir, el) {
  527. return dir === L ? this.prependTo(el) : this.appendTo(el);
  528. };
  529. });
  530. var Point = P(function(_) {
  531. _.parent = 0;
  532. _[L] = 0;
  533. _[R] = 0;
  534. _.init = function(parent, leftward, rightward) {
  535. this.parent = parent;
  536. this[L] = leftward;
  537. this[R] = rightward;
  538. };
  539. });
  540. /**
  541. * MathQuill virtual-DOM tree-node abstract base class
  542. */
  543. var Node = P(function(_) {
  544. _[L] = 0;
  545. _[R] = 0
  546. _.parent = 0;
  547. _.init = function() {
  548. this.ends = {};
  549. this.ends[L] = 0;
  550. this.ends[R] = 0;
  551. };
  552. _.children = function() {
  553. return Fragment(this.ends[L], this.ends[R]);
  554. };
  555. _.eachChild = function(fn) {
  556. return this.children().each(fn);
  557. };
  558. _.foldChildren = function(fold, fn) {
  559. return this.children().fold(fold, fn);
  560. };
  561. _.adopt = function(parent, leftward, rightward) {
  562. Fragment(this, this).adopt(parent, leftward, rightward);
  563. return this;
  564. };
  565. _.disown = function() {
  566. Fragment(this, this).disown();
  567. return this;
  568. };
  569. });
  570. /**
  571. * An entity outside the virtual tree with one-way pointers (so it's only a
  572. * "view" of part of the tree, not an actual node/entity in the tree) that
  573. * delimits a doubly-linked list of sibling nodes.
  574. * It's like a fanfic love-child between HTML DOM DocumentFragment and the Range
  575. * classes: like DocumentFragment, its contents must be sibling nodes
  576. * (unlike Range, whose contents are arbitrary contiguous pieces of subtrees),
  577. * but like Range, it has only one-way pointers to its contents, its contents
  578. * have no reference to it and in fact may still be in the visible tree (unlike
  579. * DocumentFragment, whose contents must be detached from the visible tree
  580. * and have their 'parent' pointers set to the DocumentFragment).
  581. */
  582. var Fragment = P(function(_) {
  583. _.init = function(leftEnd, rightEnd) {
  584. pray('no half-empty fragments', !leftEnd === !rightEnd);
  585. this.ends = {};
  586. if (!leftEnd) return;
  587. pray('left end node is passed to Fragment', leftEnd instanceof Node);
  588. pray('right end node is passed to Fragment', rightEnd instanceof Node);
  589. pray('leftEnd and rightEnd have the same parent',
  590. leftEnd.parent === rightEnd.parent);
  591. this.ends[L] = leftEnd;
  592. this.ends[R] = rightEnd;
  593. };
  594. function prayWellFormed(parent, leftward, rightward) {
  595. pray('a parent is always present', parent);
  596. pray('leftward is properly set up', (function() {
  597. // either it's empty and `rightward` is the left end child (possibly empty)
  598. if (!leftward) return parent.ends[L] === rightward;
  599. // or it's there and its [R] and .parent are properly set up
  600. return leftward[R] === rightward && leftward.parent === parent;
  601. })());
  602. pray('rightward is properly set up', (function() {
  603. // either it's empty and `leftward` is the right end child (possibly empty)
  604. if (!rightward) return parent.ends[R] === leftward;
  605. // or it's there and its [L] and .parent are properly set up
  606. return rightward[L] === leftward && rightward.parent === parent;
  607. })());
  608. }
  609. _.adopt = function(parent, leftward, rightward) {
  610. prayWellFormed(parent, leftward, rightward);
  611. var self = this;
  612. self.disowned = false;
  613. var leftEnd = self.ends[L];
  614. if (!leftEnd) return this;
  615. var rightEnd = self.ends[R];
  616. if (leftward) {
  617. // NB: this is handled in the ::each() block
  618. // leftward[R] = leftEnd
  619. } else {
  620. parent.ends[L] = leftEnd;
  621. }
  622. if (rightward) {
  623. rightward[L] = rightEnd;
  624. } else {
  625. parent.ends[R] = rightEnd;
  626. }
  627. self.ends[R][R] = rightward;
  628. self.each(function(el) {
  629. el[L] = leftward;
  630. el.parent = parent;
  631. if (leftward) leftward[R] = el;
  632. leftward = el;
  633. });
  634. return self;
  635. };
  636. _.disown = function() {
  637. var self = this;
  638. var leftEnd = self.ends[L];
  639. // guard for empty and already-disowned fragments
  640. if (!leftEnd || self.disowned) return self;
  641. self.disowned = true;
  642. var rightEnd = self.ends[R]
  643. var parent = leftEnd.parent;
  644. prayWellFormed(parent, leftEnd[L], leftEnd);
  645. prayWellFormed(parent, rightEnd, rightEnd[R]);
  646. if (leftEnd[L]) {
  647. leftEnd[L][R] = rightEnd[R];
  648. } else {
  649. parent.ends[L] = rightEnd[R];
  650. }
  651. if (rightEnd[R]) {
  652. rightEnd[R][L] = leftEnd[L];
  653. } else {
  654. parent.ends[R] = leftEnd[L];
  655. }
  656. return self;
  657. };
  658. _.each = function(fn) {
  659. var self = this;
  660. var el = self.ends[L];
  661. if (!el) return self;
  662. for (;el !== self.ends[R][R]; el = el[R]) {
  663. if (fn.call(self, el) === false) break;
  664. }
  665. return self;
  666. };
  667. _.fold = function(fold, fn) {
  668. this.each(function(el) {
  669. fold = fn.call(this, fold, el);
  670. });
  671. return fold;
  672. };
  673. });
  674. /*************************************************
  675. * Abstract classes of math blocks and commands.
  676. ************************************************/
  677. var uuid = (function() {
  678. var id = 0;
  679. return function() { return id += 1; };
  680. })();
  681. /**
  682. * Math tree node base class.
  683. * Some math-tree-specific extensions to Node.
  684. * Both MathBlock's and MathCommand's descend from it.
  685. */
  686. var MathElement = P(Node, function(_, _super) {
  687. _.init = function(obj) {
  688. _super.init.call(this);
  689. this.id = uuid();
  690. MathElement[this.id] = this;
  691. };
  692. _.toString = function() {
  693. return '[MathElement '+this.id+']';
  694. };
  695. _.bubble = function(event /*, args... */) {
  696. var args = __slice.call(arguments, 1);
  697. for (var ancestor = this; ancestor; ancestor = ancestor.parent) {
  698. var res = ancestor[event] && ancestor[event].apply(ancestor, args);
  699. if (res === false) break;
  700. }
  701. return this;
  702. };
  703. _.postOrder = function(fn /*, args... */) {
  704. var args = __slice.call(arguments, 1);
  705. if (typeof fn === 'string') {
  706. var methodName = fn;
  707. fn = function(el) {
  708. if (methodName in el) el[methodName].apply(el, args);
  709. };
  710. }
  711. (function recurse(desc) {
  712. desc.eachChild(recurse);
  713. fn(desc);
  714. })(this);
  715. };
  716. _.jQ = $();
  717. _.jQadd = function(jQ) { this.jQ = this.jQ.add(jQ); };
  718. this.jQize = function(html) {
  719. // Sets the .jQ of the entire math subtree rooted at this command.
  720. // Expects .createBlocks() to have been called already, since it
  721. // calls .html().
  722. var jQ = $(html);
  723. jQ.find('*').andSelf().each(function() {
  724. var jQ = $(this),
  725. cmdId = jQ.attr('mathquill-command-id'),
  726. blockId = jQ.attr('mathquill-block-id');
  727. if (cmdId) MathElement[cmdId].jQadd(jQ);
  728. if (blockId) MathElement[blockId].jQadd(jQ);
  729. });
  730. return jQ;
  731. };
  732. _.finalizeInsert = function() {
  733. var self = this;
  734. self.postOrder('finalizeTree');
  735. // note: this order is important.
  736. // empty elements need the empty box provided by blur to
  737. // be present in order for their dimensions to be measured
  738. // correctly in redraw.
  739. self.postOrder('blur');
  740. // adjust context-sensitive spacing
  741. self.postOrder('respace');
  742. if (self[R].respace) self[R].respace();
  743. if (self[L].respace) self[L].respace();
  744. self.postOrder('redraw');
  745. self.bubble('redraw');
  746. };
  747. });
  748. /**
  749. * Commands and operators, like subscripts, exponents, or fractions.
  750. * Descendant commands are organized into blocks.
  751. */
  752. var MathCommand = P(MathElement, function(_, _super) {
  753. _.init = function(ctrlSeq, htmlTemplate, textTemplate) {
  754. var cmd = this;
  755. _super.init.call(cmd);
  756. if (!cmd.ctrlSeq) cmd.ctrlSeq = ctrlSeq;
  757. if (htmlTemplate) cmd.htmlTemplate = htmlTemplate;
  758. if (textTemplate) cmd.textTemplate = textTemplate;
  759. };
  760. // obvious methods
  761. _.replaces = function(replacedFragment) {
  762. replacedFragment.disown();
  763. this.replacedFragment = replacedFragment;
  764. };
  765. _.isEmpty = function() {
  766. return this.foldChildren(true, function(isEmpty, child) {
  767. return isEmpty && child.isEmpty();
  768. });
  769. };
  770. _.parser = function() {
  771. var block = latexMathParser.block;
  772. var self = this;
  773. return block.times(self.numBlocks()).map(function(blocks) {
  774. self.blocks = blocks;
  775. for (var i = 0; i < blocks.length; i += 1) {
  776. blocks[i].adopt(self, self.ends[R], 0);
  777. }
  778. return self;
  779. });
  780. };
  781. // createLeftOf(cursor) and the methods it calls
  782. _.createLeftOf = function(cursor) {
  783. var cmd = this;
  784. var replacedFragment = cmd.replacedFragment;
  785. cmd.createBlocks();
  786. MathElement.jQize(cmd.html());
  787. if (replacedFragment) {
  788. replacedFragment.adopt(cmd.ends[L], 0, 0);
  789. replacedFragment.jQ.appendTo(cmd.ends[L].jQ);
  790. }
  791. cursor.jQ.before(cmd.jQ);
  792. cursor[L] = cmd.adopt(cursor.parent, cursor[L], cursor[R]);
  793. cmd.finalizeInsert(cursor);
  794. cmd.placeCursor(cursor);
  795. };
  796. _.createBlocks = function() {
  797. var cmd = this,
  798. numBlocks = cmd.numBlocks(),
  799. blocks = cmd.blocks = Array(numBlocks);
  800. for (var i = 0; i < numBlocks; i += 1) {
  801. var newBlock = blocks[i] = MathBlock();
  802. newBlock.adopt(cmd, cmd.ends[R], 0);
  803. }
  804. };
  805. _.respace = noop; //placeholder for context-sensitive spacing
  806. _.placeCursor = function(cursor) {
  807. //insert the cursor at the right end of the first empty child, searching
  808. //left-to-right, or if none empty, the right end child
  809. cursor.insAtRightEnd(this.foldChildren(this.ends[L], function(leftward, child) {
  810. return leftward.isEmpty() ? leftward : child;
  811. }));
  812. };
  813. // remove()
  814. _.remove = function() {
  815. this.disown();
  816. this.jQ.remove();
  817. this.postOrder(function(el) { delete MathElement[el.id]; });
  818. return this;
  819. };
  820. // methods involved in creating and cross-linking with HTML DOM nodes
  821. /*
  822. They all expect an .htmlTemplate like
  823. '<span>&0</span>'
  824. or
  825. '<span><span>&0</span><span>&1</span></span>'
  826. See html.test.js for more examples.
  827. Requirements:
  828. - For each block of the command, there must be exactly one "block content
  829. marker" of the form '&<number>' where <number> is the 0-based index of the
  830. block. (Like the LaTeX \newcommand syntax, but with a 0-based rather than
  831. 1-based index, because JavaScript because C because Dijkstra.)
  832. - The block content marker must be the sole contents of the containing
  833. element, there can't even be surrounding whitespace, or else we can't
  834. guarantee sticking to within the bounds of the block content marker when
  835. mucking with the HTML DOM.
  836. - The HTML not only must be well-formed HTML (of course), but also must
  837. conform to the XHTML requirements on tags, specifically all tags must
  838. either be self-closing (like '<br/>') or come in matching pairs.
  839. Close tags are never optional.
  840. Note that &<number> isn't well-formed HTML; if you wanted a literal '&123',
  841. your HTML template would have to have '&amp;123'.
  842. */
  843. _.numBlocks = function() {
  844. var matches = this.htmlTemplate.match(/&\d+/g);
  845. return matches ? matches.length : 0;
  846. };
  847. _.html = function() {
  848. // Render the entire math subtree rooted at this command, as HTML.
  849. // Expects .createBlocks() to have been called already, since it uses the
  850. // .blocks array of child blocks.
  851. //
  852. // See html.test.js for example templates and intended outputs.
  853. //
  854. // Given an .htmlTemplate as described above,
  855. // - insert the mathquill-command-id attribute into all top-level tags,
  856. // which will be used to set this.jQ in .jQize().
  857. // This is straightforward:
  858. // * tokenize into tags and non-tags
  859. // * loop through top-level tokens:
  860. // * add #cmdId attribute macro to top-level self-closing tags
  861. // * else add #cmdId attribute macro to top-level open tags
  862. // * skip the matching top-level close tag and all tag pairs
  863. // in between
  864. // - for each block content marker,
  865. // + replace it with the contents of the corresponding block,
  866. // rendered as HTML
  867. // + insert the mathquill-block-id attribute into the containing tag
  868. // This is even easier, a quick regex replace, since block tags cannot
  869. // contain anything besides the block content marker.
  870. //
  871. // Two notes:
  872. // - The outermost loop through top-level tokens should never encounter any
  873. // top-level close tags, because we should have first encountered a
  874. // matching top-level open tag, all inner tags should have appeared in
  875. // matching pairs and been skipped, and then we should have skipped the
  876. // close tag in question.
  877. // - All open tags should have matching close tags, which means our inner
  878. // loop should always encounter a close tag and drop nesting to 0. If
  879. // a close tag is missing, the loop will continue until i >= tokens.length
  880. // and token becomes undefined. This will not infinite loop, even in
  881. // production without pray(), because it will then TypeError on .slice().
  882. var cmd = this;
  883. var blocks = cmd.blocks;
  884. var cmdId = ' mathquill-command-id=' + cmd.id;
  885. var tokens = cmd.htmlTemplate.match(/<[^<>]+>|[^<>]+/g);
  886. pray('no unmatched angle brackets', tokens.join('') === this.htmlTemplate);
  887. // add cmdId to all top-level tags
  888. for (var i = 0, token = tokens[0]; token; i += 1, token = tokens[i]) {
  889. // top-level self-closing tags
  890. if (token.slice(-2) === '/>') {
  891. tokens[i] = token.slice(0,-2) + cmdId + '/>';
  892. }
  893. // top-level open tags
  894. else if (token.charAt(0) === '<') {
  895. pray('not an unmatched top-level close tag', token.charAt(1) !== '/');
  896. tokens[i] = token.slice(0,-1) + cmdId + '>';
  897. // skip matching top-level close tag and all tag pairs in between
  898. var nesting = 1;
  899. do {
  900. i += 1, token = tokens[i];
  901. pray('no missing close tags', token);
  902. // close tags
  903. if (token.slice(0,2) === '</') {
  904. nesting -= 1;
  905. }
  906. // non-self-closing open tags
  907. else if (token.charAt(0) === '<' && token.slice(-2) !== '/>') {
  908. nesting += 1;
  909. }
  910. } while (nesting > 0);
  911. }
  912. }
  913. return tokens.join('').replace(/>&(\d+)/g, function($0, $1) {
  914. return ' mathquill-block-id=' + blocks[$1].id + '>' + blocks[$1].join('html');
  915. });
  916. };
  917. // methods to export a string representation of the math tree
  918. _.latex = function() {
  919. return this.foldChildren(this.ctrlSeq, function(latex, child) {
  920. return latex + '{' + (child.latex() || ' ') + '}';
  921. });
  922. };
  923. _.textTemplate = [''];
  924. _.text = function() {
  925. var cmd = this, i = 0;
  926. return cmd.foldChildren(cmd.textTemplate[i], function(text, child) {
  927. i += 1;
  928. var child_text = child.text();
  929. if (text && cmd.textTemplate[i] === '('
  930. && child_text[0] === '(' && child_text.slice(-1) === ')')
  931. return text + child_text.slice(1, -1) + cmd.textTemplate[i];
  932. return text + child.text() + (cmd.textTemplate[i] || '');
  933. });
  934. };
  935. });
  936. /**
  937. * Lightweight command without blocks or children.
  938. */
  939. var Symbol = P(MathCommand, function(_, _super) {
  940. _.init = function(ctrlSeq, html, text) {
  941. if (!text) text = ctrlSeq && ctrlSeq.length > 1 ? ctrlSeq.slice(1) : ctrlSeq;
  942. _super.init.call(this, ctrlSeq, html, [ text ]);
  943. };
  944. _.parser = function() { return Parser.succeed(this); };
  945. _.numBlocks = function() { return 0; };
  946. _.replaces = function(replacedFragment) {
  947. replacedFragment.remove();
  948. };
  949. _.createBlocks = noop;
  950. _.latex = function(){ return this.ctrlSeq; };
  951. _.text = function(){ return this.textTemplate; };
  952. _.placeCursor = noop;
  953. _.isEmpty = function(){ return true; };
  954. });
  955. /**
  956. * Children and parent of MathCommand's. Basically partitions all the
  957. * symbols and operators that descend (in the Math DOM tree) from
  958. * ancestor operators.
  959. */
  960. var MathBlock = P(MathElement, function(_) {
  961. _.join = function(methodName) {
  962. return this.foldChildren('', function(fold, child) {
  963. return fold + child[methodName]();
  964. });
  965. };
  966. _.latex = function() { return this.join('latex'); };
  967. _.text = function() {
  968. return this.ends[L] === this.ends[R] ?
  969. this.ends[L].text() :
  970. '(' + this.join('text') + ')'
  971. ;
  972. };
  973. _.isEmpty = function() {
  974. return this.ends[L] === 0 && this.ends[R] === 0;
  975. };
  976. _.write = function(cursor, ch, replacedFragment) {
  977. var cmd;
  978. if (ch.match(/^[a-eg-zA-Z]$/)) //exclude f because want florin
  979. cmd = Variable(ch);
  980. else if (cmd = CharCmds[ch] || LatexCmds[ch])
  981. cmd = cmd(ch);
  982. else
  983. cmd = VanillaSymbol(ch);
  984. if (replacedFragment) cmd.replaces(replacedFragment);
  985. cmd.createLeftOf(cursor);
  986. };
  987. _.focus = function() {
  988. this.jQ.addClass('hasCursor');
  989. this.jQ.removeClass('empty');
  990. return this;
  991. };
  992. _.blur = function() {
  993. this.jQ.removeClass('hasCursor');
  994. if (this.isEmpty())
  995. this.jQ.addClass('empty');
  996. return this;
  997. };
  998. });
  999. /**
  1000. * Math tree fragment base class.
  1001. * Some math-tree-specific extensions to Fragment.
  1002. */
  1003. var MathFragment = P(Fragment, function(_, _super) {
  1004. _.init = function(leftEnd, rightEnd) {
  1005. // just select one thing if only one argument
  1006. _super.init.call(this, leftEnd, rightEnd || leftEnd);
  1007. this.jQ = this.fold($(), function(jQ, child){ return child.jQ.add(jQ); });
  1008. };
  1009. _.latex = function() {
  1010. return this.fold('', function(latex, el){ return latex + el.latex(); });
  1011. };
  1012. _.remove = function() {
  1013. this.jQ.remove();
  1014. this.each(function(el) {
  1015. el.postOrder(function(desc) {
  1016. delete MathElement[desc.id];
  1017. });
  1018. });
  1019. return this.disown();
  1020. };
  1021. });
  1022. /*********************************************
  1023. * Root math elements with event delegation.
  1024. ********************************************/
  1025. function createRoot(jQ, root, textbox, editable) {
  1026. var contents = jQ.contents().detach();
  1027. if (!textbox) {
  1028. jQ.addClass('mathquill-rendered-math');
  1029. }
  1030. root.jQ = jQ.attr(mqBlockId, root.id);
  1031. root.revert = function() {
  1032. jQ.empty().unbind('.mathquill')
  1033. .removeClass('mathquill-rendered-math mathquill-editable mathquill-textbox')
  1034. .append(contents);
  1035. };
  1036. var cursor = root.cursor = Cursor(root);
  1037. root.renderLatex(contents.text());
  1038. //textarea stuff
  1039. var textareaSpan = root.textarea = $('<span class="textarea"><textarea></textarea></span>'),
  1040. textarea = textareaSpan.children();
  1041. /******
  1042. * TODO [Han]: Document this
  1043. */
  1044. var textareaSelectionTimeout;
  1045. root.selectionChanged = function() {
  1046. if (textareaSelectionTimeout === undefined) {
  1047. textareaSelectionTimeout = setTimeout(setTextareaSelection);
  1048. }
  1049. forceIERedraw(jQ[0]);
  1050. };
  1051. function setTextareaSelection() {
  1052. textareaSelectionTimeout = undefined;
  1053. var latex = cursor.selection ? '$'+cursor.selection.latex()+'$' : '';
  1054. textareaManager.select(latex);
  1055. }
  1056. //prevent native selection except textarea
  1057. jQ.bind('selectstart.mathquill', function(e) {
  1058. if (e.target !== textarea[0]) e.preventDefault();
  1059. e.stopPropagation();
  1060. });
  1061. //drag-to-select event handling
  1062. var anticursor, blink = cursor.blink;
  1063. jQ.bind('mousedown.mathquill', function(e) {
  1064. function mousemove(e) {
  1065. cursor.seek($(e.target), e.pageX, e.pageY);
  1066. if (cursor[L] !== anticursor[L]
  1067. || cursor.parent !== anticursor.parent) {
  1068. cursor.selectFrom(anticursor);
  1069. }
  1070. return false;
  1071. }
  1072. // docmousemove is attached to the document, so that
  1073. // selection still works when the mouse leaves the window.
  1074. function docmousemove(e) {
  1075. // [Han]: i delete the target because of the way seek works.
  1076. // it will not move the mouse to the target, but will instead
  1077. // just seek those X and Y coordinates. If there is a target,
  1078. // it will try to move the cursor to document, which will not work.
  1079. // cursor.seek needs to be refactored.
  1080. delete e.target;
  1081. return mousemove(e);
  1082. }
  1083. function mouseup(e) {
  1084. anticursor = undefined;
  1085. cursor.blink = blink;
  1086. if (!cursor.selection) {
  1087. if (editable) {
  1088. cursor.show();
  1089. }
  1090. else {
  1091. textareaSpan.detach();
  1092. }
  1093. }
  1094. // delete the mouse handlers now that we're not dragging anymore
  1095. jQ.unbind('mousemove', mousemove);
  1096. $(e.target.ownerDocument).unbind('mousemove', docmousemove).unbind('mouseup', mouseup);
  1097. }
  1098. setTimeout(function() { textarea.focus(); });
  1099. // preventDefault won't prevent focus on mousedown in IE<9
  1100. // that means immediately after this mousedown, whatever was
  1101. // mousedown-ed will receive focus
  1102. // http://bugs.jquery.com/ticket/10345
  1103. cursor.blink = noop;
  1104. cursor.seek($(e.target), e.pageX, e.pageY);
  1105. anticursor = Point(cursor.parent, cursor[L], cursor[R]);
  1106. if (!editable) jQ.prepend(textareaSpan);
  1107. jQ.mousemove(mousemove);
  1108. $(e.target.ownerDocument).mousemove(docmousemove).mouseup(mouseup);
  1109. return false;
  1110. });
  1111. if (!editable) {
  1112. var textareaManager = manageTextarea(textarea, { container: jQ });
  1113. jQ.bind('cut paste', false).bind('copy', setTextareaSelection)
  1114. .prepend('<span class="selectable">$'+root.latex()+'$</span>');
  1115. textarea.blur(function() {
  1116. cursor.clearSelection();
  1117. setTimeout(detach); //detaching during blur explodes in WebKit
  1118. });
  1119. function detach() {
  1120. textareaSpan.detach();
  1121. }
  1122. return;
  1123. }
  1124. var textareaManager = manageTextarea(textarea, {
  1125. container: jQ,
  1126. key: function(key, evt) {
  1127. cursor.parent.bubble('onKey', key, evt);
  1128. },
  1129. text: function(text) {
  1130. cursor.parent.bubble('onText', text);
  1131. },
  1132. cut: function(e) {
  1133. if (cursor.selection) {
  1134. setTimeout(function() {
  1135. cursor.prepareEdit();
  1136. cursor.parent.bubble('redraw');
  1137. });
  1138. }
  1139. e.stopPropagation();
  1140. },
  1141. paste: function(text) {
  1142. // FIXME HACK the parser in RootTextBlock needs to be moved to
  1143. // Cursor::writeLatex or something so this'll work with
  1144. // MathQuill textboxes
  1145. if (text.slice(0,1) === '$' && text.slice(-1) === '$') {
  1146. text = text.slice(1, -1);
  1147. }
  1148. else {
  1149. text = '\\text{' + text + '}';
  1150. }
  1151. cursor.writeLatex(text).show();
  1152. }
  1153. });
  1154. jQ.prepend(textareaSpan);
  1155. //root CSS classes
  1156. jQ.addClass('mathquill-editable');
  1157. if (textbox)
  1158. jQ.addClass('mathquill-textbox');
  1159. //focus and blur handling
  1160. textarea.focus(function(e) {
  1161. if (!cursor.parent)
  1162. cursor.insAtRightEnd(root);
  1163. cursor.parent.jQ.addClass('hasCursor');
  1164. if (cursor.selection) {
  1165. cursor.selection.jQ.removeClass('blur');
  1166. setTimeout(root.selectionChanged); //re-select textarea contents after tabbing away and back
  1167. }
  1168. else
  1169. cursor.show();
  1170. e.stopPropagation();
  1171. }).blur(function(e) {
  1172. cursor.hide().parent.blur();
  1173. if (cursor.selection)
  1174. cursor.selection.jQ.addClass('blur');
  1175. e.stopPropagation();
  1176. });
  1177. jQ.bind('focus.mathquill blur.mathquill', function(e) {
  1178. textarea.trigger(e);
  1179. }).blur();
  1180. }
  1181. var RootMathBlock = P(MathBlock, function(_, _super) {
  1182. _.latex = function() {
  1183. return _super.latex.call(this).replace(/(\\[a-z]+) (?![a-z])/ig,'$1');
  1184. };
  1185. _.text = function() {
  1186. return this.foldChildren('', function(text, child) {
  1187. return text + child.text();
  1188. });
  1189. };
  1190. _.renderLatex = function(latex) {
  1191. var jQ = this.jQ;
  1192. jQ.children().slice(1).remove();
  1193. this.ends[L] = this.ends[R] = 0;
  1194. delete this.cursor.selection;
  1195. this.cursor.insAtRightEnd(this).writeLatex(latex);
  1196. };
  1197. _.onKey = function(key, e) {
  1198. switch (key) {
  1199. case 'Ctrl-Shift-Backspace':
  1200. case 'Ctrl-Backspace':
  1201. while (this.cursor[L] || this.cursor.selection) {
  1202. this.cursor.backspace();
  1203. }
  1204. break;
  1205. case 'Shift-Backspace':
  1206. case 'Backspace':
  1207. this.cursor.backspace();
  1208. break;
  1209. // Tab or Esc -> go one block right if it exists, else escape right.
  1210. case 'Esc':
  1211. case 'Tab':
  1212. case 'Spacebar':
  1213. var parent = this.cursor.parent;
  1214. // cursor is in root editable, continue default
  1215. if (parent === this.cursor.root) {
  1216. if (key === 'Spacebar') e.preventDefault();
  1217. return;
  1218. }
  1219. this.cursor.prepareMove();
  1220. if (parent[R]) {
  1221. // go one block right
  1222. this.cursor.insAtLeftEnd(parent[R]);
  1223. } else {
  1224. // get out of the block
  1225. this.cursor.insRightOf(parent.parent);
  1226. }
  1227. break;
  1228. // Shift-Tab -> go one block left if it exists, else escape left.
  1229. case 'Shift-Tab':
  1230. case 'Shift-Esc':
  1231. case 'Shift-Spacebar':
  1232. var parent = this.cursor.parent;
  1233. //cursor is in root editable, continue default
  1234. if (parent === this.cursor.root) {
  1235. if (key === 'Shift-Spacebar') e.preventDefault();
  1236. return;
  1237. }
  1238. this.cursor.prepareMove();
  1239. if (parent[L]) {
  1240. // go one block left
  1241. this.cursor.insAtRightEnd(parent[L]);
  1242. } else {
  1243. //get out of the block
  1244. this.cursor.insLeftOf(parent.parent);
  1245. }
  1246. break;
  1247. // Prevent newlines from showing up
  1248. case 'Enter': break;
  1249. // End -> move to the end of the current block.
  1250. case 'End':
  1251. this.cursor.prepareMove().insAtRightEnd(this.cursor.parent);
  1252. break;
  1253. // Ctrl-End -> move all the way to the end of the root block.
  1254. case 'Ctrl-End':
  1255. this.cursor.prepareMove().insAtRightEnd(this);
  1256. break;
  1257. // Shift-End -> select to the end of the current block.
  1258. case 'Shift-End':
  1259. while (this.cursor[R]) {
  1260. this.cursor.selectRight();
  1261. }
  1262. break;
  1263. // Ctrl-Shift-End -> select to the end of the root block.
  1264. case 'Ctrl-Shift-End':
  1265. while (this.cursor[R] || this.cursor.parent !== this) {
  1266. this.cursor.selectRight();
  1267. }
  1268. break;
  1269. // Home -> move to the start of the root block or the current block.
  1270. case 'Home':
  1271. this.cursor.prepareMove().insAtLeftEnd(this.cursor.parent);
  1272. break;
  1273. // Ctrl-Home -> move to the start of the current block.
  1274. case 'Ctrl-Home':
  1275. this.cursor.prepareMove().insAtLeftEnd(this);
  1276. break;
  1277. // Shift-Home -> select to the start of the current block.
  1278. case 'Shift-Home':
  1279. while (this.cursor[L]) {
  1280. this.cursor.selectLeft();
  1281. }
  1282. break;
  1283. // Ctrl-Shift-Home -> move to the start of the root block.
  1284. case 'Ctrl-Shift-Home':
  1285. while (this.cursor[L] || this.cursor.parent !== this) {
  1286. this.cursor.selectLeft();
  1287. }
  1288. break;
  1289. case 'Left': this.cursor.moveLeft(); break;
  1290. case 'Shift-Left': this.cursor.selectLeft(); break;
  1291. case 'Ctrl-Left': break;
  1292. case 'Right': this.cursor.moveRight(); break;
  1293. case 'Shift-Right': this.cursor.selectRight(); break;
  1294. case 'Ctrl-Right': break;
  1295. case 'Up': this.cursor.moveUp(); break;
  1296. case 'Down': this.cursor.moveDown(); break;
  1297. case 'Shift-Up':
  1298. if (this.cursor[L]) {
  1299. while (this.cursor[L]) this.cursor.selectLeft();
  1300. } else {
  1301. this.cursor.selectLeft();
  1302. }
  1303. case 'Shift-Down':
  1304. if (this.cursor[R]) {
  1305. while (this.cursor[R]) this.cursor.selectRight();
  1306. }
  1307. else {
  1308. this.cursor.selectRight();
  1309. }
  1310. case 'Ctrl-Up': break;
  1311. case 'Ctrl-Down': break;
  1312. case 'Ctrl-Shift-Del':
  1313. case 'Ctrl-Del':
  1314. while (this.cursor[R] || this.cursor.selection) {
  1315. this.cursor.deleteForward();
  1316. }
  1317. break;
  1318. case 'Shift-Del':
  1319. case 'Del':
  1320. this.cursor.deleteForward();
  1321. break;
  1322. case 'Meta-A':
  1323. case 'Ctrl-A':
  1324. //so not stopPropagation'd at RootMathCommand
  1325. if (this !== this.cursor.root) return;
  1326. this.cursor.prepareMove().insAtRightEnd(this);
  1327. while (this.cursor[L]) this.cursor.selectLeft();
  1328. break;
  1329. default:
  1330. return false;
  1331. }
  1332. e.preventDefault();
  1333. return false;
  1334. };
  1335. _.onText = function(ch) {
  1336. this.cursor.write(ch);
  1337. return false;
  1338. };
  1339. });
  1340. var RootMathCommand = P(MathCommand, function(_, _super) {
  1341. _.init = function(cursor) {
  1342. _super.init.call(this, '$');
  1343. this.cursor = cursor;
  1344. };
  1345. _.htmlTemplate = '<span class="mathquill-rendered-math">&0</span>';
  1346. _.createBlocks = function() {
  1347. this.ends[L] =
  1348. this.ends[R] =
  1349. RootMathBlock();
  1350. this.blocks = [ this.ends[L] ];
  1351. this.ends[L].parent = this;
  1352. this.ends[L].cursor = this.cursor;
  1353. this.ends[L].write = function(cursor, ch, replacedFragment) {
  1354. if (ch !== '$')
  1355. MathBlock.prototype.write.call(this, cursor, ch, replacedFragment);
  1356. else if (this.isEmpty()) {
  1357. cursor.insRightOf(this.parent).backspace().show();
  1358. VanillaSymbol('\\$','$').createLeftOf(cursor);
  1359. }
  1360. else if (!cursor[R])
  1361. cursor.insRightOf(this.parent);
  1362. else if (!cursor[L])
  1363. cursor.insLeftOf(this.parent);
  1364. else
  1365. MathBlock.prototype.write.call(this, cursor, ch, replacedFragment);
  1366. };
  1367. };
  1368. _.latex = function() {
  1369. return '$' + this.ends[L].latex() + '$';
  1370. };
  1371. });
  1372. var RootTextBlock = P(MathBlock, function(_) {
  1373. _.renderLatex = function(latex) {
  1374. var self = this;
  1375. var cursor = self.cursor;
  1376. self.jQ.children().slice(1).remove();
  1377. self.ends[L] = self.ends[R] = 0;
  1378. delete cursor.selection;
  1379. cursor.show().insAtRightEnd(self);
  1380. var regex = Parser.regex;
  1381. var string = Parser.string;
  1382. var eof = Parser.eof;
  1383. var all = Parser.all;
  1384. // Parser RootMathCommand
  1385. var mathMode = string('$').then(latexMathParser)
  1386. // because TeX is insane, math mode doesn't necessarily
  1387. // have to end. So we allow for the case that math mode
  1388. // continues to the end of the stream.
  1389. .skip(string('$').or(eof))
  1390. .map(function(block) {
  1391. // HACK FIXME: this shouldn't have to have access to cursor
  1392. var rootMathCommand = RootMathCommand(cursor);
  1393. rootMathCommand.createBlocks();
  1394. var rootMathBlock = rootMathCommand.ends[L];
  1395. block.children().adopt(rootMathBlock, 0, 0);
  1396. return rootMathCommand;
  1397. })
  1398. ;
  1399. var escapedDollar = string('\\$').result('$');
  1400. var textChar = escapedDollar.or(regex(/^[^$]/)).map(VanillaSymbol);
  1401. var latexText = mathMode.or(textChar).many();
  1402. var commands = latexText.skip(eof).or(all.result(false)).parse(latex);
  1403. if (commands) {
  1404. for (var i = 0; i < commands.length; i += 1) {
  1405. commands[i].adopt(self, self.ends[R], 0);
  1406. }
  1407. var html = self.join('html');
  1408. MathElement.jQize(html).appendTo(self.jQ);
  1409. this.finalizeInsert();
  1410. }
  1411. };
  1412. _.onKey = function(key) {
  1413. if (key === 'Spacebar' || key === 'Shift-Spacebar') return;
  1414. RootMathBlock.prototype.onKey.apply(this, arguments);
  1415. };
  1416. _.onText = RootMathBlock.prototype.onText;
  1417. _.write = function(cursor, ch, replacedFragment) {
  1418. if (replacedFragment) replacedFragment.remove();
  1419. if (ch === '$')
  1420. RootMathCommand(cursor).createLeftOf(cursor);
  1421. else {
  1422. var html;
  1423. if (ch === '<') html = '&lt;';
  1424. else if (ch === '>') html = '&gt;';
  1425. VanillaSymbol(ch, html).createLeftOf(cursor);
  1426. }
  1427. };
  1428. });
  1429. /***************************
  1430. * Commands and Operators.
  1431. **************************/
  1432. var CharCmds = {}, LatexCmds = {}; //single character commands, LaTeX commands
  1433. var scale, // = function(jQ, x, y) { ... }
  1434. //will use a CSS 2D transform to scale the jQuery-wrapped HTML elements,
  1435. //or the filter matrix transform fallback for IE 5.5-8, or gracefully degrade to
  1436. //increasing the fontSize to match the vertical Y scaling factor.
  1437. //ideas from http://github.com/louisremi/jquery.transform.js
  1438. //see also http://msdn.microsoft.com/en-us/library/ms533014(v=vs.85).aspx
  1439. forceIERedraw = noop,
  1440. div = document.createElement('div'),
  1441. div_style = div.style,
  1442. transformPropNames = {
  1443. transform:1,
  1444. WebkitTransform:1,
  1445. MozTransform:1,
  1446. OTransform:1,
  1447. msTransform:1
  1448. },
  1449. transformPropName;
  1450. for (var prop in transformPropNames) {
  1451. if (prop in div_style) {
  1452. transformPropName = prop;
  1453. break;
  1454. }
  1455. }
  1456. if (transformPropName) {
  1457. scale = function(jQ, x, y) {
  1458. jQ.css(transformPropName, 'scale('+x+','+y+')');
  1459. };
  1460. }
  1461. else if ('filter' in div_style) { //IE 6, 7, & 8 fallback, see https://github.com/laughinghan/mathquill/wiki/Transforms
  1462. forceIERedraw = function(el){ el.className = el.className; };
  1463. scale = function(jQ, x, y) { //NOTE: assumes y > x
  1464. x /= (1+(y-1)/2);
  1465. jQ.css('fontSize', y + 'em');
  1466. if (!jQ.hasClass('matrixed-container')) {
  1467. jQ.addClass('matrixed-container')
  1468. .wrapInner('<span class="matrixed"></span>');
  1469. }
  1470. var innerjQ = jQ.children()
  1471. .css('filter', 'progid:DXImageTransform.Microsoft'
  1472. + '.Matrix(M11=' + x + ",SizingMethod='auto expand')"
  1473. );
  1474. function calculateMarginRight() {
  1475. jQ.css('marginRight', (innerjQ.width()-1)*(x-1)/x + 'px');
  1476. }
  1477. calculateMarginRight();
  1478. var intervalId = setInterval(calculateMarginRight);
  1479. $(window).load(function() {
  1480. clearTimeout(intervalId);
  1481. calculateMarginRight();
  1482. });
  1483. };
  1484. }
  1485. else {
  1486. scale = function(jQ, x, y) {
  1487. jQ.css('fontSize', y + 'em');
  1488. };
  1489. }
  1490. var Style = P(MathCommand, function(_, _super) {
  1491. _.init = function(ctrlSeq, tagName, attrs) {
  1492. _super.init.call(this, ctrlSeq, '<'+tagName+' '+attrs+'>&0</'+tagName+'>');
  1493. };
  1494. });
  1495. //fonts
  1496. LatexCmds.mathrm = bind(Style, '\\mathrm', 'span', 'class="roman font"');
  1497. LatexCmds.mathit = bind(Style, '\\mathit', 'i', 'class="font"');
  1498. LatexCmds.mathbf = bind(Style, '\\mathbf', 'b', 'class="font"');
  1499. LatexCmds.mathsf = bind(Style, '\\mathsf', 'span', 'class="sans-serif font"');
  1500. LatexCmds.mathtt = bind(Style, '\\mathtt', 'span', 'class="monospace font"');
  1501. //text-decoration
  1502. LatexCmds.underline = bind(Style, '\\underline', 'span', 'class="non-leaf underline"');
  1503. LatexCmds.overline = LatexCmds.bar = bind(Style, '\\overline', 'span', 'class="non-leaf overline"');
  1504. var SupSub = P(MathCommand, function(_, _super) {
  1505. _.init = function(ctrlSeq, tag, text) {
  1506. _super.init.call(this, ctrlSeq, '<'+tag+' class="non-leaf">&0</'+tag+'>', [ text ]);
  1507. };
  1508. _.finalizeTree = function() {
  1509. //TODO: use inheritance
  1510. pray('SupSub is only _ and ^',
  1511. this.ctrlSeq === '^' || this.ctrlSeq === '_'
  1512. );
  1513. if (this.ctrlSeq === '_') {
  1514. this.down = this.ends[L];
  1515. this.ends[L].up = insLeftOfMeUnlessAtEnd;
  1516. }
  1517. else {
  1518. this.up = this.ends[L];
  1519. this.ends[L].down = insLeftOfMeUnlessAtEnd;
  1520. }
  1521. function insLeftOfMeUnlessAtEnd(cursor) {
  1522. // cursor.insLeftOf(cmd), unless cursor at the end of block, and every
  1523. // ancestor cmd is at the end of every ancestor block
  1524. var cmd = this.parent, ancestorCmd = cursor;
  1525. do {
  1526. if (ancestorCmd[R]) {
  1527. cursor.insLeftOf(cmd);
  1528. return false;
  1529. }
  1530. ancestorCmd = ancestorCmd.parent.parent;
  1531. } while (ancestorCmd !== cmd);
  1532. cursor.insRightOf(cmd);
  1533. return false;
  1534. }
  1535. };
  1536. _.latex = function() {
  1537. var latex = this.ends[L].latex();
  1538. if (latex.length === 1)
  1539. return this.ctrlSeq + latex;
  1540. else
  1541. return this.ctrlSeq + '{' + (latex || ' ') + '}';
  1542. };
  1543. _.redraw = function() {
  1544. if (this[L])
  1545. this[L].respace();
  1546. //SupSub::respace recursively calls respace on all the following SupSubs
  1547. //so if leftward is a SupSub, no need to call respace on this or following nodes
  1548. if (!(this[L] instanceof SupSub)) {
  1549. this.respace();
  1550. //and if rightward is a SupSub, then this.respace() will have already called
  1551. //this[R].respace()
  1552. if (this[R] && !(this[R] instanceof SupSub))
  1553. this[R].respace();
  1554. }
  1555. };
  1556. _.respace = function() {
  1557. if (
  1558. this[L].ctrlSeq === '\\int ' || (
  1559. this[L] instanceof SupSub && this[L].ctrlSeq != this.ctrlSeq
  1560. && this[L][L] && this[L][L].ctrlSeq === '\\int '
  1561. )
  1562. ) {
  1563. if (!this.limit) {
  1564. this.limit = true;
  1565. this.jQ.addClass('limit');
  1566. }
  1567. }
  1568. else {
  1569. if (this.limit) {
  1570. this.limit = false;
  1571. this.jQ.removeClass('limit');
  1572. }
  1573. }
  1574. this.respaced = this[L] instanceof SupSub && this[L].ctrlSeq != this.ctrlSeq && !this[L].respaced;
  1575. if (this.respaced) {
  1576. var fontSize = +this.jQ.css('fontSize').slice(0,-2),
  1577. leftWidth = this[L].jQ.outerWidth(),
  1578. thisWidth = this.jQ.outerWidth();
  1579. this.jQ.css({
  1580. left: (this.limit && this.ctrlSeq === '_' ? -.25 : 0) - leftWidth/fontSize + 'em',
  1581. marginRight: .1 - min(thisWidth, leftWidth)/fontSize + 'em'
  1582. //1px extra so it doesn't wrap in retarded browsers (Firefox 2, I think)
  1583. });
  1584. }
  1585. else if (this.limit && this.ctrlSeq === '_') {
  1586. this.jQ.css({
  1587. left: '-.25em',
  1588. marginRight: ''
  1589. });
  1590. }
  1591. else {
  1592. this.jQ.css({
  1593. left: '',
  1594. marginRight: ''
  1595. });
  1596. }
  1597. if (this[R] instanceof SupSub)
  1598. this[R].respace();
  1599. return this;
  1600. };
  1601. });
  1602. LatexCmds.subscript =
  1603. LatexCmds._ = bind(SupSub, '_', 'sub', '_');
  1604. LatexCmds.superscript =
  1605. LatexCmds.supscript =
  1606. LatexCmds['^'] = bind(SupSub, '^', 'sup', '**');
  1607. var Fraction =
  1608. LatexCmds.frac =
  1609. LatexCmds.dfrac =
  1610. LatexCmds.cfrac =
  1611. LatexCmds.fraction = P(MathCommand, function(_, _super) {
  1612. _.ctrlSeq = '\\frac';
  1613. _.htmlTemplate =
  1614. '<span class="fraction non-leaf">'
  1615. + '<span class="numerator">&0</span>'
  1616. + '<span class="denominator">&1</span>'
  1617. + '<span style="display:inline-block;width:0">&nbsp;</span>'
  1618. + '</span>'
  1619. ;
  1620. _.textTemplate = ['(', '/', ')'];
  1621. _.finalizeTree = function() {
  1622. this.up = this.ends[R].up = this.ends[L];
  1623. this.down = this.ends[L].down = this.ends[R];
  1624. };
  1625. });
  1626. var LiveFraction =
  1627. LatexCmds.over =
  1628. CharCmds['/'] = P(Fraction, function(_, _super) {
  1629. _.createLeftOf = function(cursor) {
  1630. if (!this.replacedFragment) {
  1631. var leftward = cursor[L];
  1632. while (leftward &&
  1633. !(
  1634. leftward instanceof BinaryOperator ||
  1635. leftward instanceof TextBlock ||
  1636. leftward instanceof BigSymbol ||
  1637. ',;:'.split('').indexOf(leftward.ctrlSeq) > -1
  1638. ) //lookbehind for operator
  1639. )
  1640. leftward = leftward[L];
  1641. if (leftward instanceof BigSymbol && leftward[R] instanceof SupSub) {
  1642. leftward = leftward[R];
  1643. if (leftward[R] instanceof SupSub && leftward[R].ctrlSeq != leftward.ctrlSeq)
  1644. leftward = leftward[R];
  1645. }
  1646. if (leftward !== cursor[L]) {
  1647. this.replaces(MathFragment(leftward[R] || cursor.parent.ends[L], cursor[L]));
  1648. cursor[L] = leftward;
  1649. }
  1650. }
  1651. _super.createLeftOf.call(this, cursor);
  1652. };
  1653. });
  1654. var SquareRoot =
  1655. LatexCmds.sqrt =
  1656. LatexCmds['√'] = P(MathCommand, function(_, _super) {
  1657. _.ctrlSeq = '\\sqrt';
  1658. _.htmlTemplate =
  1659. '<span class="non-leaf">'
  1660. + '<span class="scaled sqrt-prefix">&radic;</span>'
  1661. + '<span class="non-leaf sqrt-stem">&0</span>'
  1662. + '</span>'
  1663. ;
  1664. _.textTemplate = ['sqrt(', ')'];
  1665. _.parser = function() {
  1666. return latexMathParser.optBlock.then(function(optBlock) {
  1667. return latexMathParser.block.map(function(block) {
  1668. var nthroot = NthRoot();
  1669. nthroot.blocks = [ optBlock, block ];
  1670. optBlock.adopt(nthroot, 0, 0);
  1671. block.adopt(nthroot, optBlock, 0);
  1672. return nthroot;
  1673. });
  1674. }).or(_super.parser.call(this));
  1675. };
  1676. _.redraw = function() {
  1677. var block = this.ends[R].jQ;
  1678. scale(block.prev(), 1, block.innerHeight()/+block.css('fontSize').slice(0,-2) - .1);
  1679. };
  1680. });
  1681. var Vec = LatexCmds.vec = P(MathCommand, function(_, _super) {
  1682. _.ctrlSeq = '\\vec';
  1683. _.htmlTemplate =
  1684. '<span class="non-leaf">'
  1685. + '<span class="vector-prefix">&rarr;</span>'
  1686. + '<span class="vector-stem">&0</span>'
  1687. + '</span>'
  1688. ;
  1689. _.textTemplate = ['vec(', ')'];
  1690. });
  1691. var NthRoot =
  1692. LatexCmds.nthroot = P(SquareRoot, function(_, _super) {
  1693. _.htmlTemplate =
  1694. '<sup class="nthroot non-leaf">&0</sup>'
  1695. + '<span class="scaled">'
  1696. + '<span class="sqrt-prefix scaled">&radic;</span>'
  1697. + '<span class="sqrt-stem non-leaf">&1</span>'
  1698. + '</span>'
  1699. ;
  1700. _.textTemplate = ['sqrt[', '](', ')'];
  1701. _.latex = function() {
  1702. return '\\sqrt['+this.ends[L].latex()+']{'+this.ends[R].latex()+'}';
  1703. };
  1704. });
  1705. // Round/Square/Curly/Angle Brackets (aka Parens/Brackets/Braces)
  1706. var Bracket = P(MathCommand, function(_, _super) {
  1707. _.init = function(open, close, ctrlSeq, end) {
  1708. _super.init.call(this, '\\left'+ctrlSeq,
  1709. '<span class="non-leaf">'
  1710. + '<span class="scaled paren">'+open+'</span>'
  1711. + '<span class="non-leaf">&0</span>'
  1712. + '<span class="scaled paren">'+close+'</span>'
  1713. + '</span>',
  1714. [open, close]);
  1715. this.end = '\\right'+end;
  1716. };
  1717. _.jQadd = function() {
  1718. _super.jQadd.apply(this, arguments);
  1719. var jQ = this.jQ;
  1720. this.bracketjQs = jQ.children(':first').add(jQ.children(':last'));
  1721. };
  1722. _.latex = function() {
  1723. return this.ctrlSeq + this.ends[L].latex() + this.end;
  1724. };
  1725. _.redraw = function() {
  1726. var blockjQ = this.ends[L].jQ;
  1727. var height = blockjQ.outerHeight()/+blockjQ.css('fontSize').slice(0,-2);
  1728. scale(this.bracketjQs, min(1 + .2*(height - 1), 1.2), 1.05*height);
  1729. };
  1730. });
  1731. LatexCmds.left = P(MathCommand, function(_) {
  1732. _.parser = function() {
  1733. var regex = Parser.regex;
  1734. var string = Parser.string;
  1735. var succeed = Parser.succeed;
  1736. var optWhitespace = Parser.optWhitespace;
  1737. return optWhitespace.then(regex(/^(?:[([|]|\\\{)/))
  1738. .then(function(open) {
  1739. if (open.charAt(0) === '\\') open = open.slice(1);
  1740. var cmd = CharCmds[open]();
  1741. return latexMathParser
  1742. .map(function (block) {
  1743. cmd.blocks = [ block ];
  1744. block.adopt(cmd, 0, 0);
  1745. })
  1746. .then(string('\\right'))
  1747. .skip(optWhitespace)
  1748. .then(regex(/^(?:[\])|]|\\\})/))
  1749. .then(function(close) {
  1750. if (close.slice(-1) !== cmd.end.slice(-1)) {
  1751. return Parser.fail('open doesn\'t match close');
  1752. }
  1753. return succeed(cmd);
  1754. })
  1755. ;
  1756. })
  1757. ;
  1758. };
  1759. });
  1760. LatexCmds.right = P(MathCommand, function(_) {
  1761. _.parser = function() {
  1762. return Parser.fail('unmatched \\right');
  1763. };
  1764. });
  1765. LatexCmds.lbrace =
  1766. CharCmds['{'] = bind(Bracket, '{', '}', '\\{', '\\}');
  1767. LatexCmds.langle =
  1768. LatexCmds.lang = bind(Bracket, '&lang;','&rang;','\\langle ','\\rangle ');
  1769. // Closing bracket matching opening bracket above
  1770. var CloseBracket = P(Bracket, function(_, _super) {
  1771. _.createLeftOf = function(cursor) {
  1772. // if I'm at the end of my parent who is a matching open-paren,
  1773. // and I am not replacing a selection fragment, don't create me,
  1774. // just put cursor after my parent
  1775. if (!cursor[R] && cursor.parent.parent && cursor.parent.parent.end === this.end && !this.replacedFragment)
  1776. cursor.insRightOf(cursor.parent.parent);
  1777. else
  1778. _super.createLeftOf.call(this, cursor);
  1779. };
  1780. _.placeCursor = function(cursor) {
  1781. this.ends[L].blur();
  1782. cursor.insRightOf(this);
  1783. };
  1784. });
  1785. LatexCmds.rbrace =
  1786. CharCmds['}'] = bind(CloseBracket, '{','}','\\{','\\}');
  1787. LatexCmds.rangle =
  1788. LatexCmds.rang = bind(CloseBracket, '&lang;','&rang;','\\langle ','\\rangle ');
  1789. var parenMixin = function(_, _super) {
  1790. _.init = function(open, close) {
  1791. _super.init.call(this, open, close, open, close);
  1792. };
  1793. };
  1794. var Paren = P(Bracket, parenMixin);
  1795. LatexCmds.lparen =
  1796. CharCmds['('] = bind(Paren, '(', ')');
  1797. LatexCmds.lbrack =
  1798. LatexCmds.lbracket =
  1799. CharCmds['['] = bind(Paren, '[', ']');
  1800. var CloseParen = P(CloseBracket, parenMixin);
  1801. LatexCmds.rparen =
  1802. CharCmds[')'] = bind(CloseParen, '(', ')');
  1803. LatexCmds.rbrack =
  1804. LatexCmds.rbracket =
  1805. CharCmds[']'] = bind(CloseParen, '[', ']');
  1806. var Pipes =
  1807. LatexCmds.lpipe =
  1808. LatexCmds.rpipe =
  1809. CharCmds['|'] = P(Paren, function(_, _super) {
  1810. _.init = function() {
  1811. _super.init.call(this, '|', '|');
  1812. };
  1813. _.createLeftOf = CloseBracket.prototype.createLeftOf;
  1814. });
  1815. var TextBlock =
  1816. CharCmds.$ =
  1817. LatexCmds.text =
  1818. LatexCmds.textnormal =
  1819. LatexCmds.textrm =
  1820. LatexCmds.textup =
  1821. LatexCmds.textmd = P(MathCommand, function(_, _super) {
  1822. _.ctrlSeq = '\\text';
  1823. _.htmlTemplate = '<span class="text">&0</span>';
  1824. _.replaces = function(replacedText) {
  1825. if (replacedText instanceof MathFragment)
  1826. this.replacedText = replacedText.remove().jQ.text();
  1827. else if (typeof replacedText === 'string')
  1828. this.replacedText = replacedText;
  1829. };
  1830. _.textTemplate = ['"', '"'];
  1831. _.parser = function() {
  1832. var self = this;
  1833. // TODO: correctly parse text mode
  1834. var string = Parser.string;
  1835. var regex = Parser.regex;
  1836. var optWhitespace = Parser.optWhitespace;
  1837. return optWhitespace
  1838. .then(string('{')).then(regex(/^[^}]*/)).skip(string('}'))
  1839. .map(function(text) {
  1840. self.createBlocks();
  1841. var block = self.ends[L];
  1842. for (var i = 0; i < text.length; i += 1) {
  1843. var ch = VanillaSymbol(text.charAt(i));
  1844. ch.adopt(block, block.ends[R], 0);
  1845. }
  1846. return self;
  1847. })
  1848. ;
  1849. };
  1850. _.createBlocks = function() {
  1851. //FIXME: another possible Law of Demeter violation, but this seems much cleaner, like it was supposed to be done this way
  1852. this.ends[L] =
  1853. this.ends[R] =
  1854. InnerTextBlock();
  1855. this.blocks = [ this.ends[L] ];
  1856. this.ends[L].parent = this;
  1857. };
  1858. _.finalizeInsert = function() {
  1859. //FIXME HACK blur removes the TextBlock
  1860. this.ends[L].blur = function() { delete this.blur; return this; };
  1861. _super.finalizeInsert.call(this);
  1862. };
  1863. _.createLeftOf = function(cursor) {
  1864. _super.createLeftOf.call(this, this.cursor = cursor);
  1865. if (this.replacedText)
  1866. for (var i = 0; i < this.replacedText.length; i += 1)
  1867. this.ends[L].write(cursor, this.replacedText.charAt(i));
  1868. };
  1869. });
  1870. var InnerTextBlock = P(MathBlock, function(_, _super) {
  1871. _.onKey = function(key, e) {
  1872. if (key === 'Spacebar' || key === 'Shift-Spacebar') return false;
  1873. };
  1874. // backspace and delete at ends of block don't unwrap
  1875. _.deleteOutOf = function(dir, cursor) {
  1876. if (this.isEmpty()) cursor.insRightOf(this.parent);
  1877. };
  1878. _.write = function(cursor, ch, replacedFragment) {
  1879. if (replacedFragment) replacedFragment.remove();
  1880. if (ch !== '$') {
  1881. var html;
  1882. if (ch === '<') html = '&lt;';
  1883. else if (ch === '>') html = '&gt;';
  1884. VanillaSymbol(ch, html).createLeftOf(cursor);
  1885. }
  1886. else if (this.isEmpty()) {
  1887. cursor.insRightOf(this.parent).backspace();
  1888. VanillaSymbol('\\$','$').createLeftOf(cursor);
  1889. }
  1890. else if (!cursor[R])
  1891. cursor.insRightOf(this.parent);
  1892. else if (!cursor[L])
  1893. cursor.insLeftOf(this.parent);
  1894. else { //split apart
  1895. var rightward = TextBlock();
  1896. rightward.replaces(MathFragment(cursor[R], this.ends[R]));
  1897. cursor.insRightOf(this.parent);
  1898. // FIXME HACK: pretend no prev so they don't get merged when
  1899. // .createLeftOf() calls blur on the InnerTextBlock
  1900. rightward.adopt = function() {
  1901. delete this.adopt;
  1902. this.adopt.apply(this, arguments);
  1903. this[L] = 0;
  1904. };
  1905. rightward.createLeftOf(cursor);
  1906. rightward[L] = this.parent;
  1907. cursor.insLeftOf(rightward);
  1908. }
  1909. return false;
  1910. };
  1911. _.blur = function() {
  1912. this.jQ.removeClass('hasCursor');
  1913. if (this.isEmpty()) {
  1914. var textblock = this.parent, cursor = textblock.cursor;
  1915. if (cursor.parent === this)
  1916. this.jQ.addClass('empty');
  1917. else {
  1918. cursor.hide();
  1919. textblock.remove();
  1920. if (cursor[R] === textblock)
  1921. cursor[R] = textblock[R];
  1922. else if (cursor[L] === textblock)
  1923. cursor[L] = textblock[L];
  1924. cursor.show().parent.bubble('redraw');
  1925. }
  1926. }
  1927. return this;
  1928. };
  1929. _.focus = function() {
  1930. _super.focus.call(this);
  1931. var textblock = this.parent;
  1932. if (textblock[R].ctrlSeq === textblock.ctrlSeq) { //TODO: seems like there should be a better way to move MathElements around
  1933. var innerblock = this,
  1934. cursor = textblock.cursor,
  1935. rightward = textblock[R].ends[L];
  1936. rightward.eachChild(function(child){
  1937. child.parent = innerblock;
  1938. child.jQ.appendTo(innerblock.jQ);
  1939. });
  1940. if (this.ends[R])
  1941. this.ends[R][R] = rightward.ends[L];
  1942. else
  1943. this.ends[L] = rightward.ends[L];
  1944. rightward.ends[L][L] = this.ends[R];
  1945. this.ends[R] = rightward.ends[R];
  1946. rightward.parent.remove();
  1947. if (cursor[L])
  1948. cursor.insRightOf(cursor[L]);
  1949. else
  1950. cursor.insAtLeftEnd(this);
  1951. cursor.parent.bubble('redraw');
  1952. }
  1953. else if (textblock[L].ctrlSeq === textblock.ctrlSeq) {
  1954. var cursor = textblock.cursor;
  1955. if (cursor[L])
  1956. textblock[L].ends[L].focus();
  1957. else
  1958. cursor.insAtRightEnd(textblock[L].ends[L]);
  1959. }
  1960. return this;
  1961. };
  1962. });
  1963. function makeTextBlock(latex, tagName, attrs) {
  1964. return P(TextBlock, {
  1965. ctrlSeq: latex,
  1966. htmlTemplate: '<'+tagName+' '+attrs+'>&0</'+tagName+'>'
  1967. });
  1968. }
  1969. LatexCmds.em = LatexCmds.italic = LatexCmds.italics =
  1970. LatexCmds.emph = LatexCmds.textit = LatexCmds.textsl =
  1971. makeTextBlock('\\textit', 'i', 'class="text"');
  1972. LatexCmds.strong = LatexCmds.bold = LatexCmds.textbf =
  1973. makeTextBlock('\\textbf', 'b', 'class="text"');
  1974. LatexCmds.sf = LatexCmds.textsf =
  1975. makeTextBlock('\\textsf', 'span', 'class="sans-serif text"');
  1976. LatexCmds.tt = LatexCmds.texttt =
  1977. makeTextBlock('\\texttt', 'span', 'class="monospace text"');
  1978. LatexCmds.textsc =
  1979. makeTextBlock('\\textsc', 'span', 'style="font-variant:small-caps" class="text"');
  1980. LatexCmds.uppercase =
  1981. makeTextBlock('\\uppercase', 'span', 'style="text-transform:uppercase" class="text"');
  1982. LatexCmds.lowercase =
  1983. makeTextBlock('\\lowercase', 'span', 'style="text-transform:lowercase" class="text"');
  1984. // input box to type a variety of LaTeX commands beginning with a backslash
  1985. var LatexCommandInput =
  1986. CharCmds['\\'] = P(MathCommand, function(_, _super) {
  1987. _.ctrlSeq = '\\';
  1988. _.replaces = function(replacedFragment) {
  1989. this._replacedFragment = replacedFragment.disown();
  1990. this.isEmpty = function() { return false; };
  1991. };
  1992. _.htmlTemplate = '<span class="latex-command-input non-leaf">\\<span>&0</span></span>';
  1993. _.textTemplate = ['\\'];
  1994. _.createBlocks = function() {
  1995. _super.createBlocks.call(this);
  1996. this.ends[L].focus = function() {
  1997. this.parent.jQ.addClass('hasCursor');
  1998. if (this.isEmpty())
  1999. this.parent.jQ.removeClass('empty');
  2000. return this;
  2001. };
  2002. this.ends[L].blur = function() {
  2003. this.parent.jQ.removeClass('hasCursor');
  2004. if (this.isEmpty())
  2005. this.parent.jQ.addClass('empty');
  2006. return this;
  2007. };
  2008. };
  2009. _.createLeftOf = function(cursor) {
  2010. _super.createLeftOf.call(this, cursor);
  2011. this.cursor = cursor.insAtRightEnd(this.ends[L]);
  2012. if (this._replacedFragment) {
  2013. var el = this.jQ[0];
  2014. this.jQ =
  2015. this._replacedFragment.jQ.addClass('blur').bind(
  2016. 'mousedown mousemove', //FIXME: is monkey-patching the mousedown and mousemove handlers the right way to do this?
  2017. function(e) {
  2018. $(e.target = el).trigger(e);
  2019. return false;
  2020. }
  2021. ).insertBefore(this.jQ).add(this.jQ);
  2022. }
  2023. this.ends[L].write = function(cursor, ch, replacedFragment) {
  2024. if (replacedFragment) replacedFragment.remove();
  2025. if (ch.match(/[a-z]/i)) VanillaSymbol(ch).createLeftOf(cursor);
  2026. else {
  2027. this.parent.renderCommand();
  2028. if (ch !== '\\' || !this.isEmpty()) this.parent.parent.write(cursor, ch);
  2029. }
  2030. };
  2031. };
  2032. _.latex = function() {
  2033. return '\\' + this.ends[L].latex() + ' ';
  2034. };
  2035. _.onKey = function(key, e) {
  2036. if (key === 'Tab' || key === 'Enter' || key === 'Spacebar') {
  2037. this.renderCommand();
  2038. e.preventDefault();
  2039. return false;
  2040. }
  2041. };
  2042. _.renderCommand = function() {
  2043. this.jQ = this.jQ.last();
  2044. this.remove();
  2045. if (this[R]) {
  2046. this.cursor.insLeftOf(this[R]);
  2047. } else {
  2048. this.cursor.insAtRightEnd(this.parent);
  2049. }
  2050. var latex = this.ends[L].latex(), cmd;
  2051. if (!latex) latex = 'backslash';
  2052. this.cursor.insertCmd(latex, this._replacedFragment);
  2053. };
  2054. });
  2055. var Binomial =
  2056. LatexCmds.binom =
  2057. LatexCmds.binomial = P(MathCommand, function(_, _super) {
  2058. _.ctrlSeq = '\\binom';
  2059. _.htmlTemplate =
  2060. '<span class="paren scaled">(</span>'
  2061. + '<span class="non-leaf">'
  2062. + '<span class="array non-leaf">'
  2063. + '<span>&0</span>'
  2064. + '<span>&1</span>'
  2065. + '</span>'
  2066. + '</span>'
  2067. + '<span class="paren scaled">)</span>'
  2068. ;
  2069. _.textTemplate = ['choose(',',',')'];
  2070. _.redraw = function() {
  2071. var blockjQ = this.jQ.eq(1);
  2072. var height = blockjQ.outerHeight()/+blockjQ.css('fontSize').slice(0,-2);
  2073. var parens = this.jQ.filter('.paren');
  2074. scale(parens, min(1 + .2*(height - 1), 1.2), 1.05*height);
  2075. };
  2076. });
  2077. var Choose =
  2078. LatexCmds.choose = P(Binomial, function(_) {
  2079. _.createLeftOf = LiveFraction.prototype.createLeftOf;
  2080. });
  2081. var Vector =
  2082. LatexCmds.vector = P(MathCommand, function(_, _super) {
  2083. _.ctrlSeq = '\\vector';
  2084. _.htmlTemplate = '<span class="array"><span>&0</span></span>';
  2085. _.latex = function() {
  2086. return '\\begin{matrix}' + this.foldChildren([], function(latex, child) {
  2087. latex.push(child.latex());
  2088. return latex;
  2089. }).join('\\\\') + '\\end{matrix}';
  2090. };
  2091. _.text = function() {
  2092. return '[' + this.foldChildren([], function(text, child) {
  2093. text.push(child.text());
  2094. return text;
  2095. }).join() + ']';
  2096. };
  2097. _.createLeftOf = function(cursor) {
  2098. _super.createLeftOf.call(this, this.cursor = cursor);
  2099. };
  2100. _.onKey = function(key, e) {
  2101. var currentBlock = this.cursor.parent;
  2102. if (currentBlock.parent === this) {
  2103. if (key === 'Enter') { //enter
  2104. var newBlock = MathBlock();
  2105. newBlock.parent = this;
  2106. newBlock.jQ = $('<span></span>')
  2107. .attr(mqBlockId, newBlock.id)
  2108. .insertAfter(currentBlock.jQ);
  2109. if (currentBlock[R])
  2110. currentBlock[R][L] = newBlock;
  2111. else
  2112. this.ends[R] = newBlock;
  2113. newBlock[R] = currentBlock[R];
  2114. currentBlock[R] = newBlock;
  2115. newBlock[L] = currentBlock;
  2116. this.bubble('redraw').cursor.insAtRightEnd(newBlock);
  2117. e.preventDefault();
  2118. return false;
  2119. }
  2120. else if (key === 'Tab' && !currentBlock[R]) {
  2121. if (currentBlock.isEmpty()) {
  2122. if (currentBlock[L]) {
  2123. this.cursor.insRightOf(this);
  2124. delete currentBlock[L][R];
  2125. this.ends[R] = currentBlock[L];
  2126. currentBlock.jQ.remove();
  2127. this.bubble('redraw');
  2128. e.preventDefault();
  2129. return false;
  2130. }
  2131. else
  2132. return;
  2133. }
  2134. var newBlock = MathBlock();
  2135. newBlock.parent = this;
  2136. newBlock.jQ = $('<span></span>').attr(mqBlockId, newBlock.id).appendTo(this.jQ);
  2137. this.ends[R] = newBlock;
  2138. currentBlock[R] = newBlock;
  2139. newBlock[L] = currentBlock;
  2140. this.bubble('redraw').cursor.insAtRightEnd(newBlock);
  2141. e.preventDefault();
  2142. return false;
  2143. }
  2144. else if (e.which === 8) { //backspace
  2145. if (currentBlock.isEmpty()) {
  2146. if (currentBlock[L]) {
  2147. this.cursor.insAtRightEnd(currentBlock[L])
  2148. currentBlock[L][R] = currentBlock[R];
  2149. }
  2150. else {
  2151. this.cursor.insLeftOf(this);
  2152. this.ends[L] = currentBlock[R];
  2153. }
  2154. if (currentBlock[R])
  2155. currentBlock[R][L] = currentBlock[L];
  2156. else
  2157. this.ends[R] = currentBlock[L];
  2158. currentBlock.jQ.remove();
  2159. if (this.isEmpty())
  2160. this.cursor.deleteForward();
  2161. else
  2162. this.bubble('redraw');
  2163. e.preventDefault();
  2164. return false;
  2165. }
  2166. else if (!this.cursor[L]) {
  2167. e.preventDefault();
  2168. return false;
  2169. }
  2170. }
  2171. }
  2172. };
  2173. });
  2174. LatexCmds.editable = P(RootMathCommand, function(_, _super) {
  2175. _.init = function() {
  2176. MathCommand.prototype.init.call(this, '\\editable');
  2177. };
  2178. _.jQadd = function() {
  2179. var self = this;
  2180. // FIXME: this entire method is a giant hack to get around
  2181. // having to call createBlocks, and createRoot expecting to
  2182. // render the contents' LaTeX. Both need to be refactored.
  2183. _super.jQadd.apply(self, arguments);
  2184. var block = self.ends[L].disown();
  2185. var blockjQ = self.jQ.children().detach();
  2186. self.ends[L] =
  2187. self.ends[R] =
  2188. RootMathBlock();
  2189. self.blocks = [ self.ends[L] ];
  2190. self.ends[L].parent = self;
  2191. createRoot(self.jQ, self.ends[L], false, true);
  2192. self.cursor = self.ends[L].cursor;
  2193. block.children().adopt(self.ends[L], 0, 0);
  2194. blockjQ.appendTo(self.ends[L].jQ);
  2195. self.ends[L].cursor.insAtRightEnd(self.ends[L]);
  2196. };
  2197. _.latex = function(){ return this.ends[L].latex(); };
  2198. _.text = function(){ return this.ends[L].text(); };
  2199. });
  2200. /**********************************
  2201. * Symbols and Special Characters
  2202. *********************************/
  2203. LatexCmds.f = bind(Symbol, 'f', '<var class="florin">&fnof;</var><span style="display:inline-block;width:0">&nbsp;</span>');
  2204. var Variable = P(Symbol, function(_, _super) {
  2205. _.init = function(ch, html) {
  2206. _super.init.call(this, ch, '<var>'+(html || ch)+'</var>');
  2207. };
  2208. _.text = function() {
  2209. var text = this.ctrlSeq;
  2210. if (this[L] && !(this[L] instanceof Variable)
  2211. && !(this[L] instanceof BinaryOperator))
  2212. text = '*' + text;
  2213. if (this[R] && !(this[R] instanceof BinaryOperator)
  2214. && !(this[R].ctrlSeq === '^'))
  2215. text += '*';
  2216. return text;
  2217. };
  2218. });
  2219. var VanillaSymbol = P(Symbol, function(_, _super) {
  2220. _.init = function(ch, html) {
  2221. _super.init.call(this, ch, '<span>'+(html || ch)+'</span>');
  2222. };
  2223. });
  2224. CharCmds[' '] = bind(VanillaSymbol, '\\:', ' ');
  2225. LatexCmds.prime = CharCmds["'"] = bind(VanillaSymbol, "'", '&prime;');
  2226. // does not use Symbola font
  2227. var NonSymbolaSymbol = P(Symbol, function(_, _super) {
  2228. _.init = function(ch, html) {
  2229. _super.init.call(this, ch, '<span class="nonSymbola">'+(html || ch)+'</span>');
  2230. };
  2231. });
  2232. LatexCmds['@'] = NonSymbolaSymbol;
  2233. LatexCmds['&'] = bind(NonSymbolaSymbol, '\\&', '&amp;');
  2234. LatexCmds['%'] = bind(NonSymbolaSymbol, '\\%', '%');
  2235. //the following are all Greek to me, but this helped a lot: http://www.ams.org/STIX/ion/stixsig03.html
  2236. //lowercase Greek letter variables
  2237. LatexCmds.alpha =
  2238. LatexCmds.beta =
  2239. LatexCmds.gamma =
  2240. LatexCmds.delta =
  2241. LatexCmds.zeta =
  2242. LatexCmds.eta =
  2243. LatexCmds.theta =
  2244. LatexCmds.iota =
  2245. LatexCmds.kappa =
  2246. LatexCmds.mu =
  2247. LatexCmds.nu =
  2248. LatexCmds.xi =
  2249. LatexCmds.rho =
  2250. LatexCmds.sigma =
  2251. LatexCmds.tau =
  2252. LatexCmds.chi =
  2253. LatexCmds.psi =
  2254. LatexCmds.omega = P(Variable, function(_, _super) {
  2255. _.init = function(latex) {
  2256. _super.init.call(this,'\\'+latex+' ','&'+latex+';');
  2257. };
  2258. });
  2259. //why can't anybody FUCKING agree on these
  2260. LatexCmds.phi = //W3C or Unicode?
  2261. bind(Variable,'\\phi ','&#981;');
  2262. LatexCmds.phiv = //Elsevier and 9573-13
  2263. LatexCmds.varphi = //AMS and LaTeX
  2264. bind(Variable,'\\varphi ','&phi;');
  2265. LatexCmds.epsilon = //W3C or Unicode?
  2266. bind(Variable,'\\epsilon ','&#1013;');
  2267. LatexCmds.epsiv = //Elsevier and 9573-13
  2268. LatexCmds.varepsilon = //AMS and LaTeX
  2269. bind(Variable,'\\varepsilon ','&epsilon;');
  2270. LatexCmds.piv = //W3C/Unicode and Elsevier and 9573-13
  2271. LatexCmds.varpi = //AMS and LaTeX
  2272. bind(Variable,'\\varpi ','&piv;');
  2273. LatexCmds.sigmaf = //W3C/Unicode
  2274. LatexCmds.sigmav = //Elsevier
  2275. LatexCmds.varsigma = //LaTeX
  2276. bind(Variable,'\\varsigma ','&sigmaf;');
  2277. LatexCmds.thetav = //Elsevier and 9573-13
  2278. LatexCmds.vartheta = //AMS and LaTeX
  2279. LatexCmds.thetasym = //W3C/Unicode
  2280. bind(Variable,'\\vartheta ','&thetasym;');
  2281. LatexCmds.upsilon = //AMS and LaTeX and W3C/Unicode
  2282. LatexCmds.upsi = //Elsevier and 9573-13
  2283. bind(Variable,'\\upsilon ','&upsilon;');
  2284. //these aren't even mentioned in the HTML character entity references
  2285. LatexCmds.gammad = //Elsevier
  2286. LatexCmds.Gammad = //9573-13 -- WTF, right? I dunno if this was a typo in the reference (see above)
  2287. LatexCmds.digamma = //LaTeX
  2288. bind(Variable,'\\digamma ','&#989;');
  2289. LatexCmds.kappav = //Elsevier
  2290. LatexCmds.varkappa = //AMS and LaTeX
  2291. bind(Variable,'\\varkappa ','&#1008;');
  2292. LatexCmds.rhov = //Elsevier and 9573-13
  2293. LatexCmds.varrho = //AMS and LaTeX
  2294. bind(Variable,'\\varrho ','&#1009;');
  2295. //Greek constants, look best in un-italicised Times New Roman
  2296. LatexCmds.pi = LatexCmds['π'] = bind(NonSymbolaSymbol,'\\pi ','&pi;');
  2297. LatexCmds.lambda = bind(NonSymbolaSymbol,'\\lambda ','&lambda;');
  2298. //uppercase greek letters
  2299. LatexCmds.Upsilon = //LaTeX
  2300. LatexCmds.Upsi = //Elsevier and 9573-13
  2301. LatexCmds.upsih = //W3C/Unicode "upsilon with hook"
  2302. LatexCmds.Upsih = //'cos it makes sense to me
  2303. bind(Symbol,'\\Upsilon ','<var style="font-family: serif">&upsih;</var>'); //Symbola's 'upsilon with a hook' is a capital Y without hooks :(
  2304. //other symbols with the same LaTeX command and HTML character entity reference
  2305. LatexCmds.Gamma =
  2306. LatexCmds.Delta =
  2307. LatexCmds.Theta =
  2308. LatexCmds.Lambda =
  2309. LatexCmds.Xi =
  2310. LatexCmds.Pi =
  2311. LatexCmds.Sigma =
  2312. LatexCmds.Phi =
  2313. LatexCmds.Psi =
  2314. LatexCmds.Omega =
  2315. LatexCmds.forall = P(VanillaSymbol, function(_, _super) {
  2316. _.init = function(latex) {
  2317. _super.init.call(this,'\\'+latex+' ','&'+latex+';');
  2318. };
  2319. });
  2320. // symbols that aren't a single MathCommand, but are instead a whole
  2321. // Fragment. Creates the Fragment from a LaTeX string
  2322. var LatexFragment = P(MathCommand, function(_) {
  2323. _.init = function(latex) { this.latex = latex; };
  2324. _.createLeftOf = function(cursor) { cursor.writeLatex(this.latex); };
  2325. _.parser = function() {
  2326. var frag = latexMathParser.parse(this.latex).children();
  2327. return Parser.succeed(frag);
  2328. };
  2329. });
  2330. // for what seems to me like [stupid reasons][1], Unicode provides
  2331. // subscripted and superscripted versions of all ten Arabic numerals,
  2332. // as well as [so-called "vulgar fractions"][2].
  2333. // Nobody really cares about most of them, but some of them actually
  2334. // predate Unicode, dating back to [ISO-8859-1][3], apparently also
  2335. // known as "Latin-1", which among other things [Windows-1252][4]
  2336. // largely coincides with, so Microsoft Word sometimes inserts them
  2337. // and they get copy-pasted into MathQuill.
  2338. //
  2339. // (Irrelevant but funny story: Windows-1252 is actually a strict
  2340. // superset of the "closely related but distinct"[3] "ISO 8859-1" --
  2341. // see the lack of a dash after "ISO"? Completely different character
  2342. // set, like elephants vs elephant seals, or "Zombies" vs "Zombie
  2343. // Redneck Torture Family". What kind of idiot would get them confused.
  2344. // People in fact got them confused so much, it was so common to
  2345. // mislabel Windows-1252 text as ISO-8859-1, that most modern web
  2346. // browsers and email clients treat the MIME charset of ISO-8859-1
  2347. // as actually Windows-1252, behavior now standard in the HTML5 spec.)
  2348. //
  2349. // [1]: http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts
  2350. // [2]: http://en.wikipedia.org/wiki/Number_Forms
  2351. // [3]: http://en.wikipedia.org/wiki/ISO/IEC_8859-1
  2352. // [4]: http://en.wikipedia.org/wiki/Windows-1252
  2353. LatexCmds['¹'] = bind(LatexFragment, '^1');
  2354. LatexCmds['²'] = bind(LatexFragment, '^2');
  2355. LatexCmds['³'] = bind(LatexFragment, '^3');
  2356. LatexCmds['¼'] = bind(LatexFragment, '\\frac14');
  2357. LatexCmds['½'] = bind(LatexFragment, '\\frac12');
  2358. LatexCmds['¾'] = bind(LatexFragment, '\\frac34');
  2359. var BinaryOperator = P(Symbol, function(_, _super) {
  2360. _.init = function(ctrlSeq, html, text) {
  2361. _super.init.call(this,
  2362. ctrlSeq, '<span class="binary-operator">'+html+'</span>', text
  2363. );
  2364. };
  2365. });
  2366. var PlusMinus = P(BinaryOperator, function(_) {
  2367. _.init = VanillaSymbol.prototype.init;
  2368. _.respace = function() {
  2369. if (!this[L]) {
  2370. this.jQ[0].className = '';
  2371. }
  2372. else if (
  2373. this[L] instanceof BinaryOperator &&
  2374. this[R] && !(this[R] instanceof BinaryOperator)
  2375. ) {
  2376. this.jQ[0].className = 'unary-operator';
  2377. }
  2378. else {
  2379. this.jQ[0].className = 'binary-operator';
  2380. }
  2381. return this;
  2382. };
  2383. });
  2384. LatexCmds['+'] = bind(PlusMinus, '+', '+');
  2385. //yes, these are different dashes, I think one is an en dash and the other is a hyphen
  2386. LatexCmds['–'] = LatexCmds['-'] = bind(PlusMinus, '-', '&minus;');
  2387. LatexCmds['±'] = LatexCmds.pm = LatexCmds.plusmn = LatexCmds.plusminus =
  2388. bind(PlusMinus,'\\pm ','&plusmn;');
  2389. LatexCmds.mp = LatexCmds.mnplus = LatexCmds.minusplus =
  2390. bind(PlusMinus,'\\mp ','&#8723;');
  2391. CharCmds['*'] = LatexCmds.sdot = LatexCmds.cdot =
  2392. bind(BinaryOperator, '\\cdot ', '&middot;');
  2393. //semantically should be &sdot;, but &middot; looks better
  2394. LatexCmds['='] = bind(BinaryOperator, '=', '=');
  2395. LatexCmds['<'] = bind(BinaryOperator, '<', '&lt;');
  2396. LatexCmds['>'] = bind(BinaryOperator, '>', '&gt;');
  2397. LatexCmds.notin =
  2398. LatexCmds.sim =
  2399. LatexCmds.cong =
  2400. LatexCmds.equiv =
  2401. LatexCmds.oplus =
  2402. LatexCmds.otimes = P(BinaryOperator, function(_, _super) {
  2403. _.init = function(latex) {
  2404. _super.init.call(this, '\\'+latex+' ', '&'+latex+';');
  2405. };
  2406. });
  2407. LatexCmds.times = bind(BinaryOperator, '\\times ', '&times;', '[x]');
  2408. LatexCmds['÷'] = LatexCmds.div = LatexCmds.divide = LatexCmds.divides =
  2409. bind(BinaryOperator,'\\div ','&divide;', '[/]');
  2410. LatexCmds['≠'] = LatexCmds.ne = LatexCmds.neq = bind(BinaryOperator,'\\ne ','&ne;');
  2411. LatexCmds.ast = LatexCmds.star = LatexCmds.loast = LatexCmds.lowast =
  2412. bind(BinaryOperator,'\\ast ','&lowast;');
  2413. //case 'there4 = // a special exception for this one, perhaps?
  2414. LatexCmds.therefor = LatexCmds.therefore =
  2415. bind(BinaryOperator,'\\therefore ','&there4;');
  2416. LatexCmds.cuz = // l33t
  2417. LatexCmds.because = bind(BinaryOperator,'\\because ','&#8757;');
  2418. LatexCmds.prop = LatexCmds.propto = bind(BinaryOperator,'\\propto ','&prop;');
  2419. LatexCmds['≈'] = LatexCmds.asymp = LatexCmds.approx = bind(BinaryOperator,'\\approx ','&asymp;');
  2420. LatexCmds.lt = bind(BinaryOperator,'<','&lt;');
  2421. LatexCmds.gt = bind(BinaryOperator,'>','&gt;');
  2422. LatexCmds['≤'] = LatexCmds.le = LatexCmds.leq = bind(BinaryOperator,'\\le ','&le;');
  2423. LatexCmds['≥'] = LatexCmds.ge = LatexCmds.geq = bind(BinaryOperator,'\\ge ','&ge;');
  2424. LatexCmds.isin = LatexCmds['in'] = bind(BinaryOperator,'\\in ','&isin;');
  2425. LatexCmds.ni = LatexCmds.contains = bind(BinaryOperator,'\\ni ','&ni;');
  2426. LatexCmds.notni = LatexCmds.niton = LatexCmds.notcontains = LatexCmds.doesnotcontain =
  2427. bind(BinaryOperator,'\\not\\ni ','&#8716;');
  2428. LatexCmds.sub = LatexCmds.subset = bind(BinaryOperator,'\\subset ','&sub;');
  2429. LatexCmds.sup = LatexCmds.supset = LatexCmds.superset =
  2430. bind(BinaryOperator,'\\supset ','&sup;');
  2431. LatexCmds.nsub = LatexCmds.notsub =
  2432. LatexCmds.nsubset = LatexCmds.notsubset =
  2433. bind(BinaryOperator,'\\not\\subset ','&#8836;');
  2434. LatexCmds.nsup = LatexCmds.notsup =
  2435. LatexCmds.nsupset = LatexCmds.notsupset =
  2436. LatexCmds.nsuperset = LatexCmds.notsuperset =
  2437. bind(BinaryOperator,'\\not\\supset ','&#8837;');
  2438. LatexCmds.sube = LatexCmds.subeq = LatexCmds.subsete = LatexCmds.subseteq =
  2439. bind(BinaryOperator,'\\subseteq ','&sube;');
  2440. LatexCmds.supe = LatexCmds.supeq =
  2441. LatexCmds.supsete = LatexCmds.supseteq =
  2442. LatexCmds.supersete = LatexCmds.superseteq =
  2443. bind(BinaryOperator,'\\supseteq ','&supe;');
  2444. LatexCmds.nsube = LatexCmds.nsubeq =
  2445. LatexCmds.notsube = LatexCmds.notsubeq =
  2446. LatexCmds.nsubsete = LatexCmds.nsubseteq =
  2447. LatexCmds.notsubsete = LatexCmds.notsubseteq =
  2448. bind(BinaryOperator,'\\not\\subseteq ','&#8840;');
  2449. LatexCmds.nsupe = LatexCmds.nsupeq =
  2450. LatexCmds.notsupe = LatexCmds.notsupeq =
  2451. LatexCmds.nsupsete = LatexCmds.nsupseteq =
  2452. LatexCmds.notsupsete = LatexCmds.notsupseteq =
  2453. LatexCmds.nsupersete = LatexCmds.nsuperseteq =
  2454. LatexCmds.notsupersete = LatexCmds.notsuperseteq =
  2455. bind(BinaryOperator,'\\not\\supseteq ','&#8841;');
  2456. //sum, product, coproduct, integral
  2457. var BigSymbol = P(Symbol, function(_, _super) {
  2458. _.init = function(ch, html) {
  2459. _super.init.call(this, ch, '<big>'+html+'</big>');
  2460. };
  2461. });
  2462. LatexCmds['∑'] = LatexCmds.sum = LatexCmds.summation = bind(BigSymbol,'\\sum ','&sum;');
  2463. LatexCmds['∏'] = LatexCmds.prod = LatexCmds.product = bind(BigSymbol,'\\prod ','&prod;');
  2464. LatexCmds.coprod = LatexCmds.coproduct = bind(BigSymbol,'\\coprod ','&#8720;');
  2465. LatexCmds['∫'] = LatexCmds['int'] = LatexCmds.integral = bind(BigSymbol,'\\int ','&int;');
  2466. //the canonical sets of numbers
  2467. LatexCmds.N = LatexCmds.naturals = LatexCmds.Naturals =
  2468. bind(VanillaSymbol,'\\mathbb{N}','&#8469;');
  2469. LatexCmds.P =
  2470. LatexCmds.primes = LatexCmds.Primes =
  2471. LatexCmds.projective = LatexCmds.Projective =
  2472. LatexCmds.probability = LatexCmds.Probability =
  2473. bind(VanillaSymbol,'\\mathbb{P}','&#8473;');
  2474. LatexCmds.Z = LatexCmds.integers = LatexCmds.Integers =
  2475. bind(VanillaSymbol,'\\mathbb{Z}','&#8484;');
  2476. LatexCmds.Q = LatexCmds.rationals = LatexCmds.Rationals =
  2477. bind(VanillaSymbol,'\\mathbb{Q}','&#8474;');
  2478. LatexCmds.R = LatexCmds.reals = LatexCmds.Reals =
  2479. bind(VanillaSymbol,'\\mathbb{R}','&#8477;');
  2480. LatexCmds.C =
  2481. LatexCmds.complex = LatexCmds.Complex =
  2482. LatexCmds.complexes = LatexCmds.Complexes =
  2483. LatexCmds.complexplane = LatexCmds.Complexplane = LatexCmds.ComplexPlane =
  2484. bind(VanillaSymbol,'\\mathbb{C}','&#8450;');
  2485. LatexCmds.H = LatexCmds.Hamiltonian = LatexCmds.quaternions = LatexCmds.Quaternions =
  2486. bind(VanillaSymbol,'\\mathbb{H}','&#8461;');
  2487. //spacing
  2488. LatexCmds.quad = LatexCmds.emsp = bind(VanillaSymbol,'\\quad ',' ');
  2489. LatexCmds.qquad = bind(VanillaSymbol,'\\qquad ',' ');
  2490. /* spacing special characters, gonna have to implement this in LatexCommandInput::onText somehow
  2491. case ',':
  2492. return VanillaSymbol('\\, ',' ');
  2493. case ':':
  2494. return VanillaSymbol('\\: ',' ');
  2495. case ';':
  2496. return VanillaSymbol('\\; ',' ');
  2497. case '!':
  2498. return Symbol('\\! ','<span style="margin-right:-.2em"></span>');
  2499. */
  2500. //binary operators
  2501. LatexCmds.diamond = bind(VanillaSymbol, '\\diamond ', '&#9671;');
  2502. LatexCmds.bigtriangleup = bind(VanillaSymbol, '\\bigtriangleup ', '&#9651;');
  2503. LatexCmds.ominus = bind(VanillaSymbol, '\\ominus ', '&#8854;');
  2504. LatexCmds.uplus = bind(VanillaSymbol, '\\uplus ', '&#8846;');
  2505. LatexCmds.bigtriangledown = bind(VanillaSymbol, '\\bigtriangledown ', '&#9661;');
  2506. LatexCmds.sqcap = bind(VanillaSymbol, '\\sqcap ', '&#8851;');
  2507. LatexCmds.triangleleft = bind(VanillaSymbol, '\\triangleleft ', '&#8882;');
  2508. LatexCmds.sqcup = bind(VanillaSymbol, '\\sqcup ', '&#8852;');
  2509. LatexCmds.triangleright = bind(VanillaSymbol, '\\triangleright ', '&#8883;');
  2510. LatexCmds.odot = bind(VanillaSymbol, '\\odot ', '&#8857;');
  2511. LatexCmds.bigcirc = bind(VanillaSymbol, '\\bigcirc ', '&#9711;');
  2512. LatexCmds.dagger = bind(VanillaSymbol, '\\dagger ', '&#0134;');
  2513. LatexCmds.ddagger = bind(VanillaSymbol, '\\ddagger ', '&#135;');
  2514. LatexCmds.wr = bind(VanillaSymbol, '\\wr ', '&#8768;');
  2515. LatexCmds.amalg = bind(VanillaSymbol, '\\amalg ', '&#8720;');
  2516. //relationship symbols
  2517. LatexCmds.models = bind(VanillaSymbol, '\\models ', '&#8872;');
  2518. LatexCmds.prec = bind(VanillaSymbol, '\\prec ', '&#8826;');
  2519. LatexCmds.succ = bind(VanillaSymbol, '\\succ ', '&#8827;');
  2520. LatexCmds.preceq = bind(VanillaSymbol, '\\preceq ', '&#8828;');
  2521. LatexCmds.succeq = bind(VanillaSymbol, '\\succeq ', '&#8829;');
  2522. LatexCmds.simeq = bind(VanillaSymbol, '\\simeq ', '&#8771;');
  2523. LatexCmds.mid = bind(VanillaSymbol, '\\mid ', '&#8739;');
  2524. LatexCmds.ll = bind(VanillaSymbol, '\\ll ', '&#8810;');
  2525. LatexCmds.gg = bind(VanillaSymbol, '\\gg ', '&#8811;');
  2526. LatexCmds.parallel = bind(VanillaSymbol, '\\parallel ', '&#8741;');
  2527. LatexCmds.bowtie = bind(VanillaSymbol, '\\bowtie ', '&#8904;');
  2528. LatexCmds.sqsubset = bind(VanillaSymbol, '\\sqsubset ', '&#8847;');
  2529. LatexCmds.sqsupset = bind(VanillaSymbol, '\\sqsupset ', '&#8848;');
  2530. LatexCmds.smile = bind(VanillaSymbol, '\\smile ', '&#8995;');
  2531. LatexCmds.sqsubseteq = bind(VanillaSymbol, '\\sqsubseteq ', '&#8849;');
  2532. LatexCmds.sqsupseteq = bind(VanillaSymbol, '\\sqsupseteq ', '&#8850;');
  2533. LatexCmds.doteq = bind(VanillaSymbol, '\\doteq ', '&#8784;');
  2534. LatexCmds.frown = bind(VanillaSymbol, '\\frown ', '&#8994;');
  2535. LatexCmds.vdash = bind(VanillaSymbol, '\\vdash ', '&#8870;');
  2536. LatexCmds.dashv = bind(VanillaSymbol, '\\dashv ', '&#8867;');
  2537. //arrows
  2538. LatexCmds.longleftarrow = bind(VanillaSymbol, '\\longleftarrow ', '&#8592;');
  2539. LatexCmds.longrightarrow = bind(VanillaSymbol, '\\longrightarrow ', '&#8594;');
  2540. LatexCmds.Longleftarrow = bind(VanillaSymbol, '\\Longleftarrow ', '&#8656;');
  2541. LatexCmds.Longrightarrow = bind(VanillaSymbol, '\\Longrightarrow ', '&#8658;');
  2542. LatexCmds.longleftrightarrow = bind(VanillaSymbol, '\\longleftrightarrow ', '&#8596;');
  2543. LatexCmds.updownarrow = bind(VanillaSymbol, '\\updownarrow ', '&#8597;');
  2544. LatexCmds.Longleftrightarrow = bind(VanillaSymbol, '\\Longleftrightarrow ', '&#8660;');
  2545. LatexCmds.Updownarrow = bind(VanillaSymbol, '\\Updownarrow ', '&#8661;');
  2546. LatexCmds.mapsto = bind(VanillaSymbol, '\\mapsto ', '&#8614;');
  2547. LatexCmds.nearrow = bind(VanillaSymbol, '\\nearrow ', '&#8599;');
  2548. LatexCmds.hookleftarrow = bind(VanillaSymbol, '\\hookleftarrow ', '&#8617;');
  2549. LatexCmds.hookrightarrow = bind(VanillaSymbol, '\\hookrightarrow ', '&#8618;');
  2550. LatexCmds.searrow = bind(VanillaSymbol, '\\searrow ', '&#8600;');
  2551. LatexCmds.leftharpoonup = bind(VanillaSymbol, '\\leftharpoonup ', '&#8636;');
  2552. LatexCmds.rightharpoonup = bind(VanillaSymbol, '\\rightharpoonup ', '&#8640;');
  2553. LatexCmds.swarrow = bind(VanillaSymbol, '\\swarrow ', '&#8601;');
  2554. LatexCmds.leftharpoondown = bind(VanillaSymbol, '\\leftharpoondown ', '&#8637;');
  2555. LatexCmds.rightharpoondown = bind(VanillaSymbol, '\\rightharpoondown ', '&#8641;');
  2556. LatexCmds.nwarrow = bind(VanillaSymbol, '\\nwarrow ', '&#8598;');
  2557. //Misc
  2558. LatexCmds.ldots = bind(VanillaSymbol, '\\ldots ', '&#8230;');
  2559. LatexCmds.cdots = bind(VanillaSymbol, '\\cdots ', '&#8943;');
  2560. LatexCmds.vdots = bind(VanillaSymbol, '\\vdots ', '&#8942;');
  2561. LatexCmds.ddots = bind(VanillaSymbol, '\\ddots ', '&#8944;');
  2562. LatexCmds.surd = bind(VanillaSymbol, '\\surd ', '&#8730;');
  2563. LatexCmds.triangle = bind(VanillaSymbol, '\\triangle ', '&#9653;');
  2564. LatexCmds.ell = bind(VanillaSymbol, '\\ell ', '&#8467;');
  2565. LatexCmds.top = bind(VanillaSymbol, '\\top ', '&#8868;');
  2566. LatexCmds.flat = bind(VanillaSymbol, '\\flat ', '&#9837;');
  2567. LatexCmds.natural = bind(VanillaSymbol, '\\natural ', '&#9838;');
  2568. LatexCmds.sharp = bind(VanillaSymbol, '\\sharp ', '&#9839;');
  2569. LatexCmds.wp = bind(VanillaSymbol, '\\wp ', '&#8472;');
  2570. LatexCmds.bot = bind(VanillaSymbol, '\\bot ', '&#8869;');
  2571. LatexCmds.clubsuit = bind(VanillaSymbol, '\\clubsuit ', '&#9827;');
  2572. LatexCmds.diamondsuit = bind(VanillaSymbol, '\\diamondsuit ', '&#9826;');
  2573. LatexCmds.heartsuit = bind(VanillaSymbol, '\\heartsuit ', '&#9825;');
  2574. LatexCmds.spadesuit = bind(VanillaSymbol, '\\spadesuit ', '&#9824;');
  2575. //variable-sized
  2576. LatexCmds.oint = bind(VanillaSymbol, '\\oint ', '&#8750;');
  2577. LatexCmds.bigcap = bind(VanillaSymbol, '\\bigcap ', '&#8745;');
  2578. LatexCmds.bigcup = bind(VanillaSymbol, '\\bigcup ', '&#8746;');
  2579. LatexCmds.bigsqcup = bind(VanillaSymbol, '\\bigsqcup ', '&#8852;');
  2580. LatexCmds.bigvee = bind(VanillaSymbol, '\\bigvee ', '&#8744;');
  2581. LatexCmds.bigwedge = bind(VanillaSymbol, '\\bigwedge ', '&#8743;');
  2582. LatexCmds.bigodot = bind(VanillaSymbol, '\\bigodot ', '&#8857;');
  2583. LatexCmds.bigotimes = bind(VanillaSymbol, '\\bigotimes ', '&#8855;');
  2584. LatexCmds.bigoplus = bind(VanillaSymbol, '\\bigoplus ', '&#8853;');
  2585. LatexCmds.biguplus = bind(VanillaSymbol, '\\biguplus ', '&#8846;');
  2586. //delimiters
  2587. LatexCmds.lfloor = bind(VanillaSymbol, '\\lfloor ', '&#8970;');
  2588. LatexCmds.rfloor = bind(VanillaSymbol, '\\rfloor ', '&#8971;');
  2589. LatexCmds.lceil = bind(VanillaSymbol, '\\lceil ', '&#8968;');
  2590. LatexCmds.rceil = bind(VanillaSymbol, '\\rceil ', '&#8969;');
  2591. LatexCmds.slash = bind(VanillaSymbol, '\\slash ', '&#47;');
  2592. LatexCmds.opencurlybrace = bind(VanillaSymbol, '\\opencurlybrace ', '&#123;');
  2593. LatexCmds.closecurlybrace = bind(VanillaSymbol, '\\closecurlybrace ', '&#125;');
  2594. //various symbols
  2595. LatexCmds.caret = bind(VanillaSymbol,'\\caret ','^');
  2596. LatexCmds.underscore = bind(VanillaSymbol,'\\underscore ','_');
  2597. LatexCmds.backslash = bind(VanillaSymbol,'\\backslash ','\\');
  2598. LatexCmds.vert = bind(VanillaSymbol,'|');
  2599. LatexCmds.perp = LatexCmds.perpendicular = bind(VanillaSymbol,'\\perp ','&perp;');
  2600. LatexCmds.nabla = LatexCmds.del = bind(VanillaSymbol,'\\nabla ','&nabla;');
  2601. LatexCmds.hbar = bind(VanillaSymbol,'\\hbar ','&#8463;');
  2602. LatexCmds.AA = LatexCmds.Angstrom = LatexCmds.angstrom =
  2603. bind(VanillaSymbol,'\\text\\AA ','&#8491;');
  2604. LatexCmds.ring = LatexCmds.circ = LatexCmds.circle =
  2605. bind(VanillaSymbol,'\\circ ','&#8728;');
  2606. LatexCmds.bull = LatexCmds.bullet = bind(VanillaSymbol,'\\bullet ','&bull;');
  2607. LatexCmds.setminus = LatexCmds.smallsetminus =
  2608. bind(VanillaSymbol,'\\setminus ','&#8726;');
  2609. LatexCmds.not = //bind(Symbol,'\\not ','<span class="not">/</span>');
  2610. LatexCmds['¬'] = LatexCmds.neg = bind(VanillaSymbol,'\\neg ','&not;');
  2611. LatexCmds['…'] = LatexCmds.dots = LatexCmds.ellip = LatexCmds.hellip =
  2612. LatexCmds.ellipsis = LatexCmds.hellipsis =
  2613. bind(VanillaSymbol,'\\dots ','&hellip;');
  2614. LatexCmds.converges =
  2615. LatexCmds.darr = LatexCmds.dnarr = LatexCmds.dnarrow = LatexCmds.downarrow =
  2616. bind(VanillaSymbol,'\\downarrow ','&darr;');
  2617. LatexCmds.dArr = LatexCmds.dnArr = LatexCmds.dnArrow = LatexCmds.Downarrow =
  2618. bind(VanillaSymbol,'\\Downarrow ','&dArr;');
  2619. LatexCmds.diverges = LatexCmds.uarr = LatexCmds.uparrow =
  2620. bind(VanillaSymbol,'\\uparrow ','&uarr;');
  2621. LatexCmds.uArr = LatexCmds.Uparrow = bind(VanillaSymbol,'\\Uparrow ','&uArr;');
  2622. LatexCmds.to = bind(BinaryOperator,'\\to ','&rarr;');
  2623. LatexCmds.rarr = LatexCmds.rightarrow = bind(VanillaSymbol,'\\rightarrow ','&rarr;');
  2624. LatexCmds.implies = bind(BinaryOperator,'\\Rightarrow ','&rArr;');
  2625. LatexCmds.rArr = LatexCmds.Rightarrow = bind(VanillaSymbol,'\\Rightarrow ','&rArr;');
  2626. LatexCmds.gets = bind(BinaryOperator,'\\gets ','&larr;');
  2627. LatexCmds.larr = LatexCmds.leftarrow = bind(VanillaSymbol,'\\leftarrow ','&larr;');
  2628. LatexCmds.impliedby = bind(BinaryOperator,'\\Leftarrow ','&lArr;');
  2629. LatexCmds.lArr = LatexCmds.Leftarrow = bind(VanillaSymbol,'\\Leftarrow ','&lArr;');
  2630. LatexCmds.harr = LatexCmds.lrarr = LatexCmds.leftrightarrow =
  2631. bind(VanillaSymbol,'\\leftrightarrow ','&harr;');
  2632. LatexCmds.iff = bind(BinaryOperator,'\\Leftrightarrow ','&hArr;');
  2633. LatexCmds.hArr = LatexCmds.lrArr = LatexCmds.Leftrightarrow =
  2634. bind(VanillaSymbol,'\\Leftrightarrow ','&hArr;');
  2635. LatexCmds.Re = LatexCmds.Real = LatexCmds.real = bind(VanillaSymbol,'\\Re ','&real;');
  2636. LatexCmds.Im = LatexCmds.imag =
  2637. LatexCmds.image = LatexCmds.imagin = LatexCmds.imaginary = LatexCmds.Imaginary =
  2638. bind(VanillaSymbol,'\\Im ','&image;');
  2639. LatexCmds.part = LatexCmds.partial = bind(VanillaSymbol,'\\partial ','&part;');
  2640. LatexCmds.inf = LatexCmds.infin = LatexCmds.infty = LatexCmds.infinity =
  2641. bind(VanillaSymbol,'\\infty ','&infin;');
  2642. LatexCmds.alef = LatexCmds.alefsym = LatexCmds.aleph = LatexCmds.alephsym =
  2643. bind(VanillaSymbol,'\\aleph ','&alefsym;');
  2644. LatexCmds.xist = //LOL
  2645. LatexCmds.xists = LatexCmds.exist = LatexCmds.exists =
  2646. bind(VanillaSymbol,'\\exists ','&exist;');
  2647. LatexCmds.and = LatexCmds.land = LatexCmds.wedge =
  2648. bind(VanillaSymbol,'\\wedge ','&and;');
  2649. LatexCmds.or = LatexCmds.lor = LatexCmds.vee = bind(VanillaSymbol,'\\vee ','&or;');
  2650. LatexCmds.o = LatexCmds.O =
  2651. LatexCmds.empty = LatexCmds.emptyset =
  2652. LatexCmds.oslash = LatexCmds.Oslash =
  2653. LatexCmds.nothing = LatexCmds.varnothing =
  2654. bind(BinaryOperator,'\\varnothing ','&empty;');
  2655. LatexCmds.cup = LatexCmds.union = bind(BinaryOperator,'\\cup ','&cup;');
  2656. LatexCmds.cap = LatexCmds.intersect = LatexCmds.intersection =
  2657. bind(BinaryOperator,'\\cap ','&cap;');
  2658. LatexCmds.deg = LatexCmds.degree = bind(VanillaSymbol,'^\\circ ','&deg;');
  2659. LatexCmds.ang = LatexCmds.angle = bind(VanillaSymbol,'\\angle ','&ang;');
  2660. var NonItalicizedFunction = P(Symbol, function(_, _super) {
  2661. _.init = function(fn) {
  2662. _super.init.call(this, '\\'+fn+' ', '<span>'+fn+'</span>');
  2663. };
  2664. _.respace = function()
  2665. {
  2666. this.jQ[0].className =
  2667. (this[R] instanceof SupSub || this[R] instanceof Bracket) ?
  2668. '' : 'non-italicized-function';
  2669. };
  2670. });
  2671. LatexCmds.ln =
  2672. LatexCmds.lg =
  2673. LatexCmds.log =
  2674. LatexCmds.span =
  2675. LatexCmds.proj =
  2676. LatexCmds.det =
  2677. LatexCmds.dim =
  2678. LatexCmds.min =
  2679. LatexCmds.max =
  2680. LatexCmds.mod =
  2681. LatexCmds.lcm =
  2682. LatexCmds.gcd =
  2683. LatexCmds.gcf =
  2684. LatexCmds.hcf =
  2685. LatexCmds.lim = NonItalicizedFunction;
  2686. (function() {
  2687. var trig = ['sin', 'cos', 'tan', 'sec', 'cosec', 'csc', 'cotan', 'cot'];
  2688. for (var i in trig) {
  2689. LatexCmds[trig[i]] =
  2690. LatexCmds[trig[i]+'h'] =
  2691. LatexCmds['a'+trig[i]] = LatexCmds['arc'+trig[i]] =
  2692. LatexCmds['a'+trig[i]+'h'] = LatexCmds['arc'+trig[i]+'h'] =
  2693. NonItalicizedFunction;
  2694. }
  2695. }());
  2696. // Parser MathCommand
  2697. var latexMathParser = (function() {
  2698. function commandToBlock(cmd) {
  2699. var block = MathBlock();
  2700. cmd.adopt(block, 0, 0);
  2701. return block;
  2702. }
  2703. function joinBlocks(blocks) {
  2704. var firstBlock = blocks[0] || MathBlock();
  2705. for (var i = 1; i < blocks.length; i += 1) {
  2706. blocks[i].children().adopt(firstBlock, firstBlock.ends[R], 0);
  2707. }
  2708. return firstBlock;
  2709. }
  2710. var string = Parser.string;
  2711. var regex = Parser.regex;
  2712. var letter = Parser.letter;
  2713. var any = Parser.any;
  2714. var optWhitespace = Parser.optWhitespace;
  2715. var succeed = Parser.succeed;
  2716. var fail = Parser.fail;
  2717. // Parsers yielding MathCommands
  2718. var variable = letter.map(Variable);
  2719. var symbol = regex(/^[^${}\\_^]/).map(VanillaSymbol);
  2720. var controlSequence =
  2721. regex(/^[^\\a-eg-zA-Z]/) // hotfix #164; match MathBlock::write
  2722. .or(string('\\').then(
  2723. regex(/^[a-z]+/i)
  2724. .or(regex(/^\s+/).result(' '))
  2725. .or(any)
  2726. )).then(function(ctrlSeq) {
  2727. var cmdKlass = LatexCmds[ctrlSeq];
  2728. if (cmdKlass) {
  2729. return cmdKlass(ctrlSeq).parser();
  2730. }
  2731. else {
  2732. return fail('unknown command: \\'+ctrlSeq);
  2733. }
  2734. })
  2735. ;
  2736. var command =
  2737. controlSequence
  2738. .or(variable)
  2739. .or(symbol)
  2740. ;
  2741. // Parsers yielding MathBlocks
  2742. var mathGroup = string('{').then(function() { return mathSequence; }).skip(string('}'));
  2743. var mathBlock = optWhitespace.then(mathGroup.or(command.map(commandToBlock)));
  2744. var mathSequence = mathBlock.many().map(joinBlocks).skip(optWhitespace);
  2745. var optMathBlock =
  2746. string('[').then(
  2747. mathBlock.then(function(block) {
  2748. return block.join('latex') !== ']' ? succeed(block) : fail();
  2749. })
  2750. .many().map(joinBlocks).skip(optWhitespace)
  2751. ).skip(string(']'))
  2752. ;
  2753. var latexMath = mathSequence;
  2754. latexMath.block = mathBlock;
  2755. latexMath.optBlock = optMathBlock;
  2756. return latexMath;
  2757. })();
  2758. /********************************************
  2759. * Cursor and Selection "singleton" classes
  2760. *******************************************/
  2761. /* The main thing that manipulates the Math DOM. Makes sure to manipulate the
  2762. HTML DOM to match. */
  2763. /* Sort of singletons, since there should only be one per editable math
  2764. textbox, but any one HTML document can contain many such textboxes, so any one
  2765. JS environment could actually contain many instances. */
  2766. //A fake cursor in the fake textbox that the math is rendered in.
  2767. var Cursor = P(Point, function(_) {
  2768. _.init = function(root) {
  2769. this.parent = this.root = root;
  2770. var jQ = this.jQ = this._jQ = $('<span class="cursor">&zwj;</span>');
  2771. //closured for setInterval
  2772. this.blink = function(){ jQ.toggleClass('blink'); };
  2773. this.upDownCache = {};
  2774. };
  2775. _.show = function() {
  2776. this.jQ = this._jQ.removeClass('blink');
  2777. if ('intervalId' in this) //already was shown, just restart interval
  2778. clearInterval(this.intervalId);
  2779. else { //was hidden and detached, insert this.jQ back into HTML DOM
  2780. if (this[R]) {
  2781. if (this.selection && this.selection.ends[L][L] === this[L])
  2782. this.jQ.insertBefore(this.selection.jQ);
  2783. else
  2784. this.jQ.insertBefore(this[R].jQ.first());
  2785. }
  2786. else
  2787. this.jQ.appendTo(this.parent.jQ);
  2788. this.parent.focus();
  2789. }
  2790. this.intervalId = setInterval(this.blink, 500);
  2791. return this;
  2792. };
  2793. _.hide = function() {
  2794. if ('intervalId' in this)
  2795. clearInterval(this.intervalId);
  2796. delete this.intervalId;
  2797. this.jQ.detach();
  2798. this.jQ = $();
  2799. return this;
  2800. };
  2801. _.withDirInsertAt = function(dir, parent, withDir, oppDir) {
  2802. var oldParent = this.parent;
  2803. this.parent = parent;
  2804. this[dir] = withDir;
  2805. this[-dir] = oppDir;
  2806. oldParent.blur();
  2807. };
  2808. _.insDirOf = function(dir, el) {
  2809. prayDirection(dir);
  2810. this.withDirInsertAt(dir, el.parent, el[dir], el);
  2811. this.parent.jQ.addClass('hasCursor');
  2812. this.jQ.insDirOf(dir, el.jQ);
  2813. return this;
  2814. };
  2815. _.insLeftOf = function(el) { return this.insDirOf(L, el); };
  2816. _.insRightOf = function(el) { return this.insDirOf(R, el); };
  2817. _.insAtDirEnd = function(dir, el) {
  2818. prayDirection(dir);
  2819. this.withDirInsertAt(dir, el, 0, el.ends[dir]);
  2820. // never insert before textarea
  2821. if (dir === L && el.textarea) {
  2822. this.jQ.insDirOf(-dir, el.textarea);
  2823. }
  2824. else {
  2825. this.jQ.insAtDirEnd(dir, el.jQ);
  2826. }
  2827. el.focus();
  2828. return this;
  2829. };
  2830. _.insAtLeftEnd = function(el) { return this.insAtDirEnd(L, el); };
  2831. _.insAtRightEnd = function(el) { return this.insAtDirEnd(R, el); };
  2832. _.hopDir = function(dir) {
  2833. prayDirection(dir);
  2834. this.jQ.insDirOf(dir, this[dir].jQ);
  2835. this[-dir] = this[dir];
  2836. this[dir] = this[dir][dir];
  2837. return this;
  2838. };
  2839. _.hopLeft = function() { return this.hopDir(L); };
  2840. _.hopRight = function() { return this.hopDir(R); };
  2841. _.moveDirWithin = function(dir, block) {
  2842. prayDirection(dir);
  2843. if (this[dir]) {
  2844. if (this[dir].ends[-dir]) this.insAtDirEnd(-dir, this[dir].ends[-dir]);
  2845. else this.hopDir(dir);
  2846. }
  2847. else {
  2848. // we're at the beginning/end of the containing block, so do nothing
  2849. if (this.parent === block) return;
  2850. if (this.parent[dir]) this.insAtDirEnd(-dir, this.parent[dir]);
  2851. else this.insDirOf(dir, this.parent.parent);
  2852. }
  2853. };
  2854. _.moveLeftWithin = function(block) {
  2855. return this.moveDirWithin(L, block);
  2856. };
  2857. _.moveRightWithin = function(block) {
  2858. return this.moveDirWithin(R, block);
  2859. };
  2860. _.moveDir = function(dir) {
  2861. prayDirection(dir);
  2862. clearUpDownCache(this);
  2863. if (this.selection) {
  2864. this.insDirOf(dir, this.selection.ends[dir]).clearSelection();
  2865. }
  2866. else {
  2867. this.moveDirWithin(dir, this.root);
  2868. }
  2869. return this.show();
  2870. };
  2871. _.moveLeft = function() { return this.moveDir(L); };
  2872. _.moveRight = function() { return this.moveDir(R); };
  2873. /**
  2874. * moveUp and moveDown have almost identical algorithms:
  2875. * - first check left and right, if so insAtLeft/RightEnd of them
  2876. * - else check the parent's 'up'/'down' property - if it's a function,
  2877. * call it with the cursor as the sole argument and use the return value.
  2878. *
  2879. * Given undefined, will bubble up to the next ancestor block.
  2880. * Given false, will stop bubbling.
  2881. * Given a MathBlock,
  2882. * + moveUp will insAtRightEnd of it
  2883. * + moveDown will insAtLeftEnd of it
  2884. *
  2885. */
  2886. _.moveUp = function() { return moveUpDown(this, 'up'); };
  2887. _.moveDown = function() { return moveUpDown(this, 'down'); };
  2888. function moveUpDown(self, dir) {
  2889. if (self[R][dir]) self.insAtLeftEnd(self[R][dir]);
  2890. else if (self[L][dir]) self.insAtRightEnd(self[L][dir]);
  2891. else {
  2892. var ancestorBlock = self.parent;
  2893. do {
  2894. var prop = ancestorBlock[dir];
  2895. if (prop) {
  2896. if (typeof prop === 'function') prop = ancestorBlock[dir](self);
  2897. if (prop === false || prop instanceof MathBlock) {
  2898. self.upDownCache[ancestorBlock.id] = Point(self.parent, self[L], self[R]);
  2899. if (prop instanceof MathBlock) {
  2900. var cached = self.upDownCache[prop.id];
  2901. if (cached) {
  2902. if (cached[R]) {
  2903. self.insLeftOf(cached[R]);
  2904. } else {
  2905. self.insAtRightEnd(cached.parent);
  2906. }
  2907. } else {
  2908. var pageX = offset(self).left;
  2909. self.insAtRightEnd(prop);
  2910. self.seekHoriz(pageX, prop);
  2911. }
  2912. }
  2913. break;
  2914. }
  2915. }
  2916. ancestorBlock = ancestorBlock.parent.parent;
  2917. } while (ancestorBlock);
  2918. }
  2919. return self.clearSelection().show();
  2920. }
  2921. _.seek = function(target, pageX, pageY) {
  2922. clearUpDownCache(this);
  2923. var cmd, block, cursor = this.clearSelection().show();
  2924. if (target.hasClass('empty')) {
  2925. cursor.insAtLeftEnd(MathElement[target.attr(mqBlockId)]);
  2926. return cursor;
  2927. }
  2928. cmd = MathElement[target.attr(mqCmdId)];
  2929. if (cmd instanceof Symbol) { //insert at whichever side is closer
  2930. if (target.outerWidth() > 2*(pageX - target.offset().left))
  2931. cursor.insLeftOf(cmd);
  2932. else
  2933. cursor.insRightOf(cmd);
  2934. return cursor;
  2935. }
  2936. if (!cmd) {
  2937. block = MathElement[target.attr(mqBlockId)];
  2938. if (!block) { //if no MathQuill data, try parent, if still no, just start from the root
  2939. target = target.parent();
  2940. cmd = MathElement[target.attr(mqCmdId)];
  2941. if (!cmd) {
  2942. block = MathElement[target.attr(mqBlockId)];
  2943. if (!block) block = cursor.root;
  2944. }
  2945. }
  2946. }
  2947. if (cmd)
  2948. cursor.insRightOf(cmd);
  2949. else
  2950. cursor.insAtRightEnd(block);
  2951. return cursor.seekHoriz(pageX, cursor.root);
  2952. };
  2953. _.seekHoriz = function(pageX, block) {
  2954. //move cursor to position closest to click
  2955. var cursor = this;
  2956. var dist = offset(cursor).left - pageX;
  2957. var leftDist;
  2958. do {
  2959. cursor.moveLeftWithin(block);
  2960. leftDist = dist;
  2961. dist = offset(cursor).left - pageX;
  2962. }
  2963. while (dist > 0 && (cursor[L] || cursor.parent !== block));
  2964. if (-dist > leftDist) cursor.moveRightWithin(block);
  2965. return cursor;
  2966. };
  2967. function offset(self) {
  2968. //in Opera 11.62, .getBoundingClientRect() and hence jQuery::offset()
  2969. //returns all 0's on inline elements with negative margin-right (like
  2970. //the cursor) at the end of their parent, so temporarily remove the
  2971. //negative margin-right when calling jQuery::offset()
  2972. //Opera bug DSK-360043
  2973. //http://bugs.jquery.com/ticket/11523
  2974. //https://github.com/jquery/jquery/pull/717
  2975. var offset = self.jQ.removeClass('cursor').offset();
  2976. self.jQ.addClass('cursor');
  2977. return offset;
  2978. }
  2979. _.writeLatex = function(latex) {
  2980. var self = this;
  2981. clearUpDownCache(self);
  2982. self.show().deleteSelection();
  2983. var all = Parser.all;
  2984. var eof = Parser.eof;
  2985. var block = latexMathParser.skip(eof).or(all.result(false)).parse(latex);
  2986. if (block) {
  2987. block.children().adopt(self.parent, self[L], self[R]);
  2988. MathElement.jQize(block.join('html')).insertBefore(self.jQ);
  2989. self[L] = block.ends[R];
  2990. block.finalizeInsert();
  2991. self.parent.bubble('redraw');
  2992. }
  2993. return this.hide();
  2994. };
  2995. _.write = function(ch) {
  2996. var seln = this.prepareWrite();
  2997. return this.insertCh(ch, seln);
  2998. };
  2999. _.insertCh = function(ch, replacedFragment) {
  3000. this.parent.write(this, ch, replacedFragment);
  3001. return this;
  3002. };
  3003. _.insertCmd = function(latexCmd, replacedFragment) {
  3004. var cmd = LatexCmds[latexCmd];
  3005. if (cmd) {
  3006. cmd = cmd(latexCmd);
  3007. if (replacedFragment) cmd.replaces(replacedFragment);
  3008. cmd.createLeftOf(this);
  3009. }
  3010. else {
  3011. cmd = TextBlock();
  3012. cmd.replaces(latexCmd);
  3013. cmd.ends[L].focus = function(){ delete this.focus; return this; };
  3014. cmd.createLeftOf(this);
  3015. this.insRightOf(cmd);
  3016. if (replacedFragment)
  3017. replacedFragment.remove();
  3018. }
  3019. return this;
  3020. };
  3021. _.unwrapGramp = function() {
  3022. var gramp = this.parent.parent;
  3023. var greatgramp = gramp.parent;
  3024. var rightward = gramp[R];
  3025. var cursor = this;
  3026. var leftward = gramp[L];
  3027. gramp.disown().eachChild(function(uncle) {
  3028. if (uncle.isEmpty()) return;
  3029. uncle.children()
  3030. .adopt(greatgramp, leftward, rightward)
  3031. .each(function(cousin) {
  3032. cousin.jQ.insertBefore(gramp.jQ.first());
  3033. })
  3034. ;
  3035. leftward = uncle.ends[R];
  3036. });
  3037. if (!this[R]) { //then find something to be rightward to insLeftOf
  3038. if (this[L])
  3039. this[R] = this[L][R];
  3040. else {
  3041. while (!this[R]) {
  3042. this.parent = this.parent[R];
  3043. if (this.parent)
  3044. this[R] = this.parent.ends[L];
  3045. else {
  3046. this[R] = gramp[R];
  3047. this.parent = greatgramp;
  3048. break;
  3049. }
  3050. }
  3051. }
  3052. }
  3053. if (this[R])
  3054. this.insLeftOf(this[R]);
  3055. else
  3056. this.insAtRightEnd(greatgramp);
  3057. gramp.jQ.remove();
  3058. if (gramp[L])
  3059. gramp[L].respace();
  3060. if (gramp[R])
  3061. gramp[R].respace();
  3062. };
  3063. _.deleteDir = function(dir) {
  3064. prayDirection(dir);
  3065. clearUpDownCache(this);
  3066. this.show();
  3067. if (this.deleteSelection()); // pass
  3068. else if (this[dir]) {
  3069. if (this[dir].isEmpty())
  3070. this[dir] = this[dir].remove()[dir];
  3071. else
  3072. this.selectDir(dir);
  3073. }
  3074. else if (this.parent !== this.root) {
  3075. if (this.parent.parent.isEmpty())
  3076. return this.insDirOf(-dir, this.parent.parent).deleteDir(dir);
  3077. else
  3078. this.unwrapGramp();
  3079. }
  3080. if (this[L])
  3081. this[L].respace();
  3082. if (this[R])
  3083. this[R].respace();
  3084. this.parent.bubble('redraw');
  3085. return this;
  3086. };
  3087. _.backspace = function() { return this.deleteDir(L); };
  3088. _.deleteForward = function() { return this.deleteDir(R); };
  3089. _.selectFrom = function(anticursor) {
  3090. //find ancestors of each with common parent
  3091. var oneA = this, otherA = anticursor; //one ancestor, the other ancestor
  3092. loopThroughAncestors: while (true) {
  3093. for (var oneI = this; oneI !== oneA.parent.parent; oneI = oneI.parent.parent) //one intermediate, the other intermediate
  3094. if (oneI.parent === otherA.parent) {
  3095. left = oneI;
  3096. right = otherA;
  3097. break loopThroughAncestors;
  3098. }
  3099. for (var otherI = anticursor; otherI !== otherA.parent.parent; otherI = otherI.parent.parent)
  3100. if (oneA.parent === otherI.parent) {
  3101. left = oneA;
  3102. right = otherI;
  3103. break loopThroughAncestors;
  3104. }
  3105. if (oneA.parent.parent)
  3106. oneA = oneA.parent.parent;
  3107. if (otherA.parent.parent)
  3108. otherA = otherA.parent.parent;
  3109. }
  3110. //figure out which is leftward and which is rightward
  3111. var left, right, leftRight;
  3112. if (left[R] !== right) {
  3113. for (var rightward = left; rightward; rightward = rightward[R]) {
  3114. if (rightward === right[L]) {
  3115. leftRight = true;
  3116. break;
  3117. }
  3118. }
  3119. if (!leftRight) {
  3120. leftRight = right;
  3121. right = left;
  3122. left = leftRight;
  3123. }
  3124. }
  3125. this.hide().selection = Selection(left[L][R] || left.parent.ends[L], right[R][L] || right.parent.ends[R]);
  3126. this.insRightOf(right[R][L] || right.parent.ends[R]);
  3127. this.root.selectionChanged();
  3128. };
  3129. _.selectDir = function(dir) {
  3130. prayDirection(dir);
  3131. clearUpDownCache(this);
  3132. if (this.selection) {
  3133. // if cursor is at the (dir) edge of selection
  3134. if (this.selection.ends[dir] === this[-dir]) {
  3135. // then extend (dir) if possible
  3136. if (this[dir]) this.hopDir(dir).selection.extendDir(dir);
  3137. // else level up if possible
  3138. else if (this.parent !== this.root) {
  3139. this.insDirOf(dir, this.parent.parent).selection.levelUp();
  3140. }
  3141. }
  3142. // else cursor is at the (-dir) edge of selection, retract if possible
  3143. else {
  3144. this.hopDir(dir);
  3145. // clear the selection if we only have one thing selected
  3146. if (this.selection.ends[dir] === this.selection.ends[-dir]) {
  3147. this.clearSelection().show();
  3148. return;
  3149. }
  3150. this.selection.retractDir(dir);
  3151. }
  3152. }
  3153. // no selection, create one
  3154. else {
  3155. if (this[dir]) this.hopDir(dir);
  3156. // else edge of a block
  3157. else {
  3158. if (this.parent === this.root) return;
  3159. this.insDirOf(dir, this.parent.parent);
  3160. }
  3161. this.hide().selection = Selection(this[-dir]);
  3162. }
  3163. this.root.selectionChanged();
  3164. };
  3165. _.selectLeft = function() { return this.selectDir(L); };
  3166. _.selectRight = function() { return this.selectDir(R); };
  3167. function clearUpDownCache(self) {
  3168. self.upDownCache = {};
  3169. }
  3170. _.prepareMove = function() {
  3171. clearUpDownCache(this);
  3172. return this.show().clearSelection();
  3173. };
  3174. _.prepareEdit = function() {
  3175. clearUpDownCache(this);
  3176. return this.show().deleteSelection();
  3177. };
  3178. _.prepareWrite = function() {
  3179. clearUpDownCache(this);
  3180. return this.show().replaceSelection();
  3181. };
  3182. _.clearSelection = function() {
  3183. if (this.selection) {
  3184. this.selection.clear();
  3185. delete this.selection;
  3186. this.root.selectionChanged();
  3187. }
  3188. return this;
  3189. };
  3190. _.deleteSelection = function() {
  3191. if (!this.selection) return false;
  3192. this[L] = this.selection.ends[L][L];
  3193. this[R] = this.selection.ends[R][R];
  3194. this.selection.remove();
  3195. this.root.selectionChanged();
  3196. return delete this.selection;
  3197. };
  3198. _.replaceSelection = function() {
  3199. var seln = this.selection;
  3200. if (seln) {
  3201. this[L] = seln.ends[L][L];
  3202. this[R] = seln.ends[R][R];
  3203. delete this.selection;
  3204. }
  3205. return seln;
  3206. };
  3207. });
  3208. var Selection = P(MathFragment, function(_, _super) {
  3209. _.init = function() {
  3210. var frag = this;
  3211. _super.init.apply(frag, arguments);
  3212. frag.jQwrap(frag.jQ);
  3213. };
  3214. _.jQwrap = function(children) {
  3215. this.jQ = children.wrapAll('<span class="selection"></span>').parent();
  3216. //can't do wrapAll(this.jQ = $(...)) because wrapAll will clone it
  3217. };
  3218. _.adopt = function() {
  3219. this.jQ.replaceWith(this.jQ = this.jQ.children());
  3220. return _super.adopt.apply(this, arguments);
  3221. };
  3222. _.clear = function() {
  3223. this.jQ.replaceWith(this.jQ.children());
  3224. return this;
  3225. };
  3226. _.levelUp = function() {
  3227. var seln = this,
  3228. gramp = seln.ends[L] = seln.ends[R] = seln.ends[R].parent.parent;
  3229. seln.clear().jQwrap(gramp.jQ);
  3230. return seln;
  3231. };
  3232. _.extendDir = function(dir) {
  3233. prayDirection(dir);
  3234. this.ends[dir] = this.ends[dir][dir];
  3235. this.ends[dir].jQ.insAtDirEnd(dir, this.jQ);
  3236. return this;
  3237. };
  3238. _.extendLeft = function() { return this.extendDir(L); };
  3239. _.extendRight = function() { return this.extendDir(R); };
  3240. _.retractDir = function(dir) {
  3241. prayDirection(dir);
  3242. this.ends[-dir].jQ.insDirOf(-dir, this.jQ);
  3243. this.ends[-dir] = this.ends[-dir][dir];
  3244. };
  3245. _.retractRight = function() { return this.retractDir(R); };
  3246. _.retractLeft = function() { return this.retractDir(L); };
  3247. });
  3248. /*********************************************************
  3249. * The actual jQuery plugin and document ready handlers.
  3250. ********************************************************/
  3251. //The publicy exposed method of jQuery.prototype, available (and meant to be
  3252. //called) on jQuery-wrapped HTML DOM elements.
  3253. jQuery.fn.mathquill = function(cmd, latex) {
  3254. switch (cmd) {
  3255. case 'redraw':
  3256. return this.each(function() {
  3257. var blockId = $(this).attr(mqBlockId),
  3258. rootBlock = blockId && MathElement[blockId];
  3259. if (rootBlock) {
  3260. (function postOrderRedraw(el) {
  3261. el.eachChild(postOrderRedraw);
  3262. if (el.redraw) el.redraw();
  3263. }(rootBlock));
  3264. }
  3265. });
  3266. case 'revert':
  3267. return this.each(function() {
  3268. var blockId = $(this).attr(mqBlockId),
  3269. block = blockId && MathElement[blockId];
  3270. if (block && block.revert)
  3271. block.revert();
  3272. });
  3273. case 'latex':
  3274. if (arguments.length > 1) {
  3275. return this.each(function() {
  3276. var blockId = $(this).attr(mqBlockId),
  3277. block = blockId && MathElement[blockId];
  3278. if (block)
  3279. block.renderLatex(latex);
  3280. });
  3281. }
  3282. var blockId = $(this).attr(mqBlockId),
  3283. block = blockId && MathElement[blockId];
  3284. return block && block.latex();
  3285. case 'text':
  3286. var blockId = $(this).attr(mqBlockId),
  3287. block = blockId && MathElement[blockId];
  3288. return block && block.text();
  3289. case 'html':
  3290. return this.html().replace(/ ?hasCursor|hasCursor /, '')
  3291. .replace(/ class=(""|(?= |>))/g, '')
  3292. .replace(/<span class="?cursor( blink)?"?><\/span>/i, '')
  3293. .replace(/<span class="?textarea"?><textarea><\/textarea><\/span>/i, '');
  3294. case 'write':
  3295. if (arguments.length > 1)
  3296. return this.each(function() {
  3297. var blockId = $(this).attr(mqBlockId),
  3298. block = blockId && MathElement[blockId],
  3299. cursor = block && block.cursor;
  3300. if (cursor)
  3301. cursor.writeLatex(latex).parent.blur();
  3302. });
  3303. case 'cmd':
  3304. if (arguments.length > 1)
  3305. return this.each(function() {
  3306. var blockId = $(this).attr(mqBlockId),
  3307. block = blockId && MathElement[blockId],
  3308. cursor = block && block.cursor;
  3309. if (cursor) {
  3310. var seln = cursor.prepareWrite();
  3311. if (/^\\[a-z]+$/i.test(latex)) cursor.insertCmd(latex.slice(1), seln);
  3312. else cursor.insertCh(latex, seln);
  3313. cursor.hide().parent.blur();
  3314. }
  3315. });
  3316. default:
  3317. var textbox = cmd === 'textbox',
  3318. editable = textbox || cmd === 'editable',
  3319. RootBlock = textbox ? RootTextBlock : RootMathBlock;
  3320. return this.each(function() {
  3321. createRoot($(this), RootBlock(), textbox, editable);
  3322. });
  3323. }
  3324. };
  3325. //on document ready, mathquill-ify all `<tag class="mathquill-*">latex</tag>`
  3326. //elements according to their CSS class.
  3327. jQuery(function() {
  3328. jQuery('.mathquill-editable:not(.mathquill-rendered-math)').mathquill('editable');
  3329. jQuery('.mathquill-textbox:not(.mathquill-rendered-math)').mathquill('textbox');
  3330. jQuery('.mathquill-embedded-latex').mathquill();
  3331. });
  3332. }());