mathquill_rails 0.9.3.1

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