@project-sunbird/sunbird-questionset-editor-web-component-react 0.1.0

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 (170) hide show
  1. package/dist/api/asset.d.ts +31 -0
  2. package/dist/api/categoryDefinition.d.ts +39 -0
  3. package/dist/api/channel.d.ts +13 -0
  4. package/dist/api/client.d.ts +10 -0
  5. package/dist/api/client.test.d.ts +1 -0
  6. package/dist/api/comments.d.ts +10 -0
  7. package/dist/api/content.d.ts +14 -0
  8. package/dist/api/framework.d.ts +4 -0
  9. package/dist/api/hierarchy.d.ts +13 -0
  10. package/dist/api/license.d.ts +2 -0
  11. package/dist/api/question.d.ts +13 -0
  12. package/dist/api/question.test.d.ts +1 -0
  13. package/dist/api/urls.d.ts +64 -0
  14. package/dist/assets/libs/mathEquation/plugin/mathModal/css/mathmodal.css +1 -0
  15. package/dist/assets/libs/mathEquation/plugin/mathModal/favicon.ico +0 -0
  16. package/dist/assets/libs/mathEquation/plugin/mathModal/index.html +1 -0
  17. package/dist/assets/libs/mathEquation/plugin/mathModal/js/mathmodal.js +8 -0
  18. package/dist/assets/libs/mathEquation/plugin/mathModal/katex.min.css +1 -0
  19. package/dist/assets/libs/mathEquation/plugin/mathModal/katex.min.js +1 -0
  20. package/dist/assets/libs/mathEquation/plugin/mathModal/mathquill.css +425 -0
  21. package/dist/assets/libs/mathEquation/plugin/mathModal/mathquill.js +4925 -0
  22. package/dist/ckeditor/ckeditor.js +6 -0
  23. package/dist/components/AssetBrowser/AssetBrowser.d.ts +17 -0
  24. package/dist/components/BehaviourForm/SetBehaviourForm.d.ts +8 -0
  25. package/dist/components/CKEditorField/CKEditorField.d.ts +11 -0
  26. package/dist/components/ContextualEditor/ContextualEditor.d.ts +13 -0
  27. package/dist/components/LibraryDock/LibraryDock.d.ts +8 -0
  28. package/dist/components/OutlineTree/OutlineTree.d.ts +7 -0
  29. package/dist/components/QuestionDetail/QuestionDetail.d.ts +13 -0
  30. package/dist/components/QuestionEditor/BooleanEditor/BooleanEditor.d.ts +7 -0
  31. package/dist/components/QuestionEditor/FtbEditor/FtbEditor.d.ts +8 -0
  32. package/dist/components/QuestionEditor/McqEditor/McqEditor.d.ts +7 -0
  33. package/dist/components/QuestionEditor/MtfEditor/MtfEditor.d.ts +7 -0
  34. package/dist/components/QuestionEditor/QuestionEditor.d.ts +8 -0
  35. package/dist/components/QuestionEditor/ReoEditor/ReoEditor.d.ts +7 -0
  36. package/dist/components/QuestionEditor/SaEditor/SaEditor.d.ts +7 -0
  37. package/dist/components/QuestionEditor/SeqEditor/SeqEditor.d.ts +7 -0
  38. package/dist/components/QuestionsetEditor/QuestionsetEditor.d.ts +6 -0
  39. package/dist/components/QumlPlayer/QumlPlayer.d.ts +13 -0
  40. package/dist/components/RichTextEditor/RichTextEditor.d.ts +28 -0
  41. package/dist/components/SectionBehaviourForm/SectionBehaviourForm.d.ts +8 -0
  42. package/dist/components/SparkMetaForm/SparkMetaForm.d.ts +39 -0
  43. package/dist/components/SplitEditorShell/SplitEditorShell.d.ts +8 -0
  44. package/dist/components/Topbar/Topbar.d.ts +18 -0
  45. package/dist/components/modals/ConfirmDialog.d.ts +4 -0
  46. package/dist/components/modals/ProgressStatusModal.d.ts +7 -0
  47. package/dist/components/modals/PublishChecklist.d.ts +10 -0
  48. package/dist/components/modals/QualityParamsModal.d.ts +11 -0
  49. package/dist/components/modals/QuestionTypeSelectorModal.d.ts +4 -0
  50. package/dist/components/modals/TermAndConditionModal.d.ts +8 -0
  51. package/dist/components/modals/UnsavedChangesModal.d.ts +10 -0
  52. package/dist/components/shared/Badge.d.ts +20 -0
  53. package/dist/components/shared/Button.d.ts +25 -0
  54. package/dist/components/shared/ContentEditable.d.ts +14 -0
  55. package/dist/components/shared/Icon.d.ts +11 -0
  56. package/dist/components/shared/ImagePickerModal.d.ts +15 -0
  57. package/dist/components/shared/MathModal.d.ts +10 -0
  58. package/dist/components/shared/Modal.d.ts +29 -0
  59. package/dist/components/shared/SharedRichToolbar.d.ts +5 -0
  60. package/dist/components/shared/Spinner.d.ts +15 -0
  61. package/dist/components/shared/specialCharsData.d.ts +7 -0
  62. package/dist/dev-main.d.ts +1 -0
  63. package/dist/fonts/KaTeX_AMS-Regular.ttf +0 -0
  64. package/dist/fonts/KaTeX_AMS-Regular.woff +0 -0
  65. package/dist/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  66. package/dist/fonts/KaTeX_Caligraphic-Bold.ttf +0 -0
  67. package/dist/fonts/KaTeX_Caligraphic-Bold.woff +0 -0
  68. package/dist/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  69. package/dist/fonts/KaTeX_Caligraphic-Regular.ttf +0 -0
  70. package/dist/fonts/KaTeX_Caligraphic-Regular.woff +0 -0
  71. package/dist/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  72. package/dist/fonts/KaTeX_Fraktur-Bold.ttf +0 -0
  73. package/dist/fonts/KaTeX_Fraktur-Bold.woff +0 -0
  74. package/dist/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  75. package/dist/fonts/KaTeX_Fraktur-Regular.ttf +0 -0
  76. package/dist/fonts/KaTeX_Fraktur-Regular.woff +0 -0
  77. package/dist/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  78. package/dist/fonts/KaTeX_Main-Bold.ttf +0 -0
  79. package/dist/fonts/KaTeX_Main-Bold.woff +0 -0
  80. package/dist/fonts/KaTeX_Main-Bold.woff2 +0 -0
  81. package/dist/fonts/KaTeX_Main-BoldItalic.ttf +0 -0
  82. package/dist/fonts/KaTeX_Main-BoldItalic.woff +0 -0
  83. package/dist/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  84. package/dist/fonts/KaTeX_Main-Italic.ttf +0 -0
  85. package/dist/fonts/KaTeX_Main-Italic.woff +0 -0
  86. package/dist/fonts/KaTeX_Main-Italic.woff2 +0 -0
  87. package/dist/fonts/KaTeX_Main-Regular.ttf +0 -0
  88. package/dist/fonts/KaTeX_Main-Regular.woff +0 -0
  89. package/dist/fonts/KaTeX_Main-Regular.woff2 +0 -0
  90. package/dist/fonts/KaTeX_Math-BoldItalic.ttf +0 -0
  91. package/dist/fonts/KaTeX_Math-BoldItalic.woff +0 -0
  92. package/dist/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  93. package/dist/fonts/KaTeX_Math-Italic.ttf +0 -0
  94. package/dist/fonts/KaTeX_Math-Italic.woff +0 -0
  95. package/dist/fonts/KaTeX_Math-Italic.woff2 +0 -0
  96. package/dist/fonts/KaTeX_SansSerif-Bold.ttf +0 -0
  97. package/dist/fonts/KaTeX_SansSerif-Bold.woff +0 -0
  98. package/dist/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  99. package/dist/fonts/KaTeX_SansSerif-Italic.ttf +0 -0
  100. package/dist/fonts/KaTeX_SansSerif-Italic.woff +0 -0
  101. package/dist/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  102. package/dist/fonts/KaTeX_SansSerif-Regular.ttf +0 -0
  103. package/dist/fonts/KaTeX_SansSerif-Regular.woff +0 -0
  104. package/dist/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  105. package/dist/fonts/KaTeX_Script-Regular.ttf +0 -0
  106. package/dist/fonts/KaTeX_Script-Regular.woff +0 -0
  107. package/dist/fonts/KaTeX_Script-Regular.woff2 +0 -0
  108. package/dist/fonts/KaTeX_Size1-Regular.ttf +0 -0
  109. package/dist/fonts/KaTeX_Size1-Regular.woff +0 -0
  110. package/dist/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  111. package/dist/fonts/KaTeX_Size2-Regular.ttf +0 -0
  112. package/dist/fonts/KaTeX_Size2-Regular.woff +0 -0
  113. package/dist/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  114. package/dist/fonts/KaTeX_Size3-Regular.ttf +0 -0
  115. package/dist/fonts/KaTeX_Size3-Regular.woff +0 -0
  116. package/dist/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  117. package/dist/fonts/KaTeX_Size4-Regular.ttf +0 -0
  118. package/dist/fonts/KaTeX_Size4-Regular.woff +0 -0
  119. package/dist/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  120. package/dist/fonts/KaTeX_Typewriter-Regular.ttf +0 -0
  121. package/dist/fonts/KaTeX_Typewriter-Regular.woff +0 -0
  122. package/dist/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  123. package/dist/hooks/index.d.ts +9 -0
  124. package/dist/hooks/useChannelData.d.ts +3 -0
  125. package/dist/hooks/useEditorInit.d.ts +12 -0
  126. package/dist/hooks/useFramework.d.ts +9 -0
  127. package/dist/hooks/useLabels.d.ts +4 -0
  128. package/dist/hooks/useLibrary.d.ts +18 -0
  129. package/dist/hooks/useQuestionRead.d.ts +16 -0
  130. package/dist/hooks/useSaveHierarchy.d.ts +6 -0
  131. package/dist/hooks/useSaveQuestion.d.ts +3 -0
  132. package/dist/hooks/useTelemetry.d.ts +9 -0
  133. package/dist/hooks/useToolbarActions.d.ts +5 -0
  134. package/dist/index.d.ts +19 -0
  135. package/dist/index.js +16202 -0
  136. package/dist/locales/label.config.ar.json.d.ts +344 -0
  137. package/dist/locales/label.config.fr.json.d.ts +237 -0
  138. package/dist/locales/label.config.hi.json.d.ts +51 -0
  139. package/dist/locales/label.config.json.d.ts +379 -0
  140. package/dist/locales/label.config.pt.json.d.ts +237 -0
  141. package/dist/registry/defaultQuestionTypes.d.ts +1 -0
  142. package/dist/registry/index.d.ts +9 -0
  143. package/dist/registry/questionTypeRegistry.d.ts +38 -0
  144. package/dist/store/editor.store.d.ts +66 -0
  145. package/dist/store/index.d.ts +5 -0
  146. package/dist/store/library.store.d.ts +32 -0
  147. package/dist/store/question.store.d.ts +103 -0
  148. package/dist/store/tree.store.d.ts +43 -0
  149. package/dist/store/tree.store.test.d.ts +1 -0
  150. package/dist/store/ui.store.d.ts +16 -0
  151. package/dist/style.css +1 -0
  152. package/dist/types/content.d.ts +23 -0
  153. package/dist/types/editor.d.ts +130 -0
  154. package/dist/types/framework.d.ts +40 -0
  155. package/dist/types/question.d.ts +118 -0
  156. package/dist/utils/assetUrl.d.ts +11 -0
  157. package/dist/utils/context.d.ts +10 -0
  158. package/dist/utils/context.test.d.ts +1 -0
  159. package/dist/utils/html.d.ts +12 -0
  160. package/dist/utils/i18n.test.d.ts +1 -0
  161. package/dist/utils/i18nField.d.ts +38 -0
  162. package/dist/utils/i18nSerialize.d.ts +16 -0
  163. package/dist/utils/labels.d.ts +8 -0
  164. package/dist/utils/nodeKind.d.ts +9 -0
  165. package/dist/utils/notify.d.ts +4 -0
  166. package/dist/utils/questionRead.d.ts +10 -0
  167. package/dist/utils/questionRead.test.d.ts +1 -0
  168. package/dist/utils/telemetry.d.ts +15 -0
  169. package/dist/web-component/register.d.ts +1 -0
  170. package/package.json +99 -0
