mathquill-basic.js 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121
  1. /**
  2. * MathQuill v0.10.1 http://mathquill.com
  3. * by Han, Jeanine, and Mary maintainers@mathquill.com
  4. *
  5. * This Source Code Form is subject to the terms of the
  6. * Mozilla Public License, v. 2.0. If a copy of the MPL
  7. * was not distributed with this file, You can obtain
  8. * one at http://mozilla.org/MPL/2.0/.
  9. */
  10. (function() {
  11. var jQuery = window.jQuery,
  12. undefined,
  13. mqCmdId = 'mathquill-command-id',
  14. mqBlockId = 'mathquill-block-id',
  15. min = Math.min,
  16. max = Math.max;
  17. function noop() {}
  18. /**
  19. * A utility higher-order function that makes defining variadic
  20. * functions more convenient by letting you essentially define functions
  21. * with the last argument as a splat, i.e. the last argument "gathers up"
  22. * remaining arguments to the function:
  23. * var doStuff = variadic(function(first, rest) { return rest; });
  24. * doStuff(1, 2, 3); // => [2, 3]
  25. */
  26. var __slice = [].slice;
  27. function variadic(fn) {
  28. var numFixedArgs = fn.length - 1;
  29. return function() {
  30. var args = __slice.call(arguments, 0, numFixedArgs);
  31. var varArg = __slice.call(arguments, numFixedArgs);
  32. return fn.apply(this, args.concat([ varArg ]));
  33. };
  34. }
  35. /**
  36. * A utility higher-order function that makes combining object-oriented
  37. * programming and functional programming techniques more convenient:
  38. * given a method name and any number of arguments to be bound, returns
  39. * a function that calls it's first argument's method of that name (if
  40. * it exists) with the bound arguments and any additional arguments that
  41. * are passed:
  42. * var sendMethod = send('method', 1, 2);
  43. * var obj = { method: function() { return Array.apply(this, arguments); } };
  44. * sendMethod(obj, 3, 4); // => [1, 2, 3, 4]
  45. * // or more specifically,
  46. * var obj2 = { method: function(one, two, three) { return one*two + three; } };
  47. * sendMethod(obj2, 3); // => 5
  48. * sendMethod(obj2, 4); // => 6
  49. */
  50. var send = variadic(function(method, args) {
  51. return variadic(function(obj, moreArgs) {
  52. if (method in obj) return obj[method].apply(obj, args.concat(moreArgs));
  53. });
  54. });
  55. /**
  56. * A utility higher-order function that creates "implicit iterators"
  57. * from "generators": given a function that takes in a sole argument,
  58. * a "yield_" function, that calls "yield_" repeatedly with an object as
  59. * a sole argument (presumably objects being iterated over), returns
  60. * a function that calls it's first argument on each of those objects
  61. * (if the first argument is a function, it is called repeatedly with
  62. * each object as the first argument, otherwise it is stringified and
  63. * the method of that name is called on each object (if such a method
  64. * exists)), passing along all additional arguments:
  65. * var a = [
  66. * { method: function(list) { list.push(1); } },
  67. * { method: function(list) { list.push(2); } },
  68. * { method: function(list) { list.push(3); } }
  69. * ];
  70. * a.each = iterator(function(yield_) {
  71. * for (var i in this) yield_(this[i]);
  72. * });
  73. * var list = [];
  74. * a.each('method', list);
  75. * list; // => [1, 2, 3]
  76. * // Note that the for-in loop will yield 'each', but 'each' maps to
  77. * // the function object created by iterator() which does not have a
  78. * // .method() method, so that just fails silently.
  79. */
  80. function iterator(generator) {
  81. return variadic(function(fn, args) {
  82. if (typeof fn !== 'function') fn = send(fn);
  83. var yield_ = function(obj) { return fn.apply(obj, [ obj ].concat(args)); };
  84. return generator.call(this, yield_);
  85. });
  86. }
  87. /**
  88. * sugar to make defining lots of commands easier.
  89. * TODO: rethink this.
  90. */
  91. function bind(cons /*, args... */) {
  92. var args = __slice.call(arguments, 1);
  93. return function() {
  94. return cons.apply(this, args);
  95. };
  96. }
  97. /**
  98. * a development-only debug method. This definition and all
  99. * calls to `pray` will be stripped from the minified
  100. * build of mathquill.
  101. *
  102. * This function must be called by name to be removed
  103. * at compile time. Do not define another function
  104. * with the same name, and only call this function by
  105. * name.
  106. */
  107. function pray(message, cond) {
  108. if (!cond) throw new Error('prayer failed: '+message);
  109. }
  110. var P = (function(prototype, ownProperty, undefined) {
  111. // helper functions that also help minification
  112. function isObject(o) { return typeof o === 'object'; }
  113. function isFunction(f) { return typeof f === 'function'; }
  114. // used to extend the prototypes of superclasses (which might not
  115. // have `.Bare`s)
  116. function SuperclassBare() {}
  117. return function P(_superclass /* = Object */, definition) {
  118. // handle the case where no superclass is given
  119. if (definition === undefined) {
  120. definition = _superclass;
  121. _superclass = Object;
  122. }
  123. // C is the class to be returned.
  124. //
  125. // It delegates to instantiating an instance of `Bare`, so that it
  126. // will always return a new instance regardless of the calling
  127. // context.
  128. //
  129. // TODO: the Chrome inspector shows all created objects as `C`
  130. // rather than `Object`. Setting the .name property seems to
  131. // have no effect. Is there a way to override this behavior?
  132. function C() {
  133. var self = new Bare;
  134. if (isFunction(self.init)) self.init.apply(self, arguments);
  135. return self;
  136. }
  137. // C.Bare is a class with a noop constructor. Its prototype is the
  138. // same as C, so that instances of C.Bare are also instances of C.
  139. // New objects can be allocated without initialization by calling
  140. // `new MyClass.Bare`.
  141. function Bare() {}
  142. C.Bare = Bare;
  143. // Set up the prototype of the new class.
  144. var _super = SuperclassBare[prototype] = _superclass[prototype];
  145. var proto = Bare[prototype] = C[prototype] = C.p = new SuperclassBare;
  146. // other variables, as a minifier optimization
  147. var extensions;
  148. // set the constructor property on the prototype, for convenience
  149. proto.constructor = C;
  150. C.mixin = function(def) {
  151. Bare[prototype] = C[prototype] = P(C, def)[prototype];
  152. return C;
  153. }
  154. return (C.open = function(def) {
  155. extensions = {};
  156. if (isFunction(def)) {
  157. // call the defining function with all the arguments you need
  158. // extensions captures the return value.
  159. extensions = def.call(C, proto, _super, C, _superclass);
  160. }
  161. else if (isObject(def)) {
  162. // if you passed an object instead, we'll take it
  163. extensions = def;
  164. }
  165. // ...and extend it
  166. if (isObject(extensions)) {
  167. for (var ext in extensions) {
  168. if (ownProperty.call(extensions, ext)) {
  169. proto[ext] = extensions[ext];
  170. }
  171. }
  172. }
  173. // if there's no init, we assume we're inheriting a non-pjs class, so
  174. // we default to applying the superclass's constructor.
  175. if (!isFunction(proto.init)) {
  176. proto.init = _superclass;
  177. }
  178. return C;
  179. })(definition);
  180. }
  181. // as a minifier optimization, we've closured in a few helper functions
  182. // and the string 'prototype' (C[p] is much shorter than C.prototype)
  183. })('prototype', ({}).hasOwnProperty);
  184. /*************************************************
  185. * Base classes of edit tree-related objects
  186. *
  187. * Only doing tree node manipulation via these
  188. * adopt/ disown methods guarantees well-formedness
  189. * of the tree.
  190. ************************************************/
  191. // L = 'left'
  192. // R = 'right'
  193. //
  194. // the contract is that they can be used as object properties
  195. // and (-L) === R, and (-R) === L.
  196. var L = -1;
  197. var R = 1;
  198. function prayDirection(dir) {
  199. pray('a direction was passed', dir === L || dir === R);
  200. }
  201. /**
  202. * Tiny extension of jQuery adding directionalized DOM manipulation methods.
  203. *
  204. * Funny how Pjs v3 almost just works with `jQuery.fn.init`.
  205. *
  206. * jQuery features that don't work on $:
  207. * - jQuery.*, like jQuery.ajax, obviously (Pjs doesn't and shouldn't
  208. * copy constructor properties)
  209. *
  210. * - jQuery(function), the shortcut for `jQuery(document).ready(function)`,
  211. * because `jQuery.fn.init` is idiosyncratic and Pjs doing, essentially,
  212. * `jQuery.fn.init.apply(this, arguments)` isn't quite right, you need:
  213. *
  214. * _.init = function(s, c) { jQuery.fn.init.call(this, s, c, $(document)); };
  215. *
  216. * if you actually give a shit (really, don't bother),
  217. * see https://github.com/jquery/jquery/blob/1.7.2/src/core.js#L889
  218. *
  219. * - jQuery(selector), because jQuery translates that to
  220. * `jQuery(document).find(selector)`, but Pjs doesn't (should it?) let
  221. * you override the result of a constructor call
  222. * + note that because of the jQuery(document) shortcut-ness, there's also
  223. * the 3rd-argument-needs-to-be-`$(document)` thing above, but the fix
  224. * for that (as can be seen above) is really easy. This problem requires
  225. * a way more intrusive fix
  226. *
  227. * And that's it! Everything else just magically works because jQuery internally
  228. * uses `this.constructor()` everywhere (hence calling `$`), but never ever does
  229. * `this.constructor.find` or anything like that, always doing `jQuery.find`.
  230. */
  231. var $ = P(jQuery, function(_) {
  232. _.insDirOf = function(dir, el) {
  233. return dir === L ?
  234. this.insertBefore(el.first()) : this.insertAfter(el.last());
  235. };
  236. _.insAtDirEnd = function(dir, el) {
  237. return dir === L ? this.prependTo(el) : this.appendTo(el);
  238. };
  239. });
  240. var Point = P(function(_) {
  241. _.parent = 0;
  242. _[L] = 0;
  243. _[R] = 0;
  244. _.init = function(parent, leftward, rightward) {
  245. this.parent = parent;
  246. this[L] = leftward;
  247. this[R] = rightward;
  248. };
  249. this.copy = function(pt) {
  250. return Point(pt.parent, pt[L], pt[R]);
  251. };
  252. });
  253. /**
  254. * MathQuill virtual-DOM tree-node abstract base class
  255. */
  256. var Node = P(function(_) {
  257. _[L] = 0;
  258. _[R] = 0
  259. _.parent = 0;
  260. var id = 0;
  261. function uniqueNodeId() { return id += 1; }
  262. this.byId = {};
  263. _.init = function() {
  264. this.id = uniqueNodeId();
  265. Node.byId[this.id] = this;
  266. this.ends = {};
  267. this.ends[L] = 0;
  268. this.ends[R] = 0;
  269. };
  270. _.dispose = function() { delete Node.byId[this.id]; };
  271. _.toString = function() { return '{{ MathQuill Node #'+this.id+' }}'; };
  272. _.jQ = $();
  273. _.jQadd = function(jQ) { return this.jQ = this.jQ.add(jQ); };
  274. _.jQize = function(jQ) {
  275. // jQuery-ifies this.html() and links up the .jQ of all corresponding Nodes
  276. var jQ = $(jQ || this.html());
  277. function jQadd(el) {
  278. if (el.getAttribute) {
  279. var cmdId = el.getAttribute('mathquill-command-id');
  280. var blockId = el.getAttribute('mathquill-block-id');
  281. if (cmdId) Node.byId[cmdId].jQadd(el);
  282. if (blockId) Node.byId[blockId].jQadd(el);
  283. }
  284. for (el = el.firstChild; el; el = el.nextSibling) {
  285. jQadd(el);
  286. }
  287. }
  288. for (var i = 0; i < jQ.length; i += 1) jQadd(jQ[i]);
  289. return jQ;
  290. };
  291. _.createDir = function(dir, cursor) {
  292. prayDirection(dir);
  293. var node = this;
  294. node.jQize();
  295. node.jQ.insDirOf(dir, cursor.jQ);
  296. cursor[dir] = node.adopt(cursor.parent, cursor[L], cursor[R]);
  297. return node;
  298. };
  299. _.createLeftOf = function(el) { return this.createDir(L, el); };
  300. _.selectChildren = function(leftEnd, rightEnd) {
  301. return Selection(leftEnd, rightEnd);
  302. };
  303. _.bubble = iterator(function(yield_) {
  304. for (var ancestor = this; ancestor; ancestor = ancestor.parent) {
  305. var result = yield_(ancestor);
  306. if (result === false) break;
  307. }
  308. return this;
  309. });
  310. _.postOrder = iterator(function(yield_) {
  311. (function recurse(descendant) {
  312. descendant.eachChild(recurse);
  313. yield_(descendant);
  314. })(this);
  315. return this;
  316. });
  317. _.isEmpty = function() {
  318. return this.ends[L] === 0 && this.ends[R] === 0;
  319. };
  320. _.children = function() {
  321. return Fragment(this.ends[L], this.ends[R]);
  322. };
  323. _.eachChild = function() {
  324. var children = this.children();
  325. children.each.apply(children, arguments);
  326. return this;
  327. };
  328. _.foldChildren = function(fold, fn) {
  329. return this.children().fold(fold, fn);
  330. };
  331. _.withDirAdopt = function(dir, parent, withDir, oppDir) {
  332. Fragment(this, this).withDirAdopt(dir, parent, withDir, oppDir);
  333. return this;
  334. };
  335. _.adopt = function(parent, leftward, rightward) {
  336. Fragment(this, this).adopt(parent, leftward, rightward);
  337. return this;
  338. };
  339. _.disown = function() {
  340. Fragment(this, this).disown();
  341. return this;
  342. };
  343. _.remove = function() {
  344. this.jQ.remove();
  345. this.postOrder('dispose');
  346. return this.disown();
  347. };
  348. });
  349. function prayWellFormed(parent, leftward, rightward) {
  350. pray('a parent is always present', parent);
  351. pray('leftward is properly set up', (function() {
  352. // either it's empty and `rightward` is the left end child (possibly empty)
  353. if (!leftward) return parent.ends[L] === rightward;
  354. // or it's there and its [R] and .parent are properly set up
  355. return leftward[R] === rightward && leftward.parent === parent;
  356. })());
  357. pray('rightward is properly set up', (function() {
  358. // either it's empty and `leftward` is the right end child (possibly empty)
  359. if (!rightward) return parent.ends[R] === leftward;
  360. // or it's there and its [L] and .parent are properly set up
  361. return rightward[L] === leftward && rightward.parent === parent;
  362. })());
  363. }
  364. /**
  365. * An entity outside the virtual tree with one-way pointers (so it's only a
  366. * "view" of part of the tree, not an actual node/entity in the tree) that
  367. * delimits a doubly-linked list of sibling nodes.
  368. * It's like a fanfic love-child between HTML DOM DocumentFragment and the Range
  369. * classes: like DocumentFragment, its contents must be sibling nodes
  370. * (unlike Range, whose contents are arbitrary contiguous pieces of subtrees),
  371. * but like Range, it has only one-way pointers to its contents, its contents
  372. * have no reference to it and in fact may still be in the visible tree (unlike
  373. * DocumentFragment, whose contents must be detached from the visible tree
  374. * and have their 'parent' pointers set to the DocumentFragment).
  375. */
  376. var Fragment = P(function(_) {
  377. _.init = function(withDir, oppDir, dir) {
  378. if (dir === undefined) dir = L;
  379. prayDirection(dir);
  380. pray('no half-empty fragments', !withDir === !oppDir);
  381. this.ends = {};
  382. if (!withDir) return;
  383. pray('withDir is passed to Fragment', withDir instanceof Node);
  384. pray('oppDir is passed to Fragment', oppDir instanceof Node);
  385. pray('withDir and oppDir have the same parent',
  386. withDir.parent === oppDir.parent);
  387. this.ends[dir] = withDir;
  388. this.ends[-dir] = oppDir;
  389. // To build the jquery collection for a fragment, accumulate elements
  390. // into an array and then call jQ.add once on the result. jQ.add sorts the
  391. // collection according to document order each time it is called, so
  392. // building a collection by folding jQ.add directly takes more than
  393. // quadratic time in the number of elements.
  394. //
  395. // https://github.com/jquery/jquery/blob/2.1.4/src/traversing.js#L112
  396. var accum = this.fold([], function (accum, el) {
  397. accum.push.apply(accum, el.jQ.get());
  398. return accum;
  399. });
  400. this.jQ = this.jQ.add(accum);
  401. };
  402. _.jQ = $();
  403. // like Cursor::withDirInsertAt(dir, parent, withDir, oppDir)
  404. _.withDirAdopt = function(dir, parent, withDir, oppDir) {
  405. return (dir === L ? this.adopt(parent, withDir, oppDir)
  406. : this.adopt(parent, oppDir, withDir));
  407. };
  408. _.adopt = function(parent, leftward, rightward) {
  409. prayWellFormed(parent, leftward, rightward);
  410. var self = this;
  411. self.disowned = false;
  412. var leftEnd = self.ends[L];
  413. if (!leftEnd) return this;
  414. var rightEnd = self.ends[R];
  415. if (leftward) {
  416. // NB: this is handled in the ::each() block
  417. // leftward[R] = leftEnd
  418. } else {
  419. parent.ends[L] = leftEnd;
  420. }
  421. if (rightward) {
  422. rightward[L] = rightEnd;
  423. } else {
  424. parent.ends[R] = rightEnd;
  425. }
  426. self.ends[R][R] = rightward;
  427. self.each(function(el) {
  428. el[L] = leftward;
  429. el.parent = parent;
  430. if (leftward) leftward[R] = el;
  431. leftward = el;
  432. });
  433. return self;
  434. };
  435. _.disown = function() {
  436. var self = this;
  437. var leftEnd = self.ends[L];
  438. // guard for empty and already-disowned fragments
  439. if (!leftEnd || self.disowned) return self;
  440. self.disowned = true;
  441. var rightEnd = self.ends[R]
  442. var parent = leftEnd.parent;
  443. prayWellFormed(parent, leftEnd[L], leftEnd);
  444. prayWellFormed(parent, rightEnd, rightEnd[R]);
  445. if (leftEnd[L]) {
  446. leftEnd[L][R] = rightEnd[R];
  447. } else {
  448. parent.ends[L] = rightEnd[R];
  449. }
  450. if (rightEnd[R]) {
  451. rightEnd[R][L] = leftEnd[L];
  452. } else {
  453. parent.ends[R] = leftEnd[L];
  454. }
  455. return self;
  456. };
  457. _.remove = function() {
  458. this.jQ.remove();
  459. this.each('postOrder', 'dispose');
  460. return this.disown();
  461. };
  462. _.each = iterator(function(yield_) {
  463. var self = this;
  464. var el = self.ends[L];
  465. if (!el) return self;
  466. for (; el !== self.ends[R][R]; el = el[R]) {
  467. var result = yield_(el);
  468. if (result === false) break;
  469. }
  470. return self;
  471. });
  472. _.fold = function(fold, fn) {
  473. this.each(function(el) {
  474. fold = fn.call(this, fold, el);
  475. });
  476. return fold;
  477. };
  478. });
  479. /**
  480. * Registry of LaTeX commands and commands created when typing
  481. * a single character.
  482. *
  483. * (Commands are all subclasses of Node.)
  484. */
  485. var LatexCmds = {}, CharCmds = {};
  486. /********************************************
  487. * Cursor and Selection "singleton" classes
  488. *******************************************/
  489. /* The main thing that manipulates the Math DOM. Makes sure to manipulate the
  490. HTML DOM to match. */
  491. /* Sort of singletons, since there should only be one per editable math
  492. textbox, but any one HTML document can contain many such textboxes, so any one
  493. JS environment could actually contain many instances. */
  494. //A fake cursor in the fake textbox that the math is rendered in.
  495. var Cursor = P(Point, function(_) {
  496. _.init = function(initParent, options) {
  497. this.parent = initParent;
  498. this.options = options;
  499. var jQ = this.jQ = this._jQ = $('<span class="mq-cursor">&#8203;</span>');
  500. //closured for setInterval
  501. this.blink = function(){ jQ.toggleClass('mq-blink'); };
  502. this.upDownCache = {};
  503. };
  504. _.show = function() {
  505. this.jQ = this._jQ.removeClass('mq-blink');
  506. if ('intervalId' in this) //already was shown, just restart interval
  507. clearInterval(this.intervalId);
  508. else { //was hidden and detached, insert this.jQ back into HTML DOM
  509. if (this[R]) {
  510. if (this.selection && this.selection.ends[L][L] === this[L])
  511. this.jQ.insertBefore(this.selection.jQ);
  512. else
  513. this.jQ.insertBefore(this[R].jQ.first());
  514. }
  515. else
  516. this.jQ.appendTo(this.parent.jQ);
  517. this.parent.focus();
  518. }
  519. this.intervalId = setInterval(this.blink, 500);
  520. return this;
  521. };
  522. _.hide = function() {
  523. if ('intervalId' in this)
  524. clearInterval(this.intervalId);
  525. delete this.intervalId;
  526. this.jQ.detach();
  527. this.jQ = $();
  528. return this;
  529. };
  530. _.withDirInsertAt = function(dir, parent, withDir, oppDir) {
  531. var oldParent = this.parent;
  532. this.parent = parent;
  533. this[dir] = withDir;
  534. this[-dir] = oppDir;
  535. // by contract, .blur() is called after all has been said and done
  536. // and the cursor has actually been moved
  537. if (oldParent !== parent && oldParent.blur) oldParent.blur();
  538. };
  539. _.insDirOf = function(dir, el) {
  540. prayDirection(dir);
  541. this.jQ.insDirOf(dir, el.jQ);
  542. this.withDirInsertAt(dir, el.parent, el[dir], el);
  543. this.parent.jQ.addClass('mq-hasCursor');
  544. return this;
  545. };
  546. _.insLeftOf = function(el) { return this.insDirOf(L, el); };
  547. _.insRightOf = function(el) { return this.insDirOf(R, el); };
  548. _.insAtDirEnd = function(dir, el) {
  549. prayDirection(dir);
  550. this.jQ.insAtDirEnd(dir, el.jQ);
  551. this.withDirInsertAt(dir, el, 0, el.ends[dir]);
  552. el.focus();
  553. return this;
  554. };
  555. _.insAtLeftEnd = function(el) { return this.insAtDirEnd(L, el); };
  556. _.insAtRightEnd = function(el) { return this.insAtDirEnd(R, el); };
  557. /**
  558. * jump up or down from one block Node to another:
  559. * - cache the current Point in the node we're jumping from
  560. * - check if there's a Point in it cached for the node we're jumping to
  561. * + if so put the cursor there,
  562. * + if not seek a position in the node that is horizontally closest to
  563. * the cursor's current position
  564. */
  565. _.jumpUpDown = function(from, to) {
  566. var self = this;
  567. self.upDownCache[from.id] = Point.copy(self);
  568. var cached = self.upDownCache[to.id];
  569. if (cached) {
  570. cached[R] ? self.insLeftOf(cached[R]) : self.insAtRightEnd(cached.parent);
  571. }
  572. else {
  573. var pageX = self.offset().left;
  574. to.seek(pageX, self);
  575. }
  576. };
  577. _.offset = function() {
  578. //in Opera 11.62, .getBoundingClientRect() and hence jQuery::offset()
  579. //returns all 0's on inline elements with negative margin-right (like
  580. //the cursor) at the end of their parent, so temporarily remove the
  581. //negative margin-right when calling jQuery::offset()
  582. //Opera bug DSK-360043
  583. //http://bugs.jquery.com/ticket/11523
  584. //https://github.com/jquery/jquery/pull/717
  585. var self = this, offset = self.jQ.removeClass('mq-cursor').offset();
  586. self.jQ.addClass('mq-cursor');
  587. return offset;
  588. }
  589. _.unwrapGramp = function() {
  590. var gramp = this.parent.parent;
  591. var greatgramp = gramp.parent;
  592. var rightward = gramp[R];
  593. var cursor = this;
  594. var leftward = gramp[L];
  595. gramp.disown().eachChild(function(uncle) {
  596. if (uncle.isEmpty()) return;
  597. uncle.children()
  598. .adopt(greatgramp, leftward, rightward)
  599. .each(function(cousin) {
  600. cousin.jQ.insertBefore(gramp.jQ.first());
  601. })
  602. ;
  603. leftward = uncle.ends[R];
  604. });
  605. if (!this[R]) { //then find something to be rightward to insLeftOf
  606. if (this[L])
  607. this[R] = this[L][R];
  608. else {
  609. while (!this[R]) {
  610. this.parent = this.parent[R];
  611. if (this.parent)
  612. this[R] = this.parent.ends[L];
  613. else {
  614. this[R] = gramp[R];
  615. this.parent = greatgramp;
  616. break;
  617. }
  618. }
  619. }
  620. }
  621. if (this[R])
  622. this.insLeftOf(this[R]);
  623. else
  624. this.insAtRightEnd(greatgramp);
  625. gramp.jQ.remove();
  626. if (gramp[L].siblingDeleted) gramp[L].siblingDeleted(cursor.options, R);
  627. if (gramp[R].siblingDeleted) gramp[R].siblingDeleted(cursor.options, L);
  628. };
  629. _.startSelection = function() {
  630. var anticursor = this.anticursor = Point.copy(this);
  631. var ancestors = anticursor.ancestors = {}; // a map from each ancestor of
  632. // the anticursor, to its child that is also an ancestor; in other words,
  633. // the anticursor's ancestor chain in reverse order
  634. for (var ancestor = anticursor; ancestor.parent; ancestor = ancestor.parent) {
  635. ancestors[ancestor.parent.id] = ancestor;
  636. }
  637. };
  638. _.endSelection = function() {
  639. delete this.anticursor;
  640. };
  641. _.select = function() {
  642. var anticursor = this.anticursor;
  643. if (this[L] === anticursor[L] && this.parent === anticursor.parent) return false;
  644. // Find the lowest common ancestor (`lca`), and the ancestor of the cursor
  645. // whose parent is the LCA (which'll be an end of the selection fragment).
  646. for (var ancestor = this; ancestor.parent; ancestor = ancestor.parent) {
  647. if (ancestor.parent.id in anticursor.ancestors) {
  648. var lca = ancestor.parent;
  649. break;
  650. }
  651. }
  652. pray('cursor and anticursor in the same tree', lca);
  653. // The cursor and the anticursor should be in the same tree, because the
  654. // mousemove handler attached to the document, unlike the one attached to
  655. // the root HTML DOM element, doesn't try to get the math tree node of the
  656. // mousemove target, and Cursor::seek() based solely on coordinates stays
  657. // within the tree of `this` cursor's root.
  658. // The other end of the selection fragment, the ancestor of the anticursor
  659. // whose parent is the LCA.
  660. var antiAncestor = anticursor.ancestors[lca.id];
  661. // Now we have two either Nodes or Points, guaranteed to have a common
  662. // parent and guaranteed that if both are Points, they are not the same,
  663. // and we have to figure out which is the left end and which the right end
  664. // of the selection.
  665. var leftEnd, rightEnd, dir = R;
  666. // This is an extremely subtle algorithm.
  667. // As a special case, `ancestor` could be a Point and `antiAncestor` a Node
  668. // immediately to `ancestor`'s left.
  669. // In all other cases,
  670. // - both Nodes
  671. // - `ancestor` a Point and `antiAncestor` a Node
  672. // - `ancestor` a Node and `antiAncestor` a Point
  673. // `antiAncestor[R] === rightward[R]` for some `rightward` that is
  674. // `ancestor` or to its right, if and only if `antiAncestor` is to
  675. // the right of `ancestor`.
  676. if (ancestor[L] !== antiAncestor) {
  677. for (var rightward = ancestor; rightward; rightward = rightward[R]) {
  678. if (rightward[R] === antiAncestor[R]) {
  679. dir = L;
  680. leftEnd = ancestor;
  681. rightEnd = antiAncestor;
  682. break;
  683. }
  684. }
  685. }
  686. if (dir === R) {
  687. leftEnd = antiAncestor;
  688. rightEnd = ancestor;
  689. }
  690. // only want to select Nodes up to Points, can't select Points themselves
  691. if (leftEnd instanceof Point) leftEnd = leftEnd[R];
  692. if (rightEnd instanceof Point) rightEnd = rightEnd[L];
  693. this.hide().selection = lca.selectChildren(leftEnd, rightEnd);
  694. this.insDirOf(dir, this.selection.ends[dir]);
  695. this.selectionChanged();
  696. return true;
  697. };
  698. _.clearSelection = function() {
  699. if (this.selection) {
  700. this.selection.clear();
  701. delete this.selection;
  702. this.selectionChanged();
  703. }
  704. return this;
  705. };
  706. _.deleteSelection = function() {
  707. if (!this.selection) return;
  708. this[L] = this.selection.ends[L][L];
  709. this[R] = this.selection.ends[R][R];
  710. this.selection.remove();
  711. this.selectionChanged();
  712. delete this.selection;
  713. };
  714. _.replaceSelection = function() {
  715. var seln = this.selection;
  716. if (seln) {
  717. this[L] = seln.ends[L][L];
  718. this[R] = seln.ends[R][R];
  719. delete this.selection;
  720. }
  721. return seln;
  722. };
  723. });
  724. var Selection = P(Fragment, function(_, super_) {
  725. _.init = function() {
  726. super_.init.apply(this, arguments);
  727. this.jQ = this.jQ.wrapAll('<span class="mq-selection"></span>').parent();
  728. //can't do wrapAll(this.jQ = $(...)) because wrapAll will clone it
  729. };
  730. _.adopt = function() {
  731. this.jQ.replaceWith(this.jQ = this.jQ.children());
  732. return super_.adopt.apply(this, arguments);
  733. };
  734. _.clear = function() {
  735. // using the browser's native .childNodes property so that we
  736. // don't discard text nodes.
  737. this.jQ.replaceWith(this.jQ[0].childNodes);
  738. return this;
  739. };
  740. _.join = function(methodName) {
  741. return this.fold('', function(fold, child) {
  742. return fold + child[methodName]();
  743. });
  744. };
  745. });
  746. /*********************************************
  747. * Controller for a MathQuill instance,
  748. * on which services are registered with
  749. *
  750. * Controller.open(function(_) { ... });
  751. *
  752. ********************************************/
  753. var Controller = P(function(_) {
  754. _.init = function(root, container, options) {
  755. this.id = root.id;
  756. this.data = {};
  757. this.root = root;
  758. this.container = container;
  759. this.options = options;
  760. root.controller = this;
  761. this.cursor = root.cursor = Cursor(root, options);
  762. // TODO: stop depending on root.cursor, and rm it
  763. };
  764. _.handle = function(name, dir) {
  765. var handlers = this.options.handlers;
  766. if (handlers && handlers.fns[name]) {
  767. var mq = handlers.APIClasses[this.KIND_OF_MQ](this);
  768. if (dir === L || dir === R) handlers.fns[name](dir, mq);
  769. else handlers.fns[name](mq);
  770. }
  771. };
  772. var notifyees = [];
  773. this.onNotify = function(f) { notifyees.push(f); };
  774. _.notify = function() {
  775. for (var i = 0; i < notifyees.length; i += 1) {
  776. notifyees[i].apply(this.cursor, arguments);
  777. }
  778. return this;
  779. };
  780. });
  781. /*********************************************************
  782. * The publicly exposed MathQuill API.
  783. ********************************************************/
  784. var API = {}, Options = P(), optionProcessors = {}, Progenote = P(), EMBEDS = {};
  785. /**
  786. * Interface Versioning (#459, #495) to allow us to virtually guarantee
  787. * backcompat. v0.10.x introduces it, so for now, don't completely break the
  788. * API for people who don't know about it, just complain with console.warn().
  789. *
  790. * The methods are shimmed in outro.js so that MQ.MathField.prototype etc can
  791. * be accessed.
  792. */
  793. function insistOnInterVer() {
  794. if (window.console) console.warn(
  795. 'You are using the MathQuill API without specifying an interface version, ' +
  796. 'which will fail in v1.0.0. You can fix this easily by doing this before ' +
  797. 'doing anything else:\n' +
  798. '\n' +
  799. ' MathQuill = MathQuill.getInterface(1);\n' +
  800. ' // now MathQuill.MathField() works like it used to\n' +
  801. '\n' +
  802. 'See also the "`dev` branch (2014\u20132015) \u2192 v0.10.0 Migration Guide" at\n' +
  803. ' https://github.com/mathquill/mathquill/wiki/%60dev%60-branch-(2014%E2%80%932015)-%E2%86%92-v0.10.0-Migration-Guide'
  804. );
  805. }
  806. // globally exported API object
  807. function MathQuill(el) {
  808. insistOnInterVer();
  809. return MQ1(el);
  810. };
  811. MathQuill.prototype = Progenote.p;
  812. MathQuill.interfaceVersion = function(v) {
  813. // shim for #459-era interface versioning (ended with #495)
  814. if (v !== 1) throw 'Only interface version 1 supported. You specified: ' + v;
  815. insistOnInterVer = function() {
  816. if (window.console) console.warn(
  817. 'You called MathQuill.interfaceVersion(1); to specify the interface ' +
  818. 'version, which will fail in v1.0.0. You can fix this easily by doing ' +
  819. 'this before doing anything else:\n' +
  820. '\n' +
  821. ' MathQuill = MathQuill.getInterface(1);\n' +
  822. ' // now MathQuill.MathField() works like it used to\n' +
  823. '\n' +
  824. 'See also the "`dev` branch (2014\u20132015) \u2192 v0.10.0 Migration Guide" at\n' +
  825. ' https://github.com/mathquill/mathquill/wiki/%60dev%60-branch-(2014%E2%80%932015)-%E2%86%92-v0.10.0-Migration-Guide'
  826. );
  827. };
  828. insistOnInterVer();
  829. return MathQuill;
  830. };
  831. MathQuill.getInterface = getInterface;
  832. var MIN = getInterface.MIN = 1, MAX = getInterface.MAX = 2;
  833. function getInterface(v) {
  834. if (!(MIN <= v && v <= MAX)) throw 'Only interface versions between ' +
  835. MIN + ' and ' + MAX + ' supported. You specified: ' + v;
  836. /**
  837. * Function that takes an HTML element and, if it's the root HTML element of a
  838. * static math or math or text field, returns an API object for it (else, null).
  839. *
  840. * var mathfield = MQ.MathField(mathFieldSpan);
  841. * assert(MQ(mathFieldSpan).id === mathfield.id);
  842. * assert(MQ(mathFieldSpan).id === MQ(mathFieldSpan).id);
  843. *
  844. */
  845. function MQ(el) {
  846. if (!el || !el.nodeType) return null; // check that `el` is a HTML element, using the
  847. // same technique as jQuery: https://github.com/jquery/jquery/blob/679536ee4b7a92ae64a5f58d90e9cc38c001e807/src/core/init.js#L92
  848. var blockId = $(el).children('.mq-root-block').attr(mqBlockId);
  849. var ctrlr = blockId && Node.byId[blockId].controller;
  850. return ctrlr ? APIClasses[ctrlr.KIND_OF_MQ](ctrlr) : null;
  851. };
  852. var APIClasses = {};
  853. MQ.L = L;
  854. MQ.R = R;
  855. function config(currentOptions, newOptions) {
  856. if (newOptions && newOptions.handlers) {
  857. newOptions.handlers = { fns: newOptions.handlers, APIClasses: APIClasses };
  858. }
  859. for (var name in newOptions) if (newOptions.hasOwnProperty(name)) {
  860. var value = newOptions[name], processor = optionProcessors[name];
  861. currentOptions[name] = (processor ? processor(value) : value);
  862. }
  863. }
  864. MQ.config = function(opts) { config(Options.p, opts); return this; };
  865. MQ.registerEmbed = function(name, options) {
  866. if (!/^[a-z][a-z0-9]*$/i.test(name)) {
  867. throw 'Embed name must start with letter and be only letters and digits';
  868. }
  869. EMBEDS[name] = options;
  870. };
  871. var AbstractMathQuill = APIClasses.AbstractMathQuill = P(Progenote, function(_) {
  872. _.init = function(ctrlr) {
  873. this.__controller = ctrlr;
  874. this.__options = ctrlr.options;
  875. this.id = ctrlr.id;
  876. this.data = ctrlr.data;
  877. };
  878. _.__mathquillify = function(classNames) {
  879. var ctrlr = this.__controller, root = ctrlr.root, el = ctrlr.container;
  880. ctrlr.createTextarea();
  881. var contents = el.addClass(classNames).contents().detach();
  882. root.jQ =
  883. $('<span class="mq-root-block"/>').attr(mqBlockId, root.id).appendTo(el);
  884. this.latex(contents.text());
  885. this.revert = function() {
  886. return el.empty().unbind('.mathquill')
  887. .removeClass('mq-editable-field mq-math-mode mq-text-mode')
  888. .append(contents);
  889. };
  890. };
  891. _.config = function(opts) { config(this.__options, opts); return this; };
  892. _.el = function() { return this.__controller.container[0]; };
  893. _.text = function() { return this.__controller.exportText(); };
  894. _.latex = function(latex) {
  895. if (arguments.length > 0) {
  896. this.__controller.renderLatexMath(latex);
  897. if (this.__controller.blurred) this.__controller.cursor.hide().parent.blur();
  898. return this;
  899. }
  900. return this.__controller.exportLatex();
  901. };
  902. _.html = function() {
  903. return this.__controller.root.jQ.html()
  904. .replace(/ mathquill-(?:command|block)-id="?\d+"?/g, '')
  905. .replace(/<span class="?mq-cursor( mq-blink)?"?>.?<\/span>/i, '')
  906. .replace(/ mq-hasCursor|mq-hasCursor ?/, '')
  907. .replace(/ class=(""|(?= |>))/g, '');
  908. };
  909. _.reflow = function() {
  910. this.__controller.root.postOrder('reflow');
  911. return this;
  912. };
  913. });
  914. MQ.prototype = AbstractMathQuill.prototype;
  915. APIClasses.EditableField = P(AbstractMathQuill, function(_, super_) {
  916. _.__mathquillify = function() {
  917. super_.__mathquillify.apply(this, arguments);
  918. this.__controller.editable = true;
  919. this.__controller.delegateMouseEvents();
  920. this.__controller.editablesTextareaEvents();
  921. return this;
  922. };
  923. _.focus = function() { this.__controller.textarea.focus(); return this; };
  924. _.blur = function() { this.__controller.textarea.blur(); return this; };
  925. _.write = function(latex) {
  926. this.__controller.writeLatex(latex);
  927. this.__controller.scrollHoriz();
  928. if (this.__controller.blurred) this.__controller.cursor.hide().parent.blur();
  929. return this;
  930. };
  931. _.cmd = function(cmd) {
  932. var ctrlr = this.__controller.notify(), cursor = ctrlr.cursor;
  933. if (/^\\[a-z]+$/i.test(cmd)) {
  934. cmd = cmd.slice(1);
  935. var klass = LatexCmds[cmd];
  936. if (klass) {
  937. cmd = klass(cmd);
  938. if (cursor.selection) cmd.replaces(cursor.replaceSelection());
  939. cmd.createLeftOf(cursor.show());
  940. this.__controller.scrollHoriz();
  941. }
  942. else /* TODO: API needs better error reporting */;
  943. }
  944. else cursor.parent.write(cursor, cmd);
  945. if (ctrlr.blurred) cursor.hide().parent.blur();
  946. return this;
  947. };
  948. _.select = function() {
  949. var ctrlr = this.__controller;
  950. ctrlr.notify('move').cursor.insAtRightEnd(ctrlr.root);
  951. while (ctrlr.cursor[L]) ctrlr.selectLeft();
  952. return this;
  953. };
  954. _.clearSelection = function() {
  955. this.__controller.cursor.clearSelection();
  956. return this;
  957. };
  958. _.moveToDirEnd = function(dir) {
  959. this.__controller.notify('move').cursor.insAtDirEnd(dir, this.__controller.root);
  960. return this;
  961. };
  962. _.moveToLeftEnd = function() { return this.moveToDirEnd(L); };
  963. _.moveToRightEnd = function() { return this.moveToDirEnd(R); };
  964. _.keystroke = function(keys) {
  965. var keys = keys.replace(/^\s+|\s+$/g, '').split(/\s+/);
  966. for (var i = 0; i < keys.length; i += 1) {
  967. this.__controller.keystroke(keys[i], { preventDefault: noop });
  968. }
  969. return this;
  970. };
  971. _.typedText = function(text) {
  972. for (var i = 0; i < text.length; i += 1) this.__controller.typedText(text.charAt(i));
  973. return this;
  974. };
  975. _.dropEmbedded = function(pageX, pageY, options) {
  976. var clientX = pageX - $(window).scrollLeft();
  977. var clientY = pageY - $(window).scrollTop();
  978. var el = document.elementFromPoint(clientX, clientY);
  979. this.__controller.seek($(el), pageX, pageY);
  980. var cmd = Embed().setOptions(options);
  981. cmd.createLeftOf(this.__controller.cursor);
  982. };
  983. });
  984. MQ.EditableField = function() { throw "wtf don't call me, I'm 'abstract'"; };
  985. MQ.EditableField.prototype = APIClasses.EditableField.prototype;
  986. /**
  987. * Export the API functions that MathQuill-ify an HTML element into API objects
  988. * of each class. If the element had already been MathQuill-ified but into a
  989. * different kind (or it's not an HTML element), return null.
  990. */
  991. for (var kind in API) (function(kind, defAPIClass) {
  992. var APIClass = APIClasses[kind] = defAPIClass(APIClasses);
  993. MQ[kind] = function(el, opts) {
  994. var mq = MQ(el);
  995. if (mq instanceof APIClass || !el || !el.nodeType) return mq;
  996. var ctrlr = Controller(APIClass.RootBlock(), $(el), Options());
  997. ctrlr.KIND_OF_MQ = kind;
  998. return APIClass(ctrlr).__mathquillify(opts, v);
  999. };
  1000. MQ[kind].prototype = APIClass.prototype;
  1001. }(kind, API[kind]));
  1002. return MQ;
  1003. }
  1004. MathQuill.noConflict = function() {
  1005. window.MathQuill = origMathQuill;
  1006. return MathQuill;
  1007. };
  1008. var origMathQuill = window.MathQuill;
  1009. window.MathQuill = MathQuill;
  1010. function RootBlockMixin(_) {
  1011. var names = 'moveOutOf deleteOutOf selectOutOf upOutOf downOutOf'.split(' ');
  1012. for (var i = 0; i < names.length; i += 1) (function(name) {
  1013. _[name] = function(dir) { this.controller.handle(name, dir); };
  1014. }(names[i]));
  1015. _.reflow = function() {
  1016. this.controller.handle('reflow');
  1017. this.controller.handle('edited');
  1018. this.controller.handle('edit');
  1019. };
  1020. }
  1021. var Parser = P(function(_, super_, Parser) {
  1022. // The Parser object is a wrapper for a parser function.
  1023. // Externally, you use one to parse a string by calling
  1024. // var result = SomeParser.parse('Me Me Me! Parse Me!');
  1025. // You should never call the constructor, rather you should
  1026. // construct your Parser from the base parsers and the
  1027. // parser combinator methods.
  1028. function parseError(stream, message) {
  1029. if (stream) {
  1030. stream = "'"+stream+"'";
  1031. }
  1032. else {
  1033. stream = 'EOF';
  1034. }
  1035. throw 'Parse Error: '+message+' at '+stream;
  1036. }
  1037. _.init = function(body) { this._ = body; };
  1038. _.parse = function(stream) {
  1039. return this.skip(eof)._(''+stream, success, parseError);
  1040. function success(stream, result) { return result; }
  1041. };
  1042. // -*- primitive combinators -*- //
  1043. _.or = function(alternative) {
  1044. pray('or is passed a parser', alternative instanceof Parser);
  1045. var self = this;
  1046. return Parser(function(stream, onSuccess, onFailure) {
  1047. return self._(stream, onSuccess, failure);
  1048. function failure(newStream) {
  1049. return alternative._(stream, onSuccess, onFailure);
  1050. }
  1051. });
  1052. };
  1053. _.then = function(next) {
  1054. var self = this;
  1055. return Parser(function(stream, onSuccess, onFailure) {
  1056. return self._(stream, success, onFailure);
  1057. function success(newStream, result) {
  1058. var nextParser = (next instanceof Parser ? next : next(result));
  1059. pray('a parser is returned', nextParser instanceof Parser);
  1060. return nextParser._(newStream, onSuccess, onFailure);
  1061. }
  1062. });
  1063. };
  1064. // -*- optimized iterative combinators -*- //
  1065. _.many = function() {
  1066. var self = this;
  1067. return Parser(function(stream, onSuccess, onFailure) {
  1068. var xs = [];
  1069. while (self._(stream, success, failure));
  1070. return onSuccess(stream, xs);
  1071. function success(newStream, x) {
  1072. stream = newStream;
  1073. xs.push(x);
  1074. return true;
  1075. }
  1076. function failure() {
  1077. return false;
  1078. }
  1079. });
  1080. };
  1081. _.times = function(min, max) {
  1082. if (arguments.length < 2) max = min;
  1083. var self = this;
  1084. return Parser(function(stream, onSuccess, onFailure) {
  1085. var xs = [];
  1086. var result = true;
  1087. var failure;
  1088. for (var i = 0; i < min; i += 1) {
  1089. result = self._(stream, success, firstFailure);
  1090. if (!result) return onFailure(stream, failure);
  1091. }
  1092. for (; i < max && result; i += 1) {
  1093. result = self._(stream, success, secondFailure);
  1094. }
  1095. return onSuccess(stream, xs);
  1096. function success(newStream, x) {
  1097. xs.push(x);
  1098. stream = newStream;
  1099. return true;
  1100. }
  1101. function firstFailure(newStream, msg) {
  1102. failure = msg;
  1103. stream = newStream;
  1104. return false;
  1105. }
  1106. function secondFailure(newStream, msg) {
  1107. return false;
  1108. }
  1109. });
  1110. };
  1111. // -*- higher-level combinators -*- //
  1112. _.result = function(res) { return this.then(succeed(res)); };
  1113. _.atMost = function(n) { return this.times(0, n); };
  1114. _.atLeast = function(n) {
  1115. var self = this;
  1116. return self.times(n).then(function(start) {
  1117. return self.many().map(function(end) {
  1118. return start.concat(end);
  1119. });
  1120. });
  1121. };
  1122. _.map = function(fn) {
  1123. return this.then(function(result) { return succeed(fn(result)); });
  1124. };
  1125. _.skip = function(two) {
  1126. return this.then(function(result) { return two.result(result); });
  1127. };
  1128. // -*- primitive parsers -*- //
  1129. var string = this.string = function(str) {
  1130. var len = str.length;
  1131. var expected = "expected '"+str+"'";
  1132. return Parser(function(stream, onSuccess, onFailure) {
  1133. var head = stream.slice(0, len);
  1134. if (head === str) {
  1135. return onSuccess(stream.slice(len), head);
  1136. }
  1137. else {
  1138. return onFailure(stream, expected);
  1139. }
  1140. });
  1141. };
  1142. var regex = this.regex = function(re) {
  1143. pray('regexp parser is anchored', re.toString().charAt(1) === '^');
  1144. var expected = 'expected '+re;
  1145. return Parser(function(stream, onSuccess, onFailure) {
  1146. var match = re.exec(stream);
  1147. if (match) {
  1148. var result = match[0];
  1149. return onSuccess(stream.slice(result.length), result);
  1150. }
  1151. else {
  1152. return onFailure(stream, expected);
  1153. }
  1154. });
  1155. };
  1156. var succeed = Parser.succeed = function(result) {
  1157. return Parser(function(stream, onSuccess) {
  1158. return onSuccess(stream, result);
  1159. });
  1160. };
  1161. var fail = Parser.fail = function(msg) {
  1162. return Parser(function(stream, _, onFailure) {
  1163. return onFailure(stream, msg);
  1164. });
  1165. };
  1166. var letter = Parser.letter = regex(/^[a-z]/i);
  1167. var letters = Parser.letters = regex(/^[a-z]*/i);
  1168. var digit = Parser.digit = regex(/^[0-9]/);
  1169. var digits = Parser.digits = regex(/^[0-9]*/);
  1170. var whitespace = Parser.whitespace = regex(/^\s+/);
  1171. var optWhitespace = Parser.optWhitespace = regex(/^\s*/);
  1172. var any = Parser.any = Parser(function(stream, onSuccess, onFailure) {
  1173. if (!stream) return onFailure(stream, 'expected any character');
  1174. return onSuccess(stream.slice(1), stream.charAt(0));
  1175. });
  1176. var all = Parser.all = Parser(function(stream, onSuccess, onFailure) {
  1177. return onSuccess('', stream);
  1178. });
  1179. var eof = Parser.eof = Parser(function(stream, onSuccess, onFailure) {
  1180. if (stream) return onFailure(stream, 'expected EOF');
  1181. return onSuccess(stream, stream);
  1182. });
  1183. });
  1184. /*************************************************
  1185. * Sane Keyboard Events Shim
  1186. *
  1187. * An abstraction layer wrapping the textarea in
  1188. * an object with methods to manipulate and listen
  1189. * to events on, that hides all the nasty cross-
  1190. * browser incompatibilities behind a uniform API.
  1191. *
  1192. * Design goal: This is a *HARD* internal
  1193. * abstraction barrier. Cross-browser
  1194. * inconsistencies are not allowed to leak through
  1195. * and be dealt with by event handlers. All future
  1196. * cross-browser issues that arise must be dealt
  1197. * with here, and if necessary, the API updated.
  1198. *
  1199. * Organization:
  1200. * - key values map and stringify()
  1201. * - saneKeyboardEvents()
  1202. * + defer() and flush()
  1203. * + event handler logic
  1204. * + attach event handlers and export methods
  1205. ************************************************/
  1206. var saneKeyboardEvents = (function() {
  1207. // The following [key values][1] map was compiled from the
  1208. // [DOM3 Events appendix section on key codes][2] and
  1209. // [a widely cited report on cross-browser tests of key codes][3],
  1210. // except for 10: 'Enter', which I've empirically observed in Safari on iOS
  1211. // and doesn't appear to conflict with any other known key codes.
  1212. //
  1213. // [1]: http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#keys-keyvalues
  1214. // [2]: http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#fixed-virtual-key-codes
  1215. // [3]: http://unixpapa.com/js/key.html
  1216. var KEY_VALUES = {
  1217. 8: 'Backspace',
  1218. 9: 'Tab',
  1219. 10: 'Enter', // for Safari on iOS
  1220. 13: 'Enter',
  1221. 16: 'Shift',
  1222. 17: 'Control',
  1223. 18: 'Alt',
  1224. 20: 'CapsLock',
  1225. 27: 'Esc',
  1226. 32: 'Spacebar',
  1227. 33: 'PageUp',
  1228. 34: 'PageDown',
  1229. 35: 'End',
  1230. 36: 'Home',
  1231. 37: 'Left',
  1232. 38: 'Up',
  1233. 39: 'Right',
  1234. 40: 'Down',
  1235. 45: 'Insert',
  1236. 46: 'Del',
  1237. 144: 'NumLock'
  1238. };
  1239. // To the extent possible, create a normalized string representation
  1240. // of the key combo (i.e., key code and modifier keys).
  1241. function stringify(evt) {
  1242. var which = evt.which || evt.keyCode;
  1243. var keyVal = KEY_VALUES[which];
  1244. var key;
  1245. var modifiers = [];
  1246. if (evt.ctrlKey) modifiers.push('Ctrl');
  1247. if (evt.originalEvent && evt.originalEvent.metaKey) modifiers.push('Meta');
  1248. if (evt.altKey) modifiers.push('Alt');
  1249. if (evt.shiftKey) modifiers.push('Shift');
  1250. key = keyVal || String.fromCharCode(which);
  1251. if (!modifiers.length && !keyVal) return key;
  1252. modifiers.push(key);
  1253. return modifiers.join('-');
  1254. }
  1255. // create a keyboard events shim that calls callbacks at useful times
  1256. // and exports useful public methods
  1257. return function saneKeyboardEvents(el, handlers) {
  1258. var keydown = null;
  1259. var keypress = null;
  1260. var textarea = jQuery(el);
  1261. var target = jQuery(handlers.container || textarea);
  1262. // checkTextareaFor() is called after keypress or paste events to
  1263. // say "Hey, I think something was just typed" or "pasted" (resp.),
  1264. // so that at all subsequent opportune times (next event or timeout),
  1265. // will check for expected typed or pasted text.
  1266. // Need to check repeatedly because #135: in Safari 5.1 (at least),
  1267. // after selecting something and then typing, the textarea is
  1268. // incorrectly reported as selected during the input event (but not
  1269. // subsequently).
  1270. var checkTextarea = noop, timeoutId;
  1271. function checkTextareaFor(checker) {
  1272. checkTextarea = checker;
  1273. clearTimeout(timeoutId);
  1274. timeoutId = setTimeout(checker);
  1275. }
  1276. target.bind('keydown keypress input keyup focusout paste', function(e) { checkTextarea(e); });
  1277. // -*- public methods -*- //
  1278. function select(text) {
  1279. // check textarea at least once/one last time before munging (so
  1280. // no race condition if selection happens after keypress/paste but
  1281. // before checkTextarea), then never again ('cos it's been munged)
  1282. checkTextarea();
  1283. checkTextarea = noop;
  1284. clearTimeout(timeoutId);
  1285. textarea.val(text);
  1286. if (text && textarea[0].select) textarea[0].select();
  1287. shouldBeSelected = !!text;
  1288. }
  1289. var shouldBeSelected = false;
  1290. // -*- helper subroutines -*- //
  1291. // Determine whether there's a selection in the textarea.
  1292. // This will always return false in IE < 9, which don't support
  1293. // HTMLTextareaElement::selection{Start,End}.
  1294. function hasSelection() {
  1295. var dom = textarea[0];
  1296. if (!('selectionStart' in dom)) return false;
  1297. return dom.selectionStart !== dom.selectionEnd;
  1298. }
  1299. function handleKey() {
  1300. handlers.keystroke(stringify(keydown), keydown);
  1301. }
  1302. // -*- event handlers -*- //
  1303. function onKeydown(e) {
  1304. keydown = e;
  1305. keypress = null;
  1306. if (shouldBeSelected) checkTextareaFor(function(e) {
  1307. if (!(e && e.type === 'focusout') && textarea[0].select) {
  1308. textarea[0].select(); // re-select textarea in case it's an unrecognized
  1309. }
  1310. checkTextarea = noop; // key that clears the selection, then never
  1311. clearTimeout(timeoutId); // again, 'cos next thing might be blur
  1312. });
  1313. handleKey();
  1314. }
  1315. function onKeypress(e) {
  1316. // call the key handler for repeated keypresses.
  1317. // This excludes keypresses that happen directly
  1318. // after keydown. In that case, there will be
  1319. // no previous keypress, so we skip it here
  1320. if (keydown && keypress) handleKey();
  1321. keypress = e;
  1322. checkTextareaFor(typedText);
  1323. }
  1324. function typedText() {
  1325. // If there is a selection, the contents of the textarea couldn't
  1326. // possibly have just been typed in.
  1327. // This happens in browsers like Firefox and Opera that fire
  1328. // keypress for keystrokes that are not text entry and leave the
  1329. // selection in the textarea alone, such as Ctrl-C.
  1330. // Note: we assume that browsers that don't support hasSelection()
  1331. // also never fire keypress on keystrokes that are not text entry.
  1332. // This seems reasonably safe because:
  1333. // - all modern browsers including IE 9+ support hasSelection(),
  1334. // making it extremely unlikely any browser besides IE < 9 won't
  1335. // - as far as we know IE < 9 never fires keypress on keystrokes
  1336. // that aren't text entry, which is only as reliable as our
  1337. // tests are comprehensive, but the IE < 9 way to do
  1338. // hasSelection() is poorly documented and is also only as
  1339. // reliable as our tests are comprehensive
  1340. // If anything like #40 or #71 is reported in IE < 9, see
  1341. // b1318e5349160b665003e36d4eedd64101ceacd8
  1342. if (hasSelection()) return;
  1343. var text = textarea.val();
  1344. if (text.length === 1) {
  1345. textarea.val('');
  1346. handlers.typedText(text);
  1347. } // in Firefox, keys that don't type text, just clear seln, fire keypress
  1348. // https://github.com/mathquill/mathquill/issues/293#issuecomment-40997668
  1349. else if (text && textarea[0].select) textarea[0].select(); // re-select if that's why we're here
  1350. }
  1351. function onBlur() { keydown = keypress = null; }
  1352. function onPaste(e) {
  1353. // browsers are dumb.
  1354. //
  1355. // In Linux, middle-click pasting causes onPaste to be called,
  1356. // when the textarea is not necessarily focused. We focus it
  1357. // here to ensure that the pasted text actually ends up in the
  1358. // textarea.
  1359. //
  1360. // It's pretty nifty that by changing focus in this handler,
  1361. // we can change the target of the default action. (This works
  1362. // on keydown too, FWIW).
  1363. //
  1364. // And by nifty, we mean dumb (but useful sometimes).
  1365. textarea.focus();
  1366. checkTextareaFor(pastedText);
  1367. }
  1368. function pastedText() {
  1369. var text = textarea.val();
  1370. textarea.val('');
  1371. if (text) handlers.paste(text);
  1372. }
  1373. // -*- attach event handlers -*- //
  1374. target.bind({
  1375. keydown: onKeydown,
  1376. keypress: onKeypress,
  1377. focusout: onBlur,
  1378. paste: onPaste
  1379. });
  1380. // -*- export public methods -*- //
  1381. return {
  1382. select: select
  1383. };
  1384. };
  1385. }());
  1386. /***********************************************
  1387. * Export math in a human-readable text format
  1388. * As you can see, only half-baked so far.
  1389. **********************************************/
  1390. Controller.open(function(_, super_) {
  1391. _.exportText = function() {
  1392. return this.root.foldChildren('', function(text, child) {
  1393. return text + child.text();
  1394. });
  1395. };
  1396. });
  1397. Controller.open(function(_) {
  1398. _.focusBlurEvents = function() {
  1399. var ctrlr = this, root = ctrlr.root, cursor = ctrlr.cursor;
  1400. var blurTimeout;
  1401. ctrlr.textarea.focus(function() {
  1402. ctrlr.blurred = false;
  1403. clearTimeout(blurTimeout);
  1404. ctrlr.container.addClass('mq-focused');
  1405. if (!cursor.parent)
  1406. cursor.insAtRightEnd(root);
  1407. if (cursor.selection) {
  1408. cursor.selection.jQ.removeClass('mq-blur');
  1409. ctrlr.selectionChanged(); //re-select textarea contents after tabbing away and back
  1410. }
  1411. else
  1412. cursor.show();
  1413. }).blur(function() {
  1414. ctrlr.blurred = true;
  1415. blurTimeout = setTimeout(function() { // wait for blur on window; if
  1416. root.postOrder('intentionalBlur'); // none, intentional blur: #264
  1417. cursor.clearSelection().endSelection();
  1418. blur();
  1419. });
  1420. $(window).on('blur', windowBlur);
  1421. });
  1422. function windowBlur() { // blur event also fired on window, just switching
  1423. clearTimeout(blurTimeout); // tabs/windows, not intentional blur
  1424. if (cursor.selection) cursor.selection.jQ.addClass('mq-blur');
  1425. blur();
  1426. }
  1427. function blur() { // not directly in the textarea blur handler so as to be
  1428. cursor.hide().parent.blur(); // synchronous with/in the same frame as
  1429. ctrlr.container.removeClass('mq-focused'); // clearing/blurring selection
  1430. $(window).off('blur', windowBlur);
  1431. }
  1432. ctrlr.blurred = true;
  1433. cursor.hide().parent.blur();
  1434. };
  1435. });
  1436. /**
  1437. * TODO: I wanted to move MathBlock::focus and blur here, it would clean
  1438. * up lots of stuff like, TextBlock::focus is set to MathBlock::focus
  1439. * and TextBlock::blur calls MathBlock::blur, when instead they could
  1440. * use inheritance and super_.
  1441. *
  1442. * Problem is, there's lots of calls to .focus()/.blur() on nodes
  1443. * outside Controller::focusBlurEvents(), such as .postOrder('blur') on
  1444. * insertion, which if MathBlock::blur becomes Node::blur, would add the
  1445. * 'blur' CSS class to all Symbol's (because .isEmpty() is true for all
  1446. * of them).
  1447. *
  1448. * I'm not even sure there aren't other troublesome calls to .focus() or
  1449. * .blur(), so this is TODO for now.
  1450. */
  1451. /*****************************************
  1452. * Deals with the browser DOM events from
  1453. * interaction with the typist.
  1454. ****************************************/
  1455. Controller.open(function(_) {
  1456. _.keystroke = function(key, evt) {
  1457. this.cursor.parent.keystroke(key, evt, this);
  1458. };
  1459. });
  1460. Node.open(function(_) {
  1461. _.keystroke = function(key, e, ctrlr) {
  1462. var cursor = ctrlr.cursor;
  1463. switch (key) {
  1464. case 'Ctrl-Shift-Backspace':
  1465. case 'Ctrl-Backspace':
  1466. ctrlr.ctrlDeleteDir(L);
  1467. break;
  1468. case 'Shift-Backspace':
  1469. case 'Backspace':
  1470. ctrlr.backspace();
  1471. break;
  1472. // Tab or Esc -> go one block right if it exists, else escape right.
  1473. case 'Esc':
  1474. case 'Tab':
  1475. ctrlr.escapeDir(R, key, e);
  1476. return;
  1477. // Shift-Tab -> go one block left if it exists, else escape left.
  1478. case 'Shift-Tab':
  1479. case 'Shift-Esc':
  1480. ctrlr.escapeDir(L, key, e);
  1481. return;
  1482. // End -> move to the end of the current block.
  1483. case 'End':
  1484. ctrlr.notify('move').cursor.insAtRightEnd(cursor.parent);
  1485. break;
  1486. // Ctrl-End -> move all the way to the end of the root block.
  1487. case 'Ctrl-End':
  1488. ctrlr.notify('move').cursor.insAtRightEnd(ctrlr.root);
  1489. break;
  1490. // Shift-End -> select to the end of the current block.
  1491. case 'Shift-End':
  1492. while (cursor[R]) {
  1493. ctrlr.selectRight();
  1494. }
  1495. break;
  1496. // Ctrl-Shift-End -> select to the end of the root block.
  1497. case 'Ctrl-Shift-End':
  1498. while (cursor[R] || cursor.parent !== ctrlr.root) {
  1499. ctrlr.selectRight();
  1500. }
  1501. break;
  1502. // Home -> move to the start of the root block or the current block.
  1503. case 'Home':
  1504. ctrlr.notify('move').cursor.insAtLeftEnd(cursor.parent);
  1505. break;
  1506. // Ctrl-Home -> move to the start of the current block.
  1507. case 'Ctrl-Home':
  1508. ctrlr.notify('move').cursor.insAtLeftEnd(ctrlr.root);
  1509. break;
  1510. // Shift-Home -> select to the start of the current block.
  1511. case 'Shift-Home':
  1512. while (cursor[L]) {
  1513. ctrlr.selectLeft();
  1514. }
  1515. break;
  1516. // Ctrl-Shift-Home -> move to the start of the root block.
  1517. case 'Ctrl-Shift-Home':
  1518. while (cursor[L] || cursor.parent !== ctrlr.root) {
  1519. ctrlr.selectLeft();
  1520. }
  1521. break;
  1522. case 'Left': ctrlr.moveLeft(); break;
  1523. case 'Shift-Left': ctrlr.selectLeft(); break;
  1524. case 'Ctrl-Left': break;
  1525. case 'Right': ctrlr.moveRight(); break;
  1526. case 'Shift-Right': ctrlr.selectRight(); break;
  1527. case 'Ctrl-Right': break;
  1528. case 'Up': ctrlr.moveUp(); break;
  1529. case 'Down': ctrlr.moveDown(); break;
  1530. case 'Shift-Up':
  1531. if (cursor[L]) {
  1532. while (cursor[L]) ctrlr.selectLeft();
  1533. } else {
  1534. ctrlr.selectLeft();
  1535. }
  1536. case 'Shift-Down':
  1537. if (cursor[R]) {
  1538. while (cursor[R]) ctrlr.selectRight();
  1539. }
  1540. else {
  1541. ctrlr.selectRight();
  1542. }
  1543. case 'Ctrl-Up': break;
  1544. case 'Ctrl-Down': break;
  1545. case 'Ctrl-Shift-Del':
  1546. case 'Ctrl-Del':
  1547. ctrlr.ctrlDeleteDir(R);
  1548. break;
  1549. case 'Shift-Del':
  1550. case 'Del':
  1551. ctrlr.deleteForward();
  1552. break;
  1553. case 'Meta-A':
  1554. case 'Ctrl-A':
  1555. ctrlr.notify('move').cursor.insAtRightEnd(ctrlr.root);
  1556. while (cursor[L]) ctrlr.selectLeft();
  1557. break;
  1558. default:
  1559. return;
  1560. }
  1561. e.preventDefault();
  1562. ctrlr.scrollHoriz();
  1563. };
  1564. _.moveOutOf = // called by Controller::escapeDir, moveDir
  1565. _.moveTowards = // called by Controller::moveDir
  1566. _.deleteOutOf = // called by Controller::deleteDir
  1567. _.deleteTowards = // called by Controller::deleteDir
  1568. _.unselectInto = // called by Controller::selectDir
  1569. _.selectOutOf = // called by Controller::selectDir
  1570. _.selectTowards = // called by Controller::selectDir
  1571. function() { pray('overridden or never called on this node'); };
  1572. });
  1573. Controller.open(function(_) {
  1574. this.onNotify(function(e) {
  1575. if (e === 'move' || e === 'upDown') this.show().clearSelection();
  1576. });
  1577. _.escapeDir = function(dir, key, e) {
  1578. prayDirection(dir);
  1579. var cursor = this.cursor;
  1580. // only prevent default of Tab if not in the root editable
  1581. if (cursor.parent !== this.root) e.preventDefault();
  1582. // want to be a noop if in the root editable (in fact, Tab has an unrelated
  1583. // default browser action if so)
  1584. if (cursor.parent === this.root) return;
  1585. cursor.parent.moveOutOf(dir, cursor);
  1586. return this.notify('move');
  1587. };
  1588. optionProcessors.leftRightIntoCmdGoes = function(updown) {
  1589. if (updown && updown !== 'up' && updown !== 'down') {
  1590. throw '"up" or "down" required for leftRightIntoCmdGoes option, '
  1591. + 'got "'+updown+'"';
  1592. }
  1593. return updown;
  1594. };
  1595. _.moveDir = function(dir) {
  1596. prayDirection(dir);
  1597. var cursor = this.cursor, updown = cursor.options.leftRightIntoCmdGoes;
  1598. if (cursor.selection) {
  1599. cursor.insDirOf(dir, cursor.selection.ends[dir]);
  1600. }
  1601. else if (cursor[dir]) cursor[dir].moveTowards(dir, cursor, updown);
  1602. else cursor.parent.moveOutOf(dir, cursor, updown);
  1603. return this.notify('move');
  1604. };
  1605. _.moveLeft = function() { return this.moveDir(L); };
  1606. _.moveRight = function() { return this.moveDir(R); };
  1607. /**
  1608. * moveUp and moveDown have almost identical algorithms:
  1609. * - first check left and right, if so insAtLeft/RightEnd of them
  1610. * - else check the parent's 'upOutOf'/'downOutOf' property:
  1611. * + if it's a function, call it with the cursor as the sole argument and
  1612. * use the return value as if it were the value of the property
  1613. * + if it's a Node, jump up or down into it:
  1614. * - if there is a cached Point in the block, insert there
  1615. * - else, seekHoriz within the block to the current x-coordinate (to be
  1616. * as close to directly above/below the current position as possible)
  1617. * + unless it's exactly `true`, stop bubbling
  1618. */
  1619. _.moveUp = function() { return moveUpDown(this, 'up'); };
  1620. _.moveDown = function() { return moveUpDown(this, 'down'); };
  1621. function moveUpDown(self, dir) {
  1622. var cursor = self.notify('upDown').cursor;
  1623. var dirInto = dir+'Into', dirOutOf = dir+'OutOf';
  1624. if (cursor[R][dirInto]) cursor.insAtLeftEnd(cursor[R][dirInto]);
  1625. else if (cursor[L][dirInto]) cursor.insAtRightEnd(cursor[L][dirInto]);
  1626. else {
  1627. cursor.parent.bubble(function(ancestor) {
  1628. var prop = ancestor[dirOutOf];
  1629. if (prop) {
  1630. if (typeof prop === 'function') prop = ancestor[dirOutOf](cursor);
  1631. if (prop instanceof Node) cursor.jumpUpDown(ancestor, prop);
  1632. if (prop !== true) return false;
  1633. }
  1634. });
  1635. }
  1636. return self;
  1637. }
  1638. this.onNotify(function(e) { if (e !== 'upDown') this.upDownCache = {}; });
  1639. this.onNotify(function(e) { if (e === 'edit') this.show().deleteSelection(); });
  1640. _.deleteDir = function(dir) {
  1641. prayDirection(dir);
  1642. var cursor = this.cursor;
  1643. var hadSelection = cursor.selection;
  1644. this.notify('edit'); // deletes selection if present
  1645. if (!hadSelection) {
  1646. if (cursor[dir]) cursor[dir].deleteTowards(dir, cursor);
  1647. else cursor.parent.deleteOutOf(dir, cursor);
  1648. }
  1649. if (cursor[L].siblingDeleted) cursor[L].siblingDeleted(cursor.options, R);
  1650. if (cursor[R].siblingDeleted) cursor[R].siblingDeleted(cursor.options, L);
  1651. cursor.parent.bubble('reflow');
  1652. return this;
  1653. };
  1654. _.ctrlDeleteDir = function(dir) {
  1655. prayDirection(dir);
  1656. var cursor = this.cursor;
  1657. if (!cursor[L] || cursor.selection) return ctrlr.deleteDir();
  1658. this.notify('edit');
  1659. Fragment(cursor.parent.ends[L], cursor[L]).remove();
  1660. cursor.insAtDirEnd(L, cursor.parent);
  1661. if (cursor[L].siblingDeleted) cursor[L].siblingDeleted(cursor.options, R);
  1662. if (cursor[R].siblingDeleted) cursor[R].siblingDeleted(cursor.options, L);
  1663. cursor.parent.bubble('reflow');
  1664. return this;
  1665. };
  1666. _.backspace = function() { return this.deleteDir(L); };
  1667. _.deleteForward = function() { return this.deleteDir(R); };
  1668. this.onNotify(function(e) { if (e !== 'select') this.endSelection(); });
  1669. _.selectDir = function(dir) {
  1670. var cursor = this.notify('select').cursor, seln = cursor.selection;
  1671. prayDirection(dir);
  1672. if (!cursor.anticursor) cursor.startSelection();
  1673. var node = cursor[dir];
  1674. if (node) {
  1675. // "if node we're selecting towards is inside selection (hence retracting)
  1676. // and is on the *far side* of the selection (hence is only node selected)
  1677. // and the anticursor is *inside* that node, not just on the other side"
  1678. if (seln && seln.ends[dir] === node && cursor.anticursor[-dir] !== node) {
  1679. node.unselectInto(dir, cursor);
  1680. }
  1681. else node.selectTowards(dir, cursor);
  1682. }
  1683. else cursor.parent.selectOutOf(dir, cursor);
  1684. cursor.clearSelection();
  1685. cursor.select() || cursor.show();
  1686. };
  1687. _.selectLeft = function() { return this.selectDir(L); };
  1688. _.selectRight = function() { return this.selectDir(R); };
  1689. });
  1690. // Parser MathCommand
  1691. var latexMathParser = (function() {
  1692. function commandToBlock(cmd) {
  1693. var block = MathBlock();
  1694. cmd.adopt(block, 0, 0);
  1695. return block;
  1696. }
  1697. function joinBlocks(blocks) {
  1698. var firstBlock = blocks[0] || MathBlock();
  1699. for (var i = 1; i < blocks.length; i += 1) {
  1700. blocks[i].children().adopt(firstBlock, firstBlock.ends[R], 0);
  1701. }
  1702. return firstBlock;
  1703. }
  1704. var string = Parser.string;
  1705. var regex = Parser.regex;
  1706. var letter = Parser.letter;
  1707. var any = Parser.any;
  1708. var optWhitespace = Parser.optWhitespace;
  1709. var succeed = Parser.succeed;
  1710. var fail = Parser.fail;
  1711. // Parsers yielding either MathCommands, or Fragments of MathCommands
  1712. // (either way, something that can be adopted by a MathBlock)
  1713. var variable = letter.map(function(c) { return Letter(c); });
  1714. var symbol = regex(/^[^${}\\_^]/).map(function(c) { return VanillaSymbol(c); });
  1715. var controlSequence =
  1716. regex(/^[^\\a-eg-zA-Z]/) // hotfix #164; match MathBlock::write
  1717. .or(string('\\').then(
  1718. regex(/^[a-z]+/i)
  1719. .or(regex(/^\s+/).result(' '))
  1720. .or(any)
  1721. )).then(function(ctrlSeq) {
  1722. var cmdKlass = LatexCmds[ctrlSeq];
  1723. if (cmdKlass) {
  1724. return cmdKlass(ctrlSeq).parser();
  1725. }
  1726. else {
  1727. return fail('unknown command: \\'+ctrlSeq);
  1728. }
  1729. })
  1730. ;
  1731. var command =
  1732. controlSequence
  1733. .or(variable)
  1734. .or(symbol)
  1735. ;
  1736. // Parsers yielding MathBlocks
  1737. var mathGroup = string('{').then(function() { return mathSequence; }).skip(string('}'));
  1738. var mathBlock = optWhitespace.then(mathGroup.or(command.map(commandToBlock)));
  1739. var mathSequence = mathBlock.many().map(joinBlocks).skip(optWhitespace);
  1740. var optMathBlock =
  1741. string('[').then(
  1742. mathBlock.then(function(block) {
  1743. return block.join('latex') !== ']' ? succeed(block) : fail();
  1744. })
  1745. .many().map(joinBlocks).skip(optWhitespace)
  1746. ).skip(string(']'))
  1747. ;
  1748. var latexMath = mathSequence;
  1749. latexMath.block = mathBlock;
  1750. latexMath.optBlock = optMathBlock;
  1751. return latexMath;
  1752. })();
  1753. Controller.open(function(_, super_) {
  1754. _.exportLatex = function() {
  1755. return this.root.latex().replace(/(\\[a-z]+) (?![a-z])/ig,'$1');
  1756. };
  1757. _.writeLatex = function(latex) {
  1758. var cursor = this.notify('edit').cursor;
  1759. var all = Parser.all;
  1760. var eof = Parser.eof;
  1761. var block = latexMathParser.skip(eof).or(all.result(false)).parse(latex);
  1762. if (block && !block.isEmpty()) {
  1763. block.children().adopt(cursor.parent, cursor[L], cursor[R]);
  1764. var jQ = block.jQize();
  1765. jQ.insertBefore(cursor.jQ);
  1766. cursor[L] = block.ends[R];
  1767. block.finalizeInsert(cursor.options, cursor);
  1768. if (block.ends[R][R].siblingCreated) block.ends[R][R].siblingCreated(cursor.options, L);
  1769. if (block.ends[L][L].siblingCreated) block.ends[L][L].siblingCreated(cursor.options, R);
  1770. cursor.parent.bubble('reflow');
  1771. }
  1772. return this;
  1773. };
  1774. _.renderLatexMath = function(latex) {
  1775. var root = this.root, cursor = this.cursor;
  1776. var all = Parser.all;
  1777. var eof = Parser.eof;
  1778. var block = latexMathParser.skip(eof).or(all.result(false)).parse(latex);
  1779. root.eachChild('postOrder', 'dispose');
  1780. root.ends[L] = root.ends[R] = 0;
  1781. if (block) {
  1782. block.children().adopt(root, 0, 0);
  1783. }
  1784. var jQ = root.jQ;
  1785. if (block) {
  1786. var html = block.join('html');
  1787. jQ.html(html);
  1788. root.jQize(jQ.children());
  1789. root.finalizeInsert(cursor.options);
  1790. }
  1791. else {
  1792. jQ.empty();
  1793. }
  1794. delete cursor.selection;
  1795. cursor.insAtRightEnd(root);
  1796. };
  1797. _.renderLatexText = function(latex) {
  1798. var root = this.root, cursor = this.cursor;
  1799. root.jQ.children().slice(1).remove();
  1800. root.eachChild('postOrder', 'dispose');
  1801. root.ends[L] = root.ends[R] = 0;
  1802. delete cursor.selection;
  1803. cursor.show().insAtRightEnd(root);
  1804. var regex = Parser.regex;
  1805. var string = Parser.string;
  1806. var eof = Parser.eof;
  1807. var all = Parser.all;
  1808. // Parser RootMathCommand
  1809. var mathMode = string('$').then(latexMathParser)
  1810. // because TeX is insane, math mode doesn't necessarily
  1811. // have to end. So we allow for the case that math mode
  1812. // continues to the end of the stream.
  1813. .skip(string('$').or(eof))
  1814. .map(function(block) {
  1815. // HACK FIXME: this shouldn't have to have access to cursor
  1816. var rootMathCommand = RootMathCommand(cursor);
  1817. rootMathCommand.createBlocks();
  1818. var rootMathBlock = rootMathCommand.ends[L];
  1819. block.children().adopt(rootMathBlock, 0, 0);
  1820. return rootMathCommand;
  1821. })
  1822. ;
  1823. var escapedDollar = string('\\$').result('$');
  1824. var textChar = escapedDollar.or(regex(/^[^$]/)).map(VanillaSymbol);
  1825. var latexText = mathMode.or(textChar).many();
  1826. var commands = latexText.skip(eof).or(all.result(false)).parse(latex);
  1827. if (commands) {
  1828. for (var i = 0; i < commands.length; i += 1) {
  1829. commands[i].adopt(root, root.ends[R], 0);
  1830. }
  1831. root.jQize().appendTo(root.jQ);
  1832. root.finalizeInsert(cursor.options);
  1833. }
  1834. };
  1835. });
  1836. /********************************************************
  1837. * Deals with mouse events for clicking, drag-to-select
  1838. *******************************************************/
  1839. Controller.open(function(_) {
  1840. _.delegateMouseEvents = function() {
  1841. var ultimateRootjQ = this.root.jQ;
  1842. //drag-to-select event handling
  1843. this.container.bind('mousedown.mathquill', function(e) {
  1844. var rootjQ = $(e.target).closest('.mq-root-block');
  1845. var root = Node.byId[rootjQ.attr(mqBlockId) || ultimateRootjQ.attr(mqBlockId)];
  1846. var ctrlr = root.controller, cursor = ctrlr.cursor, blink = cursor.blink;
  1847. var textareaSpan = ctrlr.textareaSpan, textarea = ctrlr.textarea;
  1848. var target;
  1849. function mousemove(e) { target = $(e.target); }
  1850. function docmousemove(e) {
  1851. if (!cursor.anticursor) cursor.startSelection();
  1852. ctrlr.seek(target, e.pageX, e.pageY).cursor.select();
  1853. target = undefined;
  1854. }
  1855. // outside rootjQ, the MathQuill node corresponding to the target (if any)
  1856. // won't be inside this root, so don't mislead Controller::seek with it
  1857. function mouseup(e) {
  1858. cursor.blink = blink;
  1859. if (!cursor.selection) {
  1860. if (ctrlr.editable) {
  1861. cursor.show();
  1862. }
  1863. else {
  1864. textareaSpan.detach();
  1865. }
  1866. }
  1867. // delete the mouse handlers now that we're not dragging anymore
  1868. rootjQ.unbind('mousemove', mousemove);
  1869. $(e.target.ownerDocument).unbind('mousemove', docmousemove).unbind('mouseup', mouseup);
  1870. }
  1871. if (ctrlr.blurred) {
  1872. if (!ctrlr.editable) rootjQ.prepend(textareaSpan);
  1873. textarea.focus();
  1874. }
  1875. e.preventDefault(); // doesn't work in IE\u22648, but it's a one-line fix:
  1876. e.target.unselectable = true; // http://jsbin.com/yagekiji/1
  1877. cursor.blink = noop;
  1878. ctrlr.seek($(e.target), e.pageX, e.pageY).cursor.startSelection();
  1879. rootjQ.mousemove(mousemove);
  1880. $(e.target.ownerDocument).mousemove(docmousemove).mouseup(mouseup);
  1881. // listen on document not just body to not only hear about mousemove and
  1882. // mouseup on page outside field, but even outside page, except iframes: https://github.com/mathquill/mathquill/commit/8c50028afcffcace655d8ae2049f6e02482346c5#commitcomment-6175800
  1883. });
  1884. }
  1885. });
  1886. Controller.open(function(_) {
  1887. _.seek = function(target, pageX, pageY) {
  1888. var cursor = this.notify('select').cursor;
  1889. if (target) {
  1890. var nodeId = target.attr(mqBlockId) || target.attr(mqCmdId);
  1891. if (!nodeId) {
  1892. var targetParent = target.parent();
  1893. nodeId = targetParent.attr(mqBlockId) || targetParent.attr(mqCmdId);
  1894. }
  1895. }
  1896. var node = nodeId ? Node.byId[nodeId] : this.root;
  1897. pray('nodeId is the id of some Node that exists', node);
  1898. // don't clear selection until after getting node from target, in case
  1899. // target was selection span, otherwise target will have no parent and will
  1900. // seek from root, which is less accurate (e.g. fraction)
  1901. cursor.clearSelection().show();
  1902. node.seek(pageX, cursor);
  1903. this.scrollHoriz(); // before .selectFrom when mouse-selecting, so
  1904. // always hits no-selection case in scrollHoriz and scrolls slower
  1905. return this;
  1906. };
  1907. });
  1908. /***********************************************
  1909. * Horizontal panning for editable fields that
  1910. * overflow their width
  1911. **********************************************/
  1912. Controller.open(function(_) {
  1913. _.scrollHoriz = function() {
  1914. var cursor = this.cursor, seln = cursor.selection;
  1915. var rootRect = this.root.jQ[0].getBoundingClientRect();
  1916. if (!seln) {
  1917. var x = cursor.jQ[0].getBoundingClientRect().left;
  1918. if (x > rootRect.right - 20) var scrollBy = x - (rootRect.right - 20);
  1919. else if (x < rootRect.left + 20) var scrollBy = x - (rootRect.left + 20);
  1920. else return;
  1921. }
  1922. else {
  1923. var rect = seln.jQ[0].getBoundingClientRect();
  1924. var overLeft = rect.left - (rootRect.left + 20);
  1925. var overRight = rect.right - (rootRect.right - 20);
  1926. if (seln.ends[L] === cursor[R]) {
  1927. if (overLeft < 0) var scrollBy = overLeft;
  1928. else if (overRight > 0) {
  1929. if (rect.left - overRight < rootRect.left + 20) var scrollBy = overLeft;
  1930. else var scrollBy = overRight;
  1931. }
  1932. else return;
  1933. }
  1934. else {
  1935. if (overRight > 0) var scrollBy = overRight;
  1936. else if (overLeft < 0) {
  1937. if (rect.right - overLeft > rootRect.right - 20) var scrollBy = overRight;
  1938. else var scrollBy = overLeft;
  1939. }
  1940. else return;
  1941. }
  1942. }
  1943. this.root.jQ.stop().animate({ scrollLeft: '+=' + scrollBy}, 100);
  1944. };
  1945. });
  1946. /*********************************************
  1947. * Manage the MathQuill instance's textarea
  1948. * (as owned by the Controller)
  1949. ********************************************/
  1950. Controller.open(function(_) {
  1951. Options.p.substituteTextarea = function() {
  1952. return $('<textarea autocapitalize=off autocomplete=off autocorrect=off ' +
  1953. 'spellcheck=false x-palm-disable-ste-all=true />')[0];
  1954. };
  1955. _.createTextarea = function() {
  1956. var textareaSpan = this.textareaSpan = $('<span class="mq-textarea"></span>'),
  1957. textarea = this.options.substituteTextarea();
  1958. if (!textarea.nodeType) {
  1959. throw 'substituteTextarea() must return a DOM element, got ' + textarea;
  1960. }
  1961. textarea = this.textarea = $(textarea).appendTo(textareaSpan);
  1962. var ctrlr = this;
  1963. ctrlr.cursor.selectionChanged = function() { ctrlr.selectionChanged(); };
  1964. ctrlr.container.bind('copy', function() { ctrlr.setTextareaSelection(); });
  1965. };
  1966. _.selectionChanged = function() {
  1967. var ctrlr = this;
  1968. forceIERedraw(ctrlr.container[0]);
  1969. // throttle calls to setTextareaSelection(), because setting textarea.value
  1970. // and/or calling textarea.select() can have anomalously bad performance:
  1971. // https://github.com/mathquill/mathquill/issues/43#issuecomment-1399080
  1972. if (ctrlr.textareaSelectionTimeout === undefined) {
  1973. ctrlr.textareaSelectionTimeout = setTimeout(function() {
  1974. ctrlr.setTextareaSelection();
  1975. });
  1976. }
  1977. };
  1978. _.setTextareaSelection = function() {
  1979. this.textareaSelectionTimeout = undefined;
  1980. var latex = '';
  1981. if (this.cursor.selection) {
  1982. latex = this.cursor.selection.join('latex');
  1983. if (this.options.statelessClipboard) {
  1984. // FIXME: like paste, only this works for math fields; should ask parent
  1985. latex = '$' + latex + '$';
  1986. }
  1987. }
  1988. this.selectFn(latex);
  1989. };
  1990. _.staticMathTextareaEvents = function() {
  1991. var ctrlr = this, root = ctrlr.root, cursor = ctrlr.cursor,
  1992. textarea = ctrlr.textarea, textareaSpan = ctrlr.textareaSpan;
  1993. this.container.prepend('<span class="mq-selectable">$'+ctrlr.exportLatex()+'$</span>');
  1994. ctrlr.blurred = true;
  1995. textarea.bind('cut paste', false)
  1996. .focus(function() { ctrlr.blurred = false; }).blur(function() {
  1997. if (cursor.selection) cursor.selection.clear();
  1998. setTimeout(detach); //detaching during blur explodes in WebKit
  1999. });
  2000. function detach() {
  2001. textareaSpan.detach();
  2002. ctrlr.blurred = true;
  2003. }
  2004. ctrlr.selectFn = function(text) {
  2005. textarea.val(text);
  2006. if (text) textarea.select();
  2007. };
  2008. };
  2009. _.editablesTextareaEvents = function() {
  2010. var ctrlr = this, root = ctrlr.root, cursor = ctrlr.cursor,
  2011. textarea = ctrlr.textarea, textareaSpan = ctrlr.textareaSpan;
  2012. var keyboardEventsShim = saneKeyboardEvents(textarea, this);
  2013. this.selectFn = function(text) { keyboardEventsShim.select(text); };
  2014. this.container.prepend(textareaSpan)
  2015. .on('cut', function(e) {
  2016. if (cursor.selection) {
  2017. setTimeout(function() {
  2018. ctrlr.notify('edit'); // deletes selection if present
  2019. cursor.parent.bubble('reflow');
  2020. });
  2021. }
  2022. });
  2023. this.focusBlurEvents();
  2024. };
  2025. _.typedText = function(ch) {
  2026. if (ch === '\n') return this.handle('enter');
  2027. var cursor = this.notify().cursor;
  2028. cursor.parent.write(cursor, ch);
  2029. this.scrollHoriz();
  2030. };
  2031. _.paste = function(text) {
  2032. // TODO: document `statelessClipboard` config option in README, after
  2033. // making it work like it should, that is, in both text and math mode
  2034. // (currently only works in math fields, so worse than pointless, it
  2035. // only gets in the way by \text{}-ifying pasted stuff and $-ifying
  2036. // cut/copied LaTeX)
  2037. if (this.options.statelessClipboard) {
  2038. if (text.slice(0,1) === '$' && text.slice(-1) === '$') {
  2039. text = text.slice(1, -1);
  2040. }
  2041. else {
  2042. text = '\\text{'+text+'}';
  2043. }
  2044. }
  2045. // FIXME: this always inserts math or a TextBlock, even in a RootTextBlock
  2046. this.writeLatex(text).cursor.show();
  2047. };
  2048. });
  2049. /*************************************************
  2050. * Abstract classes of math blocks and commands.
  2051. ************************************************/
  2052. /**
  2053. * Math tree node base class.
  2054. * Some math-tree-specific extensions to Node.
  2055. * Both MathBlock's and MathCommand's descend from it.
  2056. */
  2057. var MathElement = P(Node, function(_, super_) {
  2058. _.finalizeInsert = function(options, cursor) { // `cursor` param is only for
  2059. // SupSub::contactWeld, and is deliberately only passed in by writeLatex,
  2060. // see ea7307eb4fac77c149a11ffdf9a831df85247693
  2061. var self = this;
  2062. self.postOrder('finalizeTree', options);
  2063. self.postOrder('contactWeld', cursor);
  2064. // note: this order is important.
  2065. // empty elements need the empty box provided by blur to
  2066. // be present in order for their dimensions to be measured
  2067. // correctly by 'reflow' handlers.
  2068. self.postOrder('blur');
  2069. self.postOrder('reflow');
  2070. if (self[R].siblingCreated) self[R].siblingCreated(options, L);
  2071. if (self[L].siblingCreated) self[L].siblingCreated(options, R);
  2072. self.bubble('reflow');
  2073. };
  2074. });
  2075. /**
  2076. * Commands and operators, like subscripts, exponents, or fractions.
  2077. * Descendant commands are organized into blocks.
  2078. */
  2079. var MathCommand = P(MathElement, function(_, super_) {
  2080. _.init = function(ctrlSeq, htmlTemplate, textTemplate) {
  2081. var cmd = this;
  2082. super_.init.call(cmd);
  2083. if (!cmd.ctrlSeq) cmd.ctrlSeq = ctrlSeq;
  2084. if (htmlTemplate) cmd.htmlTemplate = htmlTemplate;
  2085. if (textTemplate) cmd.textTemplate = textTemplate;
  2086. };
  2087. // obvious methods
  2088. _.replaces = function(replacedFragment) {
  2089. replacedFragment.disown();
  2090. this.replacedFragment = replacedFragment;
  2091. };
  2092. _.isEmpty = function() {
  2093. return this.foldChildren(true, function(isEmpty, child) {
  2094. return isEmpty && child.isEmpty();
  2095. });
  2096. };
  2097. _.parser = function() {
  2098. var block = latexMathParser.block;
  2099. var self = this;
  2100. return block.times(self.numBlocks()).map(function(blocks) {
  2101. self.blocks = blocks;
  2102. for (var i = 0; i < blocks.length; i += 1) {
  2103. blocks[i].adopt(self, self.ends[R], 0);
  2104. }
  2105. return self;
  2106. });
  2107. };
  2108. // createLeftOf(cursor) and the methods it calls
  2109. _.createLeftOf = function(cursor) {
  2110. var cmd = this;
  2111. var replacedFragment = cmd.replacedFragment;
  2112. cmd.createBlocks();
  2113. super_.createLeftOf.call(cmd, cursor);
  2114. if (replacedFragment) {
  2115. replacedFragment.adopt(cmd.ends[L], 0, 0);
  2116. replacedFragment.jQ.appendTo(cmd.ends[L].jQ);
  2117. }
  2118. cmd.finalizeInsert(cursor.options);
  2119. cmd.placeCursor(cursor);
  2120. };
  2121. _.createBlocks = function() {
  2122. var cmd = this,
  2123. numBlocks = cmd.numBlocks(),
  2124. blocks = cmd.blocks = Array(numBlocks);
  2125. for (var i = 0; i < numBlocks; i += 1) {
  2126. var newBlock = blocks[i] = MathBlock();
  2127. newBlock.adopt(cmd, cmd.ends[R], 0);
  2128. }
  2129. };
  2130. _.placeCursor = function(cursor) {
  2131. //insert the cursor at the right end of the first empty child, searching
  2132. //left-to-right, or if none empty, the right end child
  2133. cursor.insAtRightEnd(this.foldChildren(this.ends[L], function(leftward, child) {
  2134. return leftward.isEmpty() ? leftward : child;
  2135. }));
  2136. };
  2137. // editability methods: called by the cursor for editing, cursor movements,
  2138. // and selection of the MathQuill tree, these all take in a direction and
  2139. // the cursor
  2140. _.moveTowards = function(dir, cursor, updown) {
  2141. var updownInto = updown && this[updown+'Into'];
  2142. cursor.insAtDirEnd(-dir, updownInto || this.ends[-dir]);
  2143. };
  2144. _.deleteTowards = function(dir, cursor) {
  2145. if (this.isEmpty()) cursor[dir] = this.remove()[dir];
  2146. else this.moveTowards(dir, cursor, null);
  2147. };
  2148. _.selectTowards = function(dir, cursor) {
  2149. cursor[-dir] = this;
  2150. cursor[dir] = this[dir];
  2151. };
  2152. _.selectChildren = function() {
  2153. return Selection(this, this);
  2154. };
  2155. _.unselectInto = function(dir, cursor) {
  2156. cursor.insAtDirEnd(-dir, cursor.anticursor.ancestors[this.id]);
  2157. };
  2158. _.seek = function(pageX, cursor) {
  2159. function getBounds(node) {
  2160. var bounds = {}
  2161. bounds[L] = node.jQ.offset().left;
  2162. bounds[R] = bounds[L] + node.jQ.outerWidth();
  2163. return bounds;
  2164. }
  2165. var cmd = this;
  2166. var cmdBounds = getBounds(cmd);
  2167. if (pageX < cmdBounds[L]) return cursor.insLeftOf(cmd);
  2168. if (pageX > cmdBounds[R]) return cursor.insRightOf(cmd);
  2169. var leftLeftBound = cmdBounds[L];
  2170. cmd.eachChild(function(block) {
  2171. var blockBounds = getBounds(block);
  2172. if (pageX < blockBounds[L]) {
  2173. // closer to this block's left bound, or the bound left of that?
  2174. if (pageX - leftLeftBound < blockBounds[L] - pageX) {
  2175. if (block[L]) cursor.insAtRightEnd(block[L]);
  2176. else cursor.insLeftOf(cmd);
  2177. }
  2178. else cursor.insAtLeftEnd(block);
  2179. return false;
  2180. }
  2181. else if (pageX > blockBounds[R]) {
  2182. if (block[R]) leftLeftBound = blockBounds[R]; // continue to next block
  2183. else { // last (rightmost) block
  2184. // closer to this block's right bound, or the cmd's right bound?
  2185. if (cmdBounds[R] - pageX < pageX - blockBounds[R]) {
  2186. cursor.insRightOf(cmd);
  2187. }
  2188. else cursor.insAtRightEnd(block);
  2189. }
  2190. }
  2191. else {
  2192. block.seek(pageX, cursor);
  2193. return false;
  2194. }
  2195. });
  2196. }
  2197. // methods involved in creating and cross-linking with HTML DOM nodes
  2198. /*
  2199. They all expect an .htmlTemplate like
  2200. '<span>&0</span>'
  2201. or
  2202. '<span><span>&0</span><span>&1</span></span>'
  2203. See html.test.js for more examples.
  2204. Requirements:
  2205. - For each block of the command, there must be exactly one "block content
  2206. marker" of the form '&<number>' where <number> is the 0-based index of the
  2207. block. (Like the LaTeX \newcommand syntax, but with a 0-based rather than
  2208. 1-based index, because JavaScript because C because Dijkstra.)
  2209. - The block content marker must be the sole contents of the containing
  2210. element, there can't even be surrounding whitespace, or else we can't
  2211. guarantee sticking to within the bounds of the block content marker when
  2212. mucking with the HTML DOM.
  2213. - The HTML not only must be well-formed HTML (of course), but also must
  2214. conform to the XHTML requirements on tags, specifically all tags must
  2215. either be self-closing (like '<br/>') or come in matching pairs.
  2216. Close tags are never optional.
  2217. Note that &<number> isn't well-formed HTML; if you wanted a literal '&123',
  2218. your HTML template would have to have '&amp;123'.
  2219. */
  2220. _.numBlocks = function() {
  2221. var matches = this.htmlTemplate.match(/&\d+/g);
  2222. return matches ? matches.length : 0;
  2223. };
  2224. _.html = function() {
  2225. // Render the entire math subtree rooted at this command, as HTML.
  2226. // Expects .createBlocks() to have been called already, since it uses the
  2227. // .blocks array of child blocks.
  2228. //
  2229. // See html.test.js for example templates and intended outputs.
  2230. //
  2231. // Given an .htmlTemplate as described above,
  2232. // - insert the mathquill-command-id attribute into all top-level tags,
  2233. // which will be used to set this.jQ in .jQize().
  2234. // This is straightforward:
  2235. // * tokenize into tags and non-tags
  2236. // * loop through top-level tokens:
  2237. // * add #cmdId attribute macro to top-level self-closing tags
  2238. // * else add #cmdId attribute macro to top-level open tags
  2239. // * skip the matching top-level close tag and all tag pairs
  2240. // in between
  2241. // - for each block content marker,
  2242. // + replace it with the contents of the corresponding block,
  2243. // rendered as HTML
  2244. // + insert the mathquill-block-id attribute into the containing tag
  2245. // This is even easier, a quick regex replace, since block tags cannot
  2246. // contain anything besides the block content marker.
  2247. //
  2248. // Two notes:
  2249. // - The outermost loop through top-level tokens should never encounter any
  2250. // top-level close tags, because we should have first encountered a
  2251. // matching top-level open tag, all inner tags should have appeared in
  2252. // matching pairs and been skipped, and then we should have skipped the
  2253. // close tag in question.
  2254. // - All open tags should have matching close tags, which means our inner
  2255. // loop should always encounter a close tag and drop nesting to 0. If
  2256. // a close tag is missing, the loop will continue until i >= tokens.length
  2257. // and token becomes undefined. This will not infinite loop, even in
  2258. // production without pray(), because it will then TypeError on .slice().
  2259. var cmd = this;
  2260. var blocks = cmd.blocks;
  2261. var cmdId = ' mathquill-command-id=' + cmd.id;
  2262. var tokens = cmd.htmlTemplate.match(/<[^<>]+>|[^<>]+/g);
  2263. pray('no unmatched angle brackets', tokens.join('') === this.htmlTemplate);
  2264. // add cmdId to all top-level tags
  2265. for (var i = 0, token = tokens[0]; token; i += 1, token = tokens[i]) {
  2266. // top-level self-closing tags
  2267. if (token.slice(-2) === '/>') {
  2268. tokens[i] = token.slice(0,-2) + cmdId + '/>';
  2269. }
  2270. // top-level open tags
  2271. else if (token.charAt(0) === '<') {
  2272. pray('not an unmatched top-level close tag', token.charAt(1) !== '/');
  2273. tokens[i] = token.slice(0,-1) + cmdId + '>';
  2274. // skip matching top-level close tag and all tag pairs in between
  2275. var nesting = 1;
  2276. do {
  2277. i += 1, token = tokens[i];
  2278. pray('no missing close tags', token);
  2279. // close tags
  2280. if (token.slice(0,2) === '</') {
  2281. nesting -= 1;
  2282. }
  2283. // non-self-closing open tags
  2284. else if (token.charAt(0) === '<' && token.slice(-2) !== '/>') {
  2285. nesting += 1;
  2286. }
  2287. } while (nesting > 0);
  2288. }
  2289. }
  2290. return tokens.join('').replace(/>&(\d+)/g, function($0, $1) {
  2291. return ' mathquill-block-id=' + blocks[$1].id + '>' + blocks[$1].join('html');
  2292. });
  2293. };
  2294. // methods to export a string representation of the math tree
  2295. _.latex = function() {
  2296. return this.foldChildren(this.ctrlSeq, function(latex, child) {
  2297. return latex + '{' + (child.latex() || ' ') + '}';
  2298. });
  2299. };
  2300. _.textTemplate = [''];
  2301. _.text = function() {
  2302. var cmd = this, i = 0;
  2303. return cmd.foldChildren(cmd.textTemplate[i], function(text, child) {
  2304. i += 1;
  2305. var child_text = child.text();
  2306. if (text && cmd.textTemplate[i] === '('
  2307. && child_text[0] === '(' && child_text.slice(-1) === ')')
  2308. return text + child_text.slice(1, -1) + cmd.textTemplate[i];
  2309. return text + child.text() + (cmd.textTemplate[i] || '');
  2310. });
  2311. };
  2312. });
  2313. /**
  2314. * Lightweight command without blocks or children.
  2315. */
  2316. var Symbol = P(MathCommand, function(_, super_) {
  2317. _.init = function(ctrlSeq, html, text) {
  2318. if (!text) text = ctrlSeq && ctrlSeq.length > 1 ? ctrlSeq.slice(1) : ctrlSeq;
  2319. super_.init.call(this, ctrlSeq, html, [ text ]);
  2320. };
  2321. _.parser = function() { return Parser.succeed(this); };
  2322. _.numBlocks = function() { return 0; };
  2323. _.replaces = function(replacedFragment) {
  2324. replacedFragment.remove();
  2325. };
  2326. _.createBlocks = noop;
  2327. _.moveTowards = function(dir, cursor) {
  2328. cursor.jQ.insDirOf(dir, this.jQ);
  2329. cursor[-dir] = this;
  2330. cursor[dir] = this[dir];
  2331. };
  2332. _.deleteTowards = function(dir, cursor) {
  2333. cursor[dir] = this.remove()[dir];
  2334. };
  2335. _.seek = function(pageX, cursor) {
  2336. // insert at whichever side the click was closer to
  2337. if (pageX - this.jQ.offset().left < this.jQ.outerWidth()/2)
  2338. cursor.insLeftOf(this);
  2339. else
  2340. cursor.insRightOf(this);
  2341. };
  2342. _.latex = function(){ return this.ctrlSeq; };
  2343. _.text = function(){ return this.textTemplate; };
  2344. _.placeCursor = noop;
  2345. _.isEmpty = function(){ return true; };
  2346. });
  2347. var VanillaSymbol = P(Symbol, function(_, super_) {
  2348. _.init = function(ch, html) {
  2349. super_.init.call(this, ch, '<span>'+(html || ch)+'</span>');
  2350. };
  2351. });
  2352. var BinaryOperator = P(Symbol, function(_, super_) {
  2353. _.init = function(ctrlSeq, html, text) {
  2354. super_.init.call(this,
  2355. ctrlSeq, '<span class="mq-binary-operator">'+html+'</span>', text
  2356. );
  2357. };
  2358. });
  2359. /**
  2360. * Children and parent of MathCommand's. Basically partitions all the
  2361. * symbols and operators that descend (in the Math DOM tree) from
  2362. * ancestor operators.
  2363. */
  2364. var MathBlock = P(MathElement, function(_, super_) {
  2365. _.join = function(methodName) {
  2366. return this.foldChildren('', function(fold, child) {
  2367. return fold + child[methodName]();
  2368. });
  2369. };
  2370. _.html = function() { return this.join('html'); };
  2371. _.latex = function() { return this.join('latex'); };
  2372. _.text = function() {
  2373. return (this.ends[L] === this.ends[R] && this.ends[L] !== 0) ?
  2374. this.ends[L].text() :
  2375. this.join('text')
  2376. ;
  2377. };
  2378. _.keystroke = function(key, e, ctrlr) {
  2379. if (ctrlr.options.spaceBehavesLikeTab
  2380. && (key === 'Spacebar' || key === 'Shift-Spacebar')) {
  2381. e.preventDefault();
  2382. ctrlr.escapeDir(key === 'Shift-Spacebar' ? L : R, key, e);
  2383. return;
  2384. }
  2385. return super_.keystroke.apply(this, arguments);
  2386. };
  2387. // editability methods: called by the cursor for editing, cursor movements,
  2388. // and selection of the MathQuill tree, these all take in a direction and
  2389. // the cursor
  2390. _.moveOutOf = function(dir, cursor, updown) {
  2391. var updownInto = updown && this.parent[updown+'Into'];
  2392. if (!updownInto && this[dir]) cursor.insAtDirEnd(-dir, this[dir]);
  2393. else cursor.insDirOf(dir, this.parent);
  2394. };
  2395. _.selectOutOf = function(dir, cursor) {
  2396. cursor.insDirOf(dir, this.parent);
  2397. };
  2398. _.deleteOutOf = function(dir, cursor) {
  2399. cursor.unwrapGramp();
  2400. };
  2401. _.seek = function(pageX, cursor) {
  2402. var node = this.ends[R];
  2403. if (!node || node.jQ.offset().left + node.jQ.outerWidth() < pageX) {
  2404. return cursor.insAtRightEnd(this);
  2405. }
  2406. if (pageX < this.ends[L].jQ.offset().left) return cursor.insAtLeftEnd(this);
  2407. while (pageX < node.jQ.offset().left) node = node[L];
  2408. return node.seek(pageX, cursor);
  2409. };
  2410. _.chToCmd = function(ch) {
  2411. var cons;
  2412. // exclude f because it gets a dedicated command with more spacing
  2413. if (ch.match(/^[a-eg-zA-Z]$/))
  2414. return Letter(ch);
  2415. else if (/^\d$/.test(ch))
  2416. return Digit(ch);
  2417. else if (cons = CharCmds[ch] || LatexCmds[ch])
  2418. return cons(ch);
  2419. else
  2420. return VanillaSymbol(ch);
  2421. };
  2422. _.write = function(cursor, ch) {
  2423. var cmd = this.chToCmd(ch);
  2424. if (cursor.selection) cmd.replaces(cursor.replaceSelection());
  2425. cmd.createLeftOf(cursor.show());
  2426. };
  2427. _.focus = function() {
  2428. this.jQ.addClass('mq-hasCursor');
  2429. this.jQ.removeClass('mq-empty');
  2430. return this;
  2431. };
  2432. _.blur = function() {
  2433. this.jQ.removeClass('mq-hasCursor');
  2434. if (this.isEmpty())
  2435. this.jQ.addClass('mq-empty');
  2436. return this;
  2437. };
  2438. });
  2439. API.StaticMath = function(APIClasses) {
  2440. return P(APIClasses.AbstractMathQuill, function(_, super_) {
  2441. this.RootBlock = MathBlock;
  2442. _.__mathquillify = function() {
  2443. super_.__mathquillify.call(this, 'mq-math-mode');
  2444. this.__controller.delegateMouseEvents();
  2445. this.__controller.staticMathTextareaEvents();
  2446. return this;
  2447. };
  2448. _.init = function() {
  2449. super_.init.apply(this, arguments);
  2450. this.__controller.root.postOrder(
  2451. 'registerInnerField', this.innerFields = [], APIClasses.MathField);
  2452. };
  2453. _.latex = function() {
  2454. var returned = super_.latex.apply(this, arguments);
  2455. if (arguments.length > 0) {
  2456. this.__controller.root.postOrder(
  2457. 'registerInnerField', this.innerFields = [], APIClasses.MathField);
  2458. }
  2459. return returned;
  2460. };
  2461. });
  2462. };
  2463. var RootMathBlock = P(MathBlock, RootBlockMixin);
  2464. API.MathField = function(APIClasses) {
  2465. return P(APIClasses.EditableField, function(_, super_) {
  2466. this.RootBlock = RootMathBlock;
  2467. _.__mathquillify = function(opts, interfaceVersion) {
  2468. this.config(opts);
  2469. if (interfaceVersion > 1) this.__controller.root.reflow = noop;
  2470. super_.__mathquillify.call(this, 'mq-editable-field mq-math-mode');
  2471. delete this.__controller.root.reflow;
  2472. return this;
  2473. };
  2474. });
  2475. };
  2476. /*********************************
  2477. * Symbols for Basic Mathematics
  2478. ********************************/
  2479. var Digit = P(VanillaSymbol, function(_, super_) {
  2480. _.createLeftOf = function(cursor) {
  2481. if (cursor.options.autoSubscriptNumerals
  2482. && cursor.parent !== cursor.parent.parent.sub
  2483. && ((cursor[L] instanceof Variable && cursor[L].isItalic !== false)
  2484. || (cursor[L] instanceof SupSub
  2485. && cursor[L][L] instanceof Variable
  2486. && cursor[L][L].isItalic !== false))) {
  2487. LatexCmds._().createLeftOf(cursor);
  2488. super_.createLeftOf.call(this, cursor);
  2489. cursor.insRightOf(cursor.parent.parent);
  2490. }
  2491. else super_.createLeftOf.call(this, cursor);
  2492. };
  2493. });
  2494. var Variable = P(Symbol, function(_, super_) {
  2495. _.init = function(ch, html) {
  2496. super_.init.call(this, ch, '<var>'+(html || ch)+'</var>');
  2497. };
  2498. _.text = function() {
  2499. var text = this.ctrlSeq;
  2500. if (this[L] && !(this[L] instanceof Variable)
  2501. && !(this[L] instanceof BinaryOperator)
  2502. && this[L].ctrlSeq !== "\\ ")
  2503. text = '*' + text;
  2504. if (this[R] && !(this[R] instanceof BinaryOperator)
  2505. && !(this[R] instanceof SupSub))
  2506. text += '*';
  2507. return text;
  2508. };
  2509. });
  2510. Options.p.autoCommands = { _maxLength: 0 };
  2511. optionProcessors.autoCommands = function(cmds) {
  2512. if (!/^[a-z]+(?: [a-z]+)*$/i.test(cmds)) {
  2513. throw '"'+cmds+'" not a space-delimited list of only letters';
  2514. }
  2515. var list = cmds.split(' '), dict = {}, maxLength = 0;
  2516. for (var i = 0; i < list.length; i += 1) {
  2517. var cmd = list[i];
  2518. if (cmd.length < 2) {
  2519. throw 'autocommand "'+cmd+'" not minimum length of 2';
  2520. }
  2521. if (LatexCmds[cmd] === OperatorName) {
  2522. throw '"' + cmd + '" is a built-in operator name';
  2523. }
  2524. dict[cmd] = 1;
  2525. maxLength = max(maxLength, cmd.length);
  2526. }
  2527. dict._maxLength = maxLength;
  2528. return dict;
  2529. };
  2530. var Letter = P(Variable, function(_, super_) {
  2531. _.init = function(ch) { return super_.init.call(this, this.letter = ch); };
  2532. _.createLeftOf = function(cursor) {
  2533. var autoCmds = cursor.options.autoCommands, maxLength = autoCmds._maxLength;
  2534. if (maxLength > 0) {
  2535. // want longest possible autocommand, so join together longest
  2536. // sequence of letters
  2537. var str = this.letter, l = cursor[L], i = 1;
  2538. while (l instanceof Letter && i < maxLength) {
  2539. str = l.letter + str, l = l[L], i += 1;
  2540. }
  2541. // check for an autocommand, going thru substrings longest to shortest
  2542. while (str.length) {
  2543. if (autoCmds.hasOwnProperty(str)) {
  2544. for (var i = 2, l = cursor[L]; i < str.length; i += 1, l = l[L]);
  2545. Fragment(l, cursor[L]).remove();
  2546. cursor[L] = l[L];
  2547. return LatexCmds[str](str).createLeftOf(cursor);
  2548. }
  2549. str = str.slice(1);
  2550. }
  2551. }
  2552. super_.createLeftOf.apply(this, arguments);
  2553. };
  2554. _.italicize = function(bool) {
  2555. this.isItalic = bool;
  2556. this.jQ.toggleClass('mq-operator-name', !bool);
  2557. return this;
  2558. };
  2559. _.finalizeTree = _.siblingDeleted = _.siblingCreated = function(opts, dir) {
  2560. // don't auto-un-italicize if the sibling to my right changed (dir === R or
  2561. // undefined) and it's now a Letter, it will un-italicize everyone
  2562. if (dir !== L && this[R] instanceof Letter) return;
  2563. this.autoUnItalicize(opts);
  2564. };
  2565. _.autoUnItalicize = function(opts) {
  2566. var autoOps = opts.autoOperatorNames;
  2567. if (autoOps._maxLength === 0) return;
  2568. // want longest possible operator names, so join together entire contiguous
  2569. // sequence of letters
  2570. var str = this.letter;
  2571. for (var l = this[L]; l instanceof Letter; l = l[L]) str = l.letter + str;
  2572. for (var r = this[R]; r instanceof Letter; r = r[R]) str += r.letter;
  2573. // removeClass and delete flags from all letters before figuring out
  2574. // which, if any, are part of an operator name
  2575. Fragment(l[R] || this.parent.ends[L], r[L] || this.parent.ends[R]).each(function(el) {
  2576. el.italicize(true).jQ.removeClass('mq-first mq-last');
  2577. el.ctrlSeq = el.letter;
  2578. });
  2579. // check for operator names: at each position from left to right, check
  2580. // substrings from longest to shortest
  2581. outer: for (var i = 0, first = l[R] || this.parent.ends[L]; i < str.length; i += 1, first = first[R]) {
  2582. for (var len = min(autoOps._maxLength, str.length - i); len > 0; len -= 1) {
  2583. var word = str.slice(i, i + len);
  2584. if (autoOps.hasOwnProperty(word)) {
  2585. for (var j = 0, letter = first; j < len; j += 1, letter = letter[R]) {
  2586. letter.italicize(false);
  2587. var last = letter;
  2588. }
  2589. var isBuiltIn = BuiltInOpNames.hasOwnProperty(word);
  2590. first.ctrlSeq = (isBuiltIn ? '\\' : '\\operatorname{') + first.ctrlSeq;
  2591. last.ctrlSeq += (isBuiltIn ? ' ' : '}');
  2592. if (TwoWordOpNames.hasOwnProperty(word)) last[L][L][L].jQ.addClass('mq-last');
  2593. if (nonOperatorSymbol(first[L])) first.jQ.addClass('mq-first');
  2594. if (nonOperatorSymbol(last[R])) last.jQ.addClass('mq-last');
  2595. i += len - 1;
  2596. first = last;
  2597. continue outer;
  2598. }
  2599. }
  2600. }
  2601. };
  2602. function nonOperatorSymbol(node) {
  2603. return node instanceof Symbol && !(node instanceof BinaryOperator);
  2604. }
  2605. });
  2606. var BuiltInOpNames = {}; // the set of operator names like \sin, \cos, etc that
  2607. // are built-into LaTeX: http://latex.wikia.com/wiki/List_of_LaTeX_symbols#Named_operators:_sin.2C_cos.2C_etc.
  2608. // MathQuill auto-unitalicizes some operator names not in that set, like 'hcf'
  2609. // and 'arsinh', which must be exported as \operatorname{hcf} and
  2610. // \operatorname{arsinh}. Note: over/under line/arrow \lim variants like
  2611. // \varlimsup are not supported
  2612. var AutoOpNames = Options.p.autoOperatorNames = { _maxLength: 9 }; // the set
  2613. // of operator names that MathQuill auto-unitalicizes by default; overridable
  2614. var TwoWordOpNames = { limsup: 1, liminf: 1, projlim: 1, injlim: 1 };
  2615. (function() {
  2616. var mostOps = ('arg deg det dim exp gcd hom inf ker lg lim ln log max min sup'
  2617. + ' limsup liminf injlim projlim Pr').split(' ');
  2618. for (var i = 0; i < mostOps.length; i += 1) {
  2619. BuiltInOpNames[mostOps[i]] = AutoOpNames[mostOps[i]] = 1;
  2620. }
  2621. var builtInTrigs = // why coth but not sech and csch, LaTeX?
  2622. 'sin cos tan arcsin arccos arctan sinh cosh tanh sec csc cot coth'.split(' ');
  2623. for (var i = 0; i < builtInTrigs.length; i += 1) {
  2624. BuiltInOpNames[builtInTrigs[i]] = 1;
  2625. }
  2626. var autoTrigs = 'sin cos tan sec cosec csc cotan cot ctg'.split(' ');
  2627. for (var i = 0; i < autoTrigs.length; i += 1) {
  2628. AutoOpNames[autoTrigs[i]] =
  2629. AutoOpNames['arc'+autoTrigs[i]] =
  2630. AutoOpNames[autoTrigs[i]+'h'] =
  2631. AutoOpNames['ar'+autoTrigs[i]+'h'] =
  2632. AutoOpNames['arc'+autoTrigs[i]+'h'] = 1;
  2633. }
  2634. // compat with some of the nonstandard LaTeX exported by MathQuill
  2635. // before #247. None of these are real LaTeX commands so, seems safe
  2636. var moreNonstandardOps = 'gcf hcf lcm proj span'.split(' ');
  2637. for (var i = 0; i < moreNonstandardOps.length; i += 1) {
  2638. AutoOpNames[moreNonstandardOps[i]] = 1;
  2639. }
  2640. }());
  2641. optionProcessors.autoOperatorNames = function(cmds) {
  2642. if (!/^[a-z]+(?: [a-z]+)*$/i.test(cmds)) {
  2643. throw '"'+cmds+'" not a space-delimited list of only letters';
  2644. }
  2645. var list = cmds.split(' '), dict = {}, maxLength = 0;
  2646. for (var i = 0; i < list.length; i += 1) {
  2647. var cmd = list[i];
  2648. if (cmd.length < 2) {
  2649. throw '"'+cmd+'" not minimum length of 2';
  2650. }
  2651. dict[cmd] = 1;
  2652. maxLength = max(maxLength, cmd.length);
  2653. }
  2654. dict._maxLength = maxLength;
  2655. return dict;
  2656. };
  2657. var OperatorName = P(Symbol, function(_, super_) {
  2658. _.init = function(fn) { this.ctrlSeq = fn; };
  2659. _.createLeftOf = function(cursor) {
  2660. var fn = this.ctrlSeq;
  2661. for (var i = 0; i < fn.length; i += 1) {
  2662. Letter(fn.charAt(i)).createLeftOf(cursor);
  2663. }
  2664. };
  2665. _.parser = function() {
  2666. var fn = this.ctrlSeq;
  2667. var block = MathBlock();
  2668. for (var i = 0; i < fn.length; i += 1) {
  2669. Letter(fn.charAt(i)).adopt(block, block.ends[R], 0);
  2670. }
  2671. return Parser.succeed(block.children());
  2672. };
  2673. });
  2674. for (var fn in AutoOpNames) if (AutoOpNames.hasOwnProperty(fn)) {
  2675. LatexCmds[fn] = OperatorName;
  2676. }
  2677. LatexCmds.operatorname = P(MathCommand, function(_) {
  2678. _.createLeftOf = noop;
  2679. _.numBlocks = function() { return 1; };
  2680. _.parser = function() {
  2681. return latexMathParser.block.map(function(b) { return b.children(); });
  2682. };
  2683. });
  2684. LatexCmds.f = P(Letter, function(_, super_) {
  2685. _.init = function() {
  2686. Symbol.p.init.call(this, this.letter = 'f', '<var class="mq-f">f</var>');
  2687. };
  2688. _.italicize = function(bool) {
  2689. this.jQ.html('f').toggleClass('mq-f', bool);
  2690. return super_.italicize.apply(this, arguments);
  2691. };
  2692. });
  2693. // VanillaSymbol's
  2694. LatexCmds[' '] = LatexCmds.space = bind(VanillaSymbol, '\\ ', '&nbsp;');
  2695. LatexCmds["'"] = LatexCmds.prime = bind(VanillaSymbol, "'", '&prime;');
  2696. LatexCmds.backslash = bind(VanillaSymbol,'\\backslash ','\\');
  2697. if (!CharCmds['\\']) CharCmds['\\'] = LatexCmds.backslash;
  2698. LatexCmds.$ = bind(VanillaSymbol, '\\$', '$');
  2699. // does not use Symbola font
  2700. var NonSymbolaSymbol = P(Symbol, function(_, super_) {
  2701. _.init = function(ch, html) {
  2702. super_.init.call(this, ch, '<span class="mq-nonSymbola">'+(html || ch)+'</span>');
  2703. };
  2704. });
  2705. LatexCmds['@'] = NonSymbolaSymbol;
  2706. LatexCmds['&'] = bind(NonSymbolaSymbol, '\\&', '&amp;');
  2707. LatexCmds['%'] = bind(NonSymbolaSymbol, '\\%', '%');
  2708. //the following are all Greek to me, but this helped a lot: http://www.ams.org/STIX/ion/stixsig03.html
  2709. //lowercase Greek letter variables
  2710. LatexCmds.alpha =
  2711. LatexCmds.beta =
  2712. LatexCmds.gamma =
  2713. LatexCmds.delta =
  2714. LatexCmds.zeta =
  2715. LatexCmds.eta =
  2716. LatexCmds.theta =
  2717. LatexCmds.iota =
  2718. LatexCmds.kappa =
  2719. LatexCmds.mu =
  2720. LatexCmds.nu =
  2721. LatexCmds.xi =
  2722. LatexCmds.rho =
  2723. LatexCmds.sigma =
  2724. LatexCmds.tau =
  2725. LatexCmds.chi =
  2726. LatexCmds.psi =
  2727. LatexCmds.omega = P(Variable, function(_, super_) {
  2728. _.init = function(latex) {
  2729. super_.init.call(this,'\\'+latex+' ','&'+latex+';');
  2730. };
  2731. });
  2732. //why can't anybody FUCKING agree on these
  2733. LatexCmds.phi = //W3C or Unicode?
  2734. bind(Variable,'\\phi ','&#981;');
  2735. LatexCmds.phiv = //Elsevier and 9573-13
  2736. LatexCmds.varphi = //AMS and LaTeX
  2737. bind(Variable,'\\varphi ','&phi;');
  2738. LatexCmds.epsilon = //W3C or Unicode?
  2739. bind(Variable,'\\epsilon ','&#1013;');
  2740. LatexCmds.epsiv = //Elsevier and 9573-13
  2741. LatexCmds.varepsilon = //AMS and LaTeX
  2742. bind(Variable,'\\varepsilon ','&epsilon;');
  2743. LatexCmds.piv = //W3C/Unicode and Elsevier and 9573-13
  2744. LatexCmds.varpi = //AMS and LaTeX
  2745. bind(Variable,'\\varpi ','&piv;');
  2746. LatexCmds.sigmaf = //W3C/Unicode
  2747. LatexCmds.sigmav = //Elsevier
  2748. LatexCmds.varsigma = //LaTeX
  2749. bind(Variable,'\\varsigma ','&sigmaf;');
  2750. LatexCmds.thetav = //Elsevier and 9573-13
  2751. LatexCmds.vartheta = //AMS and LaTeX
  2752. LatexCmds.thetasym = //W3C/Unicode
  2753. bind(Variable,'\\vartheta ','&thetasym;');
  2754. LatexCmds.upsilon = //AMS and LaTeX and W3C/Unicode
  2755. LatexCmds.upsi = //Elsevier and 9573-13
  2756. bind(Variable,'\\upsilon ','&upsilon;');
  2757. //these aren't even mentioned in the HTML character entity references
  2758. LatexCmds.gammad = //Elsevier
  2759. LatexCmds.Gammad = //9573-13 -- WTF, right? I dunno if this was a typo in the reference (see above)
  2760. LatexCmds.digamma = //LaTeX
  2761. bind(Variable,'\\digamma ','&#989;');
  2762. LatexCmds.kappav = //Elsevier
  2763. LatexCmds.varkappa = //AMS and LaTeX
  2764. bind(Variable,'\\varkappa ','&#1008;');
  2765. LatexCmds.rhov = //Elsevier and 9573-13
  2766. LatexCmds.varrho = //AMS and LaTeX
  2767. bind(Variable,'\\varrho ','&#1009;');
  2768. //Greek constants, look best in non-italicized Times New Roman
  2769. LatexCmds.pi = LatexCmds['\u03c0'] = bind(NonSymbolaSymbol,'\\pi ','&pi;');
  2770. LatexCmds.lambda = bind(NonSymbolaSymbol,'\\lambda ','&lambda;');
  2771. //uppercase greek letters
  2772. LatexCmds.Upsilon = //LaTeX
  2773. LatexCmds.Upsi = //Elsevier and 9573-13
  2774. LatexCmds.upsih = //W3C/Unicode "upsilon with hook"
  2775. LatexCmds.Upsih = //'cos it makes sense to me
  2776. bind(Symbol,'\\Upsilon ','<var style="font-family: serif">&upsih;</var>'); //Symbola's 'upsilon with a hook' is a capital Y without hooks :(
  2777. //other symbols with the same LaTeX command and HTML character entity reference
  2778. LatexCmds.Gamma =
  2779. LatexCmds.Delta =
  2780. LatexCmds.Theta =
  2781. LatexCmds.Lambda =
  2782. LatexCmds.Xi =
  2783. LatexCmds.Pi =
  2784. LatexCmds.Sigma =
  2785. LatexCmds.Phi =
  2786. LatexCmds.Psi =
  2787. LatexCmds.Omega =
  2788. LatexCmds.forall = P(VanillaSymbol, function(_, super_) {
  2789. _.init = function(latex) {
  2790. super_.init.call(this,'\\'+latex+' ','&'+latex+';');
  2791. };
  2792. });
  2793. // symbols that aren't a single MathCommand, but are instead a whole
  2794. // Fragment. Creates the Fragment from a LaTeX string
  2795. var LatexFragment = P(MathCommand, function(_) {
  2796. _.init = function(latex) { this.latex = latex; };
  2797. _.createLeftOf = function(cursor) {
  2798. var block = latexMathParser.parse(this.latex);
  2799. block.children().adopt(cursor.parent, cursor[L], cursor[R]);
  2800. cursor[L] = block.ends[R];
  2801. block.jQize().insertBefore(cursor.jQ);
  2802. block.finalizeInsert(cursor.options, cursor);
  2803. if (block.ends[R][R].siblingCreated) block.ends[R][R].siblingCreated(cursor.options, L);
  2804. if (block.ends[L][L].siblingCreated) block.ends[L][L].siblingCreated(cursor.options, R);
  2805. cursor.parent.bubble('reflow');
  2806. };
  2807. _.parser = function() {
  2808. var frag = latexMathParser.parse(this.latex).children();
  2809. return Parser.succeed(frag);
  2810. };
  2811. });
  2812. // for what seems to me like [stupid reasons][1], Unicode provides
  2813. // subscripted and superscripted versions of all ten Arabic numerals,
  2814. // as well as [so-called "vulgar fractions"][2].
  2815. // Nobody really cares about most of them, but some of them actually
  2816. // predate Unicode, dating back to [ISO-8859-1][3], apparently also
  2817. // known as "Latin-1", which among other things [Windows-1252][4]
  2818. // largely coincides with, so Microsoft Word sometimes inserts them
  2819. // and they get copy-pasted into MathQuill.
  2820. //
  2821. // (Irrelevant but funny story: though not a superset of Latin-1 aka
  2822. // ISO-8859-1, Windows-1252 **is** a strict superset of the "closely
  2823. // related but distinct"[3] "ISO 8859-1" -- see the lack of a dash
  2824. // after "ISO"? Completely different character set, like elephants vs
  2825. // elephant seals, or "Zombies" vs "Zombie Redneck Torture Family".
  2826. // What kind of idiot would get them confused.
  2827. // People in fact got them confused so much, it was so common to
  2828. // mislabel Windows-1252 text as ISO-8859-1, that most modern web
  2829. // browsers and email clients treat the MIME charset of ISO-8859-1
  2830. // as actually Windows-1252, behavior now standard in the HTML5 spec.)
  2831. //
  2832. // [1]: http://en.wikipedia.org/wiki/Unicode_subscripts_andsuper_scripts
  2833. // [2]: http://en.wikipedia.org/wiki/Number_Forms
  2834. // [3]: http://en.wikipedia.org/wiki/ISO/IEC_8859-1
  2835. // [4]: http://en.wikipedia.org/wiki/Windows-1252
  2836. LatexCmds['\u00b9'] = bind(LatexFragment, '^1');
  2837. LatexCmds['\u00b2'] = bind(LatexFragment, '^2');
  2838. LatexCmds['\u00b3'] = bind(LatexFragment, '^3');
  2839. LatexCmds['\u00bc'] = bind(LatexFragment, '\\frac14');
  2840. LatexCmds['\u00bd'] = bind(LatexFragment, '\\frac12');
  2841. LatexCmds['\u00be'] = bind(LatexFragment, '\\frac34');
  2842. var PlusMinus = P(BinaryOperator, function(_) {
  2843. _.init = VanillaSymbol.prototype.init;
  2844. _.contactWeld = _.siblingCreated = _.siblingDeleted = function(opts, dir) {
  2845. if (dir === R) return; // ignore if sibling only changed on the right
  2846. this.jQ[0].className =
  2847. (!this[L] || this[L] instanceof BinaryOperator ? '' : 'mq-binary-operator');
  2848. return this;
  2849. };
  2850. });
  2851. LatexCmds['+'] = bind(PlusMinus, '+', '+');
  2852. //yes, these are different dashes, I think one is an en dash and the other is a hyphen
  2853. LatexCmds['\u2013'] = LatexCmds['-'] = bind(PlusMinus, '-', '&minus;');
  2854. LatexCmds['\u00b1'] = LatexCmds.pm = LatexCmds.plusmn = LatexCmds.plusminus =
  2855. bind(PlusMinus,'\\pm ','&plusmn;');
  2856. LatexCmds.mp = LatexCmds.mnplus = LatexCmds.minusplus =
  2857. bind(PlusMinus,'\\mp ','&#8723;');
  2858. CharCmds['*'] = LatexCmds.sdot = LatexCmds.cdot =
  2859. bind(BinaryOperator, '\\cdot ', '&middot;', '*');
  2860. //semantically should be &sdot;, but &middot; looks better
  2861. var Inequality = P(BinaryOperator, function(_, super_) {
  2862. _.init = function(data, strict) {
  2863. this.data = data;
  2864. this.strict = strict;
  2865. var strictness = (strict ? 'Strict' : '');
  2866. super_.init.call(this, data['ctrlSeq'+strictness], data['html'+strictness],
  2867. data['text'+strictness]);
  2868. };
  2869. _.swap = function(strict) {
  2870. this.strict = strict;
  2871. var strictness = (strict ? 'Strict' : '');
  2872. this.ctrlSeq = this.data['ctrlSeq'+strictness];
  2873. this.jQ.html(this.data['html'+strictness]);
  2874. this.textTemplate = [ this.data['text'+strictness] ];
  2875. };
  2876. _.deleteTowards = function(dir, cursor) {
  2877. if (dir === L && !this.strict) {
  2878. this.swap(true);
  2879. this.bubble('reflow');
  2880. return;
  2881. }
  2882. super_.deleteTowards.apply(this, arguments);
  2883. };
  2884. });
  2885. var less = { ctrlSeq: '\\le ', html: '&le;', text: '\u2264',
  2886. ctrlSeqStrict: '<', htmlStrict: '&lt;', textStrict: '<' };
  2887. var greater = { ctrlSeq: '\\ge ', html: '&ge;', text: '\u2265',
  2888. ctrlSeqStrict: '>', htmlStrict: '&gt;', textStrict: '>' };
  2889. LatexCmds['<'] = LatexCmds.lt = bind(Inequality, less, true);
  2890. LatexCmds['>'] = LatexCmds.gt = bind(Inequality, greater, true);
  2891. LatexCmds['\u2264'] = LatexCmds.le = LatexCmds.leq = bind(Inequality, less, false);
  2892. LatexCmds['\u2265'] = LatexCmds.ge = LatexCmds.geq = bind(Inequality, greater, false);
  2893. var Equality = P(BinaryOperator, function(_, super_) {
  2894. _.init = function() {
  2895. super_.init.call(this, '=', '=');
  2896. };
  2897. _.createLeftOf = function(cursor) {
  2898. if (cursor[L] instanceof Inequality && cursor[L].strict) {
  2899. cursor[L].swap(false);
  2900. cursor[L].bubble('reflow');
  2901. return;
  2902. }
  2903. super_.createLeftOf.apply(this, arguments);
  2904. };
  2905. });
  2906. LatexCmds['='] = Equality;
  2907. LatexCmds['\u00d7'] = LatexCmds.times = bind(BinaryOperator, '\\times ', '&times;', '[x]');
  2908. LatexCmds['\u00f7'] = LatexCmds.div = LatexCmds.divide = LatexCmds.divides =
  2909. bind(BinaryOperator,'\\div ','&divide;', '[/]');
  2910. CharCmds['~'] = LatexCmds.sim = bind(BinaryOperator, '\\sim ', '~', '~');
  2911. /***************************
  2912. * Commands and Operators.
  2913. **************************/
  2914. var scale, // = function(jQ, x, y) { ... }
  2915. //will use a CSS 2D transform to scale the jQuery-wrapped HTML elements,
  2916. //or the filter matrix transform fallback for IE 5.5-8, or gracefully degrade to
  2917. //increasing the fontSize to match the vertical Y scaling factor.
  2918. //ideas from http://github.com/louisremi/jquery.transform.js
  2919. //see also http://msdn.microsoft.com/en-us/library/ms533014(v=vs.85).aspx
  2920. forceIERedraw = noop,
  2921. div = document.createElement('div'),
  2922. div_style = div.style,
  2923. transformPropNames = {
  2924. transform:1,
  2925. WebkitTransform:1,
  2926. MozTransform:1,
  2927. OTransform:1,
  2928. msTransform:1
  2929. },
  2930. transformPropName;
  2931. for (var prop in transformPropNames) {
  2932. if (prop in div_style) {
  2933. transformPropName = prop;
  2934. break;
  2935. }
  2936. }
  2937. if (transformPropName) {
  2938. scale = function(jQ, x, y) {
  2939. jQ.css(transformPropName, 'scale('+x+','+y+')');
  2940. };
  2941. }
  2942. else if ('filter' in div_style) { //IE 6, 7, & 8 fallback, see https://github.com/laughinghan/mathquill/wiki/Transforms
  2943. forceIERedraw = function(el){ el.className = el.className; };
  2944. scale = function(jQ, x, y) { //NOTE: assumes y > x
  2945. x /= (1+(y-1)/2);
  2946. jQ.css('fontSize', y + 'em');
  2947. if (!jQ.hasClass('mq-matrixed-container')) {
  2948. jQ.addClass('mq-matrixed-container')
  2949. .wrapInner('<span class="mq-matrixed"></span>');
  2950. }
  2951. var innerjQ = jQ.children()
  2952. .css('filter', 'progid:DXImageTransform.Microsoft'
  2953. + '.Matrix(M11=' + x + ",SizingMethod='auto expand')"
  2954. );
  2955. function calculateMarginRight() {
  2956. jQ.css('marginRight', (innerjQ.width()-1)*(x-1)/x + 'px');
  2957. }
  2958. calculateMarginRight();
  2959. var intervalId = setInterval(calculateMarginRight);
  2960. $(window).load(function() {
  2961. clearTimeout(intervalId);
  2962. calculateMarginRight();
  2963. });
  2964. };
  2965. }
  2966. else {
  2967. scale = function(jQ, x, y) {
  2968. jQ.css('fontSize', y + 'em');
  2969. };
  2970. }
  2971. var Style = P(MathCommand, function(_, super_) {
  2972. _.init = function(ctrlSeq, tagName, attrs) {
  2973. super_.init.call(this, ctrlSeq, '<'+tagName+' '+attrs+'>&0</'+tagName+'>');
  2974. };
  2975. });
  2976. //fonts
  2977. LatexCmds.mathrm = bind(Style, '\\mathrm', 'span', 'class="mq-roman mq-font"');
  2978. LatexCmds.mathit = bind(Style, '\\mathit', 'i', 'class="mq-font"');
  2979. LatexCmds.mathbf = bind(Style, '\\mathbf', 'b', 'class="mq-font"');
  2980. LatexCmds.mathsf = bind(Style, '\\mathsf', 'span', 'class="mq-sans-serif mq-font"');
  2981. LatexCmds.mathtt = bind(Style, '\\mathtt', 'span', 'class="mq-monospace mq-font"');
  2982. //text-decoration
  2983. LatexCmds.underline = bind(Style, '\\underline', 'span', 'class="mq-non-leaf mq-underline"');
  2984. LatexCmds.overline = LatexCmds.bar = bind(Style, '\\overline', 'span', 'class="mq-non-leaf mq-overline"');
  2985. LatexCmds.overrightarrow = bind(Style, '\\overrightarrow', 'span', 'class="mq-non-leaf mq-overarrow mq-arrow-right"');
  2986. LatexCmds.overleftarrow = bind(Style, '\\overleftarrow', 'span', 'class="mq-non-leaf mq-overarrow mq-arrow-left"');
  2987. // `\textcolor{color}{math}` will apply a color to the given math content, where
  2988. // `color` is any valid CSS Color Value (see [SitePoint docs][] (recommended),
  2989. // [Mozilla docs][], or [W3C spec][]).
  2990. //
  2991. // [SitePoint docs]: http://reference.sitepoint.com/css/colorvalues
  2992. // [Mozilla docs]: https://developer.mozilla.org/en-US/docs/CSS/color_value#Values
  2993. // [W3C spec]: http://dev.w3.org/csswg/css3-color/#colorunits
  2994. var TextColor = LatexCmds.textcolor = P(MathCommand, function(_, super_) {
  2995. _.setColor = function(color) {
  2996. this.color = color;
  2997. this.htmlTemplate =
  2998. '<span class="mq-textcolor" style="color:' + color + '">&0</span>';
  2999. };
  3000. _.latex = function() {
  3001. return '\\textcolor{' + this.color + '}{' + this.blocks[0].latex() + '}';
  3002. };
  3003. _.parser = function() {
  3004. var self = this;
  3005. var optWhitespace = Parser.optWhitespace;
  3006. var string = Parser.string;
  3007. var regex = Parser.regex;
  3008. return optWhitespace
  3009. .then(string('{'))
  3010. .then(regex(/^[#\w\s.,()%-]*/))
  3011. .skip(string('}'))
  3012. .then(function(color) {
  3013. self.setColor(color);
  3014. return super_.parser.call(self);
  3015. })
  3016. ;
  3017. };
  3018. });
  3019. // Very similar to the \textcolor command, but will add the given CSS class.
  3020. // Usage: \class{classname}{math}
  3021. // Note regex that whitelists valid CSS classname characters:
  3022. // https://github.com/mathquill/mathquill/pull/191#discussion_r4327442
  3023. var Class = LatexCmds['class'] = P(MathCommand, function(_, super_) {
  3024. _.parser = function() {
  3025. var self = this, string = Parser.string, regex = Parser.regex;
  3026. return Parser.optWhitespace
  3027. .then(string('{'))
  3028. .then(regex(/^[-\w\s\\\xA0-\xFF]*/))
  3029. .skip(string('}'))
  3030. .then(function(cls) {
  3031. self.htmlTemplate = '<span class="mq-class '+cls+'">&0</span>';
  3032. return super_.parser.call(self);
  3033. })
  3034. ;
  3035. };
  3036. });
  3037. var SupSub = P(MathCommand, function(_, super_) {
  3038. _.ctrlSeq = '_{...}^{...}';
  3039. _.createLeftOf = function(cursor) {
  3040. if (!cursor[L] && cursor.options.supSubsRequireOperand) return;
  3041. return super_.createLeftOf.apply(this, arguments);
  3042. };
  3043. _.contactWeld = function(cursor) {
  3044. // Look on either side for a SupSub, if one is found compare my
  3045. // .sub, .sup with its .sub, .sup. If I have one that it doesn't,
  3046. // then call .addBlock() on it with my block; if I have one that
  3047. // it also has, then insert my block's children into its block,
  3048. // unless my block has none, in which case insert the cursor into
  3049. // its block (and not mine, I'm about to remove myself) in the case
  3050. // I was just typed.
  3051. // TODO: simplify
  3052. // equiv. to [L, R].forEach(function(dir) { ... });
  3053. for (var dir = L; dir; dir = (dir === L ? R : false)) {
  3054. if (this[dir] instanceof SupSub) {
  3055. // equiv. to 'sub sup'.split(' ').forEach(function(supsub) { ... });
  3056. for (var supsub = 'sub'; supsub; supsub = (supsub === 'sub' ? 'sup' : false)) {
  3057. var src = this[supsub], dest = this[dir][supsub];
  3058. if (!src) continue;
  3059. if (!dest) this[dir].addBlock(src.disown());
  3060. else if (!src.isEmpty()) { // ins src children at -dir end of dest
  3061. src.jQ.children().insAtDirEnd(-dir, dest.jQ);
  3062. var children = src.children().disown();
  3063. var pt = Point(dest, children.ends[R], dest.ends[L]);
  3064. if (dir === L) children.adopt(dest, dest.ends[R], 0);
  3065. else children.adopt(dest, 0, dest.ends[L]);
  3066. }
  3067. else var pt = Point(dest, 0, dest.ends[L]);
  3068. this.placeCursor = (function(dest, src) { // TODO: don't monkey-patch
  3069. return function(cursor) { cursor.insAtDirEnd(-dir, dest || src); };
  3070. }(dest, src));
  3071. }
  3072. this.remove();
  3073. if (cursor && cursor[L] === this) {
  3074. if (dir === R && pt) {
  3075. pt[L] ? cursor.insRightOf(pt[L]) : cursor.insAtLeftEnd(pt.parent);
  3076. }
  3077. else cursor.insRightOf(this[dir]);
  3078. }
  3079. break;
  3080. }
  3081. }
  3082. this.respace();
  3083. };
  3084. Options.p.charsThatBreakOutOfSupSub = '';
  3085. _.finalizeTree = function() {
  3086. this.ends[L].write = function(cursor, ch) {
  3087. if (cursor.options.autoSubscriptNumerals && this === this.parent.sub) {
  3088. if (ch === '_') return;
  3089. var cmd = this.chToCmd(ch);
  3090. if (cmd instanceof Symbol) cursor.deleteSelection();
  3091. else cursor.clearSelection().insRightOf(this.parent);
  3092. return cmd.createLeftOf(cursor.show());
  3093. }
  3094. if (cursor[L] && !cursor[R] && !cursor.selection
  3095. && cursor.options.charsThatBreakOutOfSupSub.indexOf(ch) > -1) {
  3096. cursor.insRightOf(this.parent);
  3097. }
  3098. MathBlock.p.write.apply(this, arguments);
  3099. };
  3100. };
  3101. _.moveTowards = function(dir, cursor, updown) {
  3102. if (cursor.options.autoSubscriptNumerals && !this.sup) {
  3103. cursor.insDirOf(dir, this);
  3104. }
  3105. else super_.moveTowards.apply(this, arguments);
  3106. };
  3107. _.deleteTowards = function(dir, cursor) {
  3108. if (cursor.options.autoSubscriptNumerals && this.sub) {
  3109. var cmd = this.sub.ends[-dir];
  3110. if (cmd instanceof Symbol) cmd.remove();
  3111. else if (cmd) cmd.deleteTowards(dir, cursor.insAtDirEnd(-dir, this.sub));
  3112. // TODO: factor out a .removeBlock() or something
  3113. if (this.sub.isEmpty()) {
  3114. this.sub.deleteOutOf(L, cursor.insAtLeftEnd(this.sub));
  3115. if (this.sup) cursor.insDirOf(-dir, this);
  3116. // Note `-dir` because in e.g. x_1^2| want backspacing (leftward)
  3117. // to delete the 1 but to end up rightward of x^2; with non-negated
  3118. // `dir` (try it), the cursor appears to have gone "through" the ^2.
  3119. }
  3120. }
  3121. else super_.deleteTowards.apply(this, arguments);
  3122. };
  3123. _.latex = function() {
  3124. function latex(prefix, block) {
  3125. var l = block && block.latex();
  3126. return block ? prefix + (l.length === 1 ? l : '{' + (l || ' ') + '}') : '';
  3127. }
  3128. return latex('_', this.sub) + latex('^', this.sup);
  3129. };
  3130. _.respace = _.siblingCreated = _.siblingDeleted = function(opts, dir) {
  3131. if (dir === R) return; // ignore if sibling only changed on the right
  3132. this.jQ.toggleClass('mq-limit', this[L].ctrlSeq === '\\int ');
  3133. };
  3134. _.addBlock = function(block) {
  3135. if (this.supsub === 'sub') {
  3136. this.sup = this.upInto = this.sub.upOutOf = block;
  3137. block.adopt(this, this.sub, 0).downOutOf = this.sub;
  3138. block.jQ = $('<span class="mq-sup"/>').append(block.jQ.children())
  3139. .attr(mqBlockId, block.id).prependTo(this.jQ);
  3140. }
  3141. else {
  3142. this.sub = this.downInto = this.sup.downOutOf = block;
  3143. block.adopt(this, 0, this.sup).upOutOf = this.sup;
  3144. block.jQ = $('<span class="mq-sub"></span>').append(block.jQ.children())
  3145. .attr(mqBlockId, block.id).appendTo(this.jQ.removeClass('mq-sup-only'));
  3146. this.jQ.append('<span style="display:inline-block;width:0">&#8203;</span>');
  3147. }
  3148. // like 'sub sup'.split(' ').forEach(function(supsub) { ... });
  3149. for (var i = 0; i < 2; i += 1) (function(cmd, supsub, oppositeSupsub, updown) {
  3150. cmd[supsub].deleteOutOf = function(dir, cursor) {
  3151. cursor.insDirOf((this[dir] ? -dir : dir), this.parent);
  3152. if (!this.isEmpty()) {
  3153. var end = this.ends[dir];
  3154. this.children().disown()
  3155. .withDirAdopt(dir, cursor.parent, cursor[dir], cursor[-dir])
  3156. .jQ.insDirOf(-dir, cursor.jQ);
  3157. cursor[-dir] = end;
  3158. }
  3159. cmd.supsub = oppositeSupsub;
  3160. delete cmd[supsub];
  3161. delete cmd[updown+'Into'];
  3162. cmd[oppositeSupsub][updown+'OutOf'] = insLeftOfMeUnlessAtEnd;
  3163. delete cmd[oppositeSupsub].deleteOutOf;
  3164. if (supsub === 'sub') $(cmd.jQ.addClass('mq-sup-only')[0].lastChild).remove();
  3165. this.remove();
  3166. };
  3167. }(this, 'sub sup'.split(' ')[i], 'sup sub'.split(' ')[i], 'down up'.split(' ')[i]));
  3168. };
  3169. });
  3170. function insLeftOfMeUnlessAtEnd(cursor) {
  3171. // cursor.insLeftOf(cmd), unless cursor at the end of block, and every
  3172. // ancestor cmd is at the end of every ancestor block
  3173. var cmd = this.parent, ancestorCmd = cursor;
  3174. do {
  3175. if (ancestorCmd[R]) return cursor.insLeftOf(cmd);
  3176. ancestorCmd = ancestorCmd.parent.parent;
  3177. } while (ancestorCmd !== cmd);
  3178. cursor.insRightOf(cmd);
  3179. }
  3180. LatexCmds.subscript =
  3181. LatexCmds._ = P(SupSub, function(_, super_) {
  3182. _.supsub = 'sub';
  3183. _.htmlTemplate =
  3184. '<span class="mq-supsub mq-non-leaf">'
  3185. + '<span class="mq-sub">&0</span>'
  3186. + '<span style="display:inline-block;width:0">&#8203;</span>'
  3187. + '</span>'
  3188. ;
  3189. _.textTemplate = [ '_' ];
  3190. _.finalizeTree = function() {
  3191. this.downInto = this.sub = this.ends[L];
  3192. this.sub.upOutOf = insLeftOfMeUnlessAtEnd;
  3193. super_.finalizeTree.call(this);
  3194. };
  3195. });
  3196. LatexCmds.superscript =
  3197. LatexCmds.supscript =
  3198. LatexCmds['^'] = P(SupSub, function(_, super_) {
  3199. _.supsub = 'sup';
  3200. _.htmlTemplate =
  3201. '<span class="mq-supsub mq-non-leaf mq-sup-only">'
  3202. + '<span class="mq-sup">&0</span>'
  3203. + '</span>'
  3204. ;
  3205. _.textTemplate = [ '^' ];
  3206. _.finalizeTree = function() {
  3207. this.upInto = this.sup = this.ends[R];
  3208. this.sup.downOutOf = insLeftOfMeUnlessAtEnd;
  3209. super_.finalizeTree.call(this);
  3210. };
  3211. });
  3212. var SummationNotation = P(MathCommand, function(_, super_) {
  3213. _.init = function(ch, html) {
  3214. var htmlTemplate =
  3215. '<span class="mq-large-operator mq-non-leaf">'
  3216. + '<span class="mq-to"><span>&1</span></span>'
  3217. + '<big>'+html+'</big>'
  3218. + '<span class="mq-from"><span>&0</span></span>'
  3219. + '</span>'
  3220. ;
  3221. Symbol.prototype.init.call(this, ch, htmlTemplate);
  3222. };
  3223. _.createLeftOf = function(cursor) {
  3224. super_.createLeftOf.apply(this, arguments);
  3225. if (cursor.options.sumStartsWithNEquals) {
  3226. Letter('n').createLeftOf(cursor);
  3227. Equality().createLeftOf(cursor);
  3228. }
  3229. };
  3230. _.latex = function() {
  3231. function simplify(latex) {
  3232. return latex.length === 1 ? latex : '{' + (latex || ' ') + '}';
  3233. }
  3234. return this.ctrlSeq + '_' + simplify(this.ends[L].latex()) +
  3235. '^' + simplify(this.ends[R].latex());
  3236. };
  3237. _.parser = function() {
  3238. var string = Parser.string;
  3239. var optWhitespace = Parser.optWhitespace;
  3240. var succeed = Parser.succeed;
  3241. var block = latexMathParser.block;
  3242. var self = this;
  3243. var blocks = self.blocks = [ MathBlock(), MathBlock() ];
  3244. for (var i = 0; i < blocks.length; i += 1) {
  3245. blocks[i].adopt(self, self.ends[R], 0);
  3246. }
  3247. return optWhitespace.then(string('_').or(string('^'))).then(function(supOrSub) {
  3248. var child = blocks[supOrSub === '_' ? 0 : 1];
  3249. return block.then(function(block) {
  3250. block.children().adopt(child, child.ends[R], 0);
  3251. return succeed(self);
  3252. });
  3253. }).many().result(self);
  3254. };
  3255. _.finalizeTree = function() {
  3256. this.downInto = this.ends[L];
  3257. this.upInto = this.ends[R];
  3258. this.ends[L].upOutOf = this.ends[R];
  3259. this.ends[R].downOutOf = this.ends[L];
  3260. };
  3261. });
  3262. LatexCmds['\u2211'] =
  3263. LatexCmds.sum =
  3264. LatexCmds.summation = bind(SummationNotation,'\\sum ','&sum;');
  3265. LatexCmds['\u220f'] =
  3266. LatexCmds.prod =
  3267. LatexCmds.product = bind(SummationNotation,'\\prod ','&prod;');
  3268. LatexCmds.coprod =
  3269. LatexCmds.coproduct = bind(SummationNotation,'\\coprod ','&#8720;');
  3270. var Fraction =
  3271. LatexCmds.frac =
  3272. LatexCmds.dfrac =
  3273. LatexCmds.cfrac =
  3274. LatexCmds.fraction = P(MathCommand, function(_, super_) {
  3275. _.ctrlSeq = '\\frac';
  3276. _.htmlTemplate =
  3277. '<span class="mq-fraction mq-non-leaf">'
  3278. + '<span class="mq-numerator">&0</span>'
  3279. + '<span class="mq-denominator">&1</span>'
  3280. + '<span style="display:inline-block;width:0">&#8203;</span>'
  3281. + '</span>'
  3282. ;
  3283. _.textTemplate = ['(', ')/(', ')'];
  3284. _.finalizeTree = function() {
  3285. this.upInto = this.ends[R].upOutOf = this.ends[L];
  3286. this.downInto = this.ends[L].downOutOf = this.ends[R];
  3287. };
  3288. });
  3289. var LiveFraction =
  3290. LatexCmds.over =
  3291. CharCmds['/'] = P(Fraction, function(_, super_) {
  3292. _.createLeftOf = function(cursor) {
  3293. if (!this.replacedFragment) {
  3294. var leftward = cursor[L];
  3295. while (leftward &&
  3296. !(
  3297. leftward instanceof BinaryOperator ||
  3298. leftward instanceof (LatexCmds.text || noop) ||
  3299. leftward instanceof SummationNotation ||
  3300. leftward.ctrlSeq === '\\ ' ||
  3301. /^[,;:]$/.test(leftward.ctrlSeq)
  3302. ) //lookbehind for operator
  3303. ) leftward = leftward[L];
  3304. if (leftward instanceof SummationNotation && leftward[R] instanceof SupSub) {
  3305. leftward = leftward[R];
  3306. if (leftward[R] instanceof SupSub && leftward[R].ctrlSeq != leftward.ctrlSeq)
  3307. leftward = leftward[R];
  3308. }
  3309. if (leftward !== cursor[L]) {
  3310. this.replaces(Fragment(leftward[R] || cursor.parent.ends[L], cursor[L]));
  3311. cursor[L] = leftward;
  3312. }
  3313. }
  3314. super_.createLeftOf.call(this, cursor);
  3315. };
  3316. });
  3317. var SquareRoot =
  3318. LatexCmds.sqrt =
  3319. LatexCmds['\u221a'] = P(MathCommand, function(_, super_) {
  3320. _.ctrlSeq = '\\sqrt';
  3321. _.htmlTemplate =
  3322. '<span class="mq-non-leaf">'
  3323. + '<span class="mq-scaled mq-sqrt-prefix">&radic;</span>'
  3324. + '<span class="mq-non-leaf mq-sqrt-stem">&0</span>'
  3325. + '</span>'
  3326. ;
  3327. _.textTemplate = ['sqrt(', ')'];
  3328. _.parser = function() {
  3329. return latexMathParser.optBlock.then(function(optBlock) {
  3330. return latexMathParser.block.map(function(block) {
  3331. var nthroot = NthRoot();
  3332. nthroot.blocks = [ optBlock, block ];
  3333. optBlock.adopt(nthroot, 0, 0);
  3334. block.adopt(nthroot, optBlock, 0);
  3335. return nthroot;
  3336. });
  3337. }).or(super_.parser.call(this));
  3338. };
  3339. _.reflow = function() {
  3340. var block = this.ends[R].jQ;
  3341. scale(block.prev(), 1, block.innerHeight()/+block.css('fontSize').slice(0,-2) - .1);
  3342. };
  3343. });
  3344. var Vec = LatexCmds.vec = P(MathCommand, function(_, super_) {
  3345. _.ctrlSeq = '\\vec';
  3346. _.htmlTemplate =
  3347. '<span class="mq-non-leaf">'
  3348. + '<span class="mq-vector-prefix">&rarr;</span>'
  3349. + '<span class="mq-vector-stem">&0</span>'
  3350. + '</span>'
  3351. ;
  3352. _.textTemplate = ['vec(', ')'];
  3353. });
  3354. var NthRoot =
  3355. LatexCmds.nthroot = P(SquareRoot, function(_, super_) {
  3356. _.htmlTemplate =
  3357. '<sup class="mq-nthroot mq-non-leaf">&0</sup>'
  3358. + '<span class="mq-scaled">'
  3359. + '<span class="mq-sqrt-prefix mq-scaled">&radic;</span>'
  3360. + '<span class="mq-sqrt-stem mq-non-leaf">&1</span>'
  3361. + '</span>'
  3362. ;
  3363. _.textTemplate = ['sqrt[', '](', ')'];
  3364. _.latex = function() {
  3365. return '\\sqrt['+this.ends[L].latex()+']{'+this.ends[R].latex()+'}';
  3366. };
  3367. });
  3368. function DelimsMixin(_, super_) {
  3369. _.jQadd = function() {
  3370. super_.jQadd.apply(this, arguments);
  3371. this.delimjQs = this.jQ.children(':first').add(this.jQ.children(':last'));
  3372. this.contentjQ = this.jQ.children(':eq(1)');
  3373. };
  3374. _.reflow = function() {
  3375. var height = this.contentjQ.outerHeight()
  3376. / parseFloat(this.contentjQ.css('fontSize'));
  3377. scale(this.delimjQs, min(1 + .2*(height - 1), 1.2), 1.2*height);
  3378. };
  3379. }
  3380. // Round/Square/Curly/Angle Brackets (aka Parens/Brackets/Braces)
  3381. // first typed as one-sided bracket with matching "ghost" bracket at
  3382. // far end of current block, until you type an opposing one
  3383. var Bracket = P(P(MathCommand, DelimsMixin), function(_, super_) {
  3384. _.init = function(side, open, close, ctrlSeq, end) {
  3385. super_.init.call(this, '\\left'+ctrlSeq, undefined, [open, close]);
  3386. this.side = side;
  3387. this.sides = {};
  3388. this.sides[L] = { ch: open, ctrlSeq: ctrlSeq };
  3389. this.sides[R] = { ch: close, ctrlSeq: end };
  3390. };
  3391. _.numBlocks = function() { return 1; };
  3392. _.html = function() { // wait until now so that .side may
  3393. this.htmlTemplate = // be set by createLeftOf or parser
  3394. '<span class="mq-non-leaf">'
  3395. + '<span class="mq-scaled mq-paren'+(this.side === R ? ' mq-ghost' : '')+'">'
  3396. + this.sides[L].ch
  3397. + '</span>'
  3398. + '<span class="mq-non-leaf">&0</span>'
  3399. + '<span class="mq-scaled mq-paren'+(this.side === L ? ' mq-ghost' : '')+'">'
  3400. + this.sides[R].ch
  3401. + '</span>'
  3402. + '</span>'
  3403. ;
  3404. return super_.html.call(this);
  3405. };
  3406. _.latex = function() {
  3407. return '\\left'+this.sides[L].ctrlSeq+this.ends[L].latex()+'\\right'+this.sides[R].ctrlSeq;
  3408. };
  3409. _.oppBrack = function(opts, node, expectedSide) {
  3410. // return node iff it's a 1-sided bracket of expected side (if any, may be
  3411. // undefined), and of opposite side from me if I'm not a pipe
  3412. return node instanceof Bracket && node.side && node.side !== -expectedSide
  3413. && (this.sides[this.side].ch === '|' || node.side === -this.side)
  3414. && (!opts.restrictMismatchedBrackets
  3415. || OPP_BRACKS[this.sides[this.side].ch] === node.sides[node.side].ch
  3416. || { '(': ']', '[': ')' }[this.sides[L].ch] === node.sides[R].ch) && node;
  3417. };
  3418. _.closeOpposing = function(brack) {
  3419. brack.side = 0;
  3420. brack.sides[this.side] = this.sides[this.side]; // copy over my info (may be
  3421. brack.delimjQs.eq(this.side === L ? 0 : 1) // mismatched, like [a, b))
  3422. .removeClass('mq-ghost').html(this.sides[this.side].ch);
  3423. };
  3424. _.createLeftOf = function(cursor) {
  3425. if (!this.replacedFragment) { // unless wrapping seln in brackets,
  3426. // check if next to or inside an opposing one-sided bracket
  3427. // (must check both sides 'cos I might be a pipe)
  3428. var opts = cursor.options;
  3429. var brack = this.oppBrack(opts, cursor[L], L)
  3430. || this.oppBrack(opts, cursor[R], R)
  3431. || this.oppBrack(opts, cursor.parent.parent);
  3432. }
  3433. if (brack) {
  3434. var side = this.side = -brack.side; // may be pipe with .side not yet set
  3435. this.closeOpposing(brack);
  3436. if (brack === cursor.parent.parent && cursor[side]) { // move the stuff between
  3437. Fragment(cursor[side], cursor.parent.ends[side], -side) // me and ghost outside
  3438. .disown().withDirAdopt(-side, brack.parent, brack, brack[side])
  3439. .jQ.insDirOf(side, brack.jQ);
  3440. brack.bubble('reflow');
  3441. }
  3442. }
  3443. else {
  3444. brack = this, side = brack.side;
  3445. if (brack.replacedFragment) brack.side = 0; // wrapping seln, don't be one-sided
  3446. else if (cursor[-side]) { // elsewise, auto-expand so ghost is at far end
  3447. brack.replaces(Fragment(cursor[-side], cursor.parent.ends[-side], side));
  3448. cursor[-side] = 0;
  3449. }
  3450. super_.createLeftOf.call(brack, cursor);
  3451. }
  3452. if (side === L) cursor.insAtLeftEnd(brack.ends[L]);
  3453. else cursor.insRightOf(brack);
  3454. };
  3455. _.placeCursor = noop;
  3456. _.unwrap = function() {
  3457. this.ends[L].children().disown().adopt(this.parent, this, this[R])
  3458. .jQ.insertAfter(this.jQ);
  3459. this.remove();
  3460. };
  3461. _.deleteSide = function(side, outward, cursor) {
  3462. var parent = this.parent, sib = this[side], farEnd = parent.ends[side];
  3463. if (side === this.side) { // deleting non-ghost of one-sided bracket, unwrap
  3464. this.unwrap();
  3465. sib ? cursor.insDirOf(-side, sib) : cursor.insAtDirEnd(side, parent);
  3466. return;
  3467. }
  3468. var opts = cursor.options, wasSolid = !this.side;
  3469. this.side = -side;
  3470. // if deleting like, outer close-brace of [(1+2)+3} where inner open-paren
  3471. if (this.oppBrack(opts, this.ends[L].ends[this.side], side)) { // is ghost,
  3472. this.closeOpposing(this.ends[L].ends[this.side]); // then become [1+2)+3
  3473. var origEnd = this.ends[L].ends[side];
  3474. this.unwrap();
  3475. if (origEnd.siblingCreated) origEnd.siblingCreated(cursor.options, side);
  3476. sib ? cursor.insDirOf(-side, sib) : cursor.insAtDirEnd(side, parent);
  3477. }
  3478. else { // if deleting like, inner close-brace of ([1+2}+3) where outer
  3479. if (this.oppBrack(opts, this.parent.parent, side)) { // open-paren is
  3480. this.parent.parent.closeOpposing(this); // ghost, then become [1+2+3)
  3481. this.parent.parent.unwrap();
  3482. } // else if deleting outward from a solid pair, unwrap
  3483. else if (outward && wasSolid) {
  3484. this.unwrap();
  3485. sib ? cursor.insDirOf(-side, sib) : cursor.insAtDirEnd(side, parent);
  3486. return;
  3487. }
  3488. else { // else deleting just one of a pair of brackets, become one-sided
  3489. this.sides[side] = { ch: OPP_BRACKS[this.sides[this.side].ch],
  3490. ctrlSeq: OPP_BRACKS[this.sides[this.side].ctrlSeq] };
  3491. this.delimjQs.removeClass('mq-ghost')
  3492. .eq(side === L ? 0 : 1).addClass('mq-ghost').html(this.sides[side].ch);
  3493. }
  3494. if (sib) { // auto-expand so ghost is at far end
  3495. var origEnd = this.ends[L].ends[side];
  3496. Fragment(sib, farEnd, -side).disown()
  3497. .withDirAdopt(-side, this.ends[L], origEnd, 0)
  3498. .jQ.insAtDirEnd(side, this.ends[L].jQ.removeClass('mq-empty'));
  3499. if (origEnd.siblingCreated) origEnd.siblingCreated(cursor.options, side);
  3500. cursor.insDirOf(-side, sib);
  3501. } // didn't auto-expand, cursor goes just outside or just inside parens
  3502. else (outward ? cursor.insDirOf(side, this)
  3503. : cursor.insAtDirEnd(side, this.ends[L]));
  3504. }
  3505. };
  3506. _.deleteTowards = function(dir, cursor) {
  3507. this.deleteSide(-dir, false, cursor);
  3508. };
  3509. _.finalizeTree = function() {
  3510. this.ends[L].deleteOutOf = function(dir, cursor) {
  3511. this.parent.deleteSide(dir, true, cursor);
  3512. };
  3513. // FIXME HACK: after initial creation/insertion, finalizeTree would only be
  3514. // called if the paren is selected and replaced, e.g. by LiveFraction
  3515. this.finalizeTree = this.intentionalBlur = function() {
  3516. this.delimjQs.eq(this.side === L ? 1 : 0).removeClass('mq-ghost');
  3517. this.side = 0;
  3518. };
  3519. };
  3520. _.siblingCreated = function(opts, dir) { // if something typed between ghost and far
  3521. if (dir === -this.side) this.finalizeTree(); // end of its block, solidify
  3522. };
  3523. });
  3524. var OPP_BRACKS = {
  3525. '(': ')',
  3526. ')': '(',
  3527. '[': ']',
  3528. ']': '[',
  3529. '{': '}',
  3530. '}': '{',
  3531. '\\{': '\\}',
  3532. '\\}': '\\{',
  3533. '&lang;': '&rang;',
  3534. '&rang;': '&lang;',
  3535. '\\langle ': '\\rangle ',
  3536. '\\rangle ': '\\langle ',
  3537. '|': '|'
  3538. };
  3539. function bindCharBracketPair(open, ctrlSeq) {
  3540. var ctrlSeq = ctrlSeq || open, close = OPP_BRACKS[open], end = OPP_BRACKS[ctrlSeq];
  3541. CharCmds[open] = bind(Bracket, L, open, close, ctrlSeq, end);
  3542. CharCmds[close] = bind(Bracket, R, open, close, ctrlSeq, end);
  3543. }
  3544. bindCharBracketPair('(');
  3545. bindCharBracketPair('[');
  3546. bindCharBracketPair('{', '\\{');
  3547. LatexCmds.langle = bind(Bracket, L, '&lang;', '&rang;', '\\langle ', '\\rangle ');
  3548. LatexCmds.rangle = bind(Bracket, R, '&lang;', '&rang;', '\\langle ', '\\rangle ');
  3549. CharCmds['|'] = bind(Bracket, L, '|', '|', '|', '|');
  3550. LatexCmds.left = P(MathCommand, function(_) {
  3551. _.parser = function() {
  3552. var regex = Parser.regex;
  3553. var string = Parser.string;
  3554. var succeed = Parser.succeed;
  3555. var optWhitespace = Parser.optWhitespace;
  3556. return optWhitespace.then(regex(/^(?:[([|]|\\\{)/))
  3557. .then(function(ctrlSeq) { // TODO: \langle, \rangle
  3558. var open = (ctrlSeq.charAt(0) === '\\' ? ctrlSeq.slice(1) : ctrlSeq);
  3559. return latexMathParser.then(function (block) {
  3560. return string('\\right').skip(optWhitespace)
  3561. .then(regex(/^(?:[\])|]|\\\})/)).map(function(end) {
  3562. var close = (end.charAt(0) === '\\' ? end.slice(1) : end);
  3563. var cmd = Bracket(0, open, close, ctrlSeq, end);
  3564. cmd.blocks = [ block ];
  3565. block.adopt(cmd, 0, 0);
  3566. return cmd;
  3567. })
  3568. ;
  3569. });
  3570. })
  3571. ;
  3572. };
  3573. });
  3574. LatexCmds.right = P(MathCommand, function(_) {
  3575. _.parser = function() {
  3576. return Parser.fail('unmatched \\right');
  3577. };
  3578. });
  3579. var Binomial =
  3580. LatexCmds.binom =
  3581. LatexCmds.binomial = P(P(MathCommand, DelimsMixin), function(_, super_) {
  3582. _.ctrlSeq = '\\binom';
  3583. _.htmlTemplate =
  3584. '<span class="mq-non-leaf">'
  3585. + '<span class="mq-paren mq-scaled">(</span>'
  3586. + '<span class="mq-non-leaf">'
  3587. + '<span class="mq-array mq-non-leaf">'
  3588. + '<span>&0</span>'
  3589. + '<span>&1</span>'
  3590. + '</span>'
  3591. + '</span>'
  3592. + '<span class="mq-paren mq-scaled">)</span>'
  3593. + '</span>'
  3594. ;
  3595. _.textTemplate = ['choose(',',',')'];
  3596. });
  3597. var Choose =
  3598. LatexCmds.choose = P(Binomial, function(_) {
  3599. _.createLeftOf = LiveFraction.prototype.createLeftOf;
  3600. });
  3601. LatexCmds.editable = // backcompat with before cfd3620 on #233
  3602. LatexCmds.MathQuillMathField = P(MathCommand, function(_, super_) {
  3603. _.ctrlSeq = '\\MathQuillMathField';
  3604. _.htmlTemplate =
  3605. '<span class="mq-editable-field">'
  3606. + '<span class="mq-root-block">&0</span>'
  3607. + '</span>'
  3608. ;
  3609. _.parser = function() {
  3610. var self = this,
  3611. string = Parser.string, regex = Parser.regex, succeed = Parser.succeed;
  3612. return string('[').then(regex(/^[a-z][a-z0-9]*/i)).skip(string(']'))
  3613. .map(function(name) { self.name = name; }).or(succeed())
  3614. .then(super_.parser.call(self));
  3615. };
  3616. _.finalizeTree = function() {
  3617. var ctrlr = Controller(this.ends[L], this.jQ, Options());
  3618. ctrlr.KIND_OF_MQ = 'MathField';
  3619. ctrlr.editable = true;
  3620. ctrlr.createTextarea();
  3621. ctrlr.editablesTextareaEvents();
  3622. ctrlr.cursor.insAtRightEnd(ctrlr.root);
  3623. RootBlockMixin(ctrlr.root);
  3624. };
  3625. _.registerInnerField = function(innerFields, MathField) {
  3626. innerFields.push(innerFields[this.name] = MathField(this.ends[L].controller));
  3627. };
  3628. _.latex = function(){ return this.ends[L].latex(); };
  3629. _.text = function(){ return this.ends[L].text(); };
  3630. });
  3631. // Embed arbitrary things
  3632. // Probably the closest DOM analogue would be an iframe?
  3633. // From MathQuill's perspective, it's a Symbol, it can be
  3634. // anywhere and the cursor can go around it but never in it.
  3635. // Create by calling public API method .dropEmbedded(),
  3636. // or by calling the global public API method .registerEmbed()
  3637. // and rendering LaTeX like \embed{registeredName} (see test).
  3638. var Embed = LatexCmds.embed = P(Symbol, function(_, super_) {
  3639. _.setOptions = function(options) {
  3640. function noop () { return ""; }
  3641. this.text = options.text || noop;
  3642. this.htmlTemplate = options.htmlString || "";
  3643. this.latex = options.latex || noop;
  3644. return this;
  3645. };
  3646. _.parser = function() {
  3647. var self = this;
  3648. string = Parser.string, regex = Parser.regex, succeed = Parser.succeed;
  3649. return string('{').then(regex(/^[a-z][a-z0-9]*/i)).skip(string('}'))
  3650. .then(function(name) {
  3651. // the chars allowed in the optional data block are arbitrary other than
  3652. // excluding curly braces and square brackets (which'd be too confusing)
  3653. return string('[').then(regex(/^[-\w\s]*/)).skip(string(']'))
  3654. .or(succeed()).map(function(data) {
  3655. return self.setOptions(EMBEDS[name](data));
  3656. })
  3657. ;
  3658. })
  3659. ;
  3660. };
  3661. });
  3662. var MQ1 = getInterface(1);
  3663. for (var key in MQ1) (function(key, val) {
  3664. if (typeof val === 'function') {
  3665. MathQuill[key] = function() {
  3666. insistOnInterVer();
  3667. return val.apply(this, arguments);
  3668. };
  3669. MathQuill[key].prototype = val.prototype;
  3670. }
  3671. else MathQuill[key] = val;
  3672. }(key, MQ1[key]));
  3673. }());