@@ -0,0 +1,4925 @@
1
+ /**
2
+ * MathQuill v0.10.1 http://mathquill.com
3
+ * by Han, Jeanine, and Mary maintainers@mathquill.com
4
+ *
5
+ * This Source Code Form is subject to the terms of the
6
+ * Mozilla Public License, v. 2.0. If a copy of the MPL
7
+ * was not distributed with this file, You can obtain
8
+ * one at http://mozilla.org/MPL/2.0/.
9
+ */
10
+
11
+ (function() {
12
+
13
+ var jQuery = window.jQuery,
14
+ undefined,
15
+ mqCmdId = 'mathquill-command-id',
16
+ mqBlockId = 'mathquill-block-id',
17
+ min = Math.min,
18
+ max = Math.max;
19
+
20
+ function noop() {}
21
+
22
+ /**
23
+ * A utility higher-order function that makes defining variadic
24
+ * functions more convenient by letting you essentially define functions
25
+ * with the last argument as a splat, i.e. the last argument "gathers up"
26
+ * remaining arguments to the function:
27
+ * var doStuff = variadic(function(first, rest) { return rest; });
28
+ * doStuff(1, 2, 3); // => [2, 3]
29
+ */
30
+ var __slice = [].slice;
31
+ function variadic(fn) {
32
+ var numFixedArgs = fn.length - 1;
33
+ return function() {
34
+ var args = __slice.call(arguments, 0, numFixedArgs);
35
+ var varArg = __slice.call(arguments, numFixedArgs);
36
+ return fn.apply(this, args.concat([ varArg ]));
37
+ };
38
+ }
39
+
40
+ /**
41
+ * A utility higher-order function that makes combining object-oriented
42
+ * programming and functional programming techniques more convenient:
43
+ * given a method name and any number of arguments to be bound, returns
44
+ * a function that calls it's first argument's method of that name (if
45
+ * it exists) with the bound arguments and any additional arguments that
46
+ * are passed:
47
+ * var sendMethod = send('method', 1, 2);
48
+ * var obj = { method: function() { return Array.apply(this, arguments); } };
49
+ * sendMethod(obj, 3, 4); // => [1, 2, 3, 4]
50
+ * // or more specifically,
51
+ * var obj2 = { method: function(one, two, three) { return one*two + three; } };
52
+ * sendMethod(obj2, 3); // => 5
53
+ * sendMethod(obj2, 4); // => 6
54
+ */
55
+ var send = variadic(function(method, args) {
56
+ return variadic(function(obj, moreArgs) {
57
+ if (method in obj) return obj[method].apply(obj, args.concat(moreArgs));
58
+ });
59
+ });
60
+
61
+ /**
62
+ * A utility higher-order function that creates "implicit iterators"
63
+ * from "generators": given a function that takes in a sole argument,
64
+ * a "yield_" function, that calls "yield_" repeatedly with an object as
65
+ * a sole argument (presumably objects being iterated over), returns
66
+ * a function that calls it's first argument on each of those objects
67
+ * (if the first argument is a function, it is called repeatedly with
68
+ * each object as the first argument, otherwise it is stringified and
69
+ * the method of that name is called on each object (if such a method
70
+ * exists)), passing along all additional arguments:
71
+ * var a = [
72
+ * { method: function(list) { list.push(1); } },
73
+ * { method: function(list) { list.push(2); } },
74
+ * { method: function(list) { list.push(3); } }
75
+ * ];
76
+ * a.each = iterator(function(yield_) {
77
+ * for (var i in this) yield_(this[i]);
78
+ * });
79
+ * var list = [];
80
+ * a.each('method', list);
81
+ * list; // => [1, 2, 3]
82
+ * // Note that the for-in loop will yield 'each', but 'each' maps to
83
+ * // the function object created by iterator() which does not have a
84
+ * // .method() method, so that just fails silently.
85
+ */
86
+ function iterator(generator) {
87
+ return variadic(function(fn, args) {
88
+ if (typeof fn !== 'function') fn = send(fn);
89
+ var yield_ = function(obj) { return fn.apply(obj, [ obj ].concat(args)); };
90
+ return generator.call(this, yield_);
91
+ });
92
+ }
93
+
94
+ /**
95
+ * sugar to make defining lots of commands easier.
96
+ * TODO: rethink this.
97
+ */
98
+ function bind(cons /*, args... */) {
99
+ var args = __slice.call(arguments, 1);
100
+ return function() {
101
+ return cons.apply(this, args);
102
+ };
103
+ }
104
+
105
+ /**
106
+ * a development-only debug method. This definition and all
107
+ * calls to `pray` will be stripped from the minified
108
+ * build of mathquill.
109
+ *
110
+ * This function must be called by name to be removed
111
+ * at compile time. Do not define another function
112
+ * with the same name, and only call this function by
113
+ * name.
114
+ */
115
+ function pray(message, cond) {
116
+ if (!cond) throw new Error('prayer failed: '+message);
117
+ }
118
+ var P = (function(prototype, ownProperty, undefined) {
119
+ // helper functions that also help minification
120
+ function isObject(o) { return typeof o === 'object'; }
121
+ function isFunction(f) { return typeof f === 'function'; }
122
+
123
+ // used to extend the prototypes of superclasses (which might not
124
+ // have `.Bare`s)
125
+ function SuperclassBare() {}
126
+
127
+ return function P(_superclass /* = Object */, definition) {
128
+ // handle the case where no superclass is given
129
+ if (definition === undefined) {
130
+ definition = _superclass;
131
+ _superclass = Object;
132
+ }
133
+
134
+ // C is the class to be returned.
135
+ //
136
+ // It delegates to instantiating an instance of `Bare`, so that it
137
+ // will always return a new instance regardless of the calling
138
+ // context.
139
+ //
140
+ // TODO: the Chrome inspector shows all created objects as `C`
141
+ // rather than `Object`. Setting the .name property seems to
142
+ // have no effect. Is there a way to override this behavior?
143
+ function C() {
144
+ var self = new Bare;
145
+ if (isFunction(self.init)) self.init.apply(self, arguments);
146
+ return self;
147
+ }
148
+
149
+ // C.Bare is a class with a noop constructor. Its prototype is the
150
+ // same as C, so that instances of C.Bare are also instances of C.
151
+ // New objects can be allocated without initialization by calling
152
+ // `new MyClass.Bare`.
153
+ function Bare() {}
154
+ C.Bare = Bare;
155
+
156
+ // Set up the prototype of the new class.
157
+ var _super = SuperclassBare[prototype] = _superclass[prototype];
158
+ var proto = Bare[prototype] = C[prototype] = C.p = new SuperclassBare;
159
+
160
+ // other variables, as a minifier optimization
161
+ var extensions;
162
+
163
+
164
+ // set the constructor property on the prototype, for convenience
165
+ proto.constructor = C;
166
+
167
+ C.mixin = function(def) {
168
+ Bare[prototype] = C[prototype] = P(C, def)[prototype];
169
+ return C;
170
+ }
171
+
172
+ return (C.open = function(def) {
173
+ extensions = {};
174
+
175
+ if (isFunction(def)) {
176
+ // call the defining function with all the arguments you need
177
+ // extensions captures the return value.
178
+ extensions = def.call(C, proto, _super, C, _superclass);
179
+ }
180
+ else if (isObject(def)) {
181
+ // if you passed an object instead, we'll take it
182
+ extensions = def;
183
+ }
184
+
185
+ // ...and extend it
186
+ if (isObject(extensions)) {
187
+ for (var ext in extensions) {
188
+ if (ownProperty.call(extensions, ext)) {
189
+ proto[ext] = extensions[ext];
190
+ }
191
+ }
192
+ }
193
+
194
+ // if there's no init, we assume we're inheriting a non-pjs class, so
195
+ // we default to applying the superclass's constructor.
196
+ if (!isFunction(proto.init)) {
197
+ proto.init = _superclass;
198
+ }
199
+
200
+ return C;
201
+ })(definition);
202
+ }
203
+
204
+ // as a minifier optimization, we've closured in a few helper functions
205
+ // and the string 'prototype' (C[p] is much shorter than C.prototype)
206
+ })('prototype', ({}).hasOwnProperty);
207
+ /*************************************************
208
+ * Base classes of edit tree-related objects
209
+ *
210
+ * Only doing tree node manipulation via these
211
+ * adopt/ disown methods guarantees well-formedness
212
+ * of the tree.
213
+ ************************************************/
214
+
215
+ // L = 'left'
216
+ // R = 'right'
217
+ //
218
+ // the contract is that they can be used as object properties
219
+ // and (-L) === R, and (-R) === L.
220
+ var L = -1;
221
+ var R = 1;
222
+
223
+ function prayDirection(dir) {
224
+ pray('a direction was passed', dir === L || dir === R);
225
+ }
226
+
227
+ /**
228
+ * Tiny extension of jQuery adding directionalized DOM manipulation methods.
229
+ *
230
+ * Funny how Pjs v3 almost just works with `jQuery.fn.init`.
231
+ *
232
+ * jQuery features that don't work on $:
233
+ * - jQuery.*, like jQuery.ajax, obviously (Pjs doesn't and shouldn't
234
+ * copy constructor properties)
235
+ *
236
+ * - jQuery(function), the shortcut for `jQuery(document).ready(function)`,
237
+ * because `jQuery.fn.init` is idiosyncratic and Pjs doing, essentially,
238
+ * `jQuery.fn.init.apply(this, arguments)` isn't quite right, you need:
239
+ *
240
+ * _.init = function(s, c) { jQuery.fn.init.call(this, s, c, $(document)); };
241
+ *
242
+ * if you actually give a shit (really, don't bother),
243
+ * see https://github.com/jquery/jquery/blob/1.7.2/src/core.js#L889
244
+ *
245
+ * - jQuery(selector), because jQuery translates that to
246
+ * `jQuery(document).find(selector)`, but Pjs doesn't (should it?) let
247
+ * you override the result of a constructor call
248
+ * + note that because of the jQuery(document) shortcut-ness, there's also
249
+ * the 3rd-argument-needs-to-be-`$(document)` thing above, but the fix
250
+ * for that (as can be seen above) is really easy. This problem requires
251
+ * a way more intrusive fix
252
+ *
253
+ * And that's it! Everything else just magically works because jQuery internally
254
+ * uses `this.constructor()` everywhere (hence calling `$`), but never ever does
255
+ * `this.constructor.find` or anything like that, always doing `jQuery.find`.
256
+ */
257
+ var $ = P(jQuery, function(_) {
258
+ _.insDirOf = function(dir, el) {
259
+ return dir === L ?
260
+ this.insertBefore(el.first()) : this.insertAfter(el.last());
261
+ };
262
+ _.insAtDirEnd = function(dir, el) {
263
+ return dir === L ? this.prependTo(el) : this.appendTo(el);
264
+ };
265
+ });
266
+
267
+ var Point = P(function(_) {
268
+ _.parent = 0;
269
+ _[L] = 0;
270
+ _[R] = 0;
271
+
272
+ _.init = function(parent, leftward, rightward) {
273
+ this.parent = parent;
274
+ this[L] = leftward;
275
+ this[R] = rightward;
276
+ };
277
+
278
+ this.copy = function(pt) {
279
+ return Point(pt.parent, pt[L], pt[R]);
280
+ };
281
+ });
282
+
283
+ /**
284
+ * MathQuill virtual-DOM tree-node abstract base class
285
+ */
286
+ var Node = P(function(_) {
287
+ _[L] = 0;
288
+ _[R] = 0
289
+ _.parent = 0;
290
+
291
+ var id = 0;
292
+ function uniqueNodeId() { return id += 1; }
293
+ this.byId = {};
294
+
295
+ _.init = function() {
296
+ this.id = uniqueNodeId();
297
+ Node.byId[this.id] = this;
298
+
299
+ this.ends = {};
300
+ this.ends[L] = 0;
301
+ this.ends[R] = 0;
302
+ };
303
+
304
+ _.dispose = function() { delete Node.byId[this.id]; };
305
+
306
+ _.toString = function() { return '{{ MathQuill Node #'+this.id+' }}'; };
307
+
308
+ _.jQ = $();
309
+ _.jQadd = function(jQ) { return this.jQ = this.jQ.add(jQ); };
310
+ _.jQize = function(jQ) {
311
+ // jQuery-ifies this.html() and links up the .jQ of all corresponding Nodes
312
+ var jQ = $(jQ || this.html());
313
+
314
+ function jQadd(el) {
315
+ if (el.getAttribute) {
316
+ var cmdId = el.getAttribute('mathquill-command-id');
317
+ var blockId = el.getAttribute('mathquill-block-id');
318
+ if (cmdId) Node.byId[cmdId].jQadd(el);
319
+ if (blockId) Node.byId[blockId].jQadd(el);
320
+ }
321
+ for (el = el.firstChild; el; el = el.nextSibling) {
322
+ jQadd(el);
323
+ }
324
+ }
325
+
326
+ for (var i = 0; i < jQ.length; i += 1) jQadd(jQ[i]);
327
+ return jQ;
328
+ };
329
+
330
+ _.createDir = function(dir, cursor) {
331
+ prayDirection(dir);
332
+ var node = this;
333
+ node.jQize();
334
+ node.jQ.insDirOf(dir, cursor.jQ);
335
+ cursor[dir] = node.adopt(cursor.parent, cursor[L], cursor[R]);
336
+ return node;
337
+ };
338
+ _.createLeftOf = function(el) { return this.createDir(L, el); };
339
+
340
+ _.selectChildren = function(leftEnd, rightEnd) {
341
+ return Selection(leftEnd, rightEnd);
342
+ };
343
+
344
+ _.bubble = iterator(function(yield_) {
345
+ for (var ancestor = this; ancestor; ancestor = ancestor.parent) {
346
+ var result = yield_(ancestor);
347
+ if (result === false) break;
348
+ }
349
+
350
+ return this;
351
+ });
352
+
353
+ _.postOrder = iterator(function(yield_) {
354
+ (function recurse(descendant) {
355
+ descendant.eachChild(recurse);
356
+ yield_(descendant);
357
+ })(this);
358
+
359
+ return this;
360
+ });
361
+
362
+ _.isEmpty = function() {
363
+ return this.ends[L] === 0 && this.ends[R] === 0;
364
+ };
365
+
366
+ _.children = function() {
367
+ return Fragment(this.ends[L], this.ends[R]);
368
+ };
369
+
370
+ _.eachChild = function() {
371
+ var children = this.children();
372
+ children.each.apply(children, arguments);
373
+ return this;
374
+ };
375
+
376
+ _.foldChildren = function(fold, fn) {
377
+ return this.children().fold(fold, fn);
378
+ };
379
+
380
+ _.withDirAdopt = function(dir, parent, withDir, oppDir) {
381
+ Fragment(this, this).withDirAdopt(dir, parent, withDir, oppDir);
382
+ return this;
383
+ };
384
+
385
+ _.adopt = function(parent, leftward, rightward) {
386
+ Fragment(this, this).adopt(parent, leftward, rightward);
387
+ return this;
388
+ };
389
+
390
+ _.disown = function() {
391
+ Fragment(this, this).disown();
392
+ return this;
393
+ };
394
+
395
+ _.remove = function() {
396
+ this.jQ.remove();
397
+ this.postOrder('dispose');
398
+ return this.disown();
399
+ };
400
+ });
401
+
402
+ function prayWellFormed(parent, leftward, rightward) {
403
+ pray('a parent is always present', parent);
404
+ pray('leftward is properly set up', (function() {
405
+ // either it's empty and `rightward` is the left end child (possibly empty)
406
+ if (!leftward) return parent.ends[L] === rightward;
407
+
408
+ // or it's there and its [R] and .parent are properly set up
409
+ return leftward[R] === rightward && leftward.parent === parent;
410
+ })());
411
+
412
+ pray('rightward is properly set up', (function() {
413
+ // either it's empty and `leftward` is the right end child (possibly empty)
414
+ if (!rightward) return parent.ends[R] === leftward;
415
+
416
+ // or it's there and its [L] and .parent are properly set up
417
+ return rightward[L] === leftward && rightward.parent === parent;
418
+ })());
419
+ }
420
+
421
+
422
+ /**
423
+ * An entity outside the virtual tree with one-way pointers (so it's only a
424
+ * "view" of part of the tree, not an actual node/entity in the tree) that
425
+ * delimits a doubly-linked list of sibling nodes.
426
+ * It's like a fanfic love-child between HTML DOM DocumentFragment and the Range
427
+ * classes: like DocumentFragment, its contents must be sibling nodes
428
+ * (unlike Range, whose contents are arbitrary contiguous pieces of subtrees),
429
+ * but like Range, it has only one-way pointers to its contents, its contents
430
+ * have no reference to it and in fact may still be in the visible tree (unlike
431
+ * DocumentFragment, whose contents must be detached from the visible tree
432
+ * and have their 'parent' pointers set to the DocumentFragment).
433
+ */
434
+ var Fragment = P(function(_) {
435
+ _.init = function(withDir, oppDir, dir) {
436
+ if (dir === undefined) dir = L;
437
+ prayDirection(dir);
438
+
439
+ pray('no half-empty fragments', !withDir === !oppDir);
440
+
441
+ this.ends = {};
442
+
443
+ if (!withDir) return;
444
+
445
+ pray('withDir is passed to Fragment', withDir instanceof Node);
446
+ pray('oppDir is passed to Fragment', oppDir instanceof Node);
447
+ pray('withDir and oppDir have the same parent',
448
+ withDir.parent === oppDir.parent);
449
+
450
+ this.ends[dir] = withDir;
451
+ this.ends[-dir] = oppDir;
452
+
453
+ // To build the jquery collection for a fragment, accumulate elements
454
+ // into an array and then call jQ.add once on the result. jQ.add sorts the
455
+ // collection according to document order each time it is called, so
456
+ // building a collection by folding jQ.add directly takes more than
457
+ // quadratic time in the number of elements.
458
+ //
459
+ // https://github.com/jquery/jquery/blob/2.1.4/src/traversing.js#L112
460
+ var accum = this.fold([], function (accum, el) {
461
+ accum.push.apply(accum, el.jQ.get());
462
+ return accum;
463
+ });
464
+
465
+ this.jQ = this.jQ.add(accum);
466
+ };
467
+ _.jQ = $();
468
+
469
+ // like Cursor::withDirInsertAt(dir, parent, withDir, oppDir)
470
+ _.withDirAdopt = function(dir, parent, withDir, oppDir) {
471
+ return (dir === L ? this.adopt(parent, withDir, oppDir)
472
+ : this.adopt(parent, oppDir, withDir));
473
+ };
474
+ _.adopt = function(parent, leftward, rightward) {
475
+ prayWellFormed(parent, leftward, rightward);
476
+
477
+ var self = this;
478
+ self.disowned = false;
479
+
480
+ var leftEnd = self.ends[L];
481
+ if (!leftEnd) return this;
482
+
483
+ var rightEnd = self.ends[R];
484
+
485
+ if (leftward) {
486
+ // NB: this is handled in the ::each() block
487
+ // leftward[R] = leftEnd
488
+ } else {
489
+ parent.ends[L] = leftEnd;
490
+ }
491
+
492
+ if (rightward) {
493
+ rightward[L] = rightEnd;
494
+ } else {
495
+ parent.ends[R] = rightEnd;
496
+ }
497
+
498
+ self.ends[R][R] = rightward;
499
+
500
+ self.each(function(el) {
501
+ el[L] = leftward;
502
+ el.parent = parent;
503
+ if (leftward) leftward[R] = el;
504
+
505
+ leftward = el;
506
+ });
507
+
508
+ return self;
509
+ };
510
+
511
+ _.disown = function() {
512
+ var self = this;
513
+ var leftEnd = self.ends[L];
514
+
515
+ // guard for empty and already-disowned fragments
516
+ if (!leftEnd || self.disowned) return self;
517
+
518
+ self.disowned = true;
519
+
520
+ var rightEnd = self.ends[R]
521
+ var parent = leftEnd.parent;
522
+
523
+ prayWellFormed(parent, leftEnd[L], leftEnd);
524
+ prayWellFormed(parent, rightEnd, rightEnd[R]);
525
+
526
+ if (leftEnd[L]) {
527
+ leftEnd[L][R] = rightEnd[R];
528
+ } else {
529
+ parent.ends[L] = rightEnd[R];
530
+ }
531
+
532
+ if (rightEnd[R]) {
533
+ rightEnd[R][L] = leftEnd[L];
534
+ } else {
535
+ parent.ends[R] = leftEnd[L];
536
+ }
537
+
538
+ return self;
539
+ };
540
+
541
+ _.remove = function() {
542
+ this.jQ.remove();
543
+ this.each('postOrder', 'dispose');
544
+ return this.disown();
545
+ };
546
+
547
+ _.each = iterator(function(yield_) {
548
+ var self = this;
549
+ var el = self.ends[L];
550
+ if (!el) return self;
551
+
552
+ for (; el !== self.ends[R][R]; el = el[R]) {
553
+ var result = yield_(el);
554
+ if (result === false) break;
555
+ }
556
+
557
+ return self;
558
+ });
559
+
560
+ _.fold = function(fold, fn) {
561
+ this.each(function(el) {
562
+ fold = fn.call(this, fold, el);
563
+ });
564
+
565
+ return fold;
566
+ };
567
+ });
568
+
569
+
570
+ /**
571
+ * Registry of LaTeX commands and commands created when typing
572
+ * a single character.
573
+ *
574
+ * (Commands are all subclasses of Node.)
575
+ */
576
+ var LatexCmds = {}, CharCmds = {};
577
+ /********************************************
578
+ * Cursor and Selection "singleton" classes
579
+ *******************************************/
580
+
581
+ /* The main thing that manipulates the Math DOM. Makes sure to manipulate the
582
+ HTML DOM to match. */
583
+
584
+ /* Sort of singletons, since there should only be one per editable math
585
+ textbox, but any one HTML document can contain many such textboxes, so any one
586
+ JS environment could actually contain many instances. */
587
+
588
+ //A fake cursor in the fake textbox that the math is rendered in.
589
+ var Cursor = P(Point, function(_) {
590
+ _.init = function(initParent, options) {
591
+ this.parent = initParent;
592
+ this.options = options;
593
+
594
+ var jQ = this.jQ = this._jQ = $('<span class="mq-cursor">&#8203;</span>');
595
+ //closured for setInterval
596
+ this.blink = function(){ jQ.toggleClass('mq-blink'); };
597
+
598
+ this.upDownCache = {};
599
+ };
600
+
601
+ _.show = function() {
602
+ this.jQ = this._jQ.removeClass('mq-blink');
603
+ if ('intervalId' in this) //already was shown, just restart interval
604
+ clearInterval(this.intervalId);
605
+ else { //was hidden and detached, insert this.jQ back into HTML DOM
606
+ if (this[R]) {
607
+ if (this.selection && this.selection.ends[L][L] === this[L])
608
+ this.jQ.insertBefore(this.selection.jQ);
609
+ else
610
+ this.jQ.insertBefore(this[R].jQ.first());
611
+ }
612
+ else
613
+ this.jQ.appendTo(this.parent.jQ);
614
+ this.parent.focus();
615
+ }
616
+ this.intervalId = setInterval(this.blink, 500);
617
+ return this;
618
+ };
619
+ _.hide = function() {
620
+ if ('intervalId' in this)
621
+ clearInterval(this.intervalId);
622
+ delete this.intervalId;
623
+ this.jQ.detach();
624
+ this.jQ = $();
625
+ return this;
626
+ };
627
+
628
+ _.withDirInsertAt = function(dir, parent, withDir, oppDir) {
629
+ var oldParent = this.parent;
630
+ this.parent = parent;
631
+ this[dir] = withDir;
632
+ this[-dir] = oppDir;
633
+ // by contract, .blur() is called after all has been said and done
634
+ // and the cursor has actually been moved
635
+ if (oldParent !== parent && oldParent.blur) oldParent.blur();
636
+ };
637
+ _.insDirOf = function(dir, el) {
638
+ prayDirection(dir);
639
+ this.jQ.insDirOf(dir, el.jQ);
640
+ this.withDirInsertAt(dir, el.parent, el[dir], el);
641
+ this.parent.jQ.addClass('mq-hasCursor');
642
+ return this;
643
+ };
644
+ _.insLeftOf = function(el) { return this.insDirOf(L, el); };
645
+ _.insRightOf = function(el) { return this.insDirOf(R, el); };
646
+
647
+ _.insAtDirEnd = function(dir, el) {
648
+ prayDirection(dir);
649
+ this.jQ.insAtDirEnd(dir, el.jQ);
650
+ this.withDirInsertAt(dir, el, 0, el.ends[dir]);
651
+ el.focus();
652
+ return this;
653
+ };
654
+ _.insAtLeftEnd = function(el) { return this.insAtDirEnd(L, el); };
655
+ _.insAtRightEnd = function(el) { return this.insAtDirEnd(R, el); };
656
+
657
+ /**
658
+ * jump up or down from one block Node to another:
659
+ * - cache the current Point in the node we're jumping from
660
+ * - check if there's a Point in it cached for the node we're jumping to
661
+ * + if so put the cursor there,
662
+ * + if not seek a position in the node that is horizontally closest to
663
+ * the cursor's current position
664
+ */
665
+ _.jumpUpDown = function(from, to) {
666
+ var self = this;
667
+ self.upDownCache[from.id] = Point.copy(self);
668
+ var cached = self.upDownCache[to.id];
669
+ if (cached) {
670
+ cached[R] ? self.insLeftOf(cached[R]) : self.insAtRightEnd(cached.parent);
671
+ }
672
+ else {
673
+ var pageX = self.offset().left;
674
+ to.seek(pageX, self);
675
+ }
676
+ };
677
+ _.offset = function() {
678
+ //in Opera 11.62, .getBoundingClientRect() and hence jQuery::offset()
679
+ //returns all 0's on inline elements with negative margin-right (like
680
+ //the cursor) at the end of their parent, so temporarily remove the
681
+ //negative margin-right when calling jQuery::offset()
682
+ //Opera bug DSK-360043
683
+ //http://bugs.jquery.com/ticket/11523
684
+ //https://github.com/jquery/jquery/pull/717
685
+ var self = this, offset = self.jQ.removeClass('mq-cursor').offset();
686
+ self.jQ.addClass('mq-cursor');
687
+ return offset;
688
+ }
689
+ _.unwrapGramp = function() {
690
+ var gramp = this.parent.parent;
691
+ var greatgramp = gramp.parent;
692
+ var rightward = gramp[R];
693
+ var cursor = this;
694
+
695
+ var leftward = gramp[L];
696
+ gramp.disown().eachChild(function(uncle) {
697
+ if (uncle.isEmpty()) return;
698
+
699
+ uncle.children()
700
+ .adopt(greatgramp, leftward, rightward)
701
+ .each(function(cousin) {
702
+ cousin.jQ.insertBefore(gramp.jQ.first());
703
+ })
704
+ ;
705
+
706
+ leftward = uncle.ends[R];
707
+ });
708
+
709
+ if (!this[R]) { //then find something to be rightward to insLeftOf
710
+ if (this[L])
711
+ this[R] = this[L][R];
712
+ else {
713
+ while (!this[R]) {
714
+ this.parent = this.parent[R];
715
+ if (this.parent)
716
+ this[R] = this.parent.ends[L];
717
+ else {
718
+ this[R] = gramp[R];
719
+ this.parent = greatgramp;
720
+ break;
721
+ }
722
+ }
723
+ }
724
+ }
725
+ if (this[R])
726
+ this.insLeftOf(this[R]);
727
+ else
728
+ this.insAtRightEnd(greatgramp);
729
+
730
+ gramp.jQ.remove();
731
+
732
+ if (gramp[L].siblingDeleted) gramp[L].siblingDeleted(cursor.options, R);
733
+ if (gramp[R].siblingDeleted) gramp[R].siblingDeleted(cursor.options, L);
734
+ };
735
+ _.startSelection = function() {
736
+ var anticursor = this.anticursor = Point.copy(this);
737
+ var ancestors = anticursor.ancestors = {}; // a map from each ancestor of
738
+ // the anticursor, to its child that is also an ancestor; in other words,
739
+ // the anticursor's ancestor chain in reverse order
740
+ for (var ancestor = anticursor; ancestor.parent; ancestor = ancestor.parent) {
741
+ ancestors[ancestor.parent.id] = ancestor;
742
+ }
743
+ };
744
+ _.endSelection = function() {
745
+ delete this.anticursor;
746
+ };
747
+ _.select = function() {
748
+ var anticursor = this.anticursor;
749
+ if (this[L] === anticursor[L] && this.parent === anticursor.parent) return false;
750
+
751
+ // Find the lowest common ancestor (`lca`), and the ancestor of the cursor
752
+ // whose parent is the LCA (which'll be an end of the selection fragment).
753
+ for (var ancestor = this; ancestor.parent; ancestor = ancestor.parent) {
754
+ if (ancestor.parent.id in anticursor.ancestors) {
755
+ var lca = ancestor.parent;
756
+ break;
757
+ }
758
+ }
759
+ pray('cursor and anticursor in the same tree', lca);
760
+ // The cursor and the anticursor should be in the same tree, because the
761
+ // mousemove handler attached to the document, unlike the one attached to
762
+ // the root HTML DOM element, doesn't try to get the math tree node of the
763
+ // mousemove target, and Cursor::seek() based solely on coordinates stays
764
+ // within the tree of `this` cursor's root.
765
+
766
+ // The other end of the selection fragment, the ancestor of the anticursor
767
+ // whose parent is the LCA.
768
+ var antiAncestor = anticursor.ancestors[lca.id];
769
+
770
+ // Now we have two either Nodes or Points, guaranteed to have a common
771
+ // parent and guaranteed that if both are Points, they are not the same,
772
+ // and we have to figure out which is the left end and which the right end
773
+ // of the selection.
774
+ var leftEnd, rightEnd, dir = R;
775
+
776
+ // This is an extremely subtle algorithm.
777
+ // As a special case, `ancestor` could be a Point and `antiAncestor` a Node
778
+ // immediately to `ancestor`'s left.
779
+ // In all other cases,
780
+ // - both Nodes
781
+ // - `ancestor` a Point and `antiAncestor` a Node
782
+ // - `ancestor` a Node and `antiAncestor` a Point
783
+ // `antiAncestor[R] === rightward[R]` for some `rightward` that is
784
+ // `ancestor` or to its right, if and only if `antiAncestor` is to
785
+ // the right of `ancestor`.
786
+ if (ancestor[L] !== antiAncestor) {
787
+ for (var rightward = ancestor; rightward; rightward = rightward[R]) {
788
+ if (rightward[R] === antiAncestor[R]) {
789
+ dir = L;
790
+ leftEnd = ancestor;
791
+ rightEnd = antiAncestor;
792
+ break;
793
+ }
794
+ }
795
+ }
796
+ if (dir === R) {
797
+ leftEnd = antiAncestor;
798
+ rightEnd = ancestor;
799
+ }
800
+
801
+ // only want to select Nodes up to Points, can't select Points themselves
802
+ if (leftEnd instanceof Point) leftEnd = leftEnd[R];
803
+ if (rightEnd instanceof Point) rightEnd = rightEnd[L];
804
+
805
+ this.hide().selection = lca.selectChildren(leftEnd, rightEnd);
806
+ this.insDirOf(dir, this.selection.ends[dir]);
807
+ this.selectionChanged();
808
+ return true;
809
+ };
810
+
811
+ _.clearSelection = function() {
812
+ if (this.selection) {
813
+ this.selection.clear();
814
+ delete this.selection;
815
+ this.selectionChanged();
816
+ }
817
+ return this;
818
+ };
819
+ _.deleteSelection = function() {
820
+ if (!this.selection) return;
821
+
822
+ this[L] = this.selection.ends[L][L];
823
+ this[R] = this.selection.ends[R][R];
824
+ this.selection.remove();
825
+ this.selectionChanged();
826
+ delete this.selection;
827
+ };
828
+ _.replaceSelection = function() {
829
+ var seln = this.selection;
830
+ if (seln) {
831
+ this[L] = seln.ends[L][L];
832
+ this[R] = seln.ends[R][R];
833
+ delete this.selection;
834
+ }
835
+ return seln;
836
+ };
837
+ });
838
+
839
+ var Selection = P(Fragment, function(_, super_) {
840
+ _.init = function() {
841
+ super_.init.apply(this, arguments);
842
+ this.jQ = this.jQ.wrapAll('<span class="mq-selection"></span>').parent();
843
+ //can't do wrapAll(this.jQ = $(...)) because wrapAll will clone it
844
+ };
845
+ _.adopt = function() {
846
+ this.jQ.replaceWith(this.jQ = this.jQ.children());
847
+ return super_.adopt.apply(this, arguments);
848
+ };
849
+ _.clear = function() {
850
+ // using the browser's native .childNodes property so that we
851
+ // don't discard text nodes.
852
+ this.jQ.replaceWith(this.jQ[0].childNodes);
853
+ return this;
854
+ };
855
+ _.join = function(methodName) {
856
+ return this.fold('', function(fold, child) {
857
+ return fold + child[methodName]();
858
+ });
859
+ };
860
+ });
861
+ /*********************************************
862
+ * Controller for a MathQuill instance,
863
+ * on which services are registered with
864
+ *
865
+ * Controller.open(function(_) { ... });
866
+ *
867
+ ********************************************/
868
+
869
+ var Controller = P(function(_) {
870
+ _.init = function(root, container, options) {
871
+ this.id = root.id;
872
+ this.data = {};
873
+
874
+ this.root = root;
875
+ this.container = container;
876
+ this.options = options;
877
+
878
+ root.controller = this;
879
+
880
+ this.cursor = root.cursor = Cursor(root, options);
881
+ // TODO: stop depending on root.cursor, and rm it
882
+ };
883
+
884
+ _.handle = function(name, dir) {
885
+ var handlers = this.options.handlers;
886
+ if (handlers && handlers.fns[name]) {
887
+ var mq = handlers.APIClasses[this.KIND_OF_MQ](this);
888
+ if (dir === L || dir === R) handlers.fns[name](dir, mq);
889
+ else handlers.fns[name](mq);
890
+ }
891
+ };
892
+
893
+ var notifyees = [];
894
+ this.onNotify = function(f) { notifyees.push(f); };
895
+ _.notify = function() {
896
+ for (var i = 0; i < notifyees.length; i += 1) {
897
+ notifyees[i].apply(this.cursor, arguments);
898
+ }
899
+ return this;
900
+ };
901
+ });
902
+ /*********************************************************
903
+ * The publicly exposed MathQuill API.
904
+ ********************************************************/
905
+
906
+ var API = {}, Options = P(), optionProcessors = {}, Progenote = P(), EMBEDS = {};
907
+
908
+ /**
909
+ * Interface Versioning (#459, #495) to allow us to virtually guarantee
910
+ * backcompat. v0.10.x introduces it, so for now, don't completely break the
911
+ * API for people who don't know about it, just complain with console.warn().
912
+ *
913
+ * The methods are shimmed in outro.js so that MQ.MathField.prototype etc can
914
+ * be accessed.
915
+ */
916
+ function insistOnInterVer() {
917
+ if (window.console) console.warn(
918
+ 'You are using the MathQuill API without specifying an interface version, ' +
919
+ 'which will fail in v1.0.0. You can fix this easily by doing this before ' +
920
+ 'doing anything else:\n' +
921
+ '\n' +
922
+ ' MathQuill = MathQuill.getInterface(1);\n' +
923
+ ' // now MathQuill.MathField() works like it used to\n' +
924
+ '\n' +
925
+ 'See also the "`dev` branch (2014\u20132015) \u2192 v0.10.0 Migration Guide" at\n' +
926
+ ' https://github.com/mathquill/mathquill/wiki/%60dev%60-branch-(2014%E2%80%932015)-%E2%86%92-v0.10.0-Migration-Guide'
927
+ );
928
+ }
929
+ // globally exported API object
930
+ function MathQuill(el) {
931
+ insistOnInterVer();
932
+ return MQ1(el);
933
+ };
934
+ MathQuill.prototype = Progenote.p;
935
+ MathQuill.interfaceVersion = function(v) {
936
+ // shim for #459-era interface versioning (ended with #495)
937
+ if (v !== 1) throw 'Only interface version 1 supported. You specified: ' + v;
938
+ insistOnInterVer = function() {
939
+ if (window.console) console.warn(
940
+ 'You called MathQuill.interfaceVersion(1); to specify the interface ' +
941
+ 'version, which will fail in v1.0.0. You can fix this easily by doing ' +
942
+ 'this before doing anything else:\n' +
943
+ '\n' +
944
+ ' MathQuill = MathQuill.getInterface(1);\n' +
945
+ ' // now MathQuill.MathField() works like it used to\n' +
946
+ '\n' +
947
+ 'See also the "`dev` branch (2014\u20132015) \u2192 v0.10.0 Migration Guide" at\n' +
948
+ ' https://github.com/mathquill/mathquill/wiki/%60dev%60-branch-(2014%E2%80%932015)-%E2%86%92-v0.10.0-Migration-Guide'
949
+ );
950
+ };
951
+ insistOnInterVer();
952
+ return MathQuill;
953
+ };
954
+ MathQuill.getInterface = getInterface;
955
+
956
+ var MIN = getInterface.MIN = 1, MAX = getInterface.MAX = 2;
957
+ function getInterface(v) {
958
+ if (!(MIN <= v && v <= MAX)) throw 'Only interface versions between ' +
959
+ MIN + ' and ' + MAX + ' supported. You specified: ' + v;
960
+
961
+ /**
962
+ * Function that takes an HTML element and, if it's the root HTML element of a
963
+ * static math or math or text field, returns an API object for it (else, null).
964
+ *
965
+ * var mathfield = MQ.MathField(mathFieldSpan);
966
+ * assert(MQ(mathFieldSpan).id === mathfield.id);
967
+ * assert(MQ(mathFieldSpan).id === MQ(mathFieldSpan).id);
968
+ *
969
+ */
970
+ function MQ(el) {
971
+ if (!el || !el.nodeType) return null; // check that `el` is a HTML element, using the
972
+ // same technique as jQuery: https://github.com/jquery/jquery/blob/679536ee4b7a92ae64a5f58d90e9cc38c001e807/src/core/init.js#L92
973
+ var blockId = $(el).children('.mq-root-block').attr(mqBlockId);
974
+ var ctrlr = blockId && Node.byId[blockId].controller;
975
+ return ctrlr ? APIClasses[ctrlr.KIND_OF_MQ](ctrlr) : null;
976
+ };
977
+ var APIClasses = {};
978
+
979
+ MQ.L = L;
980
+ MQ.R = R;
981
+
982
+ function config(currentOptions, newOptions) {
983
+ if (newOptions && newOptions.handlers) {
984
+ newOptions.handlers = { fns: newOptions.handlers, APIClasses: APIClasses };
985
+ }
986
+ for (var name in newOptions) if (newOptions.hasOwnProperty(name)) {
987
+ var value = newOptions[name], processor = optionProcessors[name];
988
+ currentOptions[name] = (processor ? processor(value) : value);
989
+ }
990
+ }
991
+ MQ.config = function(opts) { config(Options.p, opts); return this; };
992
+ MQ.registerEmbed = function(name, options) {
993
+ if (!/^[a-z][a-z0-9]*$/i.test(name)) {
994
+ throw 'Embed name must start with letter and be only letters and digits';
995
+ }
996
+ EMBEDS[name] = options;
997
+ };
998
+
999
+ var AbstractMathQuill = APIClasses.AbstractMathQuill = P(Progenote, function(_) {
1000
+ _.init = function(ctrlr) {
1001
+ this.__controller = ctrlr;
1002
+ this.__options = ctrlr.options;
1003
+ this.id = ctrlr.id;
1004
+ this.data = ctrlr.data;
1005
+ };
1006
+ _.__mathquillify = function(classNames) {
1007
+ var ctrlr = this.__controller, root = ctrlr.root, el = ctrlr.container;
1008
+ ctrlr.createTextarea();
1009
+
1010
+ var contents = el.addClass(classNames).contents().detach();
1011
+ root.jQ =
1012
+ $('<span class="mq-root-block"/>').attr(mqBlockId, root.id).appendTo(el);
1013
+ this.latex(contents.text());
1014
+
1015
+ this.revert = function() {
1016
+ return el.empty().unbind('.mathquill')
1017
+ .removeClass('mq-editable-field mq-math-mode mq-text-mode')
1018
+ .append(contents);
1019
+ };
1020
+ };
1021
+ _.config = function(opts) { config(this.__options, opts); return this; };
1022
+ _.el = function() { return this.__controller.container[0]; };
1023
+ _.text = function() { return this.__controller.exportText(); };
1024
+ _.latex = function(latex) {
1025
+ if (arguments.length > 0) {
1026
+ this.__controller.renderLatexMath(latex);
1027
+ if (this.__controller.blurred) this.__controller.cursor.hide().parent.blur();
1028
+ return this;
1029
+ }
1030
+ return this.__controller.exportLatex();
1031
+ };
1032
+ _.html = function() {
1033
+ return this.__controller.root.jQ.html()
1034
+ .replace(/ mathquill-(?:command|block)-id="?\d+"?/g, '')
1035
+ .replace(/<span class="?mq-cursor( mq-blink)?"?>.?<\/span>/i, '')
1036
+ .replace(/ mq-hasCursor|mq-hasCursor ?/, '')
1037
+ .replace(/ class=(""|(?= |>))/g, '');
1038
+ };
1039
+ _.reflow = function() {
1040
+ this.__controller.root.postOrder('reflow');
1041
+ return this;
1042
+ };
1043
+ });
1044
+ MQ.prototype = AbstractMathQuill.prototype;
1045
+
1046
+ APIClasses.EditableField = P(AbstractMathQuill, function(_, super_) {
1047
+ _.__mathquillify = function() {
1048
+ super_.__mathquillify.apply(this, arguments);
1049
+ this.__controller.editable = true;
1050
+ this.__controller.delegateMouseEvents();
1051
+ this.__controller.editablesTextareaEvents();
1052
+ return this;
1053
+ };
1054
+ _.focus = function() { this.__controller.textarea.focus(); return this; };
1055
+ _.blur = function() { this.__controller.textarea.blur(); return this; };
1056
+ _.write = function(latex) {
1057
+ this.__controller.writeLatex(latex);
1058
+ this.__controller.scrollHoriz();
1059
+ if (this.__controller.blurred) this.__controller.cursor.hide().parent.blur();
1060
+ return this;
1061
+ };
1062
+ _.cmd = function(cmd) {
1063
+ var ctrlr = this.__controller.notify(), cursor = ctrlr.cursor;
1064
+ if (/^\\[a-z]+$/i.test(cmd)) {
1065
+ cmd = cmd.slice(1);
1066
+ var klass = LatexCmds[cmd];
1067
+ if (klass) {
1068
+ cmd = klass(cmd);
1069
+ if (cursor.selection) cmd.replaces(cursor.replaceSelection());
1070
+ cmd.createLeftOf(cursor.show());
1071
+ this.__controller.scrollHoriz();
1072
+ }
1073
+ else /* TODO: API needs better error reporting */;
1074
+ }
1075
+ else cursor.parent.write(cursor, cmd);
1076
+ if (ctrlr.blurred) cursor.hide().parent.blur();
1077
+ return this;
1078
+ };
1079
+ _.select = function() {
1080
+ var ctrlr = this.__controller;
1081
+ ctrlr.notify('move').cursor.insAtRightEnd(ctrlr.root);
1082
+ while (ctrlr.cursor[L]) ctrlr.selectLeft();
1083
+ return this;
1084
+ };
1085
+ _.clearSelection = function() {
1086
+ this.__controller.cursor.clearSelection();
1087
+ return this;
1088
+ };
1089
+
1090
+ _.moveToDirEnd = function(dir) {
1091
+ this.__controller.notify('move').cursor.insAtDirEnd(dir, this.__controller.root);
1092
+ return this;
1093
+ };
1094
+ _.moveToLeftEnd = function() { return this.moveToDirEnd(L); };
1095
+ _.moveToRightEnd = function() { return this.moveToDirEnd(R); };
1096
+
1097
+ _.keystroke = function(keys) {
1098
+ var keys = keys.replace(/^\s+|\s+$/g, '').split(/\s+/);
1099
+ for (var i = 0; i < keys.length; i += 1) {
1100
+ this.__controller.keystroke(keys[i], { preventDefault: noop });
1101
+ }
1102
+ return this;
1103
+ };
1104
+ _.typedText = function(text) {
1105
+ for (var i = 0; i < text.length; i += 1) this.__controller.typedText(text.charAt(i));
1106
+ return this;
1107
+ };
1108
+ _.dropEmbedded = function(pageX, pageY, options) {
1109
+ var clientX = pageX - $(window).scrollLeft();
1110
+ var clientY = pageY - $(window).scrollTop();
1111
+
1112
+ var el = document.elementFromPoint(clientX, clientY);
1113
+ this.__controller.seek($(el), pageX, pageY);
1114
+ var cmd = Embed().setOptions(options);
1115
+ cmd.createLeftOf(this.__controller.cursor);
1116
+ };
1117
+ });
1118
+ MQ.EditableField = function() { throw "wtf don't call me, I'm 'abstract'"; };
1119
+ MQ.EditableField.prototype = APIClasses.EditableField.prototype;
1120
+
1121
+ /**
1122
+ * Export the API functions that MathQuill-ify an HTML element into API objects
1123
+ * of each class. If the element had already been MathQuill-ified but into a
1124
+ * different kind (or it's not an HTML element), return null.
1125
+ */
1126
+ for (var kind in API) (function(kind, defAPIClass) {
1127
+ var APIClass = APIClasses[kind] = defAPIClass(APIClasses);
1128
+ MQ[kind] = function(el, opts) {
1129
+ var mq = MQ(el);
1130
+ if (mq instanceof APIClass || !el || !el.nodeType) return mq;
1131
+ var ctrlr = Controller(APIClass.RootBlock(), $(el), Options());
1132
+ ctrlr.KIND_OF_MQ = kind;
1133
+ return APIClass(ctrlr).__mathquillify(opts, v);
1134
+ };
1135
+ MQ[kind].prototype = APIClass.prototype;
1136
+ }(kind, API[kind]));
1137
+
1138
+ return MQ;
1139
+ }
1140
+
1141
+ MathQuill.noConflict = function() {
1142
+ window.MathQuill = origMathQuill;
1143
+ return MathQuill;
1144
+ };
1145
+ var origMathQuill = window.MathQuill;
1146
+ window.MathQuill = MathQuill;
1147
+
1148
+ function RootBlockMixin(_) {
1149
+ var names = 'moveOutOf deleteOutOf selectOutOf upOutOf downOutOf'.split(' ');
1150
+ for (var i = 0; i < names.length; i += 1) (function(name) {
1151
+ _[name] = function(dir) { this.controller.handle(name, dir); };
1152
+ }(names[i]));
1153
+ _.reflow = function() {
1154
+ this.controller.handle('reflow');
1155
+ this.controller.handle('edited');
1156
+ this.controller.handle('edit');
1157
+ };
1158
+ }
1159
+ var Parser = P(function(_, super_, Parser) {
1160
+ // The Parser object is a wrapper for a parser function.
1161
+ // Externally, you use one to parse a string by calling
1162
+ // var result = SomeParser.parse('Me Me Me! Parse Me!');
1163
+ // You should never call the constructor, rather you should
1164
+ // construct your Parser from the base parsers and the
1165
+ // parser combinator methods.
1166
+
1167
+ function parseError(stream, message) {
1168
+ if (stream) {
1169
+ stream = "'"+stream+"'";
1170
+ }
1171
+ else {
1172
+ stream = 'EOF';
1173
+ }
1174
+
1175
+ throw 'Parse Error: '+message+' at '+stream;
1176
+ }
1177
+
1178
+ _.init = function(body) { this._ = body; };
1179
+
1180
+ _.parse = function(stream) {
1181
+ return this.skip(eof)._(''+stream, success, parseError);
1182
+
1183
+ function success(stream, result) { return result; }
1184
+ };
1185
+
1186
+ // -*- primitive combinators -*- //
1187
+ _.or = function(alternative) {
1188
+ pray('or is passed a parser', alternative instanceof Parser);
1189
+
1190
+ var self = this;
1191
+
1192
+ return Parser(function(stream, onSuccess, onFailure) {
1193
+ return self._(stream, onSuccess, failure);
1194
+
1195
+ function failure(newStream) {
1196
+ return alternative._(stream, onSuccess, onFailure);
1197
+ }
1198
+ });
1199
+ };
1200
+
1201
+ _.then = function(next) {
1202
+ var self = this;
1203
+
1204
+ return Parser(function(stream, onSuccess, onFailure) {
1205
+ return self._(stream, success, onFailure);
1206
+
1207
+ function success(newStream, result) {
1208
+ var nextParser = (next instanceof Parser ? next : next(result));
1209
+ pray('a parser is returned', nextParser instanceof Parser);
1210
+ return nextParser._(newStream, onSuccess, onFailure);
1211
+ }
1212
+ });
1213
+ };
1214
+
1215
+ // -*- optimized iterative combinators -*- //
1216
+ _.many = function() {
1217
+ var self = this;
1218
+
1219
+ return Parser(function(stream, onSuccess, onFailure) {
1220
+ var xs = [];
1221
+ while (self._(stream, success, failure));
1222
+ return onSuccess(stream, xs);
1223
+
1224
+ function success(newStream, x) {
1225
+ stream = newStream;
1226
+ xs.push(x);
1227
+ return true;
1228
+ }
1229
+
1230
+ function failure() {
1231
+ return false;
1232
+ }
1233
+ });
1234
+ };
1235
+
1236
+ _.times = function(min, max) {
1237
+ if (arguments.length < 2) max = min;
1238
+ var self = this;
1239
+
1240
+ return Parser(function(stream, onSuccess, onFailure) {
1241
+ var xs = [];
1242
+ var result = true;
1243
+ var failure;
1244
+
1245
+ for (var i = 0; i < min; i += 1) {
1246
+ result = self._(stream, success, firstFailure);
1247
+ if (!result) return onFailure(stream, failure);
1248
+ }
1249
+
1250
+ for (; i < max && result; i += 1) {
1251
+ result = self._(stream, success, secondFailure);
1252
+ }
1253
+
1254
+ return onSuccess(stream, xs);
1255
+
1256
+ function success(newStream, x) {
1257
+ xs.push(x);
1258
+ stream = newStream;
1259
+ return true;
1260
+ }
1261
+
1262
+ function firstFailure(newStream, msg) {
1263
+ failure = msg;
1264
+ stream = newStream;
1265
+ return false;
1266
+ }
1267
+
1268
+ function secondFailure(newStream, msg) {
1269
+ return false;
1270
+ }
1271
+ });
1272
+ };
1273
+
1274
+ // -*- higher-level combinators -*- //
1275
+ _.result = function(res) { return this.then(succeed(res)); };
1276
+ _.atMost = function(n) { return this.times(0, n); };
1277
+ _.atLeast = function(n) {
1278
+ var self = this;
1279
+ return self.times(n).then(function(start) {
1280
+ return self.many().map(function(end) {
1281
+ return start.concat(end);
1282
+ });
1283
+ });
1284
+ };
1285
+
1286
+ _.map = function(fn) {
1287
+ return this.then(function(result) { return succeed(fn(result)); });
1288
+ };
1289
+
1290
+ _.skip = function(two) {
1291
+ return this.then(function(result) { return two.result(result); });
1292
+ };
1293
+
1294
+ // -*- primitive parsers -*- //
1295
+ var string = this.string = function(str) {
1296
+ var len = str.length;
1297
+ var expected = "expected '"+str+"'";
1298
+
1299
+ return Parser(function(stream, onSuccess, onFailure) {
1300
+ var head = stream.slice(0, len);
1301
+
1302
+ if (head === str) {
1303
+ return onSuccess(stream.slice(len), head);
1304
+ }
1305
+ else {
1306
+ return onFailure(stream, expected);
1307
+ }
1308
+ });
1309
+ };
1310
+
1311
+ var regex = this.regex = function(re) {
1312
+ pray('regexp parser is anchored', re.toString().charAt(1) === '^');
1313
+
1314
+ var expected = 'expected '+re;
1315
+
1316
+ return Parser(function(stream, onSuccess, onFailure) {
1317
+ var match = re.exec(stream);
1318
+
1319
+ if (match) {
1320
+ var result = match[0];
1321
+ return onSuccess(stream.slice(result.length), result);
1322
+ }
1323
+ else {
1324
+ return onFailure(stream, expected);
1325
+ }
1326
+ });
1327
+ };
1328
+
1329
+ var succeed = Parser.succeed = function(result) {
1330
+ return Parser(function(stream, onSuccess) {
1331
+ return onSuccess(stream, result);
1332
+ });
1333
+ };
1334
+
1335
+ var fail = Parser.fail = function(msg) {
1336
+ return Parser(function(stream, _, onFailure) {
1337
+ return onFailure(stream, msg);
1338
+ });
1339
+ };
1340
+
1341
+ var letter = Parser.letter = regex(/^[a-z]/i);
1342
+ var letters = Parser.letters = regex(/^[a-z]*/i);
1343
+ var digit = Parser.digit = regex(/^[0-9]/);
1344
+ var digits = Parser.digits = regex(/^[0-9]*/);
1345
+ var whitespace = Parser.whitespace = regex(/^\s+/);
1346
+ var optWhitespace = Parser.optWhitespace = regex(/^\s*/);
1347
+
1348
+ var any = Parser.any = Parser(function(stream, onSuccess, onFailure) {
1349
+ if (!stream) return onFailure(stream, 'expected any character');
1350
+
1351
+ return onSuccess(stream.slice(1), stream.charAt(0));
1352
+ });
1353
+
1354
+ var all = Parser.all = Parser(function(stream, onSuccess, onFailure) {
1355
+ return onSuccess('', stream);
1356
+ });
1357
+
1358
+ var eof = Parser.eof = Parser(function(stream, onSuccess, onFailure) {
1359
+ if (stream) return onFailure(stream, 'expected EOF');
1360
+
1361
+ return onSuccess(stream, stream);
1362
+ });
1363
+ });
1364
+ /*************************************************
1365
+ * Sane Keyboard Events Shim
1366
+ *
1367
+ * An abstraction layer wrapping the textarea in
1368
+ * an object with methods to manipulate and listen
1369
+ * to events on, that hides all the nasty cross-
1370
+ * browser incompatibilities behind a uniform API.
1371
+ *
1372
+ * Design goal: This is a *HARD* internal
1373
+ * abstraction barrier. Cross-browser
1374
+ * inconsistencies are not allowed to leak through
1375
+ * and be dealt with by event handlers. All future
1376
+ * cross-browser issues that arise must be dealt
1377
+ * with here, and if necessary, the API updated.
1378
+ *
1379
+ * Organization:
1380
+ * - key values map and stringify()
1381
+ * - saneKeyboardEvents()
1382
+ * + defer() and flush()
1383
+ * + event handler logic
1384
+ * + attach event handlers and export methods
1385
+ ************************************************/
1386
+
1387
+ var saneKeyboardEvents = (function() {
1388
+ // The following [key values][1] map was compiled from the
1389
+ // [DOM3 Events appendix section on key codes][2] and
1390
+ // [a widely cited report on cross-browser tests of key codes][3],
1391
+ // except for 10: 'Enter', which I've empirically observed in Safari on iOS
1392
+ // and doesn't appear to conflict with any other known key codes.
1393
+ //
1394
+ // [1]: http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#keys-keyvalues
1395
+ // [2]: http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#fixed-virtual-key-codes
1396
+ // [3]: http://unixpapa.com/js/key.html
1397
+ var KEY_VALUES = {
1398
+ 8: 'Backspace',
1399
+ 9: 'Tab',
1400
+
1401
+ 10: 'Enter', // for Safari on iOS
1402
+
1403
+ 13: 'Enter',
1404
+
1405
+ 16: 'Shift',
1406
+ 17: 'Control',
1407
+ 18: 'Alt',
1408
+ 20: 'CapsLock',
1409
+
1410
+ 27: 'Esc',
1411
+
1412
+ 32: 'Spacebar',
1413
+
1414
+ 33: 'PageUp',
1415
+ 34: 'PageDown',
1416
+ 35: 'End',
1417
+ 36: 'Home',
1418
+
1419
+ 37: 'Left',
1420
+ 38: 'Up',
1421
+ 39: 'Right',
1422
+ 40: 'Down',
1423
+
1424
+ 45: 'Insert',
1425
+
1426
+ 46: 'Del',
1427
+
1428
+ 144: 'NumLock'
1429
+ };
1430
+
1431
+ // To the extent possible, create a normalized string representation
1432
+ // of the key combo (i.e., key code and modifier keys).
1433
+ function stringify(evt) {
1434
+ var which = evt.which || evt.keyCode;
1435
+ var keyVal = KEY_VALUES[which];
1436
+ var key;
1437
+ var modifiers = [];
1438
+
1439
+ if (evt.ctrlKey) modifiers.push('Ctrl');
1440
+ if (evt.originalEvent && evt.originalEvent.metaKey) modifiers.push('Meta');
1441
+ if (evt.altKey) modifiers.push('Alt');
1442
+ if (evt.shiftKey) modifiers.push('Shift');
1443
+
1444
+ key = keyVal || String.fromCharCode(which);
1445
+
1446
+ if (!modifiers.length && !keyVal) return key;
1447
+
1448
+ modifiers.push(key);
1449
+ return modifiers.join('-');
1450
+ }
1451
+
1452
+ // create a keyboard events shim that calls callbacks at useful times
1453
+ // and exports useful public methods
1454
+ return function saneKeyboardEvents(el, handlers) {
1455
+ var keydown = null;
1456
+ var keypress = null;
1457
+
1458
+ var textarea = jQuery(el);
1459
+ var target = jQuery(handlers.container || textarea);
1460
+
1461
+ // checkTextareaFor() is called after keypress or paste events to
1462
+ // say "Hey, I think something was just typed" or "pasted" (resp.),
1463
+ // so that at all subsequent opportune times (next event or timeout),
1464
+ // will check for expected typed or pasted text.
1465
+ // Need to check repeatedly because #135: in Safari 5.1 (at least),
1466
+ // after selecting something and then typing, the textarea is
1467
+ // incorrectly reported as selected during the input event (but not
1468
+ // subsequently).
1469
+ var checkTextarea = noop, timeoutId;
1470
+ function checkTextareaFor(checker) {
1471
+ checkTextarea = checker;
1472
+ clearTimeout(timeoutId);
1473
+ timeoutId = setTimeout(checker);
1474
+ }
1475
+ target.bind('keydown keypress input keyup focusout paste', function(e) { checkTextarea(e); });
1476
+
1477
+
1478
+ // -*- public methods -*- //
1479
+ function select(text) {
1480
+ // check textarea at least once/one last time before munging (so
1481
+ // no race condition if selection happens after keypress/paste but
1482
+ // before checkTextarea), then never again ('cos it's been munged)
1483
+ checkTextarea();
1484
+ checkTextarea = noop;
1485
+ clearTimeout(timeoutId);
1486
+
1487
+ textarea.val(text);
1488
+ if (text && textarea[0].select) textarea[0].select();
1489
+ shouldBeSelected = !!text;
1490
+ }
1491
+ var shouldBeSelected = false;
1492
+
1493
+ // -*- helper subroutines -*- //
1494
+
1495
+ // Determine whether there's a selection in the textarea.
1496
+ // This will always return false in IE < 9, which don't support
1497
+ // HTMLTextareaElement::selection{Start,End}.
1498
+ function hasSelection() {
1499
+ var dom = textarea[0];
1500
+
1501
+ if (!('selectionStart' in dom)) return false;
1502
+ return dom.selectionStart !== dom.selectionEnd;
1503
+ }
1504
+
1505
+ function handleKey() {
1506
+ handlers.keystroke(stringify(keydown), keydown);
1507
+ }
1508
+
1509
+ // -*- event handlers -*- //
1510
+ function onKeydown(e) {
1511
+ keydown = e;
1512
+ keypress = null;
1513
+
1514
+ if (shouldBeSelected) checkTextareaFor(function(e) {
1515
+ if (!(e && e.type === 'focusout') && textarea[0].select) {
1516
+ textarea[0].select(); // re-select textarea in case it's an unrecognized
1517
+ }
1518
+ checkTextarea = noop; // key that clears the selection, then never
1519
+ clearTimeout(timeoutId); // again, 'cos next thing might be blur
1520
+ });
1521
+
1522
+ handleKey();
1523
+ }
1524
+
1525
+ function onKeypress(e) {
1526
+ // call the key handler for repeated keypresses.
1527
+ // This excludes keypresses that happen directly
1528
+ // after keydown. In that case, there will be
1529
+ // no previous keypress, so we skip it here
1530
+ if (keydown && keypress) handleKey();
1531
+
1532
+ keypress = e;
1533
+
1534
+ checkTextareaFor(typedText);
1535
+ }
1536
+ function typedText() {
1537
+ // If there is a selection, the contents of the textarea couldn't
1538
+ // possibly have just been typed in.
1539
+ // This happens in browsers like Firefox and Opera that fire
1540
+ // keypress for keystrokes that are not text entry and leave the
1541
+ // selection in the textarea alone, such as Ctrl-C.
1542
+ // Note: we assume that browsers that don't support hasSelection()
1543
+ // also never fire keypress on keystrokes that are not text entry.
1544
+ // This seems reasonably safe because:
1545
+ // - all modern browsers including IE 9+ support hasSelection(),
1546
+ // making it extremely unlikely any browser besides IE < 9 won't
1547
+ // - as far as we know IE < 9 never fires keypress on keystrokes
1548
+ // that aren't text entry, which is only as reliable as our
1549
+ // tests are comprehensive, but the IE < 9 way to do
1550
+ // hasSelection() is poorly documented and is also only as
1551
+ // reliable as our tests are comprehensive
1552
+ // If anything like #40 or #71 is reported in IE < 9, see
1553
+ // b1318e5349160b665003e36d4eedd64101ceacd8
1554
+ if (hasSelection()) return;
1555
+
1556
+ var text = textarea.val();
1557
+ if (text.length === 1) {
1558
+ textarea.val('');
1559
+ handlers.typedText(text);
1560
+ } // in Firefox, keys that don't type text, just clear seln, fire keypress
1561
+ // https://github.com/mathquill/mathquill/issues/293#issuecomment-40997668
1562
+ else if (text && textarea[0].select) textarea[0].select(); // re-select if that's why we're here
1563
+ }
1564
+
1565
+ function onBlur() { keydown = keypress = null; }
1566
+
1567
+ function onPaste(e) {
1568
+ // browsers are dumb.
1569
+ //
1570
+ // In Linux, middle-click pasting causes onPaste to be called,
1571
+ // when the textarea is not necessarily focused. We focus it
1572
+ // here to ensure that the pasted text actually ends up in the
1573
+ // textarea.
1574
+ //
1575
+ // It's pretty nifty that by changing focus in this handler,
1576
+ // we can change the target of the default action. (This works
1577
+ // on keydown too, FWIW).
1578
+ //
1579
+ // And by nifty, we mean dumb (but useful sometimes).
1580
+ textarea.focus();
1581
+
1582
+ checkTextareaFor(pastedText);
1583
+ }
1584
+ function pastedText() {
1585
+ var text = textarea.val();
1586
+ textarea.val('');
1587
+ if (text) handlers.paste(text);
1588
+ }
1589
+
1590
+ // -*- attach event handlers -*- //
1591
+ target.bind({
1592
+ keydown: onKeydown,
1593
+ keypress: onKeypress,
1594
+ focusout: onBlur,
1595
+ paste: onPaste
1596
+ });
1597
+
1598
+ // -*- export public methods -*- //
1599
+ return {
1600
+ select: select
1601
+ };
1602
+ };
1603
+ }());
1604
+ /***********************************************
1605
+ * Export math in a human-readable text format
1606
+ * As you can see, only half-baked so far.
1607
+ **********************************************/
1608
+
1609
+ Controller.open(function(_, super_) {
1610
+ _.exportText = function() {
1611
+ return this.root.foldChildren('', function(text, child) {
1612
+ return text + child.text();
1613
+ });
1614
+ };
1615
+ });
1616
+ Controller.open(function(_) {
1617
+ _.focusBlurEvents = function() {
1618
+ var ctrlr = this, root = ctrlr.root, cursor = ctrlr.cursor;
1619
+ var blurTimeout;
1620
+ ctrlr.textarea.focus(function() {
1621
+ ctrlr.blurred = false;
1622
+ clearTimeout(blurTimeout);
1623
+ ctrlr.container.addClass('mq-focused');
1624
+ if (!cursor.parent)
1625
+ cursor.insAtRightEnd(root);
1626
+ if (cursor.selection) {
1627
+ cursor.selection.jQ.removeClass('mq-blur');
1628
+ ctrlr.selectionChanged(); //re-select textarea contents after tabbing away and back
1629
+ }
1630
+ else
1631
+ cursor.show();
1632
+ }).blur(function() {
1633
+ ctrlr.blurred = true;
1634
+ blurTimeout = setTimeout(function() { // wait for blur on window; if
1635
+ root.postOrder('intentionalBlur'); // none, intentional blur: #264
1636
+ cursor.clearSelection().endSelection();
1637
+ blur();
1638
+ });
1639
+ $(window).on('blur', windowBlur);
1640
+ });
1641
+ function windowBlur() { // blur event also fired on window, just switching
1642
+ clearTimeout(blurTimeout); // tabs/windows, not intentional blur
1643
+ if (cursor.selection) cursor.selection.jQ.addClass('mq-blur');
1644
+ blur();
1645
+ }
1646
+ function blur() { // not directly in the textarea blur handler so as to be
1647
+ cursor.hide().parent.blur(); // synchronous with/in the same frame as
1648
+ ctrlr.container.removeClass('mq-focused'); // clearing/blurring selection
1649
+ $(window).off('blur', windowBlur);
1650
+ }
1651
+ ctrlr.blurred = true;
1652
+ cursor.hide().parent.blur();
1653
+ };
1654
+ });
1655
+
1656
+ /**
1657
+ * TODO: I wanted to move MathBlock::focus and blur here, it would clean
1658
+ * up lots of stuff like, TextBlock::focus is set to MathBlock::focus
1659
+ * and TextBlock::blur calls MathBlock::blur, when instead they could
1660
+ * use inheritance and super_.
1661
+ *
1662
+ * Problem is, there's lots of calls to .focus()/.blur() on nodes
1663
+ * outside Controller::focusBlurEvents(), such as .postOrder('blur') on
1664
+ * insertion, which if MathBlock::blur becomes Node::blur, would add the
1665
+ * 'blur' CSS class to all Symbol's (because .isEmpty() is true for all
1666
+ * of them).
1667
+ *
1668
+ * I'm not even sure there aren't other troublesome calls to .focus() or
1669
+ * .blur(), so this is TODO for now.
1670
+ */
1671
+ /*****************************************
1672
+ * Deals with the browser DOM events from
1673
+ * interaction with the typist.
1674
+ ****************************************/
1675
+
1676
+ Controller.open(function(_) {
1677
+ _.keystroke = function(key, evt) {
1678
+ this.cursor.parent.keystroke(key, evt, this);
1679
+ };
1680
+ });
1681
+
1682
+ Node.open(function(_) {
1683
+ _.keystroke = function(key, e, ctrlr) {
1684
+ var cursor = ctrlr.cursor;
1685
+
1686
+ switch (key) {
1687
+ case 'Ctrl-Shift-Backspace':
1688
+ case 'Ctrl-Backspace':
1689
+ ctrlr.ctrlDeleteDir(L);
1690
+ break;
1691
+
1692
+ case 'Shift-Backspace':
1693
+ case 'Backspace':
1694
+ ctrlr.backspace();
1695
+ break;
1696
+
1697
+ // Tab or Esc -> go one block right if it exists, else escape right.
1698
+ case 'Esc':
1699
+ case 'Tab':
1700
+ ctrlr.escapeDir(R, key, e);
1701
+ return;
1702
+
1703
+ // Shift-Tab -> go one block left if it exists, else escape left.
1704
+ case 'Shift-Tab':
1705
+ case 'Shift-Esc':
1706
+ ctrlr.escapeDir(L, key, e);
1707
+ return;
1708
+
1709
+ // End -> move to the end of the current block.
1710
+ case 'End':
1711
+ ctrlr.notify('move').cursor.insAtRightEnd(cursor.parent);
1712
+ break;
1713
+
1714
+ // Ctrl-End -> move all the way to the end of the root block.
1715
+ case 'Ctrl-End':
1716
+ ctrlr.notify('move').cursor.insAtRightEnd(ctrlr.root);
1717
+ break;
1718
+
1719
+ // Shift-End -> select to the end of the current block.
1720
+ case 'Shift-End':
1721
+ while (cursor[R]) {
1722
+ ctrlr.selectRight();
1723
+ }
1724
+ break;
1725
+
1726
+ // Ctrl-Shift-End -> select to the end of the root block.
1727
+ case 'Ctrl-Shift-End':
1728
+ while (cursor[R] || cursor.parent !== ctrlr.root) {
1729
+ ctrlr.selectRight();
1730
+ }
1731
+ break;
1732
+
1733
+ // Home -> move to the start of the root block or the current block.
1734
+ case 'Home':
1735
+ ctrlr.notify('move').cursor.insAtLeftEnd(cursor.parent);
1736
+ break;
1737
+
1738
+ // Ctrl-Home -> move to the start of the current block.
1739
+ case 'Ctrl-Home':
1740
+ ctrlr.notify('move').cursor.insAtLeftEnd(ctrlr.root);
1741
+ break;
1742
+
1743
+ // Shift-Home -> select to the start of the current block.
1744
+ case 'Shift-Home':
1745
+ while (cursor[L]) {
1746
+ ctrlr.selectLeft();
1747
+ }
1748
+ break;
1749
+
1750
+ // Ctrl-Shift-Home -> move to the start of the root block.
1751
+ case 'Ctrl-Shift-Home':
1752
+ while (cursor[L] || cursor.parent !== ctrlr.root) {
1753
+ ctrlr.selectLeft();
1754
+ }
1755
+ break;
1756
+
1757
+ case 'Left': ctrlr.moveLeft(); break;
1758
+ case 'Shift-Left': ctrlr.selectLeft(); break;
1759
+ case 'Ctrl-Left': break;
1760
+
1761
+ case 'Right': ctrlr.moveRight(); break;
1762
+ case 'Shift-Right': ctrlr.selectRight(); break;
1763
+ case 'Ctrl-Right': break;
1764
+
1765
+ case 'Up': ctrlr.moveUp(); break;
1766
+ case 'Down': ctrlr.moveDown(); break;
1767
+
1768
+ case 'Shift-Up':
1769
+ if (cursor[L]) {
1770
+ while (cursor[L]) ctrlr.selectLeft();
1771
+ } else {
1772
+ ctrlr.selectLeft();
1773
+ }
1774
+
1775
+ case 'Shift-Down':
1776
+ if (cursor[R]) {
1777
+ while (cursor[R]) ctrlr.selectRight();
1778
+ }
1779
+ else {
1780
+ ctrlr.selectRight();
1781
+ }
1782
+
1783
+ case 'Ctrl-Up': break;
1784
+ case 'Ctrl-Down': break;
1785
+
1786
+ case 'Ctrl-Shift-Del':
1787
+ case 'Ctrl-Del':
1788
+ ctrlr.ctrlDeleteDir(R);
1789
+ break;
1790
+
1791
+ case 'Shift-Del':
1792
+ case 'Del':
1793
+ ctrlr.deleteForward();
1794
+ break;
1795
+
1796
+ case 'Meta-A':
1797
+ case 'Ctrl-A':
1798
+ ctrlr.notify('move').cursor.insAtRightEnd(ctrlr.root);
1799
+ while (cursor[L]) ctrlr.selectLeft();
1800
+ break;
1801
+
1802
+ default:
1803
+ return;
1804
+ }
1805
+ e.preventDefault();
1806
+ ctrlr.scrollHoriz();
1807
+ };
1808
+
1809
+ _.moveOutOf = // called by Controller::escapeDir, moveDir
1810
+ _.moveTowards = // called by Controller::moveDir
1811
+ _.deleteOutOf = // called by Controller::deleteDir
1812
+ _.deleteTowards = // called by Controller::deleteDir
1813
+ _.unselectInto = // called by Controller::selectDir
1814
+ _.selectOutOf = // called by Controller::selectDir
1815
+ _.selectTowards = // called by Controller::selectDir
1816
+ function() { pray('overridden or never called on this node'); };
1817
+ });
1818
+
1819
+ Controller.open(function(_) {
1820
+ this.onNotify(function(e) {
1821
+ if (e === 'move' || e === 'upDown') this.show().clearSelection();
1822
+ });
1823
+ _.escapeDir = function(dir, key, e) {
1824
+ prayDirection(dir);
1825
+ var cursor = this.cursor;
1826
+
1827
+ // only prevent default of Tab if not in the root editable
1828
+ if (cursor.parent !== this.root) e.preventDefault();
1829
+
1830
+ // want to be a noop if in the root editable (in fact, Tab has an unrelated
1831
+ // default browser action if so)
1832
+ if (cursor.parent === this.root) return;
1833
+
1834
+ cursor.parent.moveOutOf(dir, cursor);
1835
+ return this.notify('move');
1836
+ };
1837
+
1838
+ optionProcessors.leftRightIntoCmdGoes = function(updown) {
1839
+ if (updown && updown !== 'up' && updown !== 'down') {
1840
+ throw '"up" or "down" required for leftRightIntoCmdGoes option, '
1841
+ + 'got "'+updown+'"';
1842
+ }
1843
+ return updown;
1844
+ };
1845
+ _.moveDir = function(dir) {
1846
+ prayDirection(dir);
1847
+ var cursor = this.cursor, updown = cursor.options.leftRightIntoCmdGoes;
1848
+
1849
+ if (cursor.selection) {
1850
+ cursor.insDirOf(dir, cursor.selection.ends[dir]);
1851
+ }
1852
+ else if (cursor[dir]) cursor[dir].moveTowards(dir, cursor, updown);
1853
+ else cursor.parent.moveOutOf(dir, cursor, updown);
1854
+
1855
+ return this.notify('move');
1856
+ };
1857
+ _.moveLeft = function() { return this.moveDir(L); };
1858
+ _.moveRight = function() { return this.moveDir(R); };
1859
+
1860
+ /**
1861
+ * moveUp and moveDown have almost identical algorithms:
1862
+ * - first check left and right, if so insAtLeft/RightEnd of them
1863
+ * - else check the parent's 'upOutOf'/'downOutOf' property:
1864
+ * + if it's a function, call it with the cursor as the sole argument and
1865
+ * use the return value as if it were the value of the property
1866
+ * + if it's a Node, jump up or down into it:
1867
+ * - if there is a cached Point in the block, insert there
1868
+ * - else, seekHoriz within the block to the current x-coordinate (to be
1869
+ * as close to directly above/below the current position as possible)
1870
+ * + unless it's exactly `true`, stop bubbling
1871
+ */
1872
+ _.moveUp = function() { return moveUpDown(this, 'up'); };
1873
+ _.moveDown = function() { return moveUpDown(this, 'down'); };
1874
+ function moveUpDown(self, dir) {
1875
+ var cursor = self.notify('upDown').cursor;
1876
+ var dirInto = dir+'Into', dirOutOf = dir+'OutOf';
1877
+ if (cursor[R][dirInto]) cursor.insAtLeftEnd(cursor[R][dirInto]);
1878
+ else if (cursor[L][dirInto]) cursor.insAtRightEnd(cursor[L][dirInto]);
1879
+ else {
1880
+ cursor.parent.bubble(function(ancestor) {
1881
+ var prop = ancestor[dirOutOf];
1882
+ if (prop) {
1883
+ if (typeof prop === 'function') prop = ancestor[dirOutOf](cursor);
1884
+ if (prop instanceof Node) cursor.jumpUpDown(ancestor, prop);
1885
+ if (prop !== true) return false;
1886
+ }
1887
+ });
1888
+ }
1889
+ return self;
1890
+ }
1891
+ this.onNotify(function(e) { if (e !== 'upDown') this.upDownCache = {}; });
1892
+
1893
+ this.onNotify(function(e) { if (e === 'edit') this.show().deleteSelection(); });
1894
+ _.deleteDir = function(dir) {
1895
+ prayDirection(dir);
1896
+ var cursor = this.cursor;
1897
+
1898
+ var hadSelection = cursor.selection;
1899
+ this.notify('edit'); // deletes selection if present
1900
+ if (!hadSelection) {
1901
+ if (cursor[dir]) cursor[dir].deleteTowards(dir, cursor);
1902
+ else cursor.parent.deleteOutOf(dir, cursor);
1903
+ }
1904
+
1905
+ if (cursor[L].siblingDeleted) cursor[L].siblingDeleted(cursor.options, R);
1906
+ if (cursor[R].siblingDeleted) cursor[R].siblingDeleted(cursor.options, L);
1907
+ cursor.parent.bubble('reflow');
1908
+
1909
+ return this;
1910
+ };
1911
+ _.ctrlDeleteDir = function(dir) {
1912
+ prayDirection(dir);
1913
+ var cursor = this.cursor;
1914
+ if (!cursor[L] || cursor.selection) return ctrlr.deleteDir();
1915
+
1916
+ this.notify('edit');
1917
+ Fragment(cursor.parent.ends[L], cursor[L]).remove();
1918
+ cursor.insAtDirEnd(L, cursor.parent);
1919
+
1920
+ if (cursor[L].siblingDeleted) cursor[L].siblingDeleted(cursor.options, R);
1921
+ if (cursor[R].siblingDeleted) cursor[R].siblingDeleted(cursor.options, L);
1922
+ cursor.parent.bubble('reflow');
1923
+
1924
+ return this;
1925
+ };
1926
+ _.backspace = function() { return this.deleteDir(L); };
1927
+ _.deleteForward = function() { return this.deleteDir(R); };
1928
+
1929
+ this.onNotify(function(e) { if (e !== 'select') this.endSelection(); });
1930
+ _.selectDir = function(dir) {
1931
+ var cursor = this.notify('select').cursor, seln = cursor.selection;
1932
+ prayDirection(dir);
1933
+
1934
+ if (!cursor.anticursor) cursor.startSelection();
1935
+
1936
+ var node = cursor[dir];
1937
+ if (node) {
1938
+ // "if node we're selecting towards is inside selection (hence retracting)
1939
+ // and is on the *far side* of the selection (hence is only node selected)
1940
+ // and the anticursor is *inside* that node, not just on the other side"
1941
+ if (seln && seln.ends[dir] === node && cursor.anticursor[-dir] !== node) {
1942
+ node.unselectInto(dir, cursor);
1943
+ }
1944
+ else node.selectTowards(dir, cursor);
1945
+ }
1946
+ else cursor.parent.selectOutOf(dir, cursor);
1947
+
1948
+ cursor.clearSelection();
1949
+ cursor.select() || cursor.show();
1950
+ };
1951
+ _.selectLeft = function() { return this.selectDir(L); };
1952
+ _.selectRight = function() { return this.selectDir(R); };
1953
+ });
1954
+ // Parser MathCommand
1955
+ var latexMathParser = (function() {
1956
+ function commandToBlock(cmd) {
1957
+ var block = MathBlock();
1958
+ cmd.adopt(block, 0, 0);
1959
+ return block;
1960
+ }
1961
+ function joinBlocks(blocks) {
1962
+ var firstBlock = blocks[0] || MathBlock();
1963
+
1964
+ for (var i = 1; i < blocks.length; i += 1) {
1965
+ blocks[i].children().adopt(firstBlock, firstBlock.ends[R], 0);
1966
+ }
1967
+
1968
+ return firstBlock;
1969
+ }
1970
+
1971
+ var string = Parser.string;
1972
+ var regex = Parser.regex;
1973
+ var letter = Parser.letter;
1974
+ var any = Parser.any;
1975
+ var optWhitespace = Parser.optWhitespace;
1976
+ var succeed = Parser.succeed;
1977
+ var fail = Parser.fail;
1978
+
1979
+ // Parsers yielding either MathCommands, or Fragments of MathCommands
1980
+ // (either way, something that can be adopted by a MathBlock)
1981
+ var variable = letter.map(function(c) { return Letter(c); });
1982
+ var symbol = regex(/^[^${}\\_^]/).map(function(c) { return VanillaSymbol(c); });
1983
+
1984
+ var controlSequence =
1985
+ regex(/^[^\\a-eg-zA-Z]/) // hotfix #164; match MathBlock::write
1986
+ .or(string('\\').then(
1987
+ regex(/^[a-z]+/i)
1988
+ .or(regex(/^\s+/).result(' '))
1989
+ .or(any)
1990
+ )).then(function(ctrlSeq) {
1991
+ var cmdKlass = LatexCmds[ctrlSeq];
1992
+
1993
+ if (cmdKlass) {
1994
+ return cmdKlass(ctrlSeq).parser();
1995
+ }
1996
+ else {
1997
+ return fail('unknown command: \\'+ctrlSeq);
1998
+ }
1999
+ })
2000
+ ;
2001
+
2002
+ var command =
2003
+ controlSequence
2004
+ .or(variable)
2005
+ .or(symbol)
2006
+ ;
2007
+
2008
+ // Parsers yielding MathBlocks
2009
+ var mathGroup = string('{').then(function() { return mathSequence; }).skip(string('}'));
2010
+ var mathBlock = optWhitespace.then(mathGroup.or(command.map(commandToBlock)));
2011
+ var mathSequence = mathBlock.many().map(joinBlocks).skip(optWhitespace);
2012
+
2013
+ var optMathBlock =
2014
+ string('[').then(
2015
+ mathBlock.then(function(block) {
2016
+ return block.join('latex') !== ']' ? succeed(block) : fail();
2017
+ })
2018
+ .many().map(joinBlocks).skip(optWhitespace)
2019
+ ).skip(string(']'))
2020
+ ;
2021
+
2022
+ var latexMath = mathSequence;
2023
+
2024
+ latexMath.block = mathBlock;
2025
+ latexMath.optBlock = optMathBlock;
2026
+ return latexMath;
2027
+ })();
2028
+
2029
+ Controller.open(function(_, super_) {
2030
+ _.exportLatex = function() {
2031
+ return this.root.latex().replace(/(\\[a-z]+) (?![a-z])/ig,'$1');
2032
+ };
2033
+ _.writeLatex = function(latex) {
2034
+ var cursor = this.notify('edit').cursor;
2035
+
2036
+ var all = Parser.all;
2037
+ var eof = Parser.eof;
2038
+
2039
+ var block = latexMathParser.skip(eof).or(all.result(false)).parse(latex);
2040
+
2041
+ if (block && !block.isEmpty()) {
2042
+ block.children().adopt(cursor.parent, cursor[L], cursor[R]);
2043
+ var jQ = block.jQize();
2044
+ jQ.insertBefore(cursor.jQ);
2045
+ cursor[L] = block.ends[R];
2046
+ block.finalizeInsert(cursor.options, cursor);
2047
+ if (block.ends[R][R].siblingCreated) block.ends[R][R].siblingCreated(cursor.options, L);
2048
+ if (block.ends[L][L].siblingCreated) block.ends[L][L].siblingCreated(cursor.options, R);
2049
+ cursor.parent.bubble('reflow');
2050
+ }
2051
+
2052
+ return this;
2053
+ };
2054
+ _.renderLatexMath = function(latex) {
2055
+ var root = this.root, cursor = this.cursor;
2056
+
2057
+ var all = Parser.all;
2058
+ var eof = Parser.eof;
2059
+
2060
+ var block = latexMathParser.skip(eof).or(all.result(false)).parse(latex);
2061
+
2062
+ root.eachChild('postOrder', 'dispose');
2063
+ root.ends[L] = root.ends[R] = 0;
2064
+
2065
+ if (block) {
2066
+ block.children().adopt(root, 0, 0);
2067
+ }
2068
+
2069
+ var jQ = root.jQ;
2070
+
2071
+ if (block) {
2072
+ var html = block.join('html');
2073
+ jQ.html(html);
2074
+ root.jQize(jQ.children());
2075
+ root.finalizeInsert(cursor.options);
2076
+ }
2077
+ else {
2078
+ jQ.empty();
2079
+ }
2080
+
2081
+ delete cursor.selection;
2082
+ cursor.insAtRightEnd(root);
2083
+ };
2084
+ _.renderLatexText = function(latex) {
2085
+ var root = this.root, cursor = this.cursor;
2086
+
2087
+ root.jQ.children().slice(1).remove();
2088
+ root.eachChild('postOrder', 'dispose');
2089
+ root.ends[L] = root.ends[R] = 0;
2090
+ delete cursor.selection;
2091
+ cursor.show().insAtRightEnd(root);
2092
+
2093
+ var regex = Parser.regex;
2094
+ var string = Parser.string;
2095
+ var eof = Parser.eof;
2096
+ var all = Parser.all;
2097
+
2098
+ // Parser RootMathCommand
2099
+ var mathMode = string('$').then(latexMathParser)
2100
+ // because TeX is insane, math mode doesn't necessarily
2101
+ // have to end. So we allow for the case that math mode
2102
+ // continues to the end of the stream.
2103
+ .skip(string('$').or(eof))
2104
+ .map(function(block) {
2105
+ // HACK FIXME: this shouldn't have to have access to cursor
2106
+ var rootMathCommand = RootMathCommand(cursor);
2107
+
2108
+ rootMathCommand.createBlocks();
2109
+ var rootMathBlock = rootMathCommand.ends[L];
2110
+ block.children().adopt(rootMathBlock, 0, 0);
2111
+
2112
+ return rootMathCommand;
2113
+ })
2114
+ ;
2115
+
2116
+ var escapedDollar = string('\\$').result('$');
2117
+ var textChar = escapedDollar.or(regex(/^[^$]/)).map(VanillaSymbol);
2118
+ var latexText = mathMode.or(textChar).many();
2119
+ var commands = latexText.skip(eof).or(all.result(false)).parse(latex);
2120
+
2121
+ if (commands) {
2122
+ for (var i = 0; i < commands.length; i += 1) {
2123
+ commands[i].adopt(root, root.ends[R], 0);
2124
+ }
2125
+
2126
+ root.jQize().appendTo(root.jQ);
2127
+
2128
+ root.finalizeInsert(cursor.options);
2129
+ }
2130
+ };
2131
+ });
2132
+ /********************************************************
2133
+ * Deals with mouse events for clicking, drag-to-select
2134
+ *******************************************************/
2135
+
2136
+ Controller.open(function(_) {
2137
+ _.delegateMouseEvents = function() {
2138
+ var ultimateRootjQ = this.root.jQ;
2139
+ //drag-to-select event handling
2140
+ this.container.bind('mousedown.mathquill', function(e) {
2141
+ var rootjQ = $(e.target).closest('.mq-root-block');
2142
+ var root = Node.byId[rootjQ.attr(mqBlockId) || ultimateRootjQ.attr(mqBlockId)];
2143
+ var ctrlr = root.controller, cursor = ctrlr.cursor, blink = cursor.blink;
2144
+ var textareaSpan = ctrlr.textareaSpan, textarea = ctrlr.textarea;
2145
+
2146
+ var target;
2147
+ function mousemove(e) { target = $(e.target); }
2148
+ function docmousemove(e) {
2149
+ if (!cursor.anticursor) cursor.startSelection();
2150
+ ctrlr.seek(target, e.pageX, e.pageY).cursor.select();
2151
+ target = undefined;
2152
+ }
2153
+ // outside rootjQ, the MathQuill node corresponding to the target (if any)
2154
+ // won't be inside this root, so don't mislead Controller::seek with it
2155
+
2156
+ function mouseup(e) {
2157
+ cursor.blink = blink;
2158
+ if (!cursor.selection) {
2159
+ if (ctrlr.editable) {
2160
+ cursor.show();
2161
+ }
2162
+ else {
2163
+ textareaSpan.detach();
2164
+ }
2165
+ }
2166
+
2167
+ // delete the mouse handlers now that we're not dragging anymore
2168
+ rootjQ.unbind('mousemove', mousemove);
2169
+ $(e.target.ownerDocument).unbind('mousemove', docmousemove).unbind('mouseup', mouseup);
2170
+ }
2171
+
2172
+ if (ctrlr.blurred) {
2173
+ if (!ctrlr.editable) rootjQ.prepend(textareaSpan);
2174
+ textarea.focus();
2175
+ }
2176
+ e.preventDefault(); // doesn't work in IE\u22648, but it's a one-line fix:
2177
+ e.target.unselectable = true; // http://jsbin.com/yagekiji/1
2178
+
2179
+ cursor.blink = noop;
2180
+ ctrlr.seek($(e.target), e.pageX, e.pageY).cursor.startSelection();
2181
+
2182
+ rootjQ.mousemove(mousemove);
2183
+ $(e.target.ownerDocument).mousemove(docmousemove).mouseup(mouseup);
2184
+ // listen on document not just body to not only hear about mousemove and
2185
+ // mouseup on page outside field, but even outside page, except iframes: https://github.com/mathquill/mathquill/commit/8c50028afcffcace655d8ae2049f6e02482346c5#commitcomment-6175800
2186
+ });
2187
+ }
2188
+ });
2189
+
2190
+ Controller.open(function(_) {
2191
+ _.seek = function(target, pageX, pageY) {
2192
+ var cursor = this.notify('select').cursor;
2193
+
2194
+ if (target) {
2195
+ var nodeId = target.attr(mqBlockId) || target.attr(mqCmdId);
2196
+ if (!nodeId) {
2197
+ var targetParent = target.parent();
2198
+ nodeId = targetParent.attr(mqBlockId) || targetParent.attr(mqCmdId);
2199
+ }
2200
+ }
2201
+ var node = nodeId ? Node.byId[nodeId] : this.root;
2202
+ pray('nodeId is the id of some Node that exists', node);
2203
+
2204
+ // don't clear selection until after getting node from target, in case
2205
+ // target was selection span, otherwise target will have no parent and will
2206
+ // seek from root, which is less accurate (e.g. fraction)
2207
+ cursor.clearSelection().show();
2208
+
2209
+ node.seek(pageX, cursor);
2210
+ this.scrollHoriz(); // before .selectFrom when mouse-selecting, so
2211
+ // always hits no-selection case in scrollHoriz and scrolls slower
2212
+ return this;
2213
+ };
2214
+ });
2215
+ /***********************************************
2216
+ * Horizontal panning for editable fields that
2217
+ * overflow their width
2218
+ **********************************************/
2219
+
2220
+ Controller.open(function(_) {
2221
+ _.scrollHoriz = function() {
2222
+ var cursor = this.cursor, seln = cursor.selection;
2223
+ var rootRect = this.root.jQ[0].getBoundingClientRect();
2224
+ if (!seln) {
2225
+ var x = cursor.jQ[0].getBoundingClientRect().left;
2226
+ if (x > rootRect.right - 20) var scrollBy = x - (rootRect.right - 20);
2227
+ else if (x < rootRect.left + 20) var scrollBy = x - (rootRect.left + 20);
2228
+ else return;
2229
+ }
2230
+ else {
2231
+ var rect = seln.jQ[0].getBoundingClientRect();
2232
+ var overLeft = rect.left - (rootRect.left + 20);
2233
+ var overRight = rect.right - (rootRect.right - 20);
2234
+ if (seln.ends[L] === cursor[R]) {
2235
+ if (overLeft < 0) var scrollBy = overLeft;
2236
+ else if (overRight > 0) {
2237
+ if (rect.left - overRight < rootRect.left + 20) var scrollBy = overLeft;
2238
+ else var scrollBy = overRight;
2239
+ }
2240
+ else return;
2241
+ }
2242
+ else {
2243
+ if (overRight > 0) var scrollBy = overRight;
2244
+ else if (overLeft < 0) {
2245
+ if (rect.right - overLeft > rootRect.right - 20) var scrollBy = overRight;
2246
+ else var scrollBy = overLeft;
2247
+ }
2248
+ else return;
2249
+ }
2250
+ }
2251
+ this.root.jQ.stop().animate({ scrollLeft: '+=' + scrollBy}, 100);
2252
+ };
2253
+ });
2254
+ /*********************************************
2255
+ * Manage the MathQuill instance's textarea
2256
+ * (as owned by the Controller)
2257
+ ********************************************/
2258
+
2259
+ Controller.open(function(_) {
2260
+ Options.p.substituteTextarea = function() {
2261
+ return $('<textarea autocapitalize=off autocomplete=off autocorrect=off ' +
2262
+ 'spellcheck=false x-palm-disable-ste-all=true />')[0];
2263
+ };
2264
+ _.createTextarea = function() {
2265
+ var textareaSpan = this.textareaSpan = $('<span class="mq-textarea"></span>'),
2266
+ textarea = this.options.substituteTextarea();
2267
+ if (!textarea.nodeType) {
2268
+ throw 'substituteTextarea() must return a DOM element, got ' + textarea;
2269
+ }
2270
+ textarea = this.textarea = $(textarea).appendTo(textareaSpan);
2271
+
2272
+ var ctrlr = this;
2273
+ ctrlr.cursor.selectionChanged = function() { ctrlr.selectionChanged(); };
2274
+ ctrlr.container.bind('copy', function() { ctrlr.setTextareaSelection(); });
2275
+ };
2276
+ _.selectionChanged = function() {
2277
+ var ctrlr = this;
2278
+ forceIERedraw(ctrlr.container[0]);
2279
+
2280
+ // throttle calls to setTextareaSelection(), because setting textarea.value
2281
+ // and/or calling textarea.select() can have anomalously bad performance:
2282
+ // https://github.com/mathquill/mathquill/issues/43#issuecomment-1399080
2283
+ if (ctrlr.textareaSelectionTimeout === undefined) {
2284
+ ctrlr.textareaSelectionTimeout = setTimeout(function() {
2285
+ ctrlr.setTextareaSelection();
2286
+ });
2287
+ }
2288
+ };
2289
+ _.setTextareaSelection = function() {
2290
+ this.textareaSelectionTimeout = undefined;
2291
+ var latex = '';
2292
+ if (this.cursor.selection) {
2293
+ latex = this.cursor.selection.join('latex');
2294
+ if (this.options.statelessClipboard) {
2295
+ // FIXME: like paste, only this works for math fields; should ask parent
2296
+ latex = '$' + latex + '$';
2297
+ }
2298
+ }
2299
+ this.selectFn(latex);
2300
+ };
2301
+ _.staticMathTextareaEvents = function() {
2302
+ var ctrlr = this, root = ctrlr.root, cursor = ctrlr.cursor,
2303
+ textarea = ctrlr.textarea, textareaSpan = ctrlr.textareaSpan;
2304
+
2305
+ this.container.prepend('<span class="mq-selectable">$'+ctrlr.exportLatex()+'$</span>');
2306
+ ctrlr.blurred = true;
2307
+ textarea.bind('cut paste', false)
2308
+ .focus(function() { ctrlr.blurred = false; }).blur(function() {
2309
+ if (cursor.selection) cursor.selection.clear();
2310
+ setTimeout(detach); //detaching during blur explodes in WebKit
2311
+ });
2312
+ function detach() {
2313
+ textareaSpan.detach();
2314
+ ctrlr.blurred = true;
2315
+ }
2316
+
2317
+ ctrlr.selectFn = function(text) {
2318
+ textarea.val(text);
2319
+ if (text) textarea.select();
2320
+ };
2321
+ };
2322
+ _.editablesTextareaEvents = function() {
2323
+ var ctrlr = this, root = ctrlr.root, cursor = ctrlr.cursor,
2324
+ textarea = ctrlr.textarea, textareaSpan = ctrlr.textareaSpan;
2325
+
2326
+ var keyboardEventsShim = saneKeyboardEvents(textarea, this);
2327
+ this.selectFn = function(text) { keyboardEventsShim.select(text); };
2328
+
2329
+ this.container.prepend(textareaSpan)
2330
+ .on('cut', function(e) {
2331
+ if (cursor.selection) {
2332
+ setTimeout(function() {
2333
+ ctrlr.notify('edit'); // deletes selection if present
2334
+ cursor.parent.bubble('reflow');
2335
+ });
2336
+ }
2337
+ });
2338
+
2339
+ this.focusBlurEvents();
2340
+ };
2341
+ _.typedText = function(ch) {
2342
+ if (ch === '\n') return this.handle('enter');
2343
+ var cursor = this.notify().cursor;
2344
+ cursor.parent.write(cursor, ch);
2345
+ this.scrollHoriz();
2346
+ };
2347
+ _.paste = function(text) {
2348
+ // TODO: document `statelessClipboard` config option in README, after
2349
+ // making it work like it should, that is, in both text and math mode
2350
+ // (currently only works in math fields, so worse than pointless, it
2351
+ // only gets in the way by \text{}-ifying pasted stuff and $-ifying
2352
+ // cut/copied LaTeX)
2353
+ if (this.options.statelessClipboard) {
2354
+ if (text.slice(0,1) === '$' && text.slice(-1) === '$') {
2355
+ text = text.slice(1, -1);
2356
+ }
2357
+ else {
2358
+ text = '\\text{'+text+'}';
2359
+ }
2360
+ }
2361
+ // FIXME: this always inserts math or a TextBlock, even in a RootTextBlock
2362
+ this.writeLatex(text).cursor.show();
2363
+ };
2364
+ });
2365
+ /*************************************************
2366
+ * Abstract classes of math blocks and commands.
2367
+ ************************************************/
2368
+
2369
+ /**
2370
+ * Math tree node base class.
2371
+ * Some math-tree-specific extensions to Node.
2372
+ * Both MathBlock's and MathCommand's descend from it.
2373
+ */
2374
+ var MathElement = P(Node, function(_, super_) {
2375
+ _.finalizeInsert = function(options, cursor) { // `cursor` param is only for
2376
+ // SupSub::contactWeld, and is deliberately only passed in by writeLatex,
2377
+ // see ea7307eb4fac77c149a11ffdf9a831df85247693
2378
+ var self = this;
2379
+ self.postOrder('finalizeTree', options);
2380
+ self.postOrder('contactWeld', cursor);
2381
+
2382
+ // note: this order is important.
2383
+ // empty elements need the empty box provided by blur to
2384
+ // be present in order for their dimensions to be measured
2385
+ // correctly by 'reflow' handlers.
2386
+ self.postOrder('blur');
2387
+
2388
+ self.postOrder('reflow');
2389
+ if (self[R].siblingCreated) self[R].siblingCreated(options, L);
2390
+ if (self[L].siblingCreated) self[L].siblingCreated(options, R);
2391
+ self.bubble('reflow');
2392
+ };
2393
+ });
2394
+
2395
+ /**
2396
+ * Commands and operators, like subscripts, exponents, or fractions.
2397
+ * Descendant commands are organized into blocks.
2398
+ */
2399
+ var MathCommand = P(MathElement, function(_, super_) {
2400
+ _.init = function(ctrlSeq, htmlTemplate, textTemplate) {
2401
+ var cmd = this;
2402
+ super_.init.call(cmd);
2403
+
2404
+ if (!cmd.ctrlSeq) cmd.ctrlSeq = ctrlSeq;
2405
+ if (htmlTemplate) cmd.htmlTemplate = htmlTemplate;
2406
+ if (textTemplate) cmd.textTemplate = textTemplate;
2407
+ };
2408
+
2409
+ // obvious methods
2410
+ _.replaces = function(replacedFragment) {
2411
+ replacedFragment.disown();
2412
+ this.replacedFragment = replacedFragment;
2413
+ };
2414
+ _.isEmpty = function() {
2415
+ return this.foldChildren(true, function(isEmpty, child) {
2416
+ return isEmpty && child.isEmpty();
2417
+ });
2418
+ };
2419
+
2420
+ _.parser = function() {
2421
+ var block = latexMathParser.block;
2422
+ var self = this;
2423
+
2424
+ return block.times(self.numBlocks()).map(function(blocks) {
2425
+ self.blocks = blocks;
2426
+
2427
+ for (var i = 0; i < blocks.length; i += 1) {
2428
+ blocks[i].adopt(self, self.ends[R], 0);
2429
+ }
2430
+
2431
+ return self;
2432
+ });
2433
+ };
2434
+
2435
+ // createLeftOf(cursor) and the methods it calls
2436
+ _.createLeftOf = function(cursor) {
2437
+ var cmd = this;
2438
+ var replacedFragment = cmd.replacedFragment;
2439
+
2440
+ cmd.createBlocks();
2441
+ super_.createLeftOf.call(cmd, cursor);
2442
+ if (replacedFragment) {
2443
+ replacedFragment.adopt(cmd.ends[L], 0, 0);
2444
+ replacedFragment.jQ.appendTo(cmd.ends[L].jQ);
2445
+ }
2446
+ cmd.finalizeInsert(cursor.options);
2447
+ cmd.placeCursor(cursor);
2448
+ };
2449
+ _.createBlocks = function() {
2450
+ var cmd = this,
2451
+ numBlocks = cmd.numBlocks(),
2452
+ blocks = cmd.blocks = Array(numBlocks);
2453
+
2454
+ for (var i = 0; i < numBlocks; i += 1) {
2455
+ var newBlock = blocks[i] = MathBlock();
2456
+ newBlock.adopt(cmd, cmd.ends[R], 0);
2457
+ }
2458
+ };
2459
+ _.placeCursor = function(cursor) {
2460
+ //insert the cursor at the right end of the first empty child, searching
2461
+ //left-to-right, or if none empty, the right end child
2462
+ cursor.insAtRightEnd(this.foldChildren(this.ends[L], function(leftward, child) {
2463
+ return leftward.isEmpty() ? leftward : child;
2464
+ }));
2465
+ };
2466
+
2467
+ // editability methods: called by the cursor for editing, cursor movements,
2468
+ // and selection of the MathQuill tree, these all take in a direction and
2469
+ // the cursor
2470
+ _.moveTowards = function(dir, cursor, updown) {
2471
+ var updownInto = updown && this[updown+'Into'];
2472
+ cursor.insAtDirEnd(-dir, updownInto || this.ends[-dir]);
2473
+ };
2474
+ _.deleteTowards = function(dir, cursor) {
2475
+ if (this.isEmpty()) cursor[dir] = this.remove()[dir];
2476
+ else this.moveTowards(dir, cursor, null);
2477
+ };
2478
+ _.selectTowards = function(dir, cursor) {
2479
+ cursor[-dir] = this;
2480
+ cursor[dir] = this[dir];
2481
+ };
2482
+ _.selectChildren = function() {
2483
+ return Selection(this, this);
2484
+ };
2485
+ _.unselectInto = function(dir, cursor) {
2486
+ cursor.insAtDirEnd(-dir, cursor.anticursor.ancestors[this.id]);
2487
+ };
2488
+ _.seek = function(pageX, cursor) {
2489
+ function getBounds(node) {
2490
+ var bounds = {}
2491
+ bounds[L] = node.jQ.offset().left;
2492
+ bounds[R] = bounds[L] + node.jQ.outerWidth();
2493
+ return bounds;
2494
+ }
2495
+
2496
+ var cmd = this;
2497
+ var cmdBounds = getBounds(cmd);
2498
+
2499
+ if (pageX < cmdBounds[L]) return cursor.insLeftOf(cmd);
2500
+ if (pageX > cmdBounds[R]) return cursor.insRightOf(cmd);
2501
+
2502
+ var leftLeftBound = cmdBounds[L];
2503
+ cmd.eachChild(function(block) {
2504
+ var blockBounds = getBounds(block);
2505
+ if (pageX < blockBounds[L]) {
2506
+ // closer to this block's left bound, or the bound left of that?
2507
+ if (pageX - leftLeftBound < blockBounds[L] - pageX) {
2508
+ if (block[L]) cursor.insAtRightEnd(block[L]);
2509
+ else cursor.insLeftOf(cmd);
2510
+ }
2511
+ else cursor.insAtLeftEnd(block);
2512
+ return false;
2513
+ }
2514
+ else if (pageX > blockBounds[R]) {
2515
+ if (block[R]) leftLeftBound = blockBounds[R]; // continue to next block
2516
+ else { // last (rightmost) block
2517
+ // closer to this block's right bound, or the cmd's right bound?
2518
+ if (cmdBounds[R] - pageX < pageX - blockBounds[R]) {
2519
+ cursor.insRightOf(cmd);
2520
+ }
2521
+ else cursor.insAtRightEnd(block);
2522
+ }
2523
+ }
2524
+ else {
2525
+ block.seek(pageX, cursor);
2526
+ return false;
2527
+ }
2528
+ });
2529
+ }
2530
+
2531
+ // methods involved in creating and cross-linking with HTML DOM nodes
2532
+ /*
2533
+ They all expect an .htmlTemplate like
2534
+ '<span>&0</span>'
2535
+ or
2536
+ '<span><span>&0</span><span>&1</span></span>'
2537
+
2538
+ See html.test.js for more examples.
2539
+
2540
+ Requirements:
2541
+ - For each block of the command, there must be exactly one "block content
2542
+ marker" of the form '&<number>' where <number> is the 0-based index of the
2543
+ block. (Like the LaTeX \newcommand syntax, but with a 0-based rather than
2544
+ 1-based index, because JavaScript because C because Dijkstra.)
2545
+ - The block content marker must be the sole contents of the containing
2546
+ element, there can't even be surrounding whitespace, or else we can't
2547
+ guarantee sticking to within the bounds of the block content marker when
2548
+ mucking with the HTML DOM.
2549
+ - The HTML not only must be well-formed HTML (of course), but also must
2550
+ conform to the XHTML requirements on tags, specifically all tags must
2551
+ either be self-closing (like '<br/>') or come in matching pairs.
2552
+ Close tags are never optional.
2553
+
2554
+ Note that &<number> isn't well-formed HTML; if you wanted a literal '&123',
2555
+ your HTML template would have to have '&amp;123'.
2556
+ */
2557
+ _.numBlocks = function() {
2558
+ var matches = this.htmlTemplate.match(/&\d+/g);
2559
+ return matches ? matches.length : 0;
2560
+ };
2561
+ _.html = function() {
2562
+ // Render the entire math subtree rooted at this command, as HTML.
2563
+ // Expects .createBlocks() to have been called already, since it uses the
2564
+ // .blocks array of child blocks.
2565
+ //
2566
+ // See html.test.js for example templates and intended outputs.
2567
+ //
2568
+ // Given an .htmlTemplate as described above,
2569
+ // - insert the mathquill-command-id attribute into all top-level tags,
2570
+ // which will be used to set this.jQ in .jQize().
2571
+ // This is straightforward:
2572
+ // * tokenize into tags and non-tags
2573
+ // * loop through top-level tokens:
2574
+ // * add #cmdId attribute macro to top-level self-closing tags
2575
+ // * else add #cmdId attribute macro to top-level open tags
2576
+ // * skip the matching top-level close tag and all tag pairs
2577
+ // in between
2578
+ // - for each block content marker,
2579
+ // + replace it with the contents of the corresponding block,
2580
+ // rendered as HTML
2581
+ // + insert the mathquill-block-id attribute into the containing tag
2582
+ // This is even easier, a quick regex replace, since block tags cannot
2583
+ // contain anything besides the block content marker.
2584
+ //
2585
+ // Two notes:
2586
+ // - The outermost loop through top-level tokens should never encounter any
2587
+ // top-level close tags, because we should have first encountered a
2588
+ // matching top-level open tag, all inner tags should have appeared in
2589
+ // matching pairs and been skipped, and then we should have skipped the
2590
+ // close tag in question.
2591
+ // - All open tags should have matching close tags, which means our inner
2592
+ // loop should always encounter a close tag and drop nesting to 0. If
2593
+ // a close tag is missing, the loop will continue until i >= tokens.length
2594
+ // and token becomes undefined. This will not infinite loop, even in
2595
+ // production without pray(), because it will then TypeError on .slice().
2596
+
2597
+ var cmd = this;
2598
+ var blocks = cmd.blocks;
2599
+ var cmdId = ' mathquill-command-id=' + cmd.id;
2600
+ var tokens = cmd.htmlTemplate.match(/<[^<>]+>|[^<>]+/g);
2601
+
2602
+ pray('no unmatched angle brackets', tokens.join('') === this.htmlTemplate);
2603
+
2604
+ // add cmdId to all top-level tags
2605
+ for (var i = 0, token = tokens[0]; token; i += 1, token = tokens[i]) {
2606
+ // top-level self-closing tags
2607
+ if (token.slice(-2) === '/>') {
2608
+ tokens[i] = token.slice(0,-2) + cmdId + '/>';
2609
+ }
2610
+ // top-level open tags
2611
+ else if (token.charAt(0) === '<') {
2612
+ pray('not an unmatched top-level close tag', token.charAt(1) !== '/');
2613
+
2614
+ tokens[i] = token.slice(0,-1) + cmdId + '>';
2615
+
2616
+ // skip matching top-level close tag and all tag pairs in between
2617
+ var nesting = 1;
2618
+ do {
2619
+ i += 1, token = tokens[i];
2620
+ pray('no missing close tags', token);
2621
+ // close tags
2622
+ if (token.slice(0,2) === '</') {
2623
+ nesting -= 1;
2624
+ }
2625
+ // non-self-closing open tags
2626
+ else if (token.charAt(0) === '<' && token.slice(-2) !== '/>') {
2627
+ nesting += 1;
2628
+ }
2629
+ } while (nesting > 0);
2630
+ }
2631
+ }
2632
+ return tokens.join('').replace(/>&(\d+)/g, function($0, $1) {
2633
+ return ' mathquill-block-id=' + blocks[$1].id + '>' + blocks[$1].join('html');
2634
+ });
2635
+ };
2636
+
2637
+ // methods to export a string representation of the math tree
2638
+ _.latex = function() {
2639
+ return this.foldChildren(this.ctrlSeq, function(latex, child) {
2640
+ return latex + '{' + (child.latex() || ' ') + '}';
2641
+ });
2642
+ };
2643
+ _.textTemplate = [''];
2644
+ _.text = function() {
2645
+ var cmd = this, i = 0;
2646
+ return cmd.foldChildren(cmd.textTemplate[i], function(text, child) {
2647
+ i += 1;
2648
+ var child_text = child.text();
2649
+ if (text && cmd.textTemplate[i] === '('
2650
+ && child_text[0] === '(' && child_text.slice(-1) === ')')
2651
+ return text + child_text.slice(1, -1) + cmd.textTemplate[i];
2652
+ return text + child.text() + (cmd.textTemplate[i] || '');
2653
+ });
2654
+ };
2655
+ });
2656
+
2657
+ /**
2658
+ * Lightweight command without blocks or children.
2659
+ */
2660
+ var Symbol = P(MathCommand, function(_, super_) {
2661
+ _.init = function(ctrlSeq, html, text) {
2662
+ if (!text) text = ctrlSeq && ctrlSeq.length > 1 ? ctrlSeq.slice(1) : ctrlSeq;
2663
+
2664
+ super_.init.call(this, ctrlSeq, html, [ text ]);
2665
+ };
2666
+
2667
+ _.parser = function() { return Parser.succeed(this); };
2668
+ _.numBlocks = function() { return 0; };
2669
+
2670
+ _.replaces = function(replacedFragment) {
2671
+ replacedFragment.remove();
2672
+ };
2673
+ _.createBlocks = noop;
2674
+
2675
+ _.moveTowards = function(dir, cursor) {
2676
+ cursor.jQ.insDirOf(dir, this.jQ);
2677
+ cursor[-dir] = this;
2678
+ cursor[dir] = this[dir];
2679
+ };
2680
+ _.deleteTowards = function(dir, cursor) {
2681
+ cursor[dir] = this.remove()[dir];
2682
+ };
2683
+ _.seek = function(pageX, cursor) {
2684
+ // insert at whichever side the click was closer to
2685
+ if (pageX - this.jQ.offset().left < this.jQ.outerWidth()/2)
2686
+ cursor.insLeftOf(this);
2687
+ else
2688
+ cursor.insRightOf(this);
2689
+ };
2690
+
2691
+ _.latex = function(){ return this.ctrlSeq; };
2692
+ _.text = function(){ return this.textTemplate; };
2693
+ _.placeCursor = noop;
2694
+ _.isEmpty = function(){ return true; };
2695
+ });
2696
+ var VanillaSymbol = P(Symbol, function(_, super_) {
2697
+ _.init = function(ch, html) {
2698
+ super_.init.call(this, ch, '<span>'+(html || ch)+'</span>');
2699
+ };
2700
+ });
2701
+ var BinaryOperator = P(Symbol, function(_, super_) {
2702
+ _.init = function(ctrlSeq, html, text) {
2703
+ super_.init.call(this,
2704
+ ctrlSeq, '<span class="mq-binary-operator">'+html+'</span>', text
2705
+ );
2706
+ };
2707
+ });
2708
+
2709
+ /**
2710
+ * Children and parent of MathCommand's. Basically partitions all the
2711
+ * symbols and operators that descend (in the Math DOM tree) from
2712
+ * ancestor operators.
2713
+ */
2714
+ var MathBlock = P(MathElement, function(_, super_) {
2715
+ _.join = function(methodName) {
2716
+ return this.foldChildren('', function(fold, child) {
2717
+ return fold + child[methodName]();
2718
+ });
2719
+ };
2720
+ _.html = function() { return this.join('html'); };
2721
+ _.latex = function() { return this.join('latex'); };
2722
+ _.text = function() {
2723
+ return (this.ends[L] === this.ends[R] && this.ends[L] !== 0) ?
2724
+ this.ends[L].text() :
2725
+ this.join('text')
2726
+ ;
2727
+ };
2728
+
2729
+ _.keystroke = function(key, e, ctrlr) {
2730
+ if (ctrlr.options.spaceBehavesLikeTab
2731
+ && (key === 'Spacebar' || key === 'Shift-Spacebar')) {
2732
+ e.preventDefault();
2733
+ ctrlr.escapeDir(key === 'Shift-Spacebar' ? L : R, key, e);
2734
+ return;
2735
+ }
2736
+ return super_.keystroke.apply(this, arguments);
2737
+ };
2738
+
2739
+ // editability methods: called by the cursor for editing, cursor movements,
2740
+ // and selection of the MathQuill tree, these all take in a direction and
2741
+ // the cursor
2742
+ _.moveOutOf = function(dir, cursor, updown) {
2743
+ var updownInto = updown && this.parent[updown+'Into'];
2744
+ if (!updownInto && this[dir]) cursor.insAtDirEnd(-dir, this[dir]);
2745
+ else cursor.insDirOf(dir, this.parent);
2746
+ };
2747
+ _.selectOutOf = function(dir, cursor) {
2748
+ cursor.insDirOf(dir, this.parent);
2749
+ };
2750
+ _.deleteOutOf = function(dir, cursor) {
2751
+ cursor.unwrapGramp();
2752
+ };
2753
+ _.seek = function(pageX, cursor) {
2754
+ var node = this.ends[R];
2755
+ if (!node || node.jQ.offset().left + node.jQ.outerWidth() < pageX) {
2756
+ return cursor.insAtRightEnd(this);
2757
+ }
2758
+ if (pageX < this.ends[L].jQ.offset().left) return cursor.insAtLeftEnd(this);
2759
+ while (pageX < node.jQ.offset().left) node = node[L];
2760
+ return node.seek(pageX, cursor);
2761
+ };
2762
+ _.chToCmd = function(ch) {
2763
+ var cons;
2764
+ // exclude f because it gets a dedicated command with more spacing
2765
+ if (ch.match(/^[a-eg-zA-Z]$/))
2766
+ return Letter(ch);
2767
+ else if (/^\d$/.test(ch))
2768
+ return Digit(ch);
2769
+ else if (cons = CharCmds[ch] || LatexCmds[ch])
2770
+ return cons(ch);
2771
+ else
2772
+ return VanillaSymbol(ch);
2773
+ };
2774
+ _.write = function(cursor, ch) {
2775
+ var cmd = this.chToCmd(ch);
2776
+ if (cursor.selection) cmd.replaces(cursor.replaceSelection());
2777
+ cmd.createLeftOf(cursor.show());
2778
+ };
2779
+
2780
+ _.focus = function() {
2781
+ this.jQ.addClass('mq-hasCursor');
2782
+ this.jQ.removeClass('mq-empty');
2783
+
2784
+ return this;
2785
+ };
2786
+ _.blur = function() {
2787
+ this.jQ.removeClass('mq-hasCursor');
2788
+ if (this.isEmpty())
2789
+ this.jQ.addClass('mq-empty');
2790
+
2791
+ return this;
2792
+ };
2793
+ });
2794
+
2795
+ API.StaticMath = function(APIClasses) {
2796
+ return P(APIClasses.AbstractMathQuill, function(_, super_) {
2797
+ this.RootBlock = MathBlock;
2798
+ _.__mathquillify = function() {
2799
+ super_.__mathquillify.call(this, 'mq-math-mode');
2800
+ this.__controller.delegateMouseEvents();
2801
+ this.__controller.staticMathTextareaEvents();
2802
+ return this;
2803
+ };
2804
+ _.init = function() {
2805
+ super_.init.apply(this, arguments);
2806
+ this.__controller.root.postOrder(
2807
+ 'registerInnerField', this.innerFields = [], APIClasses.MathField);
2808
+ };
2809
+ _.latex = function() {
2810
+ var returned = super_.latex.apply(this, arguments);
2811
+ if (arguments.length > 0) {
2812
+ this.__controller.root.postOrder(
2813
+ 'registerInnerField', this.innerFields = [], APIClasses.MathField);
2814
+ }
2815
+ return returned;
2816
+ };
2817
+ });
2818
+ };
2819
+
2820
+ var RootMathBlock = P(MathBlock, RootBlockMixin);
2821
+ API.MathField = function(APIClasses) {
2822
+ return P(APIClasses.EditableField, function(_, super_) {
2823
+ this.RootBlock = RootMathBlock;
2824
+ _.__mathquillify = function(opts, interfaceVersion) {
2825
+ this.config(opts);
2826
+ if (interfaceVersion > 1) this.__controller.root.reflow = noop;
2827
+ super_.__mathquillify.call(this, 'mq-editable-field mq-math-mode');
2828
+ delete this.__controller.root.reflow;
2829
+ return this;
2830
+ };
2831
+ });
2832
+ };
2833
+ /*************************************************
2834
+ * Abstract classes of text blocks
2835
+ ************************************************/
2836
+
2837
+ /**
2838
+ * Blocks of plain text, with one or two TextPiece's as children.
2839
+ * Represents flat strings of typically serif-font Roman characters, as
2840
+ * opposed to hierchical, nested, tree-structured math.
2841
+ * Wraps a single HTMLSpanElement.
2842
+ */
2843
+ var TextBlock = P(Node, function(_, super_) {
2844
+ _.ctrlSeq = '\\text';
2845
+
2846
+ _.replaces = function(replacedText) {
2847
+ if (replacedText instanceof Fragment)
2848
+ this.replacedText = replacedText.remove().jQ.text();
2849
+ else if (typeof replacedText === 'string')
2850
+ this.replacedText = replacedText;
2851
+ };
2852
+
2853
+ _.jQadd = function(jQ) {
2854
+ super_.jQadd.call(this, jQ);
2855
+ if (this.ends[L]) this.ends[L].jQadd(this.jQ[0].firstChild);
2856
+ };
2857
+
2858
+ _.createLeftOf = function(cursor) {
2859
+ var textBlock = this;
2860
+ super_.createLeftOf.call(this, cursor);
2861
+
2862
+ if (textBlock[R].siblingCreated) textBlock[R].siblingCreated(cursor.options, L);
2863
+ if (textBlock[L].siblingCreated) textBlock[L].siblingCreated(cursor.options, R);
2864
+ textBlock.bubble('reflow');
2865
+
2866
+ cursor.insAtRightEnd(textBlock);
2867
+
2868
+ if (textBlock.replacedText)
2869
+ for (var i = 0; i < textBlock.replacedText.length; i += 1)
2870
+ textBlock.write(cursor, textBlock.replacedText.charAt(i));
2871
+ };
2872
+
2873
+ _.parser = function() {
2874
+ var textBlock = this;
2875
+
2876
+ // TODO: correctly parse text mode
2877
+ var string = Parser.string;
2878
+ var regex = Parser.regex;
2879
+ var optWhitespace = Parser.optWhitespace;
2880
+ return optWhitespace
2881
+ .then(string('{')).then(regex(/^[^}]*/)).skip(string('}'))
2882
+ .map(function(text) {
2883
+ // TODO: is this the correct behavior when parsing
2884
+ // the latex \text{} ? This violates the requirement that
2885
+ // the text contents are always nonempty. Should we just
2886
+ // disown the parent node instead?
2887
+ TextPiece(text).adopt(textBlock, 0, 0);
2888
+ return textBlock;
2889
+ })
2890
+ ;
2891
+ };
2892
+
2893
+ _.textContents = function() {
2894
+ return this.foldChildren('', function(text, child) {
2895
+ return text + child.text;
2896
+ });
2897
+ };
2898
+ _.text = function() { return '"' + this.textContents() + '"'; };
2899
+ _.latex = function() { return '\\text{' + this.textContents() + '}'; };
2900
+ _.html = function() {
2901
+ return (
2902
+ '<span class="mq-text-mode" mathquill-command-id='+this.id+'>'
2903
+ + this.textContents()
2904
+ + '</span>'
2905
+ );
2906
+ };
2907
+
2908
+ // editability methods: called by the cursor for editing, cursor movements,
2909
+ // and selection of the MathQuill tree, these all take in a direction and
2910
+ // the cursor
2911
+ _.moveTowards = function(dir, cursor) { cursor.insAtDirEnd(-dir, this); };
2912
+ _.moveOutOf = function(dir, cursor) { cursor.insDirOf(dir, this); };
2913
+ _.unselectInto = _.moveTowards;
2914
+
2915
+ // TODO: make these methods part of a shared mixin or something.
2916
+ _.selectTowards = MathCommand.prototype.selectTowards;
2917
+ _.deleteTowards = MathCommand.prototype.deleteTowards;
2918
+
2919
+ _.selectOutOf = function(dir, cursor) {
2920
+ cursor.insDirOf(dir, this);
2921
+ };
2922
+ _.deleteOutOf = function(dir, cursor) {
2923
+ // backspace and delete at ends of block don't unwrap
2924
+ if (this.isEmpty()) cursor.insRightOf(this);
2925
+ };
2926
+ _.write = function(cursor, ch) {
2927
+ cursor.show().deleteSelection();
2928
+
2929
+ if (ch !== '$') {
2930
+ if (!cursor[L]) TextPiece(ch).createLeftOf(cursor);
2931
+ else cursor[L].appendText(ch);
2932
+ }
2933
+ else if (this.isEmpty()) {
2934
+ cursor.insRightOf(this);
2935
+ VanillaSymbol('\\$','$').createLeftOf(cursor);
2936
+ }
2937
+ else if (!cursor[R]) cursor.insRightOf(this);
2938
+ else if (!cursor[L]) cursor.insLeftOf(this);
2939
+ else { // split apart
2940
+ var leftBlock = TextBlock();
2941
+ var leftPc = this.ends[L];
2942
+ leftPc.disown();
2943
+ leftPc.adopt(leftBlock, 0, 0);
2944
+
2945
+ cursor.insLeftOf(this);
2946
+ super_.createLeftOf.call(leftBlock, cursor);
2947
+ }
2948
+ };
2949
+
2950
+ _.seek = function(pageX, cursor) {
2951
+ cursor.hide();
2952
+ var textPc = fuseChildren(this);
2953
+
2954
+ // insert cursor at approx position in DOMTextNode
2955
+ var avgChWidth = this.jQ.width()/this.text.length;
2956
+ var approxPosition = Math.round((pageX - this.jQ.offset().left)/avgChWidth);
2957
+ if (approxPosition <= 0) cursor.insAtLeftEnd(this);
2958
+ else if (approxPosition >= textPc.text.length) cursor.insAtRightEnd(this);
2959
+ else cursor.insLeftOf(textPc.splitRight(approxPosition));
2960
+
2961
+ // move towards mousedown (pageX)
2962
+ var displ = pageX - cursor.show().offset().left; // displacement
2963
+ var dir = displ && displ < 0 ? L : R;
2964
+ var prevDispl = dir;
2965
+ // displ * prevDispl > 0 iff displacement direction === previous direction
2966
+ while (cursor[dir] && displ * prevDispl > 0) {
2967
+ cursor[dir].moveTowards(dir, cursor);
2968
+ prevDispl = displ;
2969
+ displ = pageX - cursor.offset().left;
2970
+ }
2971
+ if (dir*displ < -dir*prevDispl) cursor[-dir].moveTowards(-dir, cursor);
2972
+
2973
+ if (!cursor.anticursor) {
2974
+ // about to start mouse-selecting, the anticursor is gonna get put here
2975
+ this.anticursorPosition = cursor[L] && cursor[L].text.length;
2976
+ // ^ get it? 'cos if there's no cursor[L], it's 0... I'm a terrible person.
2977
+ }
2978
+ else if (cursor.anticursor.parent === this) {
2979
+ // mouse-selecting within this TextBlock, re-insert the anticursor
2980
+ var cursorPosition = cursor[L] && cursor[L].text.length;;
2981
+ if (this.anticursorPosition === cursorPosition) {
2982
+ cursor.anticursor = Point.copy(cursor);
2983
+ }
2984
+ else {
2985
+ if (this.anticursorPosition < cursorPosition) {
2986
+ var newTextPc = cursor[L].splitRight(this.anticursorPosition);
2987
+ cursor[L] = newTextPc;
2988
+ }
2989
+ else {
2990
+ var newTextPc = cursor[R].splitRight(this.anticursorPosition - cursorPosition);
2991
+ }
2992
+ cursor.anticursor = Point(this, newTextPc[L], newTextPc);
2993
+ }
2994
+ }
2995
+ };
2996
+
2997
+ _.blur = function() {
2998
+ MathBlock.prototype.blur.call(this);
2999
+ fuseChildren(this);
3000
+ };
3001
+
3002
+ function fuseChildren(self) {
3003
+ self.jQ[0].normalize();
3004
+
3005
+ var textPcDom = self.jQ[0].firstChild;
3006
+ pray('only node in TextBlock span is Text node', textPcDom.nodeType === 3);
3007
+ // nodeType === 3 has meant a Text node since ancient times:
3008
+ // http://reference.sitepoint.com/javascript/Node/nodeType
3009
+
3010
+ var textPc = TextPiece(textPcDom.data);
3011
+ textPc.jQadd(textPcDom);
3012
+
3013
+ self.children().disown();
3014
+ return textPc.adopt(self, 0, 0);
3015
+ }
3016
+
3017
+ _.focus = MathBlock.prototype.focus;
3018
+ });
3019
+
3020
+ /**
3021
+ * Piece of plain text, with a TextBlock as a parent and no children.
3022
+ * Wraps a single DOMTextNode.
3023
+ * For convenience, has a .text property that's just a JavaScript string
3024
+ * mirroring the text contents of the DOMTextNode.
3025
+ * Text contents must always be nonempty.
3026
+ */
3027
+ var TextPiece = P(Node, function(_, super_) {
3028
+ _.init = function(text) {
3029
+ super_.init.call(this);
3030
+ this.text = text;
3031
+ };
3032
+ _.jQadd = function(dom) { this.dom = dom; this.jQ = $(dom); };
3033
+ _.jQize = function() {
3034
+ return this.jQadd(document.createTextNode(this.text));
3035
+ };
3036
+ _.appendText = function(text) {
3037
+ this.text += text;
3038
+ this.dom.appendData(text);
3039
+ };
3040
+ _.prependText = function(text) {
3041
+ this.text = text + this.text;
3042
+ this.dom.insertData(0, text);
3043
+ };
3044
+ _.insTextAtDirEnd = function(text, dir) {
3045
+ prayDirection(dir);
3046
+ if (dir === R) this.appendText(text);
3047
+ else this.prependText(text);
3048
+ };
3049
+ _.splitRight = function(i) {
3050
+ var newPc = TextPiece(this.text.slice(i)).adopt(this.parent, this, this[R]);
3051
+ newPc.jQadd(this.dom.splitText(i));
3052
+ this.text = this.text.slice(0, i);
3053
+ return newPc;
3054
+ };
3055
+
3056
+ function endChar(dir, text) {
3057
+ return text.charAt(dir === L ? 0 : -1 + text.length);
3058
+ }
3059
+
3060
+ _.moveTowards = function(dir, cursor) {
3061
+ prayDirection(dir);
3062
+
3063
+ var ch = endChar(-dir, this.text)
3064
+
3065
+ var from = this[-dir];
3066
+ if (from) from.insTextAtDirEnd(ch, dir);
3067
+ else TextPiece(ch).createDir(-dir, cursor);
3068
+
3069
+ return this.deleteTowards(dir, cursor);
3070
+ };
3071
+
3072
+ _.latex = function() { return this.text; };
3073
+
3074
+ _.deleteTowards = function(dir, cursor) {
3075
+ if (this.text.length > 1) {
3076
+ if (dir === R) {
3077
+ this.dom.deleteData(0, 1);
3078
+ this.text = this.text.slice(1);
3079
+ }
3080
+ else {
3081
+ // note that the order of these 2 lines is annoyingly important
3082
+ // (the second line mutates this.text.length)
3083
+ this.dom.deleteData(-1 + this.text.length, 1);
3084
+ this.text = this.text.slice(0, -1);
3085
+ }
3086
+ }
3087
+ else {
3088
+ this.remove();
3089
+ this.jQ.remove();
3090
+ cursor[dir] = this[dir];
3091
+ }
3092
+ };
3093
+
3094
+ _.selectTowards = function(dir, cursor) {
3095
+ prayDirection(dir);
3096
+ var anticursor = cursor.anticursor;
3097
+
3098
+ var ch = endChar(-dir, this.text)
3099
+
3100
+ if (anticursor[dir] === this) {
3101
+ var newPc = TextPiece(ch).createDir(dir, cursor);
3102
+ anticursor[dir] = newPc;
3103
+ cursor.insDirOf(dir, newPc);
3104
+ }
3105
+ else {
3106
+ var from = this[-dir];
3107
+ if (from) from.insTextAtDirEnd(ch, dir);
3108
+ else {
3109
+ var newPc = TextPiece(ch).createDir(-dir, cursor);
3110
+ newPc.jQ.insDirOf(-dir, cursor.selection.jQ);
3111
+ }
3112
+
3113
+ if (this.text.length === 1 && anticursor[-dir] === this) {
3114
+ anticursor[-dir] = this[-dir]; // `this` will be removed in deleteTowards
3115
+ }
3116
+ }
3117
+
3118
+ return this.deleteTowards(dir, cursor);
3119
+ };
3120
+ });
3121
+
3122
+ CharCmds.$ =
3123
+ LatexCmds.text =
3124
+ LatexCmds.textnormal =
3125
+ LatexCmds.textrm =
3126
+ LatexCmds.textup =
3127
+ LatexCmds.textmd = TextBlock;
3128
+
3129
+ function makeTextBlock(latex, tagName, attrs) {
3130
+ return P(TextBlock, {
3131
+ ctrlSeq: latex,
3132
+ htmlTemplate: '<'+tagName+' '+attrs+'>&0</'+tagName+'>'
3133
+ });
3134
+ }
3135
+
3136
+ LatexCmds.em = LatexCmds.italic = LatexCmds.italics =
3137
+ LatexCmds.emph = LatexCmds.textit = LatexCmds.textsl =
3138
+ makeTextBlock('\\textit', 'i', 'class="mq-text-mode"');
3139
+ LatexCmds.strong = LatexCmds.bold = LatexCmds.textbf =
3140
+ makeTextBlock('\\textbf', 'b', 'class="mq-text-mode"');
3141
+ LatexCmds.sf = LatexCmds.textsf =
3142
+ makeTextBlock('\\textsf', 'span', 'class="mq-sans-serif mq-text-mode"');
3143
+ LatexCmds.tt = LatexCmds.texttt =
3144
+ makeTextBlock('\\texttt', 'span', 'class="mq-monospace mq-text-mode"');
3145
+ LatexCmds.textsc =
3146
+ makeTextBlock('\\textsc', 'span', 'style="font-variant:small-caps" class="mq-text-mode"');
3147
+ LatexCmds.uppercase =
3148
+ makeTextBlock('\\uppercase', 'span', 'style="text-transform:uppercase" class="mq-text-mode"');
3149
+ LatexCmds.lowercase =
3150
+ makeTextBlock('\\lowercase', 'span', 'style="text-transform:lowercase" class="mq-text-mode"');
3151
+
3152
+
3153
+ var RootMathCommand = P(MathCommand, function(_, super_) {
3154
+ _.init = function(cursor) {
3155
+ super_.init.call(this, '$');
3156
+ this.cursor = cursor;
3157
+ };
3158
+ _.htmlTemplate = '<span class="mq-math-mode">&0</span>';
3159
+ _.createBlocks = function() {
3160
+ super_.createBlocks.call(this);
3161
+
3162
+ this.ends[L].cursor = this.cursor;
3163
+ this.ends[L].write = function(cursor, ch) {
3164
+ if (ch !== '$')
3165
+ MathBlock.prototype.write.call(this, cursor, ch);
3166
+ else if (this.isEmpty()) {
3167
+ cursor.insRightOf(this.parent);
3168
+ this.parent.deleteTowards(dir, cursor);
3169
+ VanillaSymbol('\\$','$').createLeftOf(cursor.show());
3170
+ }
3171
+ else if (!cursor[R])
3172
+ cursor.insRightOf(this.parent);
3173
+ else if (!cursor[L])
3174
+ cursor.insLeftOf(this.parent);
3175
+ else
3176
+ MathBlock.prototype.write.call(this, cursor, ch);
3177
+ };
3178
+ };
3179
+ _.latex = function() {
3180
+ return '$' + this.ends[L].latex() + '$';
3181
+ };
3182
+ });
3183
+
3184
+ var RootTextBlock = P(RootMathBlock, function(_, super_) {
3185
+ _.keystroke = function(key) {
3186
+ if (key === 'Spacebar' || key === 'Shift-Spacebar') return;
3187
+ return super_.keystroke.apply(this, arguments);
3188
+ };
3189
+ _.write = function(cursor, ch) {
3190
+ cursor.show().deleteSelection();
3191
+ if (ch === '$')
3192
+ RootMathCommand(cursor).createLeftOf(cursor);
3193
+ else {
3194
+ var html;
3195
+ if (ch === '<') html = '&lt;';
3196
+ else if (ch === '>') html = '&gt;';
3197
+ VanillaSymbol(ch, html).createLeftOf(cursor);
3198
+ }
3199
+ };
3200
+ });
3201
+ API.TextField = function(APIClasses) {
3202
+ return P(APIClasses.EditableField, function(_, super_) {
3203
+ this.RootBlock = RootTextBlock;
3204
+ _.__mathquillify = function() {
3205
+ return super_.__mathquillify.call(this, 'mq-editable-field mq-text-mode');
3206
+ };
3207
+ _.latex = function(latex) {
3208
+ if (arguments.length > 0) {
3209
+ this.__controller.renderLatexText(latex);
3210
+ if (this.__controller.blurred) this.__controller.cursor.hide().parent.blur();
3211
+ return this;
3212
+ }
3213
+ return this.__controller.exportLatex();
3214
+ };
3215
+ });
3216
+ };
3217
+ /****************************************
3218
+ * Input box to type backslash commands
3219
+ ***************************************/
3220
+
3221
+ var LatexCommandInput =
3222
+ CharCmds['\\'] = P(MathCommand, function(_, super_) {
3223
+ _.ctrlSeq = '\\';
3224
+ _.replaces = function(replacedFragment) {
3225
+ this._replacedFragment = replacedFragment.disown();
3226
+ this.isEmpty = function() { return false; };
3227
+ };
3228
+ _.htmlTemplate = '<span class="mq-latex-command-input mq-non-leaf">\\<span>&0</span></span>';
3229
+ _.textTemplate = ['\\'];
3230
+ _.createBlocks = function() {
3231
+ super_.createBlocks.call(this);
3232
+ this.ends[L].focus = function() {
3233
+ this.parent.jQ.addClass('mq-hasCursor');
3234
+ if (this.isEmpty())
3235
+ this.parent.jQ.removeClass('mq-empty');
3236
+
3237
+ return this;
3238
+ };
3239
+ this.ends[L].blur = function() {
3240
+ this.parent.jQ.removeClass('mq-hasCursor');
3241
+ if (this.isEmpty())
3242
+ this.parent.jQ.addClass('mq-empty');
3243
+
3244
+ return this;
3245
+ };
3246
+ this.ends[L].write = function(cursor, ch) {
3247
+ cursor.show().deleteSelection();
3248
+
3249
+ if (ch.match(/[a-z]/i)) VanillaSymbol(ch).createLeftOf(cursor);
3250
+ else {
3251
+ this.parent.renderCommand(cursor);
3252
+ if (ch !== '\\' || !this.isEmpty()) this.parent.parent.write(cursor, ch);
3253
+ }
3254
+ };
3255
+ this.ends[L].keystroke = function(key, e, ctrlr) {
3256
+ if (key === 'Tab' || key === 'Enter' || key === 'Spacebar') {
3257
+ this.parent.renderCommand(ctrlr.cursor);
3258
+ e.preventDefault();
3259
+ return;
3260
+ }
3261
+ return super_.keystroke.apply(this, arguments);
3262
+ };
3263
+ };
3264
+ _.createLeftOf = function(cursor) {
3265
+ super_.createLeftOf.call(this, cursor);
3266
+
3267
+ if (this._replacedFragment) {
3268
+ var el = this.jQ[0];
3269
+ this.jQ =
3270
+ this._replacedFragment.jQ.addClass('mq-blur').bind(
3271
+ 'mousedown mousemove', //FIXME: is monkey-patching the mousedown and mousemove handlers the right way to do this?
3272
+ function(e) {
3273
+ $(e.target = el).trigger(e);
3274
+ return false;
3275
+ }
3276
+ ).insertBefore(this.jQ).add(this.jQ);
3277
+ }
3278
+ };
3279
+ _.latex = function() {
3280
+ return '\\' + this.ends[L].latex() + ' ';
3281
+ };
3282
+ _.renderCommand = function(cursor) {
3283
+ this.jQ = this.jQ.last();
3284
+ this.remove();
3285
+ if (this[R]) {
3286
+ cursor.insLeftOf(this[R]);
3287
+ } else {
3288
+ cursor.insAtRightEnd(this.parent);
3289
+ }
3290
+
3291
+ var latex = this.ends[L].latex();
3292
+ if (!latex) latex = ' ';
3293
+ var cmd = LatexCmds[latex];
3294
+ if (cmd) {
3295
+ cmd = cmd(latex);
3296
+ if (this._replacedFragment) cmd.replaces(this._replacedFragment);
3297
+ cmd.createLeftOf(cursor);
3298
+ }
3299
+ else {
3300
+ cmd = TextBlock();
3301
+ cmd.replaces(latex);
3302
+ cmd.createLeftOf(cursor);
3303
+ cursor.insRightOf(cmd);
3304
+ if (this._replacedFragment)
3305
+ this._replacedFragment.remove();
3306
+ }
3307
+ };
3308
+ });
3309
+
3310
+ /************************************
3311
+ * Symbols for Advanced Mathematics
3312
+ ***********************************/
3313
+
3314
+ LatexCmds.notin =
3315
+ LatexCmds.cong =
3316
+ LatexCmds.equiv =
3317
+ LatexCmds.oplus =
3318
+ LatexCmds.otimes = P(BinaryOperator, function(_, super_) {
3319
+ _.init = function(latex) {
3320
+ super_.init.call(this, '\\'+latex+' ', '&'+latex+';');
3321
+ };
3322
+ });
3323
+
3324
+ LatexCmds['\u2260'] = LatexCmds.ne = LatexCmds.neq = bind(BinaryOperator,'\\ne ','&ne;');
3325
+
3326
+ LatexCmds.ast = LatexCmds.star = LatexCmds.loast = LatexCmds.lowast =
3327
+ bind(BinaryOperator,'\\ast ','&lowast;');
3328
+ //case 'there4 = // a special exception for this one, perhaps?
3329
+ LatexCmds.therefor = LatexCmds.therefore =
3330
+ bind(BinaryOperator,'\\therefore ','&there4;');
3331
+
3332
+ LatexCmds.cuz = // l33t
3333
+ LatexCmds.because = bind(BinaryOperator,'\\because ','&#8757;');
3334
+
3335
+ LatexCmds.prop = LatexCmds.propto = bind(BinaryOperator,'\\propto ','&prop;');
3336
+
3337
+ LatexCmds['\u2248'] = LatexCmds.asymp = LatexCmds.approx = bind(BinaryOperator,'\\approx ','&asymp;');
3338
+
3339
+ LatexCmds.isin = LatexCmds['in'] = bind(BinaryOperator,'\\in ','&isin;');
3340
+
3341
+ LatexCmds.ni = LatexCmds.contains = bind(BinaryOperator,'\\ni ','&ni;');
3342
+
3343
+ LatexCmds.notni = LatexCmds.niton = LatexCmds.notcontains = LatexCmds.doesnotcontain =
3344
+ bind(BinaryOperator,'\\not\\ni ','&#8716;');
3345
+
3346
+ LatexCmds.sub = LatexCmds.subset = bind(BinaryOperator,'\\subset ','&sub;');
3347
+
3348
+ LatexCmds.sup = LatexCmds.supset = LatexCmds.superset =
3349
+ bind(BinaryOperator,'\\supset ','&sup;');
3350
+
3351
+ LatexCmds.nsub = LatexCmds.notsub =
3352
+ LatexCmds.nsubset = LatexCmds.notsubset =
3353
+ bind(BinaryOperator,'\\not\\subset ','&#8836;');
3354
+
3355
+ LatexCmds.nsup = LatexCmds.notsup =
3356
+ LatexCmds.nsupset = LatexCmds.notsupset =
3357
+ LatexCmds.nsuperset = LatexCmds.notsuperset =
3358
+ bind(BinaryOperator,'\\not\\supset ','&#8837;');
3359
+
3360
+ LatexCmds.sube = LatexCmds.subeq = LatexCmds.subsete = LatexCmds.subseteq =
3361
+ bind(BinaryOperator,'\\subseteq ','&sube;');
3362
+
3363
+ LatexCmds.supe = LatexCmds.supeq =
3364
+ LatexCmds.supsete = LatexCmds.supseteq =
3365
+ LatexCmds.supersete = LatexCmds.superseteq =
3366
+ bind(BinaryOperator,'\\supseteq ','&supe;');
3367
+
3368
+ LatexCmds.nsube = LatexCmds.nsubeq =
3369
+ LatexCmds.notsube = LatexCmds.notsubeq =
3370
+ LatexCmds.nsubsete = LatexCmds.nsubseteq =
3371
+ LatexCmds.notsubsete = LatexCmds.notsubseteq =
3372
+ bind(BinaryOperator,'\\not\\subseteq ','&#8840;');
3373
+
3374
+ LatexCmds.nsupe = LatexCmds.nsupeq =
3375
+ LatexCmds.notsupe = LatexCmds.notsupeq =
3376
+ LatexCmds.nsupsete = LatexCmds.nsupseteq =
3377
+ LatexCmds.notsupsete = LatexCmds.notsupseteq =
3378
+ LatexCmds.nsupersete = LatexCmds.nsuperseteq =
3379
+ LatexCmds.notsupersete = LatexCmds.notsuperseteq =
3380
+ bind(BinaryOperator,'\\not\\supseteq ','&#8841;');
3381
+
3382
+
3383
+ //the canonical sets of numbers
3384
+ LatexCmds.N = LatexCmds.naturals = LatexCmds.Naturals =
3385
+ bind(VanillaSymbol,'\\mathbb{N}','&#8469;');
3386
+
3387
+ LatexCmds.P =
3388
+ LatexCmds.primes = LatexCmds.Primes =
3389
+ LatexCmds.projective = LatexCmds.Projective =
3390
+ LatexCmds.probability = LatexCmds.Probability =
3391
+ bind(VanillaSymbol,'\\mathbb{P}','&#8473;');
3392
+
3393
+ LatexCmds.Z = LatexCmds.integers = LatexCmds.Integers =
3394
+ bind(VanillaSymbol,'\\mathbb{Z}','&#8484;');
3395
+
3396
+ LatexCmds.Q = LatexCmds.rationals = LatexCmds.Rationals =
3397
+ bind(VanillaSymbol,'\\mathbb{Q}','&#8474;');
3398
+
3399
+ LatexCmds.R = LatexCmds.reals = LatexCmds.Reals =
3400
+ bind(VanillaSymbol,'\\mathbb{R}','&#8477;');
3401
+
3402
+ LatexCmds.C =
3403
+ LatexCmds.complex = LatexCmds.Complex =
3404
+ LatexCmds.complexes = LatexCmds.Complexes =
3405
+ LatexCmds.complexplane = LatexCmds.Complexplane = LatexCmds.ComplexPlane =
3406
+ bind(VanillaSymbol,'\\mathbb{C}','&#8450;');
3407
+
3408
+ LatexCmds.H = LatexCmds.Hamiltonian = LatexCmds.quaternions = LatexCmds.Quaternions =
3409
+ bind(VanillaSymbol,'\\mathbb{H}','&#8461;');
3410
+
3411
+ //spacing
3412
+ LatexCmds.quad = LatexCmds.emsp = bind(VanillaSymbol,'\\quad ',' ');
3413
+ LatexCmds.qquad = bind(VanillaSymbol,'\\qquad ',' ');
3414
+ /* spacing special characters, gonna have to implement this in LatexCommandInput::onText somehow
3415
+ case ',':
3416
+ return VanillaSymbol('\\, ',' ');
3417
+ case ':':
3418
+ return VanillaSymbol('\\: ',' ');
3419
+ case ';':
3420
+ return VanillaSymbol('\\; ',' ');
3421
+ case '!':
3422
+ return Symbol('\\! ','<span style="margin-right:-.2em"></span>');
3423
+ */
3424
+
3425
+ //binary operators
3426
+ LatexCmds.diamond = bind(VanillaSymbol, '\\diamond ', '&#9671;');
3427
+ LatexCmds.bigtriangleup = bind(VanillaSymbol, '\\bigtriangleup ', '&#9651;');
3428
+ LatexCmds.ominus = bind(VanillaSymbol, '\\ominus ', '&#8854;');
3429
+ LatexCmds.uplus = bind(VanillaSymbol, '\\uplus ', '&#8846;');
3430
+ LatexCmds.bigtriangledown = bind(VanillaSymbol, '\\bigtriangledown ', '&#9661;');
3431
+ LatexCmds.sqcap = bind(VanillaSymbol, '\\sqcap ', '&#8851;');
3432
+ LatexCmds.triangleleft = bind(VanillaSymbol, '\\triangleleft ', '&#8882;');
3433
+ LatexCmds.sqcup = bind(VanillaSymbol, '\\sqcup ', '&#8852;');
3434
+ LatexCmds.triangleright = bind(VanillaSymbol, '\\triangleright ', '&#8883;');
3435
+ //circledot is not a not real LaTex command see https://github.com/mathquill/mathquill/pull/552 for more details
3436
+ LatexCmds.odot = LatexCmds.circledot = bind(VanillaSymbol, '\\odot ', '&#8857;');
3437
+ LatexCmds.bigcirc = bind(VanillaSymbol, '\\bigcirc ', '&#9711;');
3438
+ LatexCmds.dagger = bind(VanillaSymbol, '\\dagger ', '&#0134;');
3439
+ LatexCmds.ddagger = bind(VanillaSymbol, '\\ddagger ', '&#135;');
3440
+ LatexCmds.wr = bind(VanillaSymbol, '\\wr ', '&#8768;');
3441
+ LatexCmds.amalg = bind(VanillaSymbol, '\\amalg ', '&#8720;');
3442
+
3443
+ //relationship symbols
3444
+ LatexCmds.models = bind(VanillaSymbol, '\\models ', '&#8872;');
3445
+ LatexCmds.prec = bind(VanillaSymbol, '\\prec ', '&#8826;');
3446
+ LatexCmds.succ = bind(VanillaSymbol, '\\succ ', '&#8827;');
3447
+ LatexCmds.preceq = bind(VanillaSymbol, '\\preceq ', '&#8828;');
3448
+ LatexCmds.succeq = bind(VanillaSymbol, '\\succeq ', '&#8829;');
3449
+ LatexCmds.simeq = bind(VanillaSymbol, '\\simeq ', '&#8771;');
3450
+ LatexCmds.mid = bind(VanillaSymbol, '\\mid ', '&#8739;');
3451
+ LatexCmds.ll = bind(VanillaSymbol, '\\ll ', '&#8810;');
3452
+ LatexCmds.gg = bind(VanillaSymbol, '\\gg ', '&#8811;');
3453
+ LatexCmds.parallel = bind(VanillaSymbol, '\\parallel ', '&#8741;');
3454
+ LatexCmds.nparallel = bind(VanillaSymbol, '\\nparallel ', '&#8742;');
3455
+ LatexCmds.bowtie = bind(VanillaSymbol, '\\bowtie ', '&#8904;');
3456
+ LatexCmds.sqsubset = bind(VanillaSymbol, '\\sqsubset ', '&#8847;');
3457
+ LatexCmds.sqsupset = bind(VanillaSymbol, '\\sqsupset ', '&#8848;');
3458
+ LatexCmds.smile = bind(VanillaSymbol, '\\smile ', '&#8995;');
3459
+ LatexCmds.sqsubseteq = bind(VanillaSymbol, '\\sqsubseteq ', '&#8849;');
3460
+ LatexCmds.sqsupseteq = bind(VanillaSymbol, '\\sqsupseteq ', '&#8850;');
3461
+ LatexCmds.doteq = bind(VanillaSymbol, '\\doteq ', '&#8784;');
3462
+ LatexCmds.frown = bind(VanillaSymbol, '\\frown ', '&#8994;');
3463
+ LatexCmds.vdash = bind(VanillaSymbol, '\\vdash ', '&#8870;');
3464
+ LatexCmds.dashv = bind(VanillaSymbol, '\\dashv ', '&#8867;');
3465
+ LatexCmds.nless = bind(VanillaSymbol, '\\nless ', '&#8814;');
3466
+ LatexCmds.ngtr = bind(VanillaSymbol, '\\ngtr ', '&#8815;');
3467
+
3468
+ //arrows
3469
+ LatexCmds.longleftarrow = bind(VanillaSymbol, '\\longleftarrow ', '&#8592;');
3470
+ LatexCmds.longrightarrow = bind(VanillaSymbol, '\\longrightarrow ', '&#8594;');
3471
+ LatexCmds.Longleftarrow = bind(VanillaSymbol, '\\Longleftarrow ', '&#8656;');
3472
+ LatexCmds.Longrightarrow = bind(VanillaSymbol, '\\Longrightarrow ', '&#8658;');
3473
+ LatexCmds.longleftrightarrow = bind(VanillaSymbol, '\\longleftrightarrow ', '&#8596;');
3474
+ LatexCmds.updownarrow = bind(VanillaSymbol, '\\updownarrow ', '&#8597;');
3475
+ LatexCmds.Longleftrightarrow = bind(VanillaSymbol, '\\Longleftrightarrow ', '&#8660;');
3476
+ LatexCmds.Updownarrow = bind(VanillaSymbol, '\\Updownarrow ', '&#8661;');
3477
+ LatexCmds.mapsto = bind(VanillaSymbol, '\\mapsto ', '&#8614;');
3478
+ LatexCmds.nearrow = bind(VanillaSymbol, '\\nearrow ', '&#8599;');
3479
+ LatexCmds.hookleftarrow = bind(VanillaSymbol, '\\hookleftarrow ', '&#8617;');
3480
+ LatexCmds.hookrightarrow = bind(VanillaSymbol, '\\hookrightarrow ', '&#8618;');
3481
+ LatexCmds.searrow = bind(VanillaSymbol, '\\searrow ', '&#8600;');
3482
+ LatexCmds.leftharpoonup = bind(VanillaSymbol, '\\leftharpoonup ', '&#8636;');
3483
+ LatexCmds.rightharpoonup = bind(VanillaSymbol, '\\rightharpoonup ', '&#8640;');
3484
+ LatexCmds.swarrow = bind(VanillaSymbol, '\\swarrow ', '&#8601;');
3485
+ LatexCmds.leftharpoondown = bind(VanillaSymbol, '\\leftharpoondown ', '&#8637;');
3486
+ LatexCmds.rightharpoondown = bind(VanillaSymbol, '\\rightharpoondown ', '&#8641;');
3487
+ LatexCmds.nwarrow = bind(VanillaSymbol, '\\nwarrow ', '&#8598;');
3488
+
3489
+ //Misc
3490
+ LatexCmds.ldots = bind(VanillaSymbol, '\\ldots ', '&#8230;');
3491
+ LatexCmds.cdots = bind(VanillaSymbol, '\\cdots ', '&#8943;');
3492
+ LatexCmds.vdots = bind(VanillaSymbol, '\\vdots ', '&#8942;');
3493
+ LatexCmds.ddots = bind(VanillaSymbol, '\\ddots ', '&#8945;');
3494
+ LatexCmds.surd = bind(VanillaSymbol, '\\surd ', '&#8730;');
3495
+ LatexCmds.triangle = bind(VanillaSymbol, '\\triangle ', '&#9651;');
3496
+ LatexCmds.ell = bind(VanillaSymbol, '\\ell ', '&#8467;');
3497
+ LatexCmds.top = bind(VanillaSymbol, '\\top ', '&#8868;');
3498
+ LatexCmds.flat = bind(VanillaSymbol, '\\flat ', '&#9837;');
3499
+ LatexCmds.natural = bind(VanillaSymbol, '\\natural ', '&#9838;');
3500
+ LatexCmds.sharp = bind(VanillaSymbol, '\\sharp ', '&#9839;');
3501
+ LatexCmds.wp = bind(VanillaSymbol, '\\wp ', '&#8472;');
3502
+ LatexCmds.bot = bind(VanillaSymbol, '\\bot ', '&#8869;');
3503
+ LatexCmds.clubsuit = bind(VanillaSymbol, '\\clubsuit ', '&#9827;');
3504
+ LatexCmds.diamondsuit = bind(VanillaSymbol, '\\diamondsuit ', '&#9826;');
3505
+ LatexCmds.heartsuit = bind(VanillaSymbol, '\\heartsuit ', '&#9825;');
3506
+ LatexCmds.spadesuit = bind(VanillaSymbol, '\\spadesuit ', '&#9824;');
3507
+ //not real LaTex command see https://github.com/mathquill/mathquill/pull/552 for more details
3508
+ LatexCmds.parallelogram = bind(VanillaSymbol, '\\parallelogram ', '&#9649;');
3509
+ LatexCmds.square = bind(VanillaSymbol, '\\square ', '&#11036;');
3510
+
3511
+ //variable-sized
3512
+ LatexCmds.oint = bind(VanillaSymbol, '\\oint ', '&#8750;');
3513
+ LatexCmds.bigcap = bind(VanillaSymbol, '\\bigcap ', '&#8745;');
3514
+ LatexCmds.bigcup = bind(VanillaSymbol, '\\bigcup ', '&#8746;');
3515
+ LatexCmds.bigsqcup = bind(VanillaSymbol, '\\bigsqcup ', '&#8852;');
3516
+ LatexCmds.bigvee = bind(VanillaSymbol, '\\bigvee ', '&#8744;');
3517
+ LatexCmds.bigwedge = bind(VanillaSymbol, '\\bigwedge ', '&#8743;');
3518
+ LatexCmds.bigodot = bind(VanillaSymbol, '\\bigodot ', '&#8857;');
3519
+ LatexCmds.bigotimes = bind(VanillaSymbol, '\\bigotimes ', '&#8855;');
3520
+ LatexCmds.bigoplus = bind(VanillaSymbol, '\\bigoplus ', '&#8853;');
3521
+ LatexCmds.biguplus = bind(VanillaSymbol, '\\biguplus ', '&#8846;');
3522
+
3523
+ //delimiters
3524
+ LatexCmds.lfloor = bind(VanillaSymbol, '\\lfloor ', '&#8970;');
3525
+ LatexCmds.rfloor = bind(VanillaSymbol, '\\rfloor ', '&#8971;');
3526
+ LatexCmds.lceil = bind(VanillaSymbol, '\\lceil ', '&#8968;');
3527
+ LatexCmds.rceil = bind(VanillaSymbol, '\\rceil ', '&#8969;');
3528
+ LatexCmds.opencurlybrace = LatexCmds.lbrace = bind(VanillaSymbol, '\\lbrace ', '{');
3529
+ LatexCmds.closecurlybrace = LatexCmds.rbrace = bind(VanillaSymbol, '\\rbrace ', '}');
3530
+ LatexCmds.lbrack = bind(VanillaSymbol, '[');
3531
+ LatexCmds.rbrack = bind(VanillaSymbol, ']');
3532
+
3533
+ //various symbols
3534
+ LatexCmds['\u222b'] =
3535
+ LatexCmds['int'] =
3536
+ LatexCmds.integral = bind(Symbol,'\\int ','<big>&int;</big>');
3537
+
3538
+ LatexCmds.slash = bind(VanillaSymbol, '/');
3539
+ LatexCmds.vert = bind(VanillaSymbol,'|');
3540
+ LatexCmds.perp = LatexCmds.perpendicular = bind(VanillaSymbol,'\\perp ','&perp;');
3541
+ LatexCmds.nabla = LatexCmds.del = bind(VanillaSymbol,'\\nabla ','&nabla;');
3542
+ LatexCmds.hbar = bind(VanillaSymbol,'\\hbar ','&#8463;');
3543
+
3544
+ LatexCmds.AA = LatexCmds.Angstrom = LatexCmds.angstrom =
3545
+ bind(VanillaSymbol,'\\text\\AA ','&#8491;');
3546
+
3547
+ LatexCmds.ring = LatexCmds.circ = LatexCmds.circle =
3548
+ bind(VanillaSymbol,'\\circ ','&#8728;');
3549
+
3550
+ LatexCmds.bull = LatexCmds.bullet = bind(VanillaSymbol,'\\bullet ','&bull;');
3551
+
3552
+ LatexCmds.setminus = LatexCmds.smallsetminus =
3553
+ bind(VanillaSymbol,'\\setminus ','&#8726;');
3554
+
3555
+ LatexCmds.not = //bind(Symbol,'\\not ','<span class="not">/</span>');
3556
+ LatexCmds['\u00ac'] = LatexCmds.neg = bind(VanillaSymbol,'\\neg ','&not;');
3557
+
3558
+ LatexCmds['\u2026'] = LatexCmds.dots = LatexCmds.ellip = LatexCmds.hellip =
3559
+ LatexCmds.ellipsis = LatexCmds.hellipsis =
3560
+ bind(VanillaSymbol,'\\dots ','&hellip;');
3561
+
3562
+ LatexCmds.converges =
3563
+ LatexCmds.darr = LatexCmds.dnarr = LatexCmds.dnarrow = LatexCmds.downarrow =
3564
+ bind(VanillaSymbol,'\\downarrow ','&darr;');
3565
+
3566
+ LatexCmds.dArr = LatexCmds.dnArr = LatexCmds.dnArrow = LatexCmds.Downarrow =
3567
+ bind(VanillaSymbol,'\\Downarrow ','&dArr;');
3568
+
3569
+ LatexCmds.diverges = LatexCmds.uarr = LatexCmds.uparrow =
3570
+ bind(VanillaSymbol,'\\uparrow ','&uarr;');
3571
+
3572
+ LatexCmds.uArr = LatexCmds.Uparrow = bind(VanillaSymbol,'\\Uparrow ','&uArr;');
3573
+
3574
+ LatexCmds.to = bind(BinaryOperator,'\\to ','&rarr;');
3575
+
3576
+ LatexCmds.rarr = LatexCmds.rightarrow = bind(VanillaSymbol,'\\rightarrow ','&rarr;');
3577
+
3578
+ LatexCmds.implies = bind(BinaryOperator,'\\Rightarrow ','&rArr;');
3579
+
3580
+ LatexCmds.rArr = LatexCmds.Rightarrow = bind(VanillaSymbol,'\\Rightarrow ','&rArr;');
3581
+
3582
+ LatexCmds.gets = bind(BinaryOperator,'\\gets ','&larr;');
3583
+
3584
+ LatexCmds.larr = LatexCmds.leftarrow = bind(VanillaSymbol,'\\leftarrow ','&larr;');
3585
+
3586
+ LatexCmds.impliedby = bind(BinaryOperator,'\\Leftarrow ','&lArr;');
3587
+
3588
+ LatexCmds.lArr = LatexCmds.Leftarrow = bind(VanillaSymbol,'\\Leftarrow ','&lArr;');
3589
+
3590
+ LatexCmds.harr = LatexCmds.lrarr = LatexCmds.leftrightarrow =
3591
+ bind(VanillaSymbol,'\\leftrightarrow ','&harr;');
3592
+
3593
+ LatexCmds.iff = bind(BinaryOperator,'\\Leftrightarrow ','&hArr;');
3594
+
3595
+ LatexCmds.hArr = LatexCmds.lrArr = LatexCmds.Leftrightarrow =
3596
+ bind(VanillaSymbol,'\\Leftrightarrow ','&hArr;');
3597
+
3598
+ LatexCmds.Re = LatexCmds.Real = LatexCmds.real = bind(VanillaSymbol,'\\Re ','&real;');
3599
+
3600
+ LatexCmds.Im = LatexCmds.imag =
3601
+ LatexCmds.image = LatexCmds.imagin = LatexCmds.imaginary = LatexCmds.Imaginary =
3602
+ bind(VanillaSymbol,'\\Im ','&image;');
3603
+
3604
+ LatexCmds.part = LatexCmds.partial = bind(VanillaSymbol,'\\partial ','&part;');
3605
+
3606
+ LatexCmds.infty = LatexCmds.infin = LatexCmds.infinity =
3607
+ bind(VanillaSymbol,'\\infty ','&infin;');
3608
+
3609
+ LatexCmds.alef = LatexCmds.alefsym = LatexCmds.aleph = LatexCmds.alephsym =
3610
+ bind(VanillaSymbol,'\\aleph ','&alefsym;');
3611
+
3612
+ LatexCmds.xist = //LOL
3613
+ LatexCmds.xists = LatexCmds.exist = LatexCmds.exists =
3614
+ bind(VanillaSymbol,'\\exists ','&exist;');
3615
+
3616
+ LatexCmds.and = LatexCmds.land = LatexCmds.wedge =
3617
+ bind(VanillaSymbol,'\\wedge ','&and;');
3618
+
3619
+ LatexCmds.or = LatexCmds.lor = LatexCmds.vee = bind(VanillaSymbol,'\\vee ','&or;');
3620
+
3621
+ LatexCmds.o = LatexCmds.O =
3622
+ LatexCmds.empty = LatexCmds.emptyset =
3623
+ LatexCmds.oslash = LatexCmds.Oslash =
3624
+ LatexCmds.nothing = LatexCmds.varnothing =
3625
+ bind(BinaryOperator,'\\varnothing ','&empty;');
3626
+
3627
+ LatexCmds.cup = LatexCmds.union = bind(BinaryOperator,'\\cup ','&cup;');
3628
+
3629
+ LatexCmds.cap = LatexCmds.intersect = LatexCmds.intersection =
3630
+ bind(BinaryOperator,'\\cap ','&cap;');
3631
+
3632
+ // FIXME: the correct LaTeX would be ^\circ but we can't parse that
3633
+ LatexCmds.deg = LatexCmds.degree = bind(VanillaSymbol,'\\degree ','&deg;');
3634
+
3635
+ LatexCmds.ang = LatexCmds.angle = bind(VanillaSymbol,'\\angle ','&ang;');
3636
+ LatexCmds.measuredangle = bind(VanillaSymbol,'\\measuredangle ','&#8737;');
3637
+ /*********************************
3638
+ * Symbols for Basic Mathematics
3639
+ ********************************/
3640
+
3641
+ var Digit = P(VanillaSymbol, function(_, super_) {
3642
+ _.createLeftOf = function(cursor) {
3643
+ if (cursor.options.autoSubscriptNumerals
3644
+ && cursor.parent !== cursor.parent.parent.sub
3645
+ && ((cursor[L] instanceof Variable && cursor[L].isItalic !== false)
3646
+ || (cursor[L] instanceof SupSub
3647
+ && cursor[L][L] instanceof Variable
3648
+ && cursor[L][L].isItalic !== false))) {
3649
+ LatexCmds._().createLeftOf(cursor);
3650
+ super_.createLeftOf.call(this, cursor);
3651
+ cursor.insRightOf(cursor.parent.parent);
3652
+ }
3653
+ else super_.createLeftOf.call(this, cursor);
3654
+ };
3655
+ });
3656
+
3657
+ var Variable = P(Symbol, function(_, super_) {
3658
+ _.init = function(ch, html) {
3659
+ super_.init.call(this, ch, '<var>'+(html || ch)+'</var>');
3660
+ };
3661
+ _.text = function() {
3662
+ var text = this.ctrlSeq;
3663
+ if (this[L] && !(this[L] instanceof Variable)
3664
+ && !(this[L] instanceof BinaryOperator)
3665
+ && this[L].ctrlSeq !== "\\ ")
3666
+ text = '*' + text;
3667
+ if (this[R] && !(this[R] instanceof BinaryOperator)
3668
+ && !(this[R] instanceof SupSub))
3669
+ text += '*';
3670
+ return text;
3671
+ };
3672
+ });
3673
+
3674
+ Options.p.autoCommands = { _maxLength: 0 };
3675
+ optionProcessors.autoCommands = function(cmds) {
3676
+ if (!/^[a-z]+(?: [a-z]+)*$/i.test(cmds)) {
3677
+ throw '"'+cmds+'" not a space-delimited list of only letters';
3678
+ }
3679
+ var list = cmds.split(' '), dict = {}, maxLength = 0;
3680
+ for (var i = 0; i < list.length; i += 1) {
3681
+ var cmd = list[i];
3682
+ if (cmd.length < 2) {
3683
+ throw 'autocommand "'+cmd+'" not minimum length of 2';
3684
+ }
3685
+ if (LatexCmds[cmd] === OperatorName) {
3686
+ throw '"' + cmd + '" is a built-in operator name';
3687
+ }
3688
+ dict[cmd] = 1;
3689
+ maxLength = max(maxLength, cmd.length);
3690
+ }
3691
+ dict._maxLength = maxLength;
3692
+ return dict;
3693
+ };
3694
+
3695
+ var Letter = P(Variable, function(_, super_) {
3696
+ _.init = function(ch) { return super_.init.call(this, this.letter = ch); };
3697
+ _.createLeftOf = function(cursor) {
3698
+ var autoCmds = cursor.options.autoCommands, maxLength = autoCmds._maxLength;
3699
+ if (maxLength > 0) {
3700
+ // want longest possible autocommand, so join together longest
3701
+ // sequence of letters
3702
+ var str = this.letter, l = cursor[L], i = 1;
3703
+ while (l instanceof Letter && i < maxLength) {
3704
+ str = l.letter + str, l = l[L], i += 1;
3705
+ }
3706
+ // check for an autocommand, going thru substrings longest to shortest
3707
+ while (str.length) {
3708
+ if (autoCmds.hasOwnProperty(str)) {
3709
+ for (var i = 2, l = cursor[L]; i < str.length; i += 1, l = l[L]);
3710
+ Fragment(l, cursor[L]).remove();
3711
+ cursor[L] = l[L];
3712
+ return LatexCmds[str](str).createLeftOf(cursor);
3713
+ }
3714
+ str = str.slice(1);
3715
+ }
3716
+ }
3717
+ super_.createLeftOf.apply(this, arguments);
3718
+ };
3719
+ _.italicize = function(bool) {
3720
+ this.isItalic = bool;
3721
+ this.jQ.toggleClass('mq-operator-name', !bool);
3722
+ return this;
3723
+ };
3724
+ _.finalizeTree = _.siblingDeleted = _.siblingCreated = function(opts, dir) {
3725
+ // don't auto-un-italicize if the sibling to my right changed (dir === R or
3726
+ // undefined) and it's now a Letter, it will un-italicize everyone
3727
+ if (dir !== L && this[R] instanceof Letter) return;
3728
+ this.autoUnItalicize(opts);
3729
+ };
3730
+ _.autoUnItalicize = function(opts) {
3731
+ var autoOps = opts.autoOperatorNames;
3732
+ if (autoOps._maxLength === 0) return;
3733
+ // want longest possible operator names, so join together entire contiguous
3734
+ // sequence of letters
3735
+ var str = this.letter;
3736
+ for (var l = this[L]; l instanceof Letter; l = l[L]) str = l.letter + str;
3737
+ for (var r = this[R]; r instanceof Letter; r = r[R]) str += r.letter;
3738
+
3739
+ // removeClass and delete flags from all letters before figuring out
3740
+ // which, if any, are part of an operator name
3741
+ Fragment(l[R] || this.parent.ends[L], r[L] || this.parent.ends[R]).each(function(el) {
3742
+ el.italicize(true).jQ.removeClass('mq-first mq-last');
3743
+ el.ctrlSeq = el.letter;
3744
+ });
3745
+
3746
+ // check for operator names: at each position from left to right, check
3747
+ // substrings from longest to shortest
3748
+ outer: for (var i = 0, first = l[R] || this.parent.ends[L]; i < str.length; i += 1, first = first[R]) {
3749
+ for (var len = min(autoOps._maxLength, str.length - i); len > 0; len -= 1) {
3750
+ var word = str.slice(i, i + len);
3751
+ if (autoOps.hasOwnProperty(word)) {
3752
+ for (var j = 0, letter = first; j < len; j += 1, letter = letter[R]) {
3753
+ letter.italicize(false);
3754
+ var last = letter;
3755
+ }
3756
+
3757
+ var isBuiltIn = BuiltInOpNames.hasOwnProperty(word);
3758
+ first.ctrlSeq = (isBuiltIn ? '\\' : '\\operatorname{') + first.ctrlSeq;
3759
+ last.ctrlSeq += (isBuiltIn ? ' ' : '}');
3760
+ if (TwoWordOpNames.hasOwnProperty(word)) last[L][L][L].jQ.addClass('mq-last');
3761
+ if (nonOperatorSymbol(first[L])) first.jQ.addClass('mq-first');
3762
+ if (nonOperatorSymbol(last[R])) last.jQ.addClass('mq-last');
3763
+
3764
+ i += len - 1;
3765
+ first = last;
3766
+ continue outer;
3767
+ }
3768
+ }
3769
+ }
3770
+ };
3771
+ function nonOperatorSymbol(node) {
3772
+ return node instanceof Symbol && !(node instanceof BinaryOperator);
3773
+ }
3774
+ });
3775
+ var BuiltInOpNames = {}; // the set of operator names like \sin, \cos, etc that
3776
+ // are built-into LaTeX: http://latex.wikia.com/wiki/List_of_LaTeX_symbols#Named_operators:_sin.2C_cos.2C_etc.
3777
+ // MathQuill auto-unitalicizes some operator names not in that set, like 'hcf'
3778
+ // and 'arsinh', which must be exported as \operatorname{hcf} and
3779
+ // \operatorname{arsinh}. Note: over/under line/arrow \lim variants like
3780
+ // \varlimsup are not supported
3781
+ var AutoOpNames = Options.p.autoOperatorNames = { _maxLength: 9 }; // the set
3782
+ // of operator names that MathQuill auto-unitalicizes by default; overridable
3783
+ var TwoWordOpNames = { limsup: 1, liminf: 1, projlim: 1, injlim: 1 };
3784
+ (function() {
3785
+ var mostOps = ('arg deg det dim exp gcd hom inf ker lg lim ln log max min sup'
3786
+ + ' limsup liminf injlim projlim Pr').split(' ');
3787
+ for (var i = 0; i < mostOps.length; i += 1) {
3788
+ BuiltInOpNames[mostOps[i]] = AutoOpNames[mostOps[i]] = 1;
3789
+ }
3790
+
3791
+ var builtInTrigs = // why coth but not sech and csch, LaTeX?
3792
+ 'sin cos tan arcsin arccos arctan sinh cosh tanh sec csc cot coth'.split(' ');
3793
+ for (var i = 0; i < builtInTrigs.length; i += 1) {
3794
+ BuiltInOpNames[builtInTrigs[i]] = 1;
3795
+ }
3796
+
3797
+ var autoTrigs = 'sin cos tan sec cosec csc cotan cot ctg'.split(' ');
3798
+ for (var i = 0; i < autoTrigs.length; i += 1) {
3799
+ AutoOpNames[autoTrigs[i]] =
3800
+ AutoOpNames['arc'+autoTrigs[i]] =
3801
+ AutoOpNames[autoTrigs[i]+'h'] =
3802
+ AutoOpNames['ar'+autoTrigs[i]+'h'] =
3803
+ AutoOpNames['arc'+autoTrigs[i]+'h'] = 1;
3804
+ }
3805
+
3806
+ // compat with some of the nonstandard LaTeX exported by MathQuill
3807
+ // before #247. None of these are real LaTeX commands so, seems safe
3808
+ var moreNonstandardOps = 'gcf hcf lcm proj span'.split(' ');
3809
+ for (var i = 0; i < moreNonstandardOps.length; i += 1) {
3810
+ AutoOpNames[moreNonstandardOps[i]] = 1;
3811
+ }
3812
+ }());
3813
+ optionProcessors.autoOperatorNames = function(cmds) {
3814
+ if (!/^[a-z]+(?: [a-z]+)*$/i.test(cmds)) {
3815
+ throw '"'+cmds+'" not a space-delimited list of only letters';
3816
+ }
3817
+ var list = cmds.split(' '), dict = {}, maxLength = 0;
3818
+ for (var i = 0; i < list.length; i += 1) {
3819
+ var cmd = list[i];
3820
+ if (cmd.length < 2) {
3821
+ throw '"'+cmd+'" not minimum length of 2';
3822
+ }
3823
+ dict[cmd] = 1;
3824
+ maxLength = max(maxLength, cmd.length);
3825
+ }
3826
+ dict._maxLength = maxLength;
3827
+ return dict;
3828
+ };
3829
+ var OperatorName = P(Symbol, function(_, super_) {
3830
+ _.init = function(fn) { this.ctrlSeq = fn; };
3831
+ _.createLeftOf = function(cursor) {
3832
+ var fn = this.ctrlSeq;
3833
+ for (var i = 0; i < fn.length; i += 1) {
3834
+ Letter(fn.charAt(i)).createLeftOf(cursor);
3835
+ }
3836
+ };
3837
+ _.parser = function() {
3838
+ var fn = this.ctrlSeq;
3839
+ var block = MathBlock();
3840
+ for (var i = 0; i < fn.length; i += 1) {
3841
+ Letter(fn.charAt(i)).adopt(block, block.ends[R], 0);
3842
+ }
3843
+ return Parser.succeed(block.children());
3844
+ };
3845
+ });
3846
+ for (var fn in AutoOpNames) if (AutoOpNames.hasOwnProperty(fn)) {
3847
+ LatexCmds[fn] = OperatorName;
3848
+ }
3849
+ LatexCmds.operatorname = P(MathCommand, function(_) {
3850
+ _.createLeftOf = noop;
3851
+ _.numBlocks = function() { return 1; };
3852
+ _.parser = function() {
3853
+ return latexMathParser.block.map(function(b) { return b.children(); });
3854
+ };
3855
+ });
3856
+
3857
+ LatexCmds.f = P(Letter, function(_, super_) {
3858
+ _.init = function() {
3859
+ Symbol.p.init.call(this, this.letter = 'f', '<var class="mq-f">f</var>');
3860
+ };
3861
+ _.italicize = function(bool) {
3862
+ this.jQ.html('f').toggleClass('mq-f', bool);
3863
+ return super_.italicize.apply(this, arguments);
3864
+ };
3865
+ });
3866
+
3867
+ // VanillaSymbol's
3868
+ LatexCmds[' '] = LatexCmds.space = bind(VanillaSymbol, '\\ ', '&nbsp;');
3869
+
3870
+ LatexCmds["'"] = LatexCmds.prime = bind(VanillaSymbol, "'", '&prime;');
3871
+
3872
+ LatexCmds.backslash = bind(VanillaSymbol,'\\backslash ','\\');
3873
+ if (!CharCmds['\\']) CharCmds['\\'] = LatexCmds.backslash;
3874
+
3875
+ LatexCmds.$ = bind(VanillaSymbol, '\\$', '$');
3876
+
3877
+ // does not use Symbola font
3878
+ var NonSymbolaSymbol = P(Symbol, function(_, super_) {
3879
+ _.init = function(ch, html) {
3880
+ super_.init.call(this, ch, '<span class="mq-nonSymbola">'+(html || ch)+'</span>');
3881
+ };
3882
+ });
3883
+
3884
+ LatexCmds['@'] = NonSymbolaSymbol;
3885
+ LatexCmds['&'] = bind(NonSymbolaSymbol, '\\&', '&amp;');
3886
+ LatexCmds['%'] = bind(NonSymbolaSymbol, '\\%', '%');
3887
+
3888
+ //the following are all Greek to me, but this helped a lot: http://www.ams.org/STIX/ion/stixsig03.html
3889
+
3890
+ //lowercase Greek letter variables
3891
+ LatexCmds.alpha =
3892
+ LatexCmds.beta =
3893
+ LatexCmds.gamma =
3894
+ LatexCmds.delta =
3895
+ LatexCmds.zeta =
3896
+ LatexCmds.eta =
3897
+ LatexCmds.theta =
3898
+ LatexCmds.iota =
3899
+ LatexCmds.kappa =
3900
+ LatexCmds.mu =
3901
+ LatexCmds.nu =
3902
+ LatexCmds.xi =
3903
+ LatexCmds.rho =
3904
+ LatexCmds.sigma =
3905
+ LatexCmds.tau =
3906
+ LatexCmds.chi =
3907
+ LatexCmds.psi =
3908
+ LatexCmds.omega = P(Variable, function(_, super_) {
3909
+ _.init = function(latex) {
3910
+ super_.init.call(this,'\\'+latex+' ','&'+latex+';');
3911
+ };
3912
+ });
3913
+
3914
+ //why can't anybody FUCKING agree on these
3915
+ LatexCmds.phi = //W3C or Unicode?
3916
+ bind(Variable,'\\phi ','&#981;');
3917
+
3918
+ LatexCmds.phiv = //Elsevier and 9573-13
3919
+ LatexCmds.varphi = //AMS and LaTeX
3920
+ bind(Variable,'\\varphi ','&phi;');
3921
+
3922
+ LatexCmds.epsilon = //W3C or Unicode?
3923
+ bind(Variable,'\\epsilon ','&#1013;');
3924
+
3925
+ LatexCmds.epsiv = //Elsevier and 9573-13
3926
+ LatexCmds.varepsilon = //AMS and LaTeX
3927
+ bind(Variable,'\\varepsilon ','&epsilon;');
3928
+
3929
+ LatexCmds.piv = //W3C/Unicode and Elsevier and 9573-13
3930
+ LatexCmds.varpi = //AMS and LaTeX
3931
+ bind(Variable,'\\varpi ','&piv;');
3932
+
3933
+ LatexCmds.sigmaf = //W3C/Unicode
3934
+ LatexCmds.sigmav = //Elsevier
3935
+ LatexCmds.varsigma = //LaTeX
3936
+ bind(Variable,'\\varsigma ','&sigmaf;');
3937
+
3938
+ LatexCmds.thetav = //Elsevier and 9573-13
3939
+ LatexCmds.vartheta = //AMS and LaTeX
3940
+ LatexCmds.thetasym = //W3C/Unicode
3941
+ bind(Variable,'\\vartheta ','&thetasym;');
3942
+
3943
+ LatexCmds.upsilon = //AMS and LaTeX and W3C/Unicode
3944
+ LatexCmds.upsi = //Elsevier and 9573-13
3945
+ bind(Variable,'\\upsilon ','&upsilon;');
3946
+
3947
+ //these aren't even mentioned in the HTML character entity references
3948
+ LatexCmds.gammad = //Elsevier
3949
+ LatexCmds.Gammad = //9573-13 -- WTF, right? I dunno if this was a typo in the reference (see above)
3950
+ LatexCmds.digamma = //LaTeX
3951
+ bind(Variable,'\\digamma ','&#989;');
3952
+
3953
+ LatexCmds.kappav = //Elsevier
3954
+ LatexCmds.varkappa = //AMS and LaTeX
3955
+ bind(Variable,'\\varkappa ','&#1008;');
3956
+
3957
+ LatexCmds.rhov = //Elsevier and 9573-13
3958
+ LatexCmds.varrho = //AMS and LaTeX
3959
+ bind(Variable,'\\varrho ','&#1009;');
3960
+
3961
+ //Greek constants, look best in non-italicized Times New Roman
3962
+ LatexCmds.pi = LatexCmds['\u03c0'] = bind(NonSymbolaSymbol,'\\pi ','&pi;');
3963
+ LatexCmds.lambda = bind(NonSymbolaSymbol,'\\lambda ','&lambda;');
3964
+
3965
+ //uppercase greek letters
3966
+
3967
+ LatexCmds.Upsilon = //LaTeX
3968
+ LatexCmds.Upsi = //Elsevier and 9573-13
3969
+ LatexCmds.upsih = //W3C/Unicode "upsilon with hook"
3970
+ LatexCmds.Upsih = //'cos it makes sense to me
3971
+ bind(Symbol,'\\Upsilon ','<var style="font-family: serif">&upsih;</var>'); //Symbola's 'upsilon with a hook' is a capital Y without hooks :(
3972
+
3973
+ //other symbols with the same LaTeX command and HTML character entity reference
3974
+ LatexCmds.Gamma =
3975
+ LatexCmds.Delta =
3976
+ LatexCmds.Theta =
3977
+ LatexCmds.Lambda =
3978
+ LatexCmds.Xi =
3979
+ LatexCmds.Pi =
3980
+ LatexCmds.Sigma =
3981
+ LatexCmds.Phi =
3982
+ LatexCmds.Psi =
3983
+ LatexCmds.Omega =
3984
+ LatexCmds.forall = P(VanillaSymbol, function(_, super_) {
3985
+ _.init = function(latex) {
3986
+ super_.init.call(this,'\\'+latex+' ','&'+latex+';');
3987
+ };
3988
+ });
3989
+
3990
+ // symbols that aren't a single MathCommand, but are instead a whole
3991
+ // Fragment. Creates the Fragment from a LaTeX string
3992
+ var LatexFragment = P(MathCommand, function(_) {
3993
+ _.init = function(latex) { this.latex = latex; };
3994
+ _.createLeftOf = function(cursor) {
3995
+ var block = latexMathParser.parse(this.latex);
3996
+ block.children().adopt(cursor.parent, cursor[L], cursor[R]);
3997
+ cursor[L] = block.ends[R];
3998
+ block.jQize().insertBefore(cursor.jQ);
3999
+ block.finalizeInsert(cursor.options, cursor);
4000
+ if (block.ends[R][R].siblingCreated) block.ends[R][R].siblingCreated(cursor.options, L);
4001
+ if (block.ends[L][L].siblingCreated) block.ends[L][L].siblingCreated(cursor.options, R);
4002
+ cursor.parent.bubble('reflow');
4003
+ };
4004
+ _.parser = function() {
4005
+ var frag = latexMathParser.parse(this.latex).children();
4006
+ return Parser.succeed(frag);
4007
+ };
4008
+ });
4009
+
4010
+ // for what seems to me like [stupid reasons][1], Unicode provides
4011
+ // subscripted and superscripted versions of all ten Arabic numerals,
4012
+ // as well as [so-called "vulgar fractions"][2].
4013
+ // Nobody really cares about most of them, but some of them actually
4014
+ // predate Unicode, dating back to [ISO-8859-1][3], apparently also
4015
+ // known as "Latin-1", which among other things [Windows-1252][4]
4016
+ // largely coincides with, so Microsoft Word sometimes inserts them
4017
+ // and they get copy-pasted into MathQuill.
4018
+ //
4019
+ // (Irrelevant but funny story: though not a superset of Latin-1 aka
4020
+ // ISO-8859-1, Windows-1252 **is** a strict superset of the "closely
4021
+ // related but distinct"[3] "ISO 8859-1" -- see the lack of a dash
4022
+ // after "ISO"? Completely different character set, like elephants vs
4023
+ // elephant seals, or "Zombies" vs "Zombie Redneck Torture Family".
4024
+ // What kind of idiot would get them confused.
4025
+ // People in fact got them confused so much, it was so common to
4026
+ // mislabel Windows-1252 text as ISO-8859-1, that most modern web
4027
+ // browsers and email clients treat the MIME charset of ISO-8859-1
4028
+ // as actually Windows-1252, behavior now standard in the HTML5 spec.)
4029
+ //
4030
+ // [1]: http://en.wikipedia.org/wiki/Unicode_subscripts_andsuper_scripts
4031
+ // [2]: http://en.wikipedia.org/wiki/Number_Forms
4032
+ // [3]: http://en.wikipedia.org/wiki/ISO/IEC_8859-1
4033
+ // [4]: http://en.wikipedia.org/wiki/Windows-1252
4034
+ LatexCmds['\u00b9'] = bind(LatexFragment, '^1');
4035
+ LatexCmds['\u00b2'] = bind(LatexFragment, '^2');
4036
+ LatexCmds['\u00b3'] = bind(LatexFragment, '^3');
4037
+ LatexCmds['\u00bc'] = bind(LatexFragment, '\\frac14');
4038
+ LatexCmds['\u00bd'] = bind(LatexFragment, '\\frac12');
4039
+ LatexCmds['\u00be'] = bind(LatexFragment, '\\frac34');
4040
+
4041
+ var PlusMinus = P(BinaryOperator, function(_) {
4042
+ _.init = VanillaSymbol.prototype.init;
4043
+
4044
+ _.contactWeld = _.siblingCreated = _.siblingDeleted = function(opts, dir) {
4045
+ if (dir === R) return; // ignore if sibling only changed on the right
4046
+ this.jQ[0].className =
4047
+ (!this[L] || this[L] instanceof BinaryOperator ? '' : 'mq-binary-operator');
4048
+ return this;
4049
+ };
4050
+ });
4051
+
4052
+ LatexCmds['+'] = bind(PlusMinus, '+', '+');
4053
+ //yes, these are different dashes, I think one is an en dash and the other is a hyphen
4054
+ LatexCmds['\u2013'] = LatexCmds['-'] = bind(PlusMinus, '-', '&minus;');
4055
+ LatexCmds['\u00b1'] = LatexCmds.pm = LatexCmds.plusmn = LatexCmds.plusminus =
4056
+ bind(PlusMinus,'\\pm ','&plusmn;');
4057
+ LatexCmds.mp = LatexCmds.mnplus = LatexCmds.minusplus =
4058
+ bind(PlusMinus,'\\mp ','&#8723;');
4059
+
4060
+ CharCmds['*'] = LatexCmds.sdot = LatexCmds.cdot =
4061
+ bind(BinaryOperator, '\\cdot ', '&middot;', '*');
4062
+ //semantically should be &sdot;, but &middot; looks better
4063
+
4064
+ var Inequality = P(BinaryOperator, function(_, super_) {
4065
+ _.init = function(data, strict) {
4066
+ this.data = data;
4067
+ this.strict = strict;
4068
+ var strictness = (strict ? 'Strict' : '');
4069
+ super_.init.call(this, data['ctrlSeq'+strictness], data['html'+strictness],
4070
+ data['text'+strictness]);
4071
+ };
4072
+ _.swap = function(strict) {
4073
+ this.strict = strict;
4074
+ var strictness = (strict ? 'Strict' : '');
4075
+ this.ctrlSeq = this.data['ctrlSeq'+strictness];
4076
+ this.jQ.html(this.data['html'+strictness]);
4077
+ this.textTemplate = [ this.data['text'+strictness] ];
4078
+ };
4079
+ _.deleteTowards = function(dir, cursor) {
4080
+ if (dir === L && !this.strict) {
4081
+ this.swap(true);
4082
+ this.bubble('reflow');
4083
+ return;
4084
+ }
4085
+ super_.deleteTowards.apply(this, arguments);
4086
+ };
4087
+ });
4088
+
4089
+ var less = { ctrlSeq: '\\le ', html: '&le;', text: '\u2264',
4090
+ ctrlSeqStrict: '<', htmlStrict: '&lt;', textStrict: '<' };
4091
+ var greater = { ctrlSeq: '\\ge ', html: '&ge;', text: '\u2265',
4092
+ ctrlSeqStrict: '>', htmlStrict: '&gt;', textStrict: '>' };
4093
+
4094
+ LatexCmds['<'] = LatexCmds.lt = bind(Inequality, less, true);
4095
+ LatexCmds['>'] = LatexCmds.gt = bind(Inequality, greater, true);
4096
+ LatexCmds['\u2264'] = LatexCmds.le = LatexCmds.leq = bind(Inequality, less, false);
4097
+ LatexCmds['\u2265'] = LatexCmds.ge = LatexCmds.geq = bind(Inequality, greater, false);
4098
+
4099
+ var Equality = P(BinaryOperator, function(_, super_) {
4100
+ _.init = function() {
4101
+ super_.init.call(this, '=', '=');
4102
+ };
4103
+ _.createLeftOf = function(cursor) {
4104
+ if (cursor[L] instanceof Inequality && cursor[L].strict) {
4105
+ cursor[L].swap(false);
4106
+ cursor[L].bubble('reflow');
4107
+ return;
4108
+ }
4109
+ super_.createLeftOf.apply(this, arguments);
4110
+ };
4111
+ });
4112
+ LatexCmds['='] = Equality;
4113
+
4114
+ LatexCmds['\u00d7'] = LatexCmds.times = bind(BinaryOperator, '\\times ', '&times;', '[x]');
4115
+
4116
+ LatexCmds['\u00f7'] = LatexCmds.div = LatexCmds.divide = LatexCmds.divides =
4117
+ bind(BinaryOperator,'\\div ','&divide;', '[/]');
4118
+
4119
+ CharCmds['~'] = LatexCmds.sim = bind(BinaryOperator, '\\sim ', '~', '~');
4120
+ /***************************
4121
+ * Commands and Operators.
4122
+ **************************/
4123
+
4124
+ var scale, // = function(jQ, x, y) { ... }
4125
+ //will use a CSS 2D transform to scale the jQuery-wrapped HTML elements,
4126
+ //or the filter matrix transform fallback for IE 5.5-8, or gracefully degrade to
4127
+ //increasing the fontSize to match the vertical Y scaling factor.
4128
+
4129
+ //ideas from http://github.com/louisremi/jquery.transform.js
4130
+ //see also http://msdn.microsoft.com/en-us/library/ms533014(v=vs.85).aspx
4131
+
4132
+ forceIERedraw = noop,
4133
+ div = document.createElement('div'),
4134
+ div_style = div.style,
4135
+ transformPropNames = {
4136
+ transform:1,
4137
+ WebkitTransform:1,
4138
+ MozTransform:1,
4139
+ OTransform:1,
4140
+ msTransform:1
4141
+ },
4142
+ transformPropName;
4143
+
4144
+ for (var prop in transformPropNames) {
4145
+ if (prop in div_style) {
4146
+ transformPropName = prop;
4147
+ break;
4148
+ }
4149
+ }
4150
+
4151
+ if (transformPropName) {
4152
+ scale = function(jQ, x, y) {
4153
+ jQ.css(transformPropName, 'scale('+x+','+y+')');
4154
+ };
4155
+ }
4156
+ else if ('filter' in div_style) { //IE 6, 7, & 8 fallback, see https://github.com/laughinghan/mathquill/wiki/Transforms
4157
+ forceIERedraw = function(el){ el.className = el.className; };
4158
+ scale = function(jQ, x, y) { //NOTE: assumes y > x
4159
+ x /= (1+(y-1)/2);
4160
+ jQ.css('fontSize', y + 'em');
4161
+ if (!jQ.hasClass('mq-matrixed-container')) {
4162
+ jQ.addClass('mq-matrixed-container')
4163
+ .wrapInner('<span class="mq-matrixed"></span>');
4164
+ }
4165
+ var innerjQ = jQ.children()
4166
+ .css('filter', 'progid:DXImageTransform.Microsoft'
4167
+ + '.Matrix(M11=' + x + ",SizingMethod='auto expand')"
4168
+ );
4169
+ function calculateMarginRight() {
4170
+ jQ.css('marginRight', (innerjQ.width()-1)*(x-1)/x + 'px');
4171
+ }
4172
+ calculateMarginRight();
4173
+ var intervalId = setInterval(calculateMarginRight);
4174
+ $(window).load(function() {
4175
+ clearTimeout(intervalId);
4176
+ calculateMarginRight();
4177
+ });
4178
+ };
4179
+ }
4180
+ else {
4181
+ scale = function(jQ, x, y) {
4182
+ jQ.css('fontSize', y + 'em');
4183
+ };
4184
+ }
4185
+
4186
+ var Style = P(MathCommand, function(_, super_) {
4187
+ _.init = function(ctrlSeq, tagName, attrs) {
4188
+ super_.init.call(this, ctrlSeq, '<'+tagName+' '+attrs+'>&0</'+tagName+'>');
4189
+ };
4190
+ });
4191
+
4192
+ //fonts
4193
+ LatexCmds.mathrm = bind(Style, '\\mathrm', 'span', 'class="mq-roman mq-font"');
4194
+ LatexCmds.mathit = bind(Style, '\\mathit', 'i', 'class="mq-font"');
4195
+ LatexCmds.mathbf = bind(Style, '\\mathbf', 'b', 'class="mq-font"');
4196
+ LatexCmds.mathsf = bind(Style, '\\mathsf', 'span', 'class="mq-sans-serif mq-font"');
4197
+ LatexCmds.mathtt = bind(Style, '\\mathtt', 'span', 'class="mq-monospace mq-font"');
4198
+ //text-decoration
4199
+ LatexCmds.underline = bind(Style, '\\underline', 'span', 'class="mq-non-leaf mq-underline"');
4200
+ LatexCmds.overline = LatexCmds.bar = bind(Style, '\\overline', 'span', 'class="mq-non-leaf mq-overline"');
4201
+ LatexCmds.overrightarrow = bind(Style, '\\overrightarrow', 'span', 'class="mq-non-leaf mq-overarrow mq-arrow-right"');
4202
+ LatexCmds.overleftarrow = bind(Style, '\\overleftarrow', 'span', 'class="mq-non-leaf mq-overarrow mq-arrow-left"');
4203
+
4204
+ // `\textcolor{color}{math}` will apply a color to the given math content, where
4205
+ // `color` is any valid CSS Color Value (see [SitePoint docs][] (recommended),
4206
+ // [Mozilla docs][], or [W3C spec][]).
4207
+ //
4208
+ // [SitePoint docs]: http://reference.sitepoint.com/css/colorvalues
4209
+ // [Mozilla docs]: https://developer.mozilla.org/en-US/docs/CSS/color_value#Values
4210
+ // [W3C spec]: http://dev.w3.org/csswg/css3-color/#colorunits
4211
+ var TextColor = LatexCmds.textcolor = P(MathCommand, function(_, super_) {
4212
+ _.setColor = function(color) {
4213
+ this.color = color;
4214
+ this.htmlTemplate =
4215
+ '<span class="mq-textcolor" style="color:' + color + '">&0</span>';
4216
+ };
4217
+ _.latex = function() {
4218
+ return '\\textcolor{' + this.color + '}{' + this.blocks[0].latex() + '}';
4219
+ };
4220
+ _.parser = function() {
4221
+ var self = this;
4222
+ var optWhitespace = Parser.optWhitespace;
4223
+ var string = Parser.string;
4224
+ var regex = Parser.regex;
4225
+
4226
+ return optWhitespace
4227
+ .then(string('{'))
4228
+ .then(regex(/^[#\w\s.,()%-]*/))
4229
+ .skip(string('}'))
4230
+ .then(function(color) {
4231
+ self.setColor(color);
4232
+ return super_.parser.call(self);
4233
+ })
4234
+ ;
4235
+ };
4236
+ });
4237
+
4238
+ // Very similar to the \textcolor command, but will add the given CSS class.
4239
+ // Usage: \class{classname}{math}
4240
+ // Note regex that whitelists valid CSS classname characters:
4241
+ // https://github.com/mathquill/mathquill/pull/191#discussion_r4327442
4242
+ var Class = LatexCmds['class'] = P(MathCommand, function(_, super_) {
4243
+ _.parser = function() {
4244
+ var self = this, string = Parser.string, regex = Parser.regex;
4245
+ return Parser.optWhitespace
4246
+ .then(string('{'))
4247
+ .then(regex(/^[-\w\s\\\xA0-\xFF]*/))
4248
+ .skip(string('}'))
4249
+ .then(function(cls) {
4250
+ self.htmlTemplate = '<span class="mq-class '+cls+'">&0</span>';
4251
+ return super_.parser.call(self);
4252
+ })
4253
+ ;
4254
+ };
4255
+ });
4256
+
4257
+ var SupSub = P(MathCommand, function(_, super_) {
4258
+ _.ctrlSeq = '_{...}^{...}';
4259
+ _.createLeftOf = function(cursor) {
4260
+ if (!cursor[L] && cursor.options.supSubsRequireOperand) return;
4261
+ return super_.createLeftOf.apply(this, arguments);
4262
+ };
4263
+ _.contactWeld = function(cursor) {
4264
+ // Look on either side for a SupSub, if one is found compare my
4265
+ // .sub, .sup with its .sub, .sup. If I have one that it doesn't,
4266
+ // then call .addBlock() on it with my block; if I have one that
4267
+ // it also has, then insert my block's children into its block,
4268
+ // unless my block has none, in which case insert the cursor into
4269
+ // its block (and not mine, I'm about to remove myself) in the case
4270
+ // I was just typed.
4271
+ // TODO: simplify
4272
+
4273
+ // equiv. to [L, R].forEach(function(dir) { ... });
4274
+ for (var dir = L; dir; dir = (dir === L ? R : false)) {
4275
+ if (this[dir] instanceof SupSub) {
4276
+ // equiv. to 'sub sup'.split(' ').forEach(function(supsub) { ... });
4277
+ for (var supsub = 'sub'; supsub; supsub = (supsub === 'sub' ? 'sup' : false)) {
4278
+ var src = this[supsub], dest = this[dir][supsub];
4279
+ if (!src) continue;
4280
+ if (!dest) this[dir].addBlock(src.disown());
4281
+ else if (!src.isEmpty()) { // ins src children at -dir end of dest
4282
+ src.jQ.children().insAtDirEnd(-dir, dest.jQ);
4283
+ var children = src.children().disown();
4284
+ var pt = Point(dest, children.ends[R], dest.ends[L]);
4285
+ if (dir === L) children.adopt(dest, dest.ends[R], 0);
4286
+ else children.adopt(dest, 0, dest.ends[L]);
4287
+ }
4288
+ else var pt = Point(dest, 0, dest.ends[L]);
4289
+ this.placeCursor = (function(dest, src) { // TODO: don't monkey-patch
4290
+ return function(cursor) { cursor.insAtDirEnd(-dir, dest || src); };
4291
+ }(dest, src));
4292
+ }
4293
+ this.remove();
4294
+ if (cursor && cursor[L] === this) {
4295
+ if (dir === R && pt) {
4296
+ pt[L] ? cursor.insRightOf(pt[L]) : cursor.insAtLeftEnd(pt.parent);
4297
+ }
4298
+ else cursor.insRightOf(this[dir]);
4299
+ }
4300
+ break;
4301
+ }
4302
+ }
4303
+ this.respace();
4304
+ };
4305
+ Options.p.charsThatBreakOutOfSupSub = '';
4306
+ _.finalizeTree = function() {
4307
+ this.ends[L].write = function(cursor, ch) {
4308
+ if (cursor.options.autoSubscriptNumerals && this === this.parent.sub) {
4309
+ if (ch === '_') return;
4310
+ var cmd = this.chToCmd(ch);
4311
+ if (cmd instanceof Symbol) cursor.deleteSelection();
4312
+ else cursor.clearSelection().insRightOf(this.parent);
4313
+ return cmd.createLeftOf(cursor.show());
4314
+ }
4315
+ if (cursor[L] && !cursor[R] && !cursor.selection
4316
+ && cursor.options.charsThatBreakOutOfSupSub.indexOf(ch) > -1) {
4317
+ cursor.insRightOf(this.parent);
4318
+ }
4319
+ MathBlock.p.write.apply(this, arguments);
4320
+ };
4321
+ };
4322
+ _.moveTowards = function(dir, cursor, updown) {
4323
+ if (cursor.options.autoSubscriptNumerals && !this.sup) {
4324
+ cursor.insDirOf(dir, this);
4325
+ }
4326
+ else super_.moveTowards.apply(this, arguments);
4327
+ };
4328
+ _.deleteTowards = function(dir, cursor) {
4329
+ if (cursor.options.autoSubscriptNumerals && this.sub) {
4330
+ var cmd = this.sub.ends[-dir];
4331
+ if (cmd instanceof Symbol) cmd.remove();
4332
+ else if (cmd) cmd.deleteTowards(dir, cursor.insAtDirEnd(-dir, this.sub));
4333
+
4334
+ // TODO: factor out a .removeBlock() or something
4335
+ if (this.sub.isEmpty()) {
4336
+ this.sub.deleteOutOf(L, cursor.insAtLeftEnd(this.sub));
4337
+ if (this.sup) cursor.insDirOf(-dir, this);
4338
+ // Note `-dir` because in e.g. x_1^2| want backspacing (leftward)
4339
+ // to delete the 1 but to end up rightward of x^2; with non-negated
4340
+ // `dir` (try it), the cursor appears to have gone "through" the ^2.
4341
+ }
4342
+ }
4343
+ else super_.deleteTowards.apply(this, arguments);
4344
+ };
4345
+ _.latex = function() {
4346
+ function latex(prefix, block) {
4347
+ var l = block && block.latex();
4348
+ return block ? prefix + (l.length === 1 ? l : '{' + (l || ' ') + '}') : '';
4349
+ }
4350
+ return latex('_', this.sub) + latex('^', this.sup);
4351
+ };
4352
+ _.respace = _.siblingCreated = _.siblingDeleted = function(opts, dir) {
4353
+ if (dir === R) return; // ignore if sibling only changed on the right
4354
+ this.jQ.toggleClass('mq-limit', this[L].ctrlSeq === '\\int ');
4355
+ };
4356
+ _.addBlock = function(block) {
4357
+ if (this.supsub === 'sub') {
4358
+ this.sup = this.upInto = this.sub.upOutOf = block;
4359
+ block.adopt(this, this.sub, 0).downOutOf = this.sub;
4360
+ block.jQ = $('<span class="mq-sup"/>').append(block.jQ.children())
4361
+ .attr(mqBlockId, block.id).prependTo(this.jQ);
4362
+ }
4363
+ else {
4364
+ this.sub = this.downInto = this.sup.downOutOf = block;
4365
+ block.adopt(this, 0, this.sup).upOutOf = this.sup;
4366
+ block.jQ = $('<span class="mq-sub"></span>').append(block.jQ.children())
4367
+ .attr(mqBlockId, block.id).appendTo(this.jQ.removeClass('mq-sup-only'));
4368
+ this.jQ.append('<span style="display:inline-block;width:0">&#8203;</span>');
4369
+ }
4370
+ // like 'sub sup'.split(' ').forEach(function(supsub) { ... });
4371
+ for (var i = 0; i < 2; i += 1) (function(cmd, supsub, oppositeSupsub, updown) {
4372
+ cmd[supsub].deleteOutOf = function(dir, cursor) {
4373
+ cursor.insDirOf((this[dir] ? -dir : dir), this.parent);
4374
+ if (!this.isEmpty()) {
4375
+ var end = this.ends[dir];
4376
+ this.children().disown()
4377
+ .withDirAdopt(dir, cursor.parent, cursor[dir], cursor[-dir])
4378
+ .jQ.insDirOf(-dir, cursor.jQ);
4379
+ cursor[-dir] = end;
4380
+ }
4381
+ cmd.supsub = oppositeSupsub;
4382
+ delete cmd[supsub];
4383
+ delete cmd[updown+'Into'];
4384
+ cmd[oppositeSupsub][updown+'OutOf'] = insLeftOfMeUnlessAtEnd;
4385
+ delete cmd[oppositeSupsub].deleteOutOf;
4386
+ if (supsub === 'sub') $(cmd.jQ.addClass('mq-sup-only')[0].lastChild).remove();
4387
+ this.remove();
4388
+ };
4389
+ }(this, 'sub sup'.split(' ')[i], 'sup sub'.split(' ')[i], 'down up'.split(' ')[i]));
4390
+ };
4391
+ });
4392
+
4393
+ function insLeftOfMeUnlessAtEnd(cursor) {
4394
+ // cursor.insLeftOf(cmd), unless cursor at the end of block, and every
4395
+ // ancestor cmd is at the end of every ancestor block
4396
+ var cmd = this.parent, ancestorCmd = cursor;
4397
+ do {
4398
+ if (ancestorCmd[R]) return cursor.insLeftOf(cmd);
4399
+ ancestorCmd = ancestorCmd.parent.parent;
4400
+ } while (ancestorCmd !== cmd);
4401
+ cursor.insRightOf(cmd);
4402
+ }
4403
+
4404
+ LatexCmds.subscript =
4405
+ LatexCmds._ = P(SupSub, function(_, super_) {
4406
+ _.supsub = 'sub';
4407
+ _.htmlTemplate =
4408
+ '<span class="mq-supsub mq-non-leaf">'
4409
+ + '<span class="mq-sub">&0</span>'
4410
+ + '<span style="display:inline-block;width:0">&#8203;</span>'
4411
+ + '</span>'
4412
+ ;
4413
+ _.textTemplate = [ '_' ];
4414
+ _.finalizeTree = function() {
4415
+ this.downInto = this.sub = this.ends[L];
4416
+ this.sub.upOutOf = insLeftOfMeUnlessAtEnd;
4417
+ super_.finalizeTree.call(this);
4418
+ };
4419
+ });
4420
+
4421
+ LatexCmds.superscript =
4422
+ LatexCmds.supscript =
4423
+ LatexCmds['^'] = P(SupSub, function(_, super_) {
4424
+ _.supsub = 'sup';
4425
+ _.htmlTemplate =
4426
+ '<span class="mq-supsub mq-non-leaf mq-sup-only">'
4427
+ + '<span class="mq-sup">&0</span>'
4428
+ + '</span>'
4429
+ ;
4430
+ _.textTemplate = [ '^' ];
4431
+ _.finalizeTree = function() {
4432
+ this.upInto = this.sup = this.ends[R];
4433
+ this.sup.downOutOf = insLeftOfMeUnlessAtEnd;
4434
+ super_.finalizeTree.call(this);
4435
+ };
4436
+ });
4437
+
4438
+ var SummationNotation = P(MathCommand, function(_, super_) {
4439
+ _.init = function(ch, html) {
4440
+ var htmlTemplate =
4441
+ '<span class="mq-large-operator mq-non-leaf">'
4442
+ + '<span class="mq-to"><span>&1</span></span>'
4443
+ + '<big>'+html+'</big>'
4444
+ + '<span class="mq-from"><span>&0</span></span>'
4445
+ + '</span>'
4446
+ ;
4447
+ Symbol.prototype.init.call(this, ch, htmlTemplate);
4448
+ };
4449
+ _.createLeftOf = function(cursor) {
4450
+ super_.createLeftOf.apply(this, arguments);
4451
+ if (cursor.options.sumStartsWithNEquals) {
4452
+ Letter('n').createLeftOf(cursor);
4453
+ Equality().createLeftOf(cursor);
4454
+ }
4455
+ };
4456
+ _.latex = function() {
4457
+ function simplify(latex) {
4458
+ return latex.length === 1 ? latex : '{' + (latex || ' ') + '}';
4459
+ }
4460
+ return this.ctrlSeq + '_' + simplify(this.ends[L].latex()) +
4461
+ '^' + simplify(this.ends[R].latex());
4462
+ };
4463
+ _.parser = function() {
4464
+ var string = Parser.string;
4465
+ var optWhitespace = Parser.optWhitespace;
4466
+ var succeed = Parser.succeed;
4467
+ var block = latexMathParser.block;
4468
+
4469
+ var self = this;
4470
+ var blocks = self.blocks = [ MathBlock(), MathBlock() ];
4471
+ for (var i = 0; i < blocks.length; i += 1) {
4472
+ blocks[i].adopt(self, self.ends[R], 0);
4473
+ }
4474
+
4475
+ return optWhitespace.then(string('_').or(string('^'))).then(function(supOrSub) {
4476
+ var child = blocks[supOrSub === '_' ? 0 : 1];
4477
+ return block.then(function(block) {
4478
+ block.children().adopt(child, child.ends[R], 0);
4479
+ return succeed(self);
4480
+ });
4481
+ }).many().result(self);
4482
+ };
4483
+ _.finalizeTree = function() {
4484
+ this.downInto = this.ends[L];
4485
+ this.upInto = this.ends[R];
4486
+ this.ends[L].upOutOf = this.ends[R];
4487
+ this.ends[R].downOutOf = this.ends[L];
4488
+ };
4489
+ });
4490
+
4491
+ LatexCmds['\u2211'] =
4492
+ LatexCmds.sum =
4493
+ LatexCmds.summation = bind(SummationNotation,'\\sum ','&sum;');
4494
+
4495
+ LatexCmds['\u220f'] =
4496
+ LatexCmds.prod =
4497
+ LatexCmds.product = bind(SummationNotation,'\\prod ','&prod;');
4498
+
4499
+ LatexCmds.coprod =
4500
+ LatexCmds.coproduct = bind(SummationNotation,'\\coprod ','&#8720;');
4501
+
4502
+ var Fraction =
4503
+ LatexCmds.frac =
4504
+ LatexCmds.dfrac =
4505
+ LatexCmds.cfrac =
4506
+ LatexCmds.fraction = P(MathCommand, function(_, super_) {
4507
+ _.ctrlSeq = '\\frac';
4508
+ _.htmlTemplate =
4509
+ '<span class="mq-fraction mq-non-leaf">'
4510
+ + '<span class="mq-numerator">&0</span>'
4511
+ + '<span class="mq-denominator">&1</span>'
4512
+ + '<span style="display:inline-block;width:0">&#8203;</span>'
4513
+ + '</span>'
4514
+ ;
4515
+ _.textTemplate = ['(', ')/(', ')'];
4516
+ _.finalizeTree = function() {
4517
+ this.upInto = this.ends[R].upOutOf = this.ends[L];
4518
+ this.downInto = this.ends[L].downOutOf = this.ends[R];
4519
+ };
4520
+ });
4521
+
4522
+ var LiveFraction =
4523
+ LatexCmds.over =
4524
+ CharCmds['/'] = P(Fraction, function(_, super_) {
4525
+ _.createLeftOf = function(cursor) {
4526
+ if (!this.replacedFragment) {
4527
+ var leftward = cursor[L];
4528
+ while (leftward &&
4529
+ !(
4530
+ leftward instanceof BinaryOperator ||
4531
+ leftward instanceof (LatexCmds.text || noop) ||
4532
+ leftward instanceof SummationNotation ||
4533
+ leftward.ctrlSeq === '\\ ' ||
4534
+ /^[,;:]$/.test(leftward.ctrlSeq)
4535
+ ) //lookbehind for operator
4536
+ ) leftward = leftward[L];
4537
+
4538
+ if (leftward instanceof SummationNotation && leftward[R] instanceof SupSub) {
4539
+ leftward = leftward[R];
4540
+ if (leftward[R] instanceof SupSub && leftward[R].ctrlSeq != leftward.ctrlSeq)
4541
+ leftward = leftward[R];
4542
+ }
4543
+
4544
+ if (leftward !== cursor[L]) {
4545
+ this.replaces(Fragment(leftward[R] || cursor.parent.ends[L], cursor[L]));
4546
+ cursor[L] = leftward;
4547
+ }
4548
+ }
4549
+ super_.createLeftOf.call(this, cursor);
4550
+ };
4551
+ });
4552
+
4553
+ var SquareRoot =
4554
+ LatexCmds.sqrt =
4555
+ LatexCmds['\u221a'] = P(MathCommand, function(_, super_) {
4556
+ _.ctrlSeq = '\\sqrt';
4557
+ _.htmlTemplate =
4558
+ '<span class="mq-non-leaf">'
4559
+ + '<span class="mq-scaled mq-sqrt-prefix">&radic;</span>'
4560
+ + '<span class="mq-non-leaf mq-sqrt-stem">&0</span>'
4561
+ + '</span>'
4562
+ ;
4563
+ _.textTemplate = ['sqrt(', ')'];
4564
+ _.parser = function() {
4565
+ return latexMathParser.optBlock.then(function(optBlock) {
4566
+ return latexMathParser.block.map(function(block) {
4567
+ var nthroot = NthRoot();
4568
+ nthroot.blocks = [ optBlock, block ];
4569
+ optBlock.adopt(nthroot, 0, 0);
4570
+ block.adopt(nthroot, optBlock, 0);
4571
+ return nthroot;
4572
+ });
4573
+ }).or(super_.parser.call(this));
4574
+ };
4575
+ _.reflow = function() {
4576
+ var block = this.ends[R].jQ;
4577
+ scale(block.prev(), 1, block.innerHeight()/+block.css('fontSize').slice(0,-2) - .1);
4578
+ };
4579
+ });
4580
+
4581
+ var Vec = LatexCmds.vec = P(MathCommand, function(_, super_) {
4582
+ _.ctrlSeq = '\\vec';
4583
+ _.htmlTemplate =
4584
+ '<span class="mq-non-leaf">'
4585
+ + '<span class="mq-vector-prefix">&rarr;</span>'
4586
+ + '<span class="mq-vector-stem">&0</span>'
4587
+ + '</span>'
4588
+ ;
4589
+ _.textTemplate = ['vec(', ')'];
4590
+ });
4591
+
4592
+ var NthRoot =
4593
+ LatexCmds.nthroot = P(SquareRoot, function(_, super_) {
4594
+ _.htmlTemplate =
4595
+ '<sup class="mq-nthroot mq-non-leaf">&0</sup>'
4596
+ + '<span class="mq-scaled">'
4597
+ + '<span class="mq-sqrt-prefix mq-scaled">&radic;</span>'
4598
+ + '<span class="mq-sqrt-stem mq-non-leaf">&1</span>'
4599
+ + '</span>'
4600
+ ;
4601
+ _.textTemplate = ['sqrt[', '](', ')'];
4602
+ _.latex = function() {
4603
+ return '\\sqrt['+this.ends[L].latex()+']{'+this.ends[R].latex()+'}';
4604
+ };
4605
+ });
4606
+
4607
+ function DelimsMixin(_, super_) {
4608
+ _.jQadd = function() {
4609
+ super_.jQadd.apply(this, arguments);
4610
+ this.delimjQs = this.jQ.children(':first').add(this.jQ.children(':last'));
4611
+ this.contentjQ = this.jQ.children(':eq(1)');
4612
+ };
4613
+ _.reflow = function() {
4614
+ var height = this.contentjQ.outerHeight()
4615
+ / parseFloat(this.contentjQ.css('fontSize'));
4616
+ scale(this.delimjQs, min(1 + .2*(height - 1), 1.2), 1.2*height);
4617
+ };
4618
+ }
4619
+
4620
+ // Round/Square/Curly/Angle Brackets (aka Parens/Brackets/Braces)
4621
+ // first typed as one-sided bracket with matching "ghost" bracket at
4622
+ // far end of current block, until you type an opposing one
4623
+ var Bracket = P(P(MathCommand, DelimsMixin), function(_, super_) {
4624
+ _.init = function(side, open, close, ctrlSeq, end) {
4625
+ super_.init.call(this, '\\left'+ctrlSeq, undefined, [open, close]);
4626
+ this.side = side;
4627
+ this.sides = {};
4628
+ this.sides[L] = { ch: open, ctrlSeq: ctrlSeq };
4629
+ this.sides[R] = { ch: close, ctrlSeq: end };
4630
+ };
4631
+ _.numBlocks = function() { return 1; };
4632
+ _.html = function() { // wait until now so that .side may
4633
+ this.htmlTemplate = // be set by createLeftOf or parser
4634
+ '<span class="mq-non-leaf">'
4635
+ + '<span class="mq-scaled mq-paren'+(this.side === R ? ' mq-ghost' : '')+'">'
4636
+ + this.sides[L].ch
4637
+ + '</span>'
4638
+ + '<span class="mq-non-leaf">&0</span>'
4639
+ + '<span class="mq-scaled mq-paren'+(this.side === L ? ' mq-ghost' : '')+'">'
4640
+ + this.sides[R].ch
4641
+ + '</span>'
4642
+ + '</span>'
4643
+ ;
4644
+ return super_.html.call(this);
4645
+ };
4646
+ _.latex = function() {
4647
+ return '\\left'+this.sides[L].ctrlSeq+this.ends[L].latex()+'\\right'+this.sides[R].ctrlSeq;
4648
+ };
4649
+ _.oppBrack = function(opts, node, expectedSide) {
4650
+ // return node iff it's a 1-sided bracket of expected side (if any, may be
4651
+ // undefined), and of opposite side from me if I'm not a pipe
4652
+ return node instanceof Bracket && node.side && node.side !== -expectedSide
4653
+ && (this.sides[this.side].ch === '|' || node.side === -this.side)
4654
+ && (!opts.restrictMismatchedBrackets
4655
+ || OPP_BRACKS[this.sides[this.side].ch] === node.sides[node.side].ch
4656
+ || { '(': ']', '[': ')' }[this.sides[L].ch] === node.sides[R].ch) && node;
4657
+ };
4658
+ _.closeOpposing = function(brack) {
4659
+ brack.side = 0;
4660
+ brack.sides[this.side] = this.sides[this.side]; // copy over my info (may be
4661
+ brack.delimjQs.eq(this.side === L ? 0 : 1) // mismatched, like [a, b))
4662
+ .removeClass('mq-ghost').html(this.sides[this.side].ch);
4663
+ };
4664
+ _.createLeftOf = function(cursor) {
4665
+ if (!this.replacedFragment) { // unless wrapping seln in brackets,
4666
+ // check if next to or inside an opposing one-sided bracket
4667
+ // (must check both sides 'cos I might be a pipe)
4668
+ var opts = cursor.options;
4669
+ var brack = this.oppBrack(opts, cursor[L], L)
4670
+ || this.oppBrack(opts, cursor[R], R)
4671
+ || this.oppBrack(opts, cursor.parent.parent);
4672
+ }
4673
+ if (brack) {
4674
+ var side = this.side = -brack.side; // may be pipe with .side not yet set
4675
+ this.closeOpposing(brack);
4676
+ if (brack === cursor.parent.parent && cursor[side]) { // move the stuff between
4677
+ Fragment(cursor[side], cursor.parent.ends[side], -side) // me and ghost outside
4678
+ .disown().withDirAdopt(-side, brack.parent, brack, brack[side])
4679
+ .jQ.insDirOf(side, brack.jQ);
4680
+ brack.bubble('reflow');
4681
+ }
4682
+ }
4683
+ else {
4684
+ brack = this, side = brack.side;
4685
+ if (brack.replacedFragment) brack.side = 0; // wrapping seln, don't be one-sided
4686
+ else if (cursor[-side]) { // elsewise, auto-expand so ghost is at far end
4687
+ brack.replaces(Fragment(cursor[-side], cursor.parent.ends[-side], side));
4688
+ cursor[-side] = 0;
4689
+ }
4690
+ super_.createLeftOf.call(brack, cursor);
4691
+ }
4692
+ if (side === L) cursor.insAtLeftEnd(brack.ends[L]);
4693
+ else cursor.insRightOf(brack);
4694
+ };
4695
+ _.placeCursor = noop;
4696
+ _.unwrap = function() {
4697
+ this.ends[L].children().disown().adopt(this.parent, this, this[R])
4698
+ .jQ.insertAfter(this.jQ);
4699
+ this.remove();
4700
+ };
4701
+ _.deleteSide = function(side, outward, cursor) {
4702
+ var parent = this.parent, sib = this[side], farEnd = parent.ends[side];
4703
+
4704
+ if (side === this.side) { // deleting non-ghost of one-sided bracket, unwrap
4705
+ this.unwrap();
4706
+ sib ? cursor.insDirOf(-side, sib) : cursor.insAtDirEnd(side, parent);
4707
+ return;
4708
+ }
4709
+
4710
+ var opts = cursor.options, wasSolid = !this.side;
4711
+ this.side = -side;
4712
+ // if deleting like, outer close-brace of [(1+2)+3} where inner open-paren
4713
+ if (this.oppBrack(opts, this.ends[L].ends[this.side], side)) { // is ghost,
4714
+ this.closeOpposing(this.ends[L].ends[this.side]); // then become [1+2)+3
4715
+ var origEnd = this.ends[L].ends[side];
4716
+ this.unwrap();
4717
+ if (origEnd.siblingCreated) origEnd.siblingCreated(cursor.options, side);
4718
+ sib ? cursor.insDirOf(-side, sib) : cursor.insAtDirEnd(side, parent);
4719
+ }
4720
+ else { // if deleting like, inner close-brace of ([1+2}+3) where outer
4721
+ if (this.oppBrack(opts, this.parent.parent, side)) { // open-paren is
4722
+ this.parent.parent.closeOpposing(this); // ghost, then become [1+2+3)
4723
+ this.parent.parent.unwrap();
4724
+ } // else if deleting outward from a solid pair, unwrap
4725
+ else if (outward && wasSolid) {
4726
+ this.unwrap();
4727
+ sib ? cursor.insDirOf(-side, sib) : cursor.insAtDirEnd(side, parent);
4728
+ return;
4729
+ }
4730
+ else { // else deleting just one of a pair of brackets, become one-sided
4731
+ this.sides[side] = { ch: OPP_BRACKS[this.sides[this.side].ch],
4732
+ ctrlSeq: OPP_BRACKS[this.sides[this.side].ctrlSeq] };
4733
+ this.delimjQs.removeClass('mq-ghost')
4734
+ .eq(side === L ? 0 : 1).addClass('mq-ghost').html(this.sides[side].ch);
4735
+ }
4736
+ if (sib) { // auto-expand so ghost is at far end
4737
+ var origEnd = this.ends[L].ends[side];
4738
+ Fragment(sib, farEnd, -side).disown()
4739
+ .withDirAdopt(-side, this.ends[L], origEnd, 0)
4740
+ .jQ.insAtDirEnd(side, this.ends[L].jQ.removeClass('mq-empty'));
4741
+ if (origEnd.siblingCreated) origEnd.siblingCreated(cursor.options, side);
4742
+ cursor.insDirOf(-side, sib);
4743
+ } // didn't auto-expand, cursor goes just outside or just inside parens
4744
+ else (outward ? cursor.insDirOf(side, this)
4745
+ : cursor.insAtDirEnd(side, this.ends[L]));
4746
+ }
4747
+ };
4748
+ _.deleteTowards = function(dir, cursor) {
4749
+ this.deleteSide(-dir, false, cursor);
4750
+ };
4751
+ _.finalizeTree = function() {
4752
+ this.ends[L].deleteOutOf = function(dir, cursor) {
4753
+ this.parent.deleteSide(dir, true, cursor);
4754
+ };
4755
+ // FIXME HACK: after initial creation/insertion, finalizeTree would only be
4756
+ // called if the paren is selected and replaced, e.g. by LiveFraction
4757
+ this.finalizeTree = this.intentionalBlur = function() {
4758
+ this.delimjQs.eq(this.side === L ? 1 : 0).removeClass('mq-ghost');
4759
+ this.side = 0;
4760
+ };
4761
+ };
4762
+ _.siblingCreated = function(opts, dir) { // if something typed between ghost and far
4763
+ if (dir === -this.side) this.finalizeTree(); // end of its block, solidify
4764
+ };
4765
+ });
4766
+
4767
+ var OPP_BRACKS = {
4768
+ '(': ')',
4769
+ ')': '(',
4770
+ '[': ']',
4771
+ ']': '[',
4772
+ '{': '}',
4773
+ '}': '{',
4774
+ '\\{': '\\}',
4775
+ '\\}': '\\{',
4776
+ '&lang;': '&rang;',
4777
+ '&rang;': '&lang;',
4778
+ '\\langle ': '\\rangle ',
4779
+ '\\rangle ': '\\langle ',
4780
+ '|': '|'
4781
+ };
4782
+
4783
+ function bindCharBracketPair(open, ctrlSeq) {
4784
+ var ctrlSeq = ctrlSeq || open, close = OPP_BRACKS[open], end = OPP_BRACKS[ctrlSeq];
4785
+ CharCmds[open] = bind(Bracket, L, open, close, ctrlSeq, end);
4786
+ CharCmds[close] = bind(Bracket, R, open, close, ctrlSeq, end);
4787
+ }
4788
+ bindCharBracketPair('(');
4789
+ bindCharBracketPair('[');
4790
+ bindCharBracketPair('{', '\\{');
4791
+ LatexCmds.langle = bind(Bracket, L, '&lang;', '&rang;', '\\langle ', '\\rangle ');
4792
+ LatexCmds.rangle = bind(Bracket, R, '&lang;', '&rang;', '\\langle ', '\\rangle ');
4793
+ CharCmds['|'] = bind(Bracket, L, '|', '|', '|', '|');
4794
+
4795
+ LatexCmds.left = P(MathCommand, function(_) {
4796
+ _.parser = function() {
4797
+ var regex = Parser.regex;
4798
+ var string = Parser.string;
4799
+ var succeed = Parser.succeed;
4800
+ var optWhitespace = Parser.optWhitespace;
4801
+
4802
+ return optWhitespace.then(regex(/^(?:[([|]|\\\{)/))
4803
+ .then(function(ctrlSeq) { // TODO: \langle, \rangle
4804
+ var open = (ctrlSeq.charAt(0) === '\\' ? ctrlSeq.slice(1) : ctrlSeq);
4805
+ return latexMathParser.then(function (block) {
4806
+ return string('\\right').skip(optWhitespace)
4807
+ .then(regex(/^(?:[\])|]|\\\})/)).map(function(end) {
4808
+ var close = (end.charAt(0) === '\\' ? end.slice(1) : end);
4809
+ var cmd = Bracket(0, open, close, ctrlSeq, end);
4810
+ cmd.blocks = [ block ];
4811
+ block.adopt(cmd, 0, 0);
4812
+ return cmd;
4813
+ })
4814
+ ;
4815
+ });
4816
+ })
4817
+ ;
4818
+ };
4819
+ });
4820
+
4821
+ LatexCmds.right = P(MathCommand, function(_) {
4822
+ _.parser = function() {
4823
+ return Parser.fail('unmatched \\right');
4824
+ };
4825
+ });
4826
+
4827
+ var Binomial =
4828
+ LatexCmds.binom =
4829
+ LatexCmds.binomial = P(P(MathCommand, DelimsMixin), function(_, super_) {
4830
+ _.ctrlSeq = '\\binom';
4831
+ _.htmlTemplate =
4832
+ '<span class="mq-non-leaf">'
4833
+ + '<span class="mq-paren mq-scaled">(</span>'
4834
+ + '<span class="mq-non-leaf">'
4835
+ + '<span class="mq-array mq-non-leaf">'
4836
+ + '<span>&0</span>'
4837
+ + '<span>&1</span>'
4838
+ + '</span>'
4839
+ + '</span>'
4840
+ + '<span class="mq-paren mq-scaled">)</span>'
4841
+ + '</span>'
4842
+ ;
4843
+ _.textTemplate = ['choose(',',',')'];
4844
+ });
4845
+
4846
+ var Choose =
4847
+ LatexCmds.choose = P(Binomial, function(_) {
4848
+ _.createLeftOf = LiveFraction.prototype.createLeftOf;
4849
+ });
4850
+
4851
+ LatexCmds.editable = // backcompat with before cfd3620 on #233
4852
+ LatexCmds.MathQuillMathField = P(MathCommand, function(_, super_) {
4853
+ _.ctrlSeq = '\\MathQuillMathField';
4854
+ _.htmlTemplate =
4855
+ '<span class="mq-editable-field">'
4856
+ + '<span class="mq-root-block">&0</span>'
4857
+ + '</span>'
4858
+ ;
4859
+ _.parser = function() {
4860
+ var self = this,
4861
+ string = Parser.string, regex = Parser.regex, succeed = Parser.succeed;
4862
+ return string('[').then(regex(/^[a-z][a-z0-9]*/i)).skip(string(']'))
4863
+ .map(function(name) { self.name = name; }).or(succeed())
4864
+ .then(super_.parser.call(self));
4865
+ };
4866
+ _.finalizeTree = function() {
4867
+ var ctrlr = Controller(this.ends[L], this.jQ, Options());
4868
+ ctrlr.KIND_OF_MQ = 'MathField';
4869
+ ctrlr.editable = true;
4870
+ ctrlr.createTextarea();
4871
+ ctrlr.editablesTextareaEvents();
4872
+ ctrlr.cursor.insAtRightEnd(ctrlr.root);
4873
+ RootBlockMixin(ctrlr.root);
4874
+ };
4875
+ _.registerInnerField = function(innerFields, MathField) {
4876
+ innerFields.push(innerFields[this.name] = MathField(this.ends[L].controller));
4877
+ };
4878
+ _.latex = function(){ return this.ends[L].latex(); };
4879
+ _.text = function(){ return this.ends[L].text(); };
4880
+ });
4881
+
4882
+ // Embed arbitrary things
4883
+ // Probably the closest DOM analogue would be an iframe?
4884
+ // From MathQuill's perspective, it's a Symbol, it can be
4885
+ // anywhere and the cursor can go around it but never in it.
4886
+ // Create by calling public API method .dropEmbedded(),
4887
+ // or by calling the global public API method .registerEmbed()
4888
+ // and rendering LaTeX like \embed{registeredName} (see test).
4889
+ var Embed = LatexCmds.embed = P(Symbol, function(_, super_) {
4890
+ _.setOptions = function(options) {
4891
+ function noop () { return ""; }
4892
+ this.text = options.text || noop;
4893
+ this.htmlTemplate = options.htmlString || "";
4894
+ this.latex = options.latex || noop;
4895
+ return this;
4896
+ };
4897
+ _.parser = function() {
4898
+ var self = this;
4899
+ string = Parser.string, regex = Parser.regex, succeed = Parser.succeed;
4900
+ return string('{').then(regex(/^[a-z][a-z0-9]*/i)).skip(string('}'))
4901
+ .then(function(name) {
4902
+ // the chars allowed in the optional data block are arbitrary other than
4903
+ // excluding curly braces and square brackets (which'd be too confusing)
4904
+ return string('[').then(regex(/^[-\w\s]*/)).skip(string(']'))
4905
+ .or(succeed()).map(function(data) {
4906
+ return self.setOptions(EMBEDS[name](data));
4907
+ })
4908
+ ;
4909
+ })
4910
+ ;
4911
+ };
4912
+ });
4913
+ var MQ1 = getInterface(1);
4914
+ for (var key in MQ1) (function(key, val) {
4915
+ if (typeof val === 'function') {
4916
+ MathQuill[key] = function() {
4917
+ insistOnInterVer();
4918
+ return val.apply(this, arguments);
4919
+ };
4920
+ MathQuill[key].prototype = val.prototype;
4921
+ }
4922
+ else MathQuill[key] = val;
4923
+ }(key, MQ1[key]));
4924
+
4925
+ }());