reqless 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (81) hide show
  1. checksums.yaml +7 -0
  2. data/Gemfile +8 -0
  3. data/README.md +648 -0
  4. data/Rakefile +117 -0
  5. data/bin/docker-build-and-test +22 -0
  6. data/exe/reqless-web +11 -0
  7. data/lib/reqless/config.rb +31 -0
  8. data/lib/reqless/failure_formatter.rb +43 -0
  9. data/lib/reqless/job.rb +496 -0
  10. data/lib/reqless/job_reservers/ordered.rb +29 -0
  11. data/lib/reqless/job_reservers/round_robin.rb +46 -0
  12. data/lib/reqless/job_reservers/shuffled_round_robin.rb +21 -0
  13. data/lib/reqless/lua/reqless-lib.lua +2965 -0
  14. data/lib/reqless/lua/reqless.lua +2545 -0
  15. data/lib/reqless/lua_script.rb +90 -0
  16. data/lib/reqless/middleware/requeue_exceptions.rb +94 -0
  17. data/lib/reqless/middleware/retry_exceptions.rb +72 -0
  18. data/lib/reqless/middleware/sentry.rb +66 -0
  19. data/lib/reqless/middleware/timeout.rb +63 -0
  20. data/lib/reqless/queue.rb +189 -0
  21. data/lib/reqless/queue_priority_pattern.rb +16 -0
  22. data/lib/reqless/server/static/css/bootstrap-responsive.css +686 -0
  23. data/lib/reqless/server/static/css/bootstrap-responsive.min.css +12 -0
  24. data/lib/reqless/server/static/css/bootstrap.css +3991 -0
  25. data/lib/reqless/server/static/css/bootstrap.min.css +689 -0
  26. data/lib/reqless/server/static/css/codemirror.css +112 -0
  27. data/lib/reqless/server/static/css/docs.css +839 -0
  28. data/lib/reqless/server/static/css/jquery.noty.css +105 -0
  29. data/lib/reqless/server/static/css/noty_theme_twitter.css +137 -0
  30. data/lib/reqless/server/static/css/style.css +200 -0
  31. data/lib/reqless/server/static/favicon.ico +0 -0
  32. data/lib/reqless/server/static/img/glyphicons-halflings-white.png +0 -0
  33. data/lib/reqless/server/static/img/glyphicons-halflings.png +0 -0
  34. data/lib/reqless/server/static/js/bootstrap-alert.js +94 -0
  35. data/lib/reqless/server/static/js/bootstrap-scrollspy.js +125 -0
  36. data/lib/reqless/server/static/js/bootstrap-tab.js +130 -0
  37. data/lib/reqless/server/static/js/bootstrap-tooltip.js +270 -0
  38. data/lib/reqless/server/static/js/bootstrap-typeahead.js +285 -0
  39. data/lib/reqless/server/static/js/bootstrap.js +1726 -0
  40. data/lib/reqless/server/static/js/bootstrap.min.js +6 -0
  41. data/lib/reqless/server/static/js/codemirror.js +2972 -0
  42. data/lib/reqless/server/static/js/jquery.noty.js +220 -0
  43. data/lib/reqless/server/static/js/mode/javascript.js +360 -0
  44. data/lib/reqless/server/static/js/theme/cobalt.css +18 -0
  45. data/lib/reqless/server/static/js/theme/eclipse.css +25 -0
  46. data/lib/reqless/server/static/js/theme/elegant.css +10 -0
  47. data/lib/reqless/server/static/js/theme/lesser-dark.css +45 -0
  48. data/lib/reqless/server/static/js/theme/monokai.css +28 -0
  49. data/lib/reqless/server/static/js/theme/neat.css +9 -0
  50. data/lib/reqless/server/static/js/theme/night.css +21 -0
  51. data/lib/reqless/server/static/js/theme/rubyblue.css +21 -0
  52. data/lib/reqless/server/static/js/theme/xq-dark.css +46 -0
  53. data/lib/reqless/server/views/_job.erb +259 -0
  54. data/lib/reqless/server/views/_job_list.erb +8 -0
  55. data/lib/reqless/server/views/_pagination.erb +7 -0
  56. data/lib/reqless/server/views/about.erb +130 -0
  57. data/lib/reqless/server/views/completed.erb +11 -0
  58. data/lib/reqless/server/views/config.erb +14 -0
  59. data/lib/reqless/server/views/failed.erb +48 -0
  60. data/lib/reqless/server/views/failed_type.erb +18 -0
  61. data/lib/reqless/server/views/job.erb +17 -0
  62. data/lib/reqless/server/views/layout.erb +451 -0
  63. data/lib/reqless/server/views/overview.erb +137 -0
  64. data/lib/reqless/server/views/queue.erb +125 -0
  65. data/lib/reqless/server/views/queues.erb +45 -0
  66. data/lib/reqless/server/views/tag.erb +6 -0
  67. data/lib/reqless/server/views/throttles.erb +38 -0
  68. data/lib/reqless/server/views/track.erb +75 -0
  69. data/lib/reqless/server/views/worker.erb +34 -0
  70. data/lib/reqless/server/views/workers.erb +14 -0
  71. data/lib/reqless/server.rb +549 -0
  72. data/lib/reqless/subscriber.rb +74 -0
  73. data/lib/reqless/test_helpers/worker_helpers.rb +55 -0
  74. data/lib/reqless/throttle.rb +57 -0
  75. data/lib/reqless/version.rb +5 -0
  76. data/lib/reqless/worker/base.rb +237 -0
  77. data/lib/reqless/worker/forking.rb +215 -0
  78. data/lib/reqless/worker/serial.rb +41 -0
  79. data/lib/reqless/worker.rb +5 -0
  80. data/lib/reqless.rb +309 -0
  81. metadata +399 -0
@@ -0,0 +1,2972 @@
1
+ // CodeMirror version 2.23
2
+ //
3
+ // All functions that need access to the editor's state live inside
4
+ // the CodeMirror function. Below that, at the bottom of the file,
5
+ // some utilities are defined.
6
+
7
+ // CodeMirror is the only global var we claim
8
+ var CodeMirror = (function() {
9
+ // This is the function that produces an editor instance. Its
10
+ // closure is used to store the editor state.
11
+ function CodeMirror(place, givenOptions) {
12
+ // Determine effective options based on given values and defaults.
13
+ var options = {}, defaults = CodeMirror.defaults;
14
+ for (var opt in defaults)
15
+ if (defaults.hasOwnProperty(opt))
16
+ options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
17
+
18
+ // The element in which the editor lives.
19
+ var wrapper = document.createElement("div");
20
+ wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "");
21
+ // This mess creates the base DOM structure for the editor.
22
+ wrapper.innerHTML =
23
+ '<div style="overflow: hidden; position: relative; width: 3px; height: 0px;">' + // Wraps and hides input textarea
24
+ '<textarea style="position: absolute; padding: 0; width: 1px; height: 1em" wrap="off" ' +
25
+ 'autocorrect="off" autocapitalize="off"></textarea></div>' +
26
+ '<div class="CodeMirror-scroll" tabindex="-1">' +
27
+ '<div style="position: relative">' + // Set to the height of the text, causes scrolling
28
+ '<div style="position: relative">' + // Moved around its parent to cover visible view
29
+ '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
30
+ // Provides positioning relative to (visible) text origin
31
+ '<div class="CodeMirror-lines"><div style="position: relative; z-index: 0">' +
32
+ '<div style="position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden;"></div>' +
33
+ '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
34
+ '<div style="position: relative; z-index: -1"></div><div></div>' + // DIVs containing the selection and the actual code
35
+ '</div></div></div></div></div>';
36
+ if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
37
+ // I've never seen more elegant code in my life.
38
+ var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
39
+ scroller = wrapper.lastChild, code = scroller.firstChild,
40
+ mover = code.firstChild, gutter = mover.firstChild, gutterText = gutter.firstChild,
41
+ lineSpace = gutter.nextSibling.firstChild, measure = lineSpace.firstChild,
42
+ cursor = measure.nextSibling, selectionDiv = cursor.nextSibling,
43
+ lineDiv = selectionDiv.nextSibling;
44
+ themeChanged();
45
+ // Needed to hide big blue blinking cursor on Mobile Safari
46
+ if (ios) input.style.width = "0px";
47
+ if (!webkit) lineSpace.draggable = true;
48
+ lineSpace.style.outline = "none";
49
+ if (options.tabindex != null) input.tabIndex = options.tabindex;
50
+ if (options.autofocus) focusInput();
51
+ if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
52
+ // Needed to handle Tab key in KHTML
53
+ if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
54
+
55
+ // Check for problem with IE innerHTML not working when we have a
56
+ // P (or similar) parent node.
57
+ try { stringWidth("x"); }
58
+ catch (e) {
59
+ if (e.message.match(/runtime/i))
60
+ e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)");
61
+ throw e;
62
+ }
63
+
64
+ // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
65
+ var poll = new Delayed(), highlight = new Delayed(), blinker;
66
+
67
+ // mode holds a mode API object. doc is the tree of Line objects,
68
+ // work an array of lines that should be parsed, and history the
69
+ // undo history (instance of History constructor).
70
+ var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused;
71
+ loadMode();
72
+ // The selection. These are always maintained to point at valid
73
+ // positions. Inverted is used to remember that the user is
74
+ // selecting bottom-to-top.
75
+ var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
76
+ // Selection-related flags. shiftSelecting obviously tracks
77
+ // whether the user is holding shift.
78
+ var shiftSelecting, lastClick, lastDoubleClick, lastScrollPos = 0, draggingText,
79
+ overwrite = false, suppressEdits = false;
80
+ // Variables used by startOperation/endOperation to track what
81
+ // happened during the operation.
82
+ var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone,
83
+ gutterDirty, callbacks;
84
+ // Current visible range (may be bigger than the view window).
85
+ var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
86
+ // bracketHighlighted is used to remember that a bracket has been
87
+ // marked.
88
+ var bracketHighlighted;
89
+ // Tracks the maximum line length so that the horizontal scrollbar
90
+ // can be kept static when scrolling.
91
+ var maxLine = "", maxWidth;
92
+ var tabCache = {};
93
+
94
+ // Initialize the content.
95
+ operation(function(){setValue(options.value || ""); updateInput = false;})();
96
+ var history = new History();
97
+
98
+ // Register our event handlers.
99
+ connect(scroller, "mousedown", operation(onMouseDown));
100
+ connect(scroller, "dblclick", operation(onDoubleClick));
101
+ connect(lineSpace, "dragstart", onDragStart);
102
+ connect(lineSpace, "selectstart", e_preventDefault);
103
+ // Gecko browsers fire contextmenu *after* opening the menu, at
104
+ // which point we can't mess with it anymore. Context menu is
105
+ // handled in onMouseDown for Gecko.
106
+ if (!gecko) connect(scroller, "contextmenu", onContextMenu);
107
+ connect(scroller, "scroll", function() {
108
+ lastScrollPos = scroller.scrollTop;
109
+ updateDisplay([]);
110
+ if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px";
111
+ if (options.onScroll) options.onScroll(instance);
112
+ });
113
+ connect(window, "resize", function() {updateDisplay(true);});
114
+ connect(input, "keyup", operation(onKeyUp));
115
+ connect(input, "input", fastPoll);
116
+ connect(input, "keydown", operation(onKeyDown));
117
+ connect(input, "keypress", operation(onKeyPress));
118
+ connect(input, "focus", onFocus);
119
+ connect(input, "blur", onBlur);
120
+
121
+ connect(scroller, "dragenter", e_stop);
122
+ connect(scroller, "dragover", e_stop);
123
+ connect(scroller, "drop", operation(onDrop));
124
+ connect(scroller, "paste", function(){focusInput(); fastPoll();});
125
+ connect(input, "paste", fastPoll);
126
+ connect(input, "cut", operation(function(){
127
+ if (!options.readOnly) replaceSelection("");
128
+ }));
129
+
130
+ // Needed to handle Tab key in KHTML
131
+ if (khtml) connect(code, "mouseup", function() {
132
+ if (document.activeElement == input) input.blur();
133
+ focusInput();
134
+ });
135
+
136
+ // IE throws unspecified error in certain cases, when
137
+ // trying to access activeElement before onload
138
+ var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { }
139
+ if (hasFocus || options.autofocus) setTimeout(onFocus, 20);
140
+ else onBlur();
141
+
142
+ function isLine(l) {return l >= 0 && l < doc.size;}
143
+ // The instance object that we'll return. Mostly calls out to
144
+ // local functions in the CodeMirror function. Some do some extra
145
+ // range checking and/or clipping. operation is used to wrap the
146
+ // call so that changes it makes are tracked, and the display is
147
+ // updated afterwards.
148
+ var instance = wrapper.CodeMirror = {
149
+ getValue: getValue,
150
+ setValue: operation(setValue),
151
+ getSelection: getSelection,
152
+ replaceSelection: operation(replaceSelection),
153
+ focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();},
154
+ setOption: function(option, value) {
155
+ var oldVal = options[option];
156
+ options[option] = value;
157
+ if (option == "mode" || option == "indentUnit") loadMode();
158
+ else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();}
159
+ else if (option == "readOnly" && !value) {resetInput(true);}
160
+ else if (option == "theme") themeChanged();
161
+ else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
162
+ else if (option == "tabSize") updateDisplay(true);
163
+ if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme") {
164
+ gutterChanged();
165
+ updateDisplay(true);
166
+ }
167
+ },
168
+ getOption: function(option) {return options[option];},
169
+ undo: operation(undo),
170
+ redo: operation(redo),
171
+ indentLine: operation(function(n, dir) {
172
+ if (typeof dir != "string") {
173
+ if (dir == null) dir = options.smartIndent ? "smart" : "prev";
174
+ else dir = dir ? "add" : "subtract";
175
+ }
176
+ if (isLine(n)) indentLine(n, dir);
177
+ }),
178
+ indentSelection: operation(indentSelected),
179
+ historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
180
+ clearHistory: function() {history = new History();},
181
+ matchBrackets: operation(function(){matchBrackets(true);}),
182
+ getTokenAt: operation(function(pos) {
183
+ pos = clipPos(pos);
184
+ return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), pos.ch);
185
+ }),
186
+ getStateAfter: function(line) {
187
+ line = clipLine(line == null ? doc.size - 1: line);
188
+ return getStateBefore(line + 1);
189
+ },
190
+ cursorCoords: function(start, mode) {
191
+ if (start == null) start = sel.inverted;
192
+ return this.charCoords(start ? sel.from : sel.to, mode);
193
+ },
194
+ charCoords: function(pos, mode) {
195
+ pos = clipPos(pos);
196
+ if (mode == "local") return localCoords(pos, false);
197
+ if (mode == "div") return localCoords(pos, true);
198
+ return pageCoords(pos);
199
+ },
200
+ coordsChar: function(coords) {
201
+ var off = eltOffset(lineSpace);
202
+ return coordsChar(coords.x - off.left, coords.y - off.top);
203
+ },
204
+ markText: operation(markText),
205
+ setBookmark: setBookmark,
206
+ findMarksAt: findMarksAt,
207
+ setMarker: operation(addGutterMarker),
208
+ clearMarker: operation(removeGutterMarker),
209
+ setLineClass: operation(setLineClass),
210
+ hideLine: operation(function(h) {return setLineHidden(h, true);}),
211
+ showLine: operation(function(h) {return setLineHidden(h, false);}),
212
+ onDeleteLine: function(line, f) {
213
+ if (typeof line == "number") {
214
+ if (!isLine(line)) return null;
215
+ line = getLine(line);
216
+ }
217
+ (line.handlers || (line.handlers = [])).push(f);
218
+ return line;
219
+ },
220
+ lineInfo: lineInfo,
221
+ addWidget: function(pos, node, scroll, vert, horiz) {
222
+ pos = localCoords(clipPos(pos));
223
+ var top = pos.yBot, left = pos.x;
224
+ node.style.position = "absolute";
225
+ code.appendChild(node);
226
+ if (vert == "over") top = pos.y;
227
+ else if (vert == "near") {
228
+ var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()),
229
+ hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
230
+ if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
231
+ top = pos.y - node.offsetHeight;
232
+ if (left + node.offsetWidth > hspace)
233
+ left = hspace - node.offsetWidth;
234
+ }
235
+ node.style.top = (top + paddingTop()) + "px";
236
+ node.style.left = node.style.right = "";
237
+ if (horiz == "right") {
238
+ left = code.clientWidth - node.offsetWidth;
239
+ node.style.right = "0px";
240
+ } else {
241
+ if (horiz == "left") left = 0;
242
+ else if (horiz == "middle") left = (code.clientWidth - node.offsetWidth) / 2;
243
+ node.style.left = (left + paddingLeft()) + "px";
244
+ }
245
+ if (scroll)
246
+ scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
247
+ },
248
+
249
+ lineCount: function() {return doc.size;},
250
+ clipPos: clipPos,
251
+ getCursor: function(start) {
252
+ if (start == null) start = sel.inverted;
253
+ return copyPos(start ? sel.from : sel.to);
254
+ },
255
+ somethingSelected: function() {return !posEq(sel.from, sel.to);},
256
+ setCursor: operation(function(line, ch, user) {
257
+ if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user);
258
+ else setCursor(line, ch, user);
259
+ }),
260
+ setSelection: operation(function(from, to, user) {
261
+ (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from));
262
+ }),
263
+ getLine: function(line) {if (isLine(line)) return getLine(line).text;},
264
+ getLineHandle: function(line) {if (isLine(line)) return getLine(line);},
265
+ setLine: operation(function(line, text) {
266
+ if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
267
+ }),
268
+ removeLine: operation(function(line) {
269
+ if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
270
+ }),
271
+ replaceRange: operation(replaceRange),
272
+ getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
273
+
274
+ triggerOnKeyDown: operation(onKeyDown),
275
+ execCommand: function(cmd) {return commands[cmd](instance);},
276
+ // Stuff used by commands, probably not much use to outside code.
277
+ moveH: operation(moveH),
278
+ deleteH: operation(deleteH),
279
+ moveV: operation(moveV),
280
+ toggleOverwrite: function() {
281
+ if(overwrite){
282
+ overwrite = false;
283
+ cursor.className = cursor.className.replace(" CodeMirror-overwrite", "");
284
+ } else {
285
+ overwrite = true;
286
+ cursor.className += " CodeMirror-overwrite";
287
+ }
288
+ },
289
+
290
+ posFromIndex: function(off) {
291
+ var lineNo = 0, ch;
292
+ doc.iter(0, doc.size, function(line) {
293
+ var sz = line.text.length + 1;
294
+ if (sz > off) { ch = off; return true; }
295
+ off -= sz;
296
+ ++lineNo;
297
+ });
298
+ return clipPos({line: lineNo, ch: ch});
299
+ },
300
+ indexFromPos: function (coords) {
301
+ if (coords.line < 0 || coords.ch < 0) return 0;
302
+ var index = coords.ch;
303
+ doc.iter(0, coords.line, function (line) {
304
+ index += line.text.length + 1;
305
+ });
306
+ return index;
307
+ },
308
+ scrollTo: function(x, y) {
309
+ if (x != null) scroller.scrollLeft = x;
310
+ if (y != null) scroller.scrollTop = y;
311
+ updateDisplay([]);
312
+ },
313
+
314
+ operation: function(f){return operation(f)();},
315
+ refresh: function(){
316
+ updateDisplay(true);
317
+ if (scroller.scrollHeight > lastScrollPos)
318
+ scroller.scrollTop = lastScrollPos;
319
+ },
320
+ getInputField: function(){return input;},
321
+ getWrapperElement: function(){return wrapper;},
322
+ getScrollerElement: function(){return scroller;},
323
+ getGutterElement: function(){return gutter;}
324
+ };
325
+
326
+ function getLine(n) { return getLineAt(doc, n); }
327
+ function updateLineHeight(line, height) {
328
+ gutterDirty = true;
329
+ var diff = height - line.height;
330
+ for (var n = line; n; n = n.parent) n.height += diff;
331
+ }
332
+
333
+ function setValue(code) {
334
+ var top = {line: 0, ch: 0};
335
+ updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length},
336
+ splitLines(code), top, top);
337
+ updateInput = true;
338
+ }
339
+ function getValue(code) {
340
+ var text = [];
341
+ doc.iter(0, doc.size, function(line) { text.push(line.text); });
342
+ return text.join("\n");
343
+ }
344
+
345
+ function onMouseDown(e) {
346
+ setShift(e_prop(e, "shiftKey"));
347
+ // Check whether this is a click in a widget
348
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
349
+ if (n.parentNode == code && n != mover) return;
350
+
351
+ // See if this is a click in the gutter
352
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
353
+ if (n.parentNode == gutterText) {
354
+ if (options.onGutterClick)
355
+ options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e);
356
+ return e_preventDefault(e);
357
+ }
358
+
359
+ var start = posFromMouse(e);
360
+
361
+ switch (e_button(e)) {
362
+ case 3:
363
+ if (gecko && !mac) onContextMenu(e);
364
+ return;
365
+ case 2:
366
+ if (start) setCursor(start.line, start.ch, true);
367
+ return;
368
+ }
369
+ // For button 1, if it was clicked inside the editor
370
+ // (posFromMouse returning non-null), we have to adjust the
371
+ // selection.
372
+ if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
373
+
374
+ if (!focused) onFocus();
375
+
376
+ var now = +new Date;
377
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
378
+ e_preventDefault(e);
379
+ setTimeout(focusInput, 20);
380
+ return selectLine(start.line);
381
+ } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
382
+ lastDoubleClick = {time: now, pos: start};
383
+ e_preventDefault(e);
384
+ return selectWordAt(start);
385
+ } else { lastClick = {time: now, pos: start}; }
386
+
387
+ var last = start, going;
388
+ if (dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) &&
389
+ !posLess(start, sel.from) && !posLess(sel.to, start)) {
390
+ // Let the drag handler handle this.
391
+ if (webkit) lineSpace.draggable = true;
392
+ var up = connect(document, "mouseup", operation(function(e2) {
393
+ if (webkit) lineSpace.draggable = false;
394
+ draggingText = false;
395
+ up();
396
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
397
+ e_preventDefault(e2);
398
+ setCursor(start.line, start.ch, true);
399
+ focusInput();
400
+ }
401
+ }), true);
402
+ draggingText = true;
403
+ // IE's approach to draggable
404
+ if (lineSpace.dragDrop) lineSpace.dragDrop();
405
+ return;
406
+ }
407
+ e_preventDefault(e);
408
+ setCursor(start.line, start.ch, true);
409
+
410
+ function extend(e) {
411
+ var cur = posFromMouse(e, true);
412
+ if (cur && !posEq(cur, last)) {
413
+ if (!focused) onFocus();
414
+ last = cur;
415
+ setSelectionUser(start, cur);
416
+ updateInput = false;
417
+ var visible = visibleLines();
418
+ if (cur.line >= visible.to || cur.line < visible.from)
419
+ going = setTimeout(operation(function(){extend(e);}), 150);
420
+ }
421
+ }
422
+
423
+ function done(e) {
424
+ clearTimeout(going);
425
+ var cur = posFromMouse(e);
426
+ if (cur) setSelectionUser(start, cur);
427
+ e_preventDefault(e);
428
+ focusInput();
429
+ updateInput = true;
430
+ move(); up();
431
+ }
432
+ var move = connect(document, "mousemove", operation(function(e) {
433
+ clearTimeout(going);
434
+ e_preventDefault(e);
435
+ if (!ie && !e_button(e)) done(e);
436
+ else extend(e);
437
+ }), true);
438
+ var up = connect(document, "mouseup", operation(done), true);
439
+ }
440
+ function onDoubleClick(e) {
441
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
442
+ if (n.parentNode == gutterText) return e_preventDefault(e);
443
+ var start = posFromMouse(e);
444
+ if (!start) return;
445
+ lastDoubleClick = {time: +new Date, pos: start};
446
+ e_preventDefault(e);
447
+ selectWordAt(start);
448
+ }
449
+ function onDrop(e) {
450
+ e.preventDefault();
451
+ var pos = posFromMouse(e, true), files = e.dataTransfer.files;
452
+ if (!pos || options.readOnly) return;
453
+ if (files && files.length && window.FileReader && window.File) {
454
+ function loadFile(file, i) {
455
+ var reader = new FileReader;
456
+ reader.onload = function() {
457
+ text[i] = reader.result;
458
+ if (++read == n) {
459
+ pos = clipPos(pos);
460
+ operation(function() {
461
+ var end = replaceRange(text.join(""), pos, pos);
462
+ setSelectionUser(pos, end);
463
+ })();
464
+ }
465
+ };
466
+ reader.readAsText(file);
467
+ }
468
+ var n = files.length, text = Array(n), read = 0;
469
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
470
+ }
471
+ else {
472
+ try {
473
+ var text = e.dataTransfer.getData("Text");
474
+ if (text) {
475
+ var curFrom = sel.from, curTo = sel.to;
476
+ setSelectionUser(pos, pos);
477
+ if (draggingText) replaceRange("", curFrom, curTo);
478
+ replaceSelection(text);
479
+ focusInput();
480
+ }
481
+ }
482
+ catch(e){}
483
+ }
484
+ }
485
+ function onDragStart(e) {
486
+ var txt = getSelection();
487
+ e.dataTransfer.setData("Text", txt);
488
+
489
+ // Use dummy image instead of default browsers image.
490
+ if (gecko || chrome) {
491
+ var img = document.createElement('img');
492
+ img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image
493
+ e.dataTransfer.setDragImage(img, 0, 0);
494
+ }
495
+ }
496
+
497
+ function doHandleBinding(bound, dropShift) {
498
+ if (typeof bound == "string") {
499
+ bound = commands[bound];
500
+ if (!bound) return false;
501
+ }
502
+ var prevShift = shiftSelecting;
503
+ try {
504
+ if (options.readOnly) suppressEdits = true;
505
+ if (dropShift) shiftSelecting = null;
506
+ bound(instance);
507
+ } catch(e) {
508
+ if (e != Pass) throw e;
509
+ return false;
510
+ } finally {
511
+ shiftSelecting = prevShift;
512
+ suppressEdits = false;
513
+ }
514
+ return true;
515
+ }
516
+ function handleKeyBinding(e) {
517
+ // Handle auto keymap transitions
518
+ var startMap = getKeyMap(options.keyMap), next = startMap.auto;
519
+ clearTimeout(maybeTransition);
520
+ if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
521
+ if (getKeyMap(options.keyMap) == startMap) {
522
+ options.keyMap = (next.call ? next.call(null, instance) : next);
523
+ }
524
+ }, 50);
525
+
526
+ var name = keyNames[e_prop(e, "keyCode")], handled = false;
527
+ if (name == null || e.altGraphKey) return false;
528
+ if (e_prop(e, "altKey")) name = "Alt-" + name;
529
+ if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name;
530
+ if (e_prop(e, "metaKey")) name = "Cmd-" + name;
531
+
532
+ if (e_prop(e, "shiftKey")) {
533
+ handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap,
534
+ function(b) {return doHandleBinding(b, true);})
535
+ || lookupKey(name, options.extraKeys, options.keyMap, function(b) {
536
+ if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b);
537
+ });
538
+ } else {
539
+ handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding);
540
+ }
541
+ if (handled) {
542
+ e_preventDefault(e);
543
+ if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
544
+ }
545
+ return handled;
546
+ }
547
+ function handleCharBinding(e, ch) {
548
+ var handled = lookupKey("'" + ch + "'", options.extraKeys,
549
+ options.keyMap, doHandleBinding);
550
+ if (handled) e_preventDefault(e);
551
+ return handled;
552
+ }
553
+
554
+ var lastStoppedKey = null, maybeTransition;
555
+ function onKeyDown(e) {
556
+ if (!focused) onFocus();
557
+ if (ie && e.keyCode == 27) { e.returnValue = false; }
558
+ if (pollingFast) { if (readInput()) pollingFast = false; }
559
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
560
+ var code = e_prop(e, "keyCode");
561
+ // IE does strange things with escape.
562
+ setShift(code == 16 || e_prop(e, "shiftKey"));
563
+ // First give onKeyEvent option a chance to handle this.
564
+ var handled = handleKeyBinding(e);
565
+ if (window.opera) {
566
+ lastStoppedKey = handled ? code : null;
567
+ // Opera has no cut event... we try to at least catch the key combo
568
+ if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey"))
569
+ replaceSelection("");
570
+ }
571
+ }
572
+ function onKeyPress(e) {
573
+ if (pollingFast) readInput();
574
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
575
+ var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
576
+ if (window.opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
577
+ if (((window.opera && !e.which) || khtml) && handleKeyBinding(e)) return;
578
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
579
+ if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) {
580
+ if (mode.electricChars.indexOf(ch) > -1)
581
+ setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75);
582
+ }
583
+ if (handleCharBinding(e, ch)) return;
584
+ fastPoll();
585
+ }
586
+ function onKeyUp(e) {
587
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
588
+ if (e_prop(e, "keyCode") == 16) shiftSelecting = null;
589
+ }
590
+
591
+ function onFocus() {
592
+ if (options.readOnly == "nocursor") return;
593
+ if (!focused) {
594
+ if (options.onFocus) options.onFocus(instance);
595
+ focused = true;
596
+ if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
597
+ wrapper.className += " CodeMirror-focused";
598
+ if (!leaveInputAlone) resetInput(true);
599
+ }
600
+ slowPoll();
601
+ restartBlink();
602
+ }
603
+ function onBlur() {
604
+ if (focused) {
605
+ if (options.onBlur) options.onBlur(instance);
606
+ focused = false;
607
+ if (bracketHighlighted)
608
+ operation(function(){
609
+ if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; }
610
+ })();
611
+ wrapper.className = wrapper.className.replace(" CodeMirror-focused", "");
612
+ }
613
+ clearInterval(blinker);
614
+ setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
615
+ }
616
+
617
+ // Replace the range from from to to by the strings in newText.
618
+ // Afterwards, set the selection to selFrom, selTo.
619
+ function updateLines(from, to, newText, selFrom, selTo) {
620
+ if (suppressEdits) return;
621
+ if (history) {
622
+ var old = [];
623
+ doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); });
624
+ history.addChange(from.line, newText.length, old);
625
+ while (history.done.length > options.undoDepth) history.done.shift();
626
+ }
627
+ updateLinesNoUndo(from, to, newText, selFrom, selTo);
628
+ }
629
+ function unredoHelper(from, to) {
630
+ if (!from.length) return;
631
+ var set = from.pop(), out = [];
632
+ for (var i = set.length - 1; i >= 0; i -= 1) {
633
+ var change = set[i];
634
+ var replaced = [], end = change.start + change.added;
635
+ doc.iter(change.start, end, function(line) { replaced.push(line.text); });
636
+ out.push({start: change.start, added: change.old.length, old: replaced});
637
+ var pos = clipPos({line: change.start + change.old.length - 1,
638
+ ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])});
639
+ updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos);
640
+ }
641
+ updateInput = true;
642
+ to.push(out);
643
+ }
644
+ function undo() {unredoHelper(history.done, history.undone);}
645
+ function redo() {unredoHelper(history.undone, history.done);}
646
+
647
+ function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
648
+ if (suppressEdits) return;
649
+ var recomputeMaxLength = false, maxLineLength = maxLine.length;
650
+ if (!options.lineWrapping)
651
+ doc.iter(from.line, to.line, function(line) {
652
+ if (line.text.length == maxLineLength) {recomputeMaxLength = true; return true;}
653
+ });
654
+ if (from.line != to.line || newText.length > 1) gutterDirty = true;
655
+
656
+ var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line);
657
+ // First adjust the line structure, taking some care to leave highlighting intact.
658
+ if (from.ch == 0 && to.ch == 0 && newText[newText.length - 1] == "") {
659
+ // This is a whole-line replace. Treated specially to make
660
+ // sure line objects move the way they are supposed to.
661
+ var added = [], prevLine = null;
662
+ if (from.line) {
663
+ prevLine = getLine(from.line - 1);
664
+ prevLine.fixMarkEnds(lastLine);
665
+ } else lastLine.fixMarkStarts();
666
+ for (var i = 0, e = newText.length - 1; i < e; ++i)
667
+ added.push(Line.inheritMarks(newText[i], prevLine));
668
+ if (nlines) doc.remove(from.line, nlines, callbacks);
669
+ if (added.length) doc.insert(from.line, added);
670
+ } else if (firstLine == lastLine) {
671
+ if (newText.length == 1)
672
+ firstLine.replace(from.ch, to.ch, newText[0]);
673
+ else {
674
+ lastLine = firstLine.split(to.ch, newText[newText.length-1]);
675
+ firstLine.replace(from.ch, null, newText[0]);
676
+ firstLine.fixMarkEnds(lastLine);
677
+ var added = [];
678
+ for (var i = 1, e = newText.length - 1; i < e; ++i)
679
+ added.push(Line.inheritMarks(newText[i], firstLine));
680
+ added.push(lastLine);
681
+ doc.insert(from.line + 1, added);
682
+ }
683
+ } else if (newText.length == 1) {
684
+ firstLine.replace(from.ch, null, newText[0]);
685
+ lastLine.replace(null, to.ch, "");
686
+ firstLine.append(lastLine);
687
+ doc.remove(from.line + 1, nlines, callbacks);
688
+ } else {
689
+ var added = [];
690
+ firstLine.replace(from.ch, null, newText[0]);
691
+ lastLine.replace(null, to.ch, newText[newText.length-1]);
692
+ firstLine.fixMarkEnds(lastLine);
693
+ for (var i = 1, e = newText.length - 1; i < e; ++i)
694
+ added.push(Line.inheritMarks(newText[i], firstLine));
695
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks);
696
+ doc.insert(from.line + 1, added);
697
+ }
698
+ if (options.lineWrapping) {
699
+ var perLine = scroller.clientWidth / charWidth() - 3;
700
+ doc.iter(from.line, from.line + newText.length, function(line) {
701
+ if (line.hidden) return;
702
+ var guess = Math.ceil(line.text.length / perLine) || 1;
703
+ if (guess != line.height) updateLineHeight(line, guess);
704
+ });
705
+ } else {
706
+ doc.iter(from.line, i + newText.length, function(line) {
707
+ var l = line.text;
708
+ if (l.length > maxLineLength) {
709
+ maxLine = l; maxLineLength = l.length; maxWidth = null;
710
+ recomputeMaxLength = false;
711
+ }
712
+ });
713
+ if (recomputeMaxLength) {
714
+ maxLineLength = 0; maxLine = ""; maxWidth = null;
715
+ doc.iter(0, doc.size, function(line) {
716
+ var l = line.text;
717
+ if (l.length > maxLineLength) {
718
+ maxLineLength = l.length; maxLine = l;
719
+ }
720
+ });
721
+ }
722
+ }
723
+
724
+ // Add these lines to the work array, so that they will be
725
+ // highlighted. Adjust work lines if lines were added/removed.
726
+ var newWork = [], lendiff = newText.length - nlines - 1;
727
+ for (var i = 0, l = work.length; i < l; ++i) {
728
+ var task = work[i];
729
+ if (task < from.line) newWork.push(task);
730
+ else if (task > to.line) newWork.push(task + lendiff);
731
+ }
732
+ var hlEnd = from.line + Math.min(newText.length, 500);
733
+ highlightLines(from.line, hlEnd);
734
+ newWork.push(hlEnd);
735
+ work = newWork;
736
+ startWorker(100);
737
+ // Remember that these lines changed, for updating the display
738
+ changes.push({from: from.line, to: to.line + 1, diff: lendiff});
739
+ var changeObj = {from: from, to: to, text: newText};
740
+ if (textChanged) {
741
+ for (var cur = textChanged; cur.next; cur = cur.next) {}
742
+ cur.next = changeObj;
743
+ } else textChanged = changeObj;
744
+
745
+ // Update the selection
746
+ function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
747
+ setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line));
748
+
749
+ // Make sure the scroll-size div has the correct height.
750
+ if (scroller.clientHeight)
751
+ code.style.height = (doc.height * textHeight() + 2 * paddingTop()) + "px";
752
+ }
753
+
754
+ function replaceRange(code, from, to) {
755
+ from = clipPos(from);
756
+ if (!to) to = from; else to = clipPos(to);
757
+ code = splitLines(code);
758
+ function adjustPos(pos) {
759
+ if (posLess(pos, from)) return pos;
760
+ if (!posLess(to, pos)) return end;
761
+ var line = pos.line + code.length - (to.line - from.line) - 1;
762
+ var ch = pos.ch;
763
+ if (pos.line == to.line)
764
+ ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
765
+ return {line: line, ch: ch};
766
+ }
767
+ var end;
768
+ replaceRange1(code, from, to, function(end1) {
769
+ end = end1;
770
+ return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
771
+ });
772
+ return end;
773
+ }
774
+ function replaceSelection(code, collapse) {
775
+ replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
776
+ if (collapse == "end") return {from: end, to: end};
777
+ else if (collapse == "start") return {from: sel.from, to: sel.from};
778
+ else return {from: sel.from, to: end};
779
+ });
780
+ }
781
+ function replaceRange1(code, from, to, computeSel) {
782
+ var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
783
+ var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
784
+ updateLines(from, to, code, newSel.from, newSel.to);
785
+ }
786
+
787
+ function getRange(from, to) {
788
+ var l1 = from.line, l2 = to.line;
789
+ if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch);
790
+ var code = [getLine(l1).text.slice(from.ch)];
791
+ doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
792
+ code.push(getLine(l2).text.slice(0, to.ch));
793
+ return code.join("\n");
794
+ }
795
+ function getSelection() {
796
+ return getRange(sel.from, sel.to);
797
+ }
798
+
799
+ var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
800
+ function slowPoll() {
801
+ if (pollingFast) return;
802
+ poll.set(options.pollInterval, function() {
803
+ startOperation();
804
+ readInput();
805
+ if (focused) slowPoll();
806
+ endOperation();
807
+ });
808
+ }
809
+ function fastPoll() {
810
+ var missed = false;
811
+ pollingFast = true;
812
+ function p() {
813
+ startOperation();
814
+ var changed = readInput();
815
+ if (!changed && !missed) {missed = true; poll.set(60, p);}
816
+ else {pollingFast = false; slowPoll();}
817
+ endOperation();
818
+ }
819
+ poll.set(20, p);
820
+ }
821
+
822
+ // Previnput is a hack to work with IME. If we reset the textarea
823
+ // on every change, that breaks IME. So we look for changes
824
+ // compared to the previous content instead. (Modern browsers have
825
+ // events that indicate IME taking place, but these are not widely
826
+ // supported or compatible enough yet to rely on.)
827
+ var prevInput = "";
828
+ function readInput() {
829
+ if (leaveInputAlone || !focused || hasSelection(input) || options.readOnly) return false;
830
+ var text = input.value;
831
+ if (text == prevInput) return false;
832
+ shiftSelecting = null;
833
+ var same = 0, l = Math.min(prevInput.length, text.length);
834
+ while (same < l && prevInput[same] == text[same]) ++same;
835
+ if (same < prevInput.length)
836
+ sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)};
837
+ else if (overwrite && posEq(sel.from, sel.to))
838
+ sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))};
839
+ replaceSelection(text.slice(same), "end");
840
+ prevInput = text;
841
+ return true;
842
+ }
843
+ function resetInput(user) {
844
+ if (!posEq(sel.from, sel.to)) {
845
+ prevInput = "";
846
+ input.value = getSelection();
847
+ selectInput(input);
848
+ } else if (user) prevInput = input.value = "";
849
+ }
850
+
851
+ function focusInput() {
852
+ if (options.readOnly != "nocursor") input.focus();
853
+ }
854
+
855
+ function scrollEditorIntoView() {
856
+ if (!cursor.getBoundingClientRect) return;
857
+ var rect = cursor.getBoundingClientRect();
858
+ // IE returns bogus coordinates when the instance sits inside of an iframe and the cursor is hidden
859
+ if (ie && rect.top == rect.bottom) return;
860
+ var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
861
+ if (rect.top < 0 || rect.bottom > winH) cursor.scrollIntoView();
862
+ }
863
+ function scrollCursorIntoView() {
864
+ var cursor = localCoords(sel.inverted ? sel.from : sel.to);
865
+ var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x;
866
+ return scrollIntoView(x, cursor.y, x, cursor.yBot);
867
+ }
868
+ function scrollIntoView(x1, y1, x2, y2) {
869
+ var pl = paddingLeft(), pt = paddingTop();
870
+ y1 += pt; y2 += pt; x1 += pl; x2 += pl;
871
+ var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
872
+ if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1); scrolled = true;}
873
+ else if (y2 > screentop + screen) {scroller.scrollTop = y2 - screen; scrolled = true;}
874
+
875
+ var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
876
+ var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
877
+ if (x1 < screenleft + gutterw) {
878
+ if (x1 < 50) x1 = 0;
879
+ scroller.scrollLeft = Math.max(0, x1 - 10 - gutterw);
880
+ scrolled = true;
881
+ }
882
+ else if (x2 > screenw + screenleft - 3) {
883
+ scroller.scrollLeft = x2 + 10 - screenw;
884
+ scrolled = true;
885
+ if (x2 > code.clientWidth) result = false;
886
+ }
887
+ if (scrolled && options.onScroll) options.onScroll(instance);
888
+ return result;
889
+ }
890
+
891
+ function visibleLines() {
892
+ var lh = textHeight(), top = scroller.scrollTop - paddingTop();
893
+ var from_height = Math.max(0, Math.floor(top / lh));
894
+ var to_height = Math.ceil((top + scroller.clientHeight) / lh);
895
+ return {from: lineAtHeight(doc, from_height),
896
+ to: lineAtHeight(doc, to_height)};
897
+ }
898
+ // Uses a set of changes plus the current scroll position to
899
+ // determine which DOM updates have to be made, and makes the
900
+ // updates.
901
+ function updateDisplay(changes, suppressCallback) {
902
+ if (!scroller.clientWidth) {
903
+ showingFrom = showingTo = displayOffset = 0;
904
+ return;
905
+ }
906
+ // Compute the new visible window
907
+ var visible = visibleLines();
908
+ // Bail out if the visible area is already rendered and nothing changed.
909
+ if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) return;
910
+ var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100);
911
+ if (showingFrom < from && from - showingFrom < 20) from = showingFrom;
912
+ if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo);
913
+
914
+ // Create a range of theoretically intact lines, and punch holes
915
+ // in that using the change info.
916
+ var intact = changes === true ? [] :
917
+ computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes);
918
+ // Clip off the parts that won't be visible
919
+ var intactLines = 0;
920
+ for (var i = 0; i < intact.length; ++i) {
921
+ var range = intact[i];
922
+ if (range.from < from) {range.domStart += (from - range.from); range.from = from;}
923
+ if (range.to > to) range.to = to;
924
+ if (range.from >= range.to) intact.splice(i--, 1);
925
+ else intactLines += range.to - range.from;
926
+ }
927
+ if (intactLines == to - from) return;
928
+ intact.sort(function(a, b) {return a.domStart - b.domStart;});
929
+
930
+ var th = textHeight(), gutterDisplay = gutter.style.display;
931
+ lineDiv.style.display = "none";
932
+ patchDisplay(from, to, intact);
933
+ lineDiv.style.display = gutter.style.display = "";
934
+
935
+ // Position the mover div to align with the lines it's supposed
936
+ // to be showing (which will cover the visible display)
937
+ var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th;
938
+ // This is just a bogus formula that detects when the editor is
939
+ // resized or the font size changes.
940
+ if (different) lastSizeC = scroller.clientHeight + th;
941
+ showingFrom = from; showingTo = to;
942
+ displayOffset = heightAtLine(doc, from);
943
+ mover.style.top = (displayOffset * th) + "px";
944
+ if (scroller.clientHeight)
945
+ code.style.height = (doc.height * th + 2 * paddingTop()) + "px";
946
+
947
+ // Since this is all rather error prone, it is honoured with the
948
+ // only assertion in the whole file.
949
+ if (lineDiv.childNodes.length != showingTo - showingFrom)
950
+ throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
951
+ " nodes=" + lineDiv.childNodes.length);
952
+
953
+ function checkHeights() {
954
+ maxWidth = scroller.clientWidth;
955
+ var curNode = lineDiv.firstChild, heightChanged = false;
956
+ doc.iter(showingFrom, showingTo, function(line) {
957
+ if (!line.hidden) {
958
+ var height = Math.round(curNode.offsetHeight / th) || 1;
959
+ if (line.height != height) {
960
+ updateLineHeight(line, height);
961
+ gutterDirty = heightChanged = true;
962
+ }
963
+ }
964
+ curNode = curNode.nextSibling;
965
+ });
966
+ if (heightChanged)
967
+ code.style.height = (doc.height * th + 2 * paddingTop()) + "px";
968
+ return heightChanged;
969
+ }
970
+
971
+ if (options.lineWrapping) {
972
+ checkHeights();
973
+ } else {
974
+ if (maxWidth == null) maxWidth = stringWidth(maxLine);
975
+ if (maxWidth > scroller.clientWidth) {
976
+ lineSpace.style.width = maxWidth + "px";
977
+ // Needed to prevent odd wrapping/hiding of widgets placed in here.
978
+ code.style.width = "";
979
+ code.style.width = scroller.scrollWidth + "px";
980
+ } else {
981
+ lineSpace.style.width = code.style.width = "";
982
+ }
983
+ }
984
+
985
+ gutter.style.display = gutterDisplay;
986
+ if (different || gutterDirty) {
987
+ // If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
988
+ updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
989
+ }
990
+ updateSelection();
991
+ if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
992
+ return true;
993
+ }
994
+
995
+ function computeIntact(intact, changes) {
996
+ for (var i = 0, l = changes.length || 0; i < l; ++i) {
997
+ var change = changes[i], intact2 = [], diff = change.diff || 0;
998
+ for (var j = 0, l2 = intact.length; j < l2; ++j) {
999
+ var range = intact[j];
1000
+ if (change.to <= range.from && change.diff)
1001
+ intact2.push({from: range.from + diff, to: range.to + diff,
1002
+ domStart: range.domStart});
1003
+ else if (change.to <= range.from || change.from >= range.to)
1004
+ intact2.push(range);
1005
+ else {
1006
+ if (change.from > range.from)
1007
+ intact2.push({from: range.from, to: change.from, domStart: range.domStart});
1008
+ if (change.to < range.to)
1009
+ intact2.push({from: change.to + diff, to: range.to + diff,
1010
+ domStart: range.domStart + (change.to - range.from)});
1011
+ }
1012
+ }
1013
+ intact = intact2;
1014
+ }
1015
+ return intact;
1016
+ }
1017
+
1018
+ function patchDisplay(from, to, intact) {
1019
+ // The first pass removes the DOM nodes that aren't intact.
1020
+ if (!intact.length) lineDiv.innerHTML = "";
1021
+ else {
1022
+ function killNode(node) {
1023
+ var tmp = node.nextSibling;
1024
+ node.parentNode.removeChild(node);
1025
+ return tmp;
1026
+ }
1027
+ var domPos = 0, curNode = lineDiv.firstChild, n;
1028
+ for (var i = 0; i < intact.length; ++i) {
1029
+ var cur = intact[i];
1030
+ while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;}
1031
+ for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;}
1032
+ }
1033
+ while (curNode) curNode = killNode(curNode);
1034
+ }
1035
+ // This pass fills in the lines that actually changed.
1036
+ var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
1037
+ var scratch = document.createElement("div");
1038
+ doc.iter(from, to, function(line) {
1039
+ if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
1040
+ if (!nextIntact || nextIntact.from > j) {
1041
+ if (line.hidden) var html = scratch.innerHTML = "<pre></pre>";
1042
+ else {
1043
+ var html = '<pre' + (line.className ? ' class="' + line.className + '"' : '') + '>'
1044
+ + line.getHTML(makeTab) + '</pre>';
1045
+ // Kludge to make sure the styled element lies behind the selection (by z-index)
1046
+ if (line.bgClassName)
1047
+ html = '<div style="position: relative"><pre class="' + line.bgClassName +
1048
+ '" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2">&#160;</pre>' + html + "</div>";
1049
+ }
1050
+ scratch.innerHTML = html;
1051
+ lineDiv.insertBefore(scratch.firstChild, curNode);
1052
+ } else {
1053
+ curNode = curNode.nextSibling;
1054
+ }
1055
+ ++j;
1056
+ });
1057
+ }
1058
+
1059
+ function updateGutter() {
1060
+ if (!options.gutter && !options.lineNumbers) return;
1061
+ var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
1062
+ gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
1063
+ var html = [], i = showingFrom, normalNode;
1064
+ doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
1065
+ if (line.hidden) {
1066
+ html.push("<pre></pre>");
1067
+ } else {
1068
+ var marker = line.gutterMarker;
1069
+ var text = options.lineNumbers ? i + options.firstLineNumber : null;
1070
+ if (marker && marker.text)
1071
+ text = marker.text.replace("%N%", text != null ? text : "");
1072
+ else if (text == null)
1073
+ text = "\u00a0";
1074
+ html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text);
1075
+ for (var j = 1; j < line.height; ++j) html.push("<br/>&#160;");
1076
+ html.push("</pre>");
1077
+ if (!marker) normalNode = i;
1078
+ }
1079
+ ++i;
1080
+ });
1081
+ gutter.style.display = "none";
1082
+ gutterText.innerHTML = html.join("");
1083
+ // Make sure scrolling doesn't cause number gutter size to pop
1084
+ if (normalNode != null) {
1085
+ var node = gutterText.childNodes[normalNode - showingFrom];
1086
+ var minwidth = String(doc.size).length, val = eltText(node), pad = "";
1087
+ while (val.length + pad.length < minwidth) pad += "\u00a0";
1088
+ if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild);
1089
+ }
1090
+ gutter.style.display = "";
1091
+ var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2;
1092
+ lineSpace.style.marginLeft = gutter.offsetWidth + "px";
1093
+ gutterDirty = false;
1094
+ return resized;
1095
+ }
1096
+ function updateSelection() {
1097
+ var collapsed = posEq(sel.from, sel.to);
1098
+ var fromPos = localCoords(sel.from, true);
1099
+ var toPos = collapsed ? fromPos : localCoords(sel.to, true);
1100
+ var headPos = sel.inverted ? fromPos : toPos, th = textHeight();
1101
+ var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv);
1102
+ inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px";
1103
+ inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px";
1104
+ if (collapsed) {
1105
+ cursor.style.top = headPos.y + "px";
1106
+ cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px";
1107
+ cursor.style.display = "";
1108
+ selectionDiv.style.display = "none";
1109
+ } else {
1110
+ var sameLine = fromPos.y == toPos.y, html = "";
1111
+ function add(left, top, right, height) {
1112
+ html += '<div class="CodeMirror-selected" style="position: absolute; left: ' + left +
1113
+ 'px; top: ' + top + 'px; right: ' + right + 'px; height: ' + height + 'px"></div>';
1114
+ }
1115
+ var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
1116
+ var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
1117
+ if (sel.from.ch && fromPos.y >= 0) {
1118
+ var right = sameLine ? clientWidth - toPos.x : 0;
1119
+ add(fromPos.x, fromPos.y, right, th);
1120
+ }
1121
+ var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0));
1122
+ var middleHeight = Math.min(toPos.y, clientHeight) - middleStart;
1123
+ if (middleHeight > 0.2 * th)
1124
+ add(0, middleStart, 0, middleHeight);
1125
+ if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
1126
+ add(0, toPos.y, clientWidth - toPos.x, th);
1127
+ selectionDiv.innerHTML = html;
1128
+ cursor.style.display = "none";
1129
+ selectionDiv.style.display = "";
1130
+ }
1131
+ }
1132
+
1133
+ function setShift(val) {
1134
+ if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
1135
+ else shiftSelecting = null;
1136
+ }
1137
+ function setSelectionUser(from, to) {
1138
+ var sh = shiftSelecting && clipPos(shiftSelecting);
1139
+ if (sh) {
1140
+ if (posLess(sh, from)) from = sh;
1141
+ else if (posLess(to, sh)) to = sh;
1142
+ }
1143
+ setSelection(from, to);
1144
+ userSelChange = true;
1145
+ }
1146
+ // Update the selection. Last two args are only used by
1147
+ // updateLines, since they have to be expressed in the line
1148
+ // numbers before the update.
1149
+ function setSelection(from, to, oldFrom, oldTo) {
1150
+ goalColumn = null;
1151
+ if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
1152
+ if (posEq(sel.from, from) && posEq(sel.to, to)) return;
1153
+ if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
1154
+
1155
+ // Skip over hidden lines.
1156
+ if (from.line != oldFrom) {
1157
+ var from1 = skipHidden(from, oldFrom, sel.from.ch);
1158
+ // If there is no non-hidden line left, force visibility on current line
1159
+ if (!from1) setLineHidden(from.line, false);
1160
+ else from = from1;
1161
+ }
1162
+ if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
1163
+
1164
+ if (posEq(from, to)) sel.inverted = false;
1165
+ else if (posEq(from, sel.to)) sel.inverted = false;
1166
+ else if (posEq(to, sel.from)) sel.inverted = true;
1167
+
1168
+ if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
1169
+ var head = sel.inverted ? from : to;
1170
+ if (head.line != sel.from.line && sel.from.line < doc.size) {
1171
+ var oldLine = getLine(sel.from.line);
1172
+ if (/^\s+$/.test(oldLine.text))
1173
+ setTimeout(operation(function() {
1174
+ if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
1175
+ var no = lineNo(oldLine);
1176
+ replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
1177
+ }
1178
+ }, 10));
1179
+ }
1180
+ }
1181
+
1182
+ sel.from = from; sel.to = to;
1183
+ selectionChanged = true;
1184
+ }
1185
+ function skipHidden(pos, oldLine, oldCh) {
1186
+ function getNonHidden(dir) {
1187
+ var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1;
1188
+ while (lNo != end) {
1189
+ var line = getLine(lNo);
1190
+ if (!line.hidden) {
1191
+ var ch = pos.ch;
1192
+ if (ch > oldCh || ch > line.text.length) ch = line.text.length;
1193
+ return {line: lNo, ch: ch};
1194
+ }
1195
+ lNo += dir;
1196
+ }
1197
+ }
1198
+ var line = getLine(pos.line);
1199
+ if (!line.hidden) return pos;
1200
+ if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1);
1201
+ else return getNonHidden(-1) || getNonHidden(1);
1202
+ }
1203
+ function setCursor(line, ch, user) {
1204
+ var pos = clipPos({line: line, ch: ch || 0});
1205
+ (user ? setSelectionUser : setSelection)(pos, pos);
1206
+ }
1207
+
1208
+ function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));}
1209
+ function clipPos(pos) {
1210
+ if (pos.line < 0) return {line: 0, ch: 0};
1211
+ if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length};
1212
+ var ch = pos.ch, linelen = getLine(pos.line).text.length;
1213
+ if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
1214
+ else if (ch < 0) return {line: pos.line, ch: 0};
1215
+ else return pos;
1216
+ }
1217
+
1218
+ function findPosH(dir, unit) {
1219
+ var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch;
1220
+ var lineObj = getLine(line);
1221
+ function findNextLine() {
1222
+ for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) {
1223
+ var lo = getLine(l);
1224
+ if (!lo.hidden) { line = l; lineObj = lo; return true; }
1225
+ }
1226
+ }
1227
+ function moveOnce(boundToLine) {
1228
+ if (ch == (dir < 0 ? 0 : lineObj.text.length)) {
1229
+ if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0;
1230
+ else return false;
1231
+ } else ch += dir;
1232
+ return true;
1233
+ }
1234
+ if (unit == "char") moveOnce();
1235
+ else if (unit == "column") moveOnce(true);
1236
+ else if (unit == "word") {
1237
+ var sawWord = false;
1238
+ for (;;) {
1239
+ if (dir < 0) if (!moveOnce()) break;
1240
+ if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
1241
+ else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
1242
+ if (dir > 0) if (!moveOnce()) break;
1243
+ }
1244
+ }
1245
+ return {line: line, ch: ch};
1246
+ }
1247
+ function moveH(dir, unit) {
1248
+ var pos = dir < 0 ? sel.from : sel.to;
1249
+ if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit);
1250
+ setCursor(pos.line, pos.ch, true);
1251
+ }
1252
+ function deleteH(dir, unit) {
1253
+ if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to);
1254
+ else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to);
1255
+ else replaceRange("", sel.from, findPosH(dir, unit));
1256
+ userSelChange = true;
1257
+ }
1258
+ var goalColumn = null;
1259
+ function moveV(dir, unit) {
1260
+ var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true);
1261
+ if (goalColumn != null) pos.x = goalColumn;
1262
+ if (unit == "page") dist = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
1263
+ else if (unit == "line") dist = textHeight();
1264
+ var target = coordsChar(pos.x, pos.y + dist * dir + 2);
1265
+ if (unit == "page") scroller.scrollTop += localCoords(target, true).y - pos.y;
1266
+ setCursor(target.line, target.ch, true);
1267
+ goalColumn = pos.x;
1268
+ }
1269
+
1270
+ function selectWordAt(pos) {
1271
+ var line = getLine(pos.line).text;
1272
+ var start = pos.ch, end = pos.ch;
1273
+ while (start > 0 && isWordChar(line.charAt(start - 1))) --start;
1274
+ while (end < line.length && isWordChar(line.charAt(end))) ++end;
1275
+ setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
1276
+ }
1277
+ function selectLine(line) {
1278
+ setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0}));
1279
+ }
1280
+ function indentSelected(mode) {
1281
+ if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
1282
+ var e = sel.to.line - (sel.to.ch ? 0 : 1);
1283
+ for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
1284
+ }
1285
+
1286
+ function indentLine(n, how) {
1287
+ if (!how) how = "add";
1288
+ if (how == "smart") {
1289
+ if (!mode.indent) how = "prev";
1290
+ else var state = getStateBefore(n);
1291
+ }
1292
+
1293
+ var line = getLine(n), curSpace = line.indentation(options.tabSize),
1294
+ curSpaceString = line.text.match(/^\s*/)[0], indentation;
1295
+ if (how == "prev") {
1296
+ if (n) indentation = getLine(n-1).indentation(options.tabSize);
1297
+ else indentation = 0;
1298
+ }
1299
+ else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text);
1300
+ else if (how == "add") indentation = curSpace + options.indentUnit;
1301
+ else if (how == "subtract") indentation = curSpace - options.indentUnit;
1302
+ indentation = Math.max(0, indentation);
1303
+ var diff = indentation - curSpace;
1304
+
1305
+ if (!diff) {
1306
+ if (sel.from.line != n && sel.to.line != n) return;
1307
+ var indentString = curSpaceString;
1308
+ }
1309
+ else {
1310
+ var indentString = "", pos = 0;
1311
+ if (options.indentWithTabs)
1312
+ for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";}
1313
+ while (pos < indentation) {++pos; indentString += " ";}
1314
+ }
1315
+
1316
+ replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
1317
+ }
1318
+
1319
+ function loadMode() {
1320
+ mode = CodeMirror.getMode(options, options.mode);
1321
+ doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
1322
+ work = [0];
1323
+ startWorker();
1324
+ }
1325
+ function gutterChanged() {
1326
+ var visible = options.gutter || options.lineNumbers;
1327
+ gutter.style.display = visible ? "" : "none";
1328
+ if (visible) gutterDirty = true;
1329
+ else lineDiv.parentNode.style.marginLeft = 0;
1330
+ }
1331
+ function wrappingChanged(from, to) {
1332
+ if (options.lineWrapping) {
1333
+ wrapper.className += " CodeMirror-wrap";
1334
+ var perLine = scroller.clientWidth / charWidth() - 3;
1335
+ doc.iter(0, doc.size, function(line) {
1336
+ if (line.hidden) return;
1337
+ var guess = Math.ceil(line.text.length / perLine) || 1;
1338
+ if (guess != 1) updateLineHeight(line, guess);
1339
+ });
1340
+ lineSpace.style.width = code.style.width = "";
1341
+ } else {
1342
+ wrapper.className = wrapper.className.replace(" CodeMirror-wrap", "");
1343
+ maxWidth = null; maxLine = "";
1344
+ doc.iter(0, doc.size, function(line) {
1345
+ if (line.height != 1 && !line.hidden) updateLineHeight(line, 1);
1346
+ if (line.text.length > maxLine.length) maxLine = line.text;
1347
+ });
1348
+ }
1349
+ changes.push({from: 0, to: doc.size});
1350
+ }
1351
+ function makeTab(col) {
1352
+ var w = options.tabSize - col % options.tabSize, cached = tabCache[w];
1353
+ if (cached) return cached;
1354
+ for (var str = '<span class="cm-tab">', i = 0; i < w; ++i) str += " ";
1355
+ return (tabCache[w] = {html: str + "</span>", width: w});
1356
+ }
1357
+ function themeChanged() {
1358
+ scroller.className = scroller.className.replace(/\s*cm-s-\w+/g, "") +
1359
+ options.theme.replace(/(^|\s)\s*/g, " cm-s-");
1360
+ }
1361
+
1362
+ function TextMarker() { this.set = []; }
1363
+ TextMarker.prototype.clear = operation(function() {
1364
+ var min = Infinity, max = -Infinity;
1365
+ for (var i = 0, e = this.set.length; i < e; ++i) {
1366
+ var line = this.set[i], mk = line.marked;
1367
+ if (!mk || !line.parent) continue;
1368
+ var lineN = lineNo(line);
1369
+ min = Math.min(min, lineN); max = Math.max(max, lineN);
1370
+ for (var j = 0; j < mk.length; ++j)
1371
+ if (mk[j].marker == this) mk.splice(j--, 1);
1372
+ }
1373
+ if (min != Infinity)
1374
+ changes.push({from: min, to: max + 1});
1375
+ });
1376
+ TextMarker.prototype.find = function() {
1377
+ var from, to;
1378
+ for (var i = 0, e = this.set.length; i < e; ++i) {
1379
+ var line = this.set[i], mk = line.marked;
1380
+ for (var j = 0; j < mk.length; ++j) {
1381
+ var mark = mk[j];
1382
+ if (mark.marker == this) {
1383
+ if (mark.from != null || mark.to != null) {
1384
+ var found = lineNo(line);
1385
+ if (found != null) {
1386
+ if (mark.from != null) from = {line: found, ch: mark.from};
1387
+ if (mark.to != null) to = {line: found, ch: mark.to};
1388
+ }
1389
+ }
1390
+ }
1391
+ }
1392
+ }
1393
+ return {from: from, to: to};
1394
+ };
1395
+
1396
+ function markText(from, to, className) {
1397
+ from = clipPos(from); to = clipPos(to);
1398
+ var tm = new TextMarker();
1399
+ if (!posLess(from, to)) return tm;
1400
+ function add(line, from, to, className) {
1401
+ getLine(line).addMark(new MarkedText(from, to, className, tm));
1402
+ }
1403
+ if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1404
+ else {
1405
+ add(from.line, from.ch, null, className);
1406
+ for (var i = from.line + 1, e = to.line; i < e; ++i)
1407
+ add(i, null, null, className);
1408
+ add(to.line, null, to.ch, className);
1409
+ }
1410
+ changes.push({from: from.line, to: to.line + 1});
1411
+ return tm;
1412
+ }
1413
+
1414
+ function setBookmark(pos) {
1415
+ pos = clipPos(pos);
1416
+ var bm = new Bookmark(pos.ch);
1417
+ getLine(pos.line).addMark(bm);
1418
+ return bm;
1419
+ }
1420
+
1421
+ function findMarksAt(pos) {
1422
+ pos = clipPos(pos);
1423
+ var markers = [], marked = getLine(pos.line).marked;
1424
+ if (!marked) return markers;
1425
+ for (var i = 0, e = marked.length; i < e; ++i) {
1426
+ var m = marked[i];
1427
+ if ((m.from == null || m.from <= pos.ch) &&
1428
+ (m.to == null || m.to >= pos.ch))
1429
+ markers.push(m.marker || m);
1430
+ }
1431
+ return markers;
1432
+ }
1433
+
1434
+ function addGutterMarker(line, text, className) {
1435
+ if (typeof line == "number") line = getLine(clipLine(line));
1436
+ line.gutterMarker = {text: text, style: className};
1437
+ gutterDirty = true;
1438
+ return line;
1439
+ }
1440
+ function removeGutterMarker(line) {
1441
+ if (typeof line == "number") line = getLine(clipLine(line));
1442
+ line.gutterMarker = null;
1443
+ gutterDirty = true;
1444
+ }
1445
+
1446
+ function changeLine(handle, op) {
1447
+ var no = handle, line = handle;
1448
+ if (typeof handle == "number") line = getLine(clipLine(handle));
1449
+ else no = lineNo(handle);
1450
+ if (no == null) return null;
1451
+ if (op(line, no)) changes.push({from: no, to: no + 1});
1452
+ else return null;
1453
+ return line;
1454
+ }
1455
+ function setLineClass(handle, className, bgClassName) {
1456
+ return changeLine(handle, function(line) {
1457
+ if (line.className != className || line.bgClassName != bgClassName) {
1458
+ line.className = className;
1459
+ line.bgClassName = bgClassName;
1460
+ return true;
1461
+ }
1462
+ });
1463
+ }
1464
+ function setLineHidden(handle, hidden) {
1465
+ return changeLine(handle, function(line, no) {
1466
+ if (line.hidden != hidden) {
1467
+ line.hidden = hidden;
1468
+ updateLineHeight(line, hidden ? 0 : 1);
1469
+ var fline = sel.from.line, tline = sel.to.line;
1470
+ if (hidden && (fline == no || tline == no)) {
1471
+ var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from;
1472
+ var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to;
1473
+ // Can't hide the last visible line, we'd have no place to put the cursor
1474
+ if (!to) return;
1475
+ setSelection(from, to);
1476
+ }
1477
+ return (gutterDirty = true);
1478
+ }
1479
+ });
1480
+ }
1481
+
1482
+ function lineInfo(line) {
1483
+ if (typeof line == "number") {
1484
+ if (!isLine(line)) return null;
1485
+ var n = line;
1486
+ line = getLine(line);
1487
+ if (!line) return null;
1488
+ }
1489
+ else {
1490
+ var n = lineNo(line);
1491
+ if (n == null) return null;
1492
+ }
1493
+ var marker = line.gutterMarker;
1494
+ return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
1495
+ markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
1496
+ }
1497
+
1498
+ function stringWidth(str) {
1499
+ measure.innerHTML = "<pre><span>x</span></pre>";
1500
+ measure.firstChild.firstChild.firstChild.nodeValue = str;
1501
+ return measure.firstChild.firstChild.offsetWidth || 10;
1502
+ }
1503
+ // These are used to go from pixel positions to character
1504
+ // positions, taking varying character widths into account.
1505
+ function charFromX(line, x) {
1506
+ if (x <= 0) return 0;
1507
+ var lineObj = getLine(line), text = lineObj.text;
1508
+ function getX(len) {
1509
+ measure.innerHTML = "<pre><span>" + lineObj.getHTML(makeTab, len) + "</span></pre>";
1510
+ return measure.firstChild.firstChild.offsetWidth;
1511
+ }
1512
+ var from = 0, fromX = 0, to = text.length, toX;
1513
+ // Guess a suitable upper bound for our search.
1514
+ var estimated = Math.min(to, Math.ceil(x / charWidth()));
1515
+ for (;;) {
1516
+ var estX = getX(estimated);
1517
+ if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1518
+ else {toX = estX; to = estimated; break;}
1519
+ }
1520
+ if (x > toX) return to;
1521
+ // Try to guess a suitable lower bound as well.
1522
+ estimated = Math.floor(to * 0.8); estX = getX(estimated);
1523
+ if (estX < x) {from = estimated; fromX = estX;}
1524
+ // Do a binary search between these bounds.
1525
+ for (;;) {
1526
+ if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1527
+ var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1528
+ if (middleX > x) {to = middle; toX = middleX;}
1529
+ else {from = middle; fromX = middleX;}
1530
+ }
1531
+ }
1532
+
1533
+ var tempId = Math.floor(Math.random() * 0xffffff).toString(16);
1534
+ function measureLine(line, ch) {
1535
+ if (ch == 0) return {top: 0, left: 0};
1536
+ var extra = "";
1537
+ // Include extra text at the end to make sure the measured line is wrapped in the right way.
1538
+ if (options.lineWrapping) {
1539
+ var end = line.text.indexOf(" ", ch + 6);
1540
+ extra = htmlEscape(line.text.slice(ch + 1, end < 0 ? line.text.length : end + (ie ? 5 : 0)));
1541
+ }
1542
+ measure.innerHTML = "<pre>" + line.getHTML(makeTab, ch) +
1543
+ '<span id="CodeMirror-temp-' + tempId + '">' + htmlEscape(line.text.charAt(ch) || " ") + "</span>" +
1544
+ extra + "</pre>";
1545
+ var elt = document.getElementById("CodeMirror-temp-" + tempId);
1546
+ var top = elt.offsetTop, left = elt.offsetLeft;
1547
+ // Older IEs report zero offsets for spans directly after a wrap
1548
+ if (ie && top == 0 && left == 0) {
1549
+ var backup = document.createElement("span");
1550
+ backup.innerHTML = "x";
1551
+ elt.parentNode.insertBefore(backup, elt.nextSibling);
1552
+ top = backup.offsetTop;
1553
+ }
1554
+ return {top: top, left: left};
1555
+ }
1556
+ function localCoords(pos, inLineWrap) {
1557
+ var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0));
1558
+ if (pos.ch == 0) x = 0;
1559
+ else {
1560
+ var sp = measureLine(getLine(pos.line), pos.ch);
1561
+ x = sp.left;
1562
+ if (options.lineWrapping) y += Math.max(0, sp.top);
1563
+ }
1564
+ return {x: x, y: y, yBot: y + lh};
1565
+ }
1566
+ // Coords must be lineSpace-local
1567
+ function coordsChar(x, y) {
1568
+ if (y < 0) y = 0;
1569
+ var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th);
1570
+ var lineNo = lineAtHeight(doc, heightPos);
1571
+ if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length};
1572
+ var lineObj = getLine(lineNo), text = lineObj.text;
1573
+ var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0;
1574
+ if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0};
1575
+ function getX(len) {
1576
+ var sp = measureLine(lineObj, len);
1577
+ if (tw) {
1578
+ var off = Math.round(sp.top / th);
1579
+ return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth);
1580
+ }
1581
+ return sp.left;
1582
+ }
1583
+ var from = 0, fromX = 0, to = text.length, toX;
1584
+ // Guess a suitable upper bound for our search.
1585
+ var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw));
1586
+ for (;;) {
1587
+ var estX = getX(estimated);
1588
+ if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1589
+ else {toX = estX; to = estimated; break;}
1590
+ }
1591
+ if (x > toX) return {line: lineNo, ch: to};
1592
+ // Try to guess a suitable lower bound as well.
1593
+ estimated = Math.floor(to * 0.8); estX = getX(estimated);
1594
+ if (estX < x) {from = estimated; fromX = estX;}
1595
+ // Do a binary search between these bounds.
1596
+ for (;;) {
1597
+ if (to - from <= 1) return {line: lineNo, ch: (toX - x > x - fromX) ? from : to};
1598
+ var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1599
+ if (middleX > x) {to = middle; toX = middleX;}
1600
+ else {from = middle; fromX = middleX;}
1601
+ }
1602
+ }
1603
+ function pageCoords(pos) {
1604
+ var local = localCoords(pos, true), off = eltOffset(lineSpace);
1605
+ return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1606
+ }
1607
+
1608
+ var cachedHeight, cachedHeightFor, measureText;
1609
+ function textHeight() {
1610
+ if (measureText == null) {
1611
+ measureText = "<pre>";
1612
+ for (var i = 0; i < 49; ++i) measureText += "x<br/>";
1613
+ measureText += "x</pre>";
1614
+ }
1615
+ var offsetHeight = lineDiv.clientHeight;
1616
+ if (offsetHeight == cachedHeightFor) return cachedHeight;
1617
+ cachedHeightFor = offsetHeight;
1618
+ measure.innerHTML = measureText;
1619
+ cachedHeight = measure.firstChild.offsetHeight / 50 || 1;
1620
+ measure.innerHTML = "";
1621
+ return cachedHeight;
1622
+ }
1623
+ var cachedWidth, cachedWidthFor = 0;
1624
+ function charWidth() {
1625
+ if (scroller.clientWidth == cachedWidthFor) return cachedWidth;
1626
+ cachedWidthFor = scroller.clientWidth;
1627
+ return (cachedWidth = stringWidth("x"));
1628
+ }
1629
+ function paddingTop() {return lineSpace.offsetTop;}
1630
+ function paddingLeft() {return lineSpace.offsetLeft;}
1631
+
1632
+ function posFromMouse(e, liberal) {
1633
+ var offW = eltOffset(scroller, true), x, y;
1634
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1635
+ try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1636
+ // This is a mess of a heuristic to try and determine whether a
1637
+ // scroll-bar was clicked or not, and to return null if one was
1638
+ // (and !liberal).
1639
+ if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1640
+ return null;
1641
+ var offL = eltOffset(lineSpace, true);
1642
+ return coordsChar(x - offL.left, y - offL.top);
1643
+ }
1644
+ function onContextMenu(e) {
1645
+ var pos = posFromMouse(e), scrollPos = scroller.scrollTop;
1646
+ if (!pos || window.opera) return; // Opera is difficult.
1647
+ if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1648
+ operation(setCursor)(pos.line, pos.ch);
1649
+
1650
+ var oldCSS = input.style.cssText;
1651
+ inputDiv.style.position = "absolute";
1652
+ input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1653
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
1654
+ "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1655
+ leaveInputAlone = true;
1656
+ var val = input.value = getSelection();
1657
+ focusInput();
1658
+ selectInput(input);
1659
+ function rehide() {
1660
+ var newVal = splitLines(input.value).join("\n");
1661
+ if (newVal != val) operation(replaceSelection)(newVal, "end");
1662
+ inputDiv.style.position = "relative";
1663
+ input.style.cssText = oldCSS;
1664
+ if (ie_lt9) scroller.scrollTop = scrollPos;
1665
+ leaveInputAlone = false;
1666
+ resetInput(true);
1667
+ slowPoll();
1668
+ }
1669
+
1670
+ if (gecko) {
1671
+ e_stop(e);
1672
+ var mouseup = connect(window, "mouseup", function() {
1673
+ mouseup();
1674
+ setTimeout(rehide, 20);
1675
+ }, true);
1676
+ } else {
1677
+ setTimeout(rehide, 50);
1678
+ }
1679
+ }
1680
+
1681
+ // Cursor-blinking
1682
+ function restartBlink() {
1683
+ clearInterval(blinker);
1684
+ var on = true;
1685
+ cursor.style.visibility = "";
1686
+ blinker = setInterval(function() {
1687
+ cursor.style.visibility = (on = !on) ? "" : "hidden";
1688
+ }, 650);
1689
+ }
1690
+
1691
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1692
+ function matchBrackets(autoclear) {
1693
+ var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1;
1694
+ var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1695
+ if (!match) return;
1696
+ var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1697
+ for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1698
+ if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1699
+
1700
+ var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1701
+ function scan(line, from, to) {
1702
+ if (!line.text) return;
1703
+ var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1704
+ for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1705
+ var text = st[i];
1706
+ if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;}
1707
+ for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1708
+ if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1709
+ var match = matching[cur];
1710
+ if (match.charAt(1) == ">" == forward) stack.push(cur);
1711
+ else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1712
+ else if (!stack.length) return {pos: pos, match: true};
1713
+ }
1714
+ }
1715
+ }
1716
+ }
1717
+ for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) {
1718
+ var line = getLine(i), first = i == head.line;
1719
+ var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1720
+ if (found) break;
1721
+ }
1722
+ if (!found) found = {pos: null, match: false};
1723
+ var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1724
+ var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1725
+ two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style);
1726
+ var clear = operation(function(){one.clear(); two && two.clear();});
1727
+ if (autoclear) setTimeout(clear, 800);
1728
+ else bracketHighlighted = clear;
1729
+ }
1730
+
1731
+ // Finds the line to start with when starting a parse. Tries to
1732
+ // find a line with a stateAfter, so that it can start with a
1733
+ // valid state. If that fails, it returns the line with the
1734
+ // smallest indentation, which tends to need the least context to
1735
+ // parse correctly.
1736
+ function findStartLine(n) {
1737
+ var minindent, minline;
1738
+ for (var search = n, lim = n - 40; search > lim; --search) {
1739
+ if (search == 0) return 0;
1740
+ var line = getLine(search-1);
1741
+ if (line.stateAfter) return search;
1742
+ var indented = line.indentation(options.tabSize);
1743
+ if (minline == null || minindent > indented) {
1744
+ minline = search - 1;
1745
+ minindent = indented;
1746
+ }
1747
+ }
1748
+ return minline;
1749
+ }
1750
+ function getStateBefore(n) {
1751
+ var start = findStartLine(n), state = start && getLine(start-1).stateAfter;
1752
+ if (!state) state = startState(mode);
1753
+ else state = copyState(mode, state);
1754
+ doc.iter(start, n, function(line) {
1755
+ line.highlight(mode, state, options.tabSize);
1756
+ line.stateAfter = copyState(mode, state);
1757
+ });
1758
+ if (start < n) changes.push({from: start, to: n});
1759
+ if (n < doc.size && !getLine(n).stateAfter) work.push(n);
1760
+ return state;
1761
+ }
1762
+ function highlightLines(start, end) {
1763
+ var state = getStateBefore(start);
1764
+ doc.iter(start, end, function(line) {
1765
+ line.highlight(mode, state, options.tabSize);
1766
+ line.stateAfter = copyState(mode, state);
1767
+ });
1768
+ }
1769
+ function highlightWorker() {
1770
+ var end = +new Date + options.workTime;
1771
+ var foundWork = work.length;
1772
+ while (work.length) {
1773
+ if (!getLine(showingFrom).stateAfter) var task = showingFrom;
1774
+ else var task = work.pop();
1775
+ if (task >= doc.size) continue;
1776
+ var start = findStartLine(task), state = start && getLine(start-1).stateAfter;
1777
+ if (state) state = copyState(mode, state);
1778
+ else state = startState(mode);
1779
+
1780
+ var unchanged = 0, compare = mode.compareStates, realChange = false,
1781
+ i = start, bail = false;
1782
+ doc.iter(i, doc.size, function(line) {
1783
+ var hadState = line.stateAfter;
1784
+ if (+new Date > end) {
1785
+ work.push(i);
1786
+ startWorker(options.workDelay);
1787
+ if (realChange) changes.push({from: task, to: i + 1});
1788
+ return (bail = true);
1789
+ }
1790
+ var changed = line.highlight(mode, state, options.tabSize);
1791
+ if (changed) realChange = true;
1792
+ line.stateAfter = copyState(mode, state);
1793
+ if (compare) {
1794
+ if (hadState && compare(hadState, state)) return true;
1795
+ } else {
1796
+ if (changed !== false || !hadState) unchanged = 0;
1797
+ else if (++unchanged > 3 && (!mode.indent || mode.indent(hadState, "") == mode.indent(state, "")))
1798
+ return true;
1799
+ }
1800
+ ++i;
1801
+ });
1802
+ if (bail) return;
1803
+ if (realChange) changes.push({from: task, to: i + 1});
1804
+ }
1805
+ if (foundWork && options.onHighlightComplete)
1806
+ options.onHighlightComplete(instance);
1807
+ }
1808
+ function startWorker(time) {
1809
+ if (!work.length) return;
1810
+ highlight.set(time, operation(highlightWorker));
1811
+ }
1812
+
1813
+ // Operations are used to wrap changes in such a way that each
1814
+ // change won't have to update the cursor and display (which would
1815
+ // be awkward, slow, and error-prone), but instead updates are
1816
+ // batched and then all combined and executed at once.
1817
+ function startOperation() {
1818
+ updateInput = userSelChange = textChanged = null;
1819
+ changes = []; selectionChanged = false; callbacks = [];
1820
+ }
1821
+ function endOperation() {
1822
+ var reScroll = false, updated;
1823
+ if (selectionChanged) reScroll = !scrollCursorIntoView();
1824
+ if (changes.length) updated = updateDisplay(changes, true);
1825
+ else {
1826
+ if (selectionChanged) updateSelection();
1827
+ if (gutterDirty) updateGutter();
1828
+ }
1829
+ if (reScroll) scrollCursorIntoView();
1830
+ if (selectionChanged) {scrollEditorIntoView(); restartBlink();}
1831
+
1832
+ if (focused && !leaveInputAlone &&
1833
+ (updateInput === true || (updateInput !== false && selectionChanged)))
1834
+ resetInput(userSelChange);
1835
+
1836
+ if (selectionChanged && options.matchBrackets)
1837
+ setTimeout(operation(function() {
1838
+ if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
1839
+ if (posEq(sel.from, sel.to)) matchBrackets(false);
1840
+ }), 20);
1841
+ var tc = textChanged, cbs = callbacks; // these can be reset by callbacks
1842
+ if (selectionChanged && options.onCursorActivity)
1843
+ options.onCursorActivity(instance);
1844
+ if (tc && options.onChange && instance)
1845
+ options.onChange(instance, tc);
1846
+ for (var i = 0; i < cbs.length; ++i) cbs[i](instance);
1847
+ if (updated && options.onUpdate) options.onUpdate(instance);
1848
+ }
1849
+ var nestedOperation = 0;
1850
+ function operation(f) {
1851
+ return function() {
1852
+ if (!nestedOperation++) startOperation();
1853
+ try {var result = f.apply(this, arguments);}
1854
+ finally {if (!--nestedOperation) endOperation();}
1855
+ return result;
1856
+ };
1857
+ }
1858
+
1859
+ for (var ext in extensions)
1860
+ if (extensions.propertyIsEnumerable(ext) &&
1861
+ !instance.propertyIsEnumerable(ext))
1862
+ instance[ext] = extensions[ext];
1863
+ return instance;
1864
+ } // (end of function CodeMirror)
1865
+
1866
+ // The default configuration options.
1867
+ CodeMirror.defaults = {
1868
+ value: "",
1869
+ mode: null,
1870
+ theme: "default",
1871
+ indentUnit: 2,
1872
+ indentWithTabs: false,
1873
+ smartIndent: true,
1874
+ tabSize: 4,
1875
+ keyMap: "default",
1876
+ extraKeys: null,
1877
+ electricChars: true,
1878
+ autoClearEmptyLines: false,
1879
+ onKeyEvent: null,
1880
+ lineWrapping: false,
1881
+ lineNumbers: false,
1882
+ gutter: false,
1883
+ fixedGutter: false,
1884
+ firstLineNumber: 1,
1885
+ readOnly: false,
1886
+ onChange: null,
1887
+ onCursorActivity: null,
1888
+ onGutterClick: null,
1889
+ onHighlightComplete: null,
1890
+ onUpdate: null,
1891
+ onFocus: null, onBlur: null, onScroll: null,
1892
+ matchBrackets: false,
1893
+ workTime: 100,
1894
+ workDelay: 200,
1895
+ pollInterval: 100,
1896
+ undoDepth: 40,
1897
+ tabindex: null,
1898
+ autofocus: null
1899
+ };
1900
+
1901
+ var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
1902
+ var mac = ios || /Mac/.test(navigator.platform);
1903
+ var win = /Win/.test(navigator.platform);
1904
+
1905
+ // Known modes, by name and by MIME
1906
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
1907
+ CodeMirror.defineMode = function(name, mode) {
1908
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
1909
+ modes[name] = mode;
1910
+ };
1911
+ CodeMirror.defineMIME = function(mime, spec) {
1912
+ mimeModes[mime] = spec;
1913
+ };
1914
+ CodeMirror.resolveMode = function(spec) {
1915
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
1916
+ spec = mimeModes[spec];
1917
+ else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
1918
+ return CodeMirror.resolveMode("application/xml");
1919
+ if (typeof spec == "string") return {name: spec};
1920
+ else return spec || {name: "null"};
1921
+ };
1922
+ CodeMirror.getMode = function(options, spec) {
1923
+ var spec = CodeMirror.resolveMode(spec);
1924
+ var mfactory = modes[spec.name];
1925
+ if (!mfactory) {
1926
+ if (window.console) console.warn("No mode " + spec.name + " found, falling back to plain text.");
1927
+ return CodeMirror.getMode(options, "text/plain");
1928
+ }
1929
+ return mfactory(options, spec);
1930
+ };
1931
+ CodeMirror.listModes = function() {
1932
+ var list = [];
1933
+ for (var m in modes)
1934
+ if (modes.propertyIsEnumerable(m)) list.push(m);
1935
+ return list;
1936
+ };
1937
+ CodeMirror.listMIMEs = function() {
1938
+ var list = [];
1939
+ for (var m in mimeModes)
1940
+ if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]});
1941
+ return list;
1942
+ };
1943
+
1944
+ var extensions = CodeMirror.extensions = {};
1945
+ CodeMirror.defineExtension = function(name, func) {
1946
+ extensions[name] = func;
1947
+ };
1948
+
1949
+ var commands = CodeMirror.commands = {
1950
+ selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
1951
+ killLine: function(cm) {
1952
+ var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
1953
+ if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0});
1954
+ else cm.replaceRange("", from, sel ? to : {line: from.line});
1955
+ },
1956
+ deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});},
1957
+ undo: function(cm) {cm.undo();},
1958
+ redo: function(cm) {cm.redo();},
1959
+ goDocStart: function(cm) {cm.setCursor(0, 0, true);},
1960
+ goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);},
1961
+ goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);},
1962
+ goLineStartSmart: function(cm) {
1963
+ var cur = cm.getCursor();
1964
+ var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/));
1965
+ cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true);
1966
+ },
1967
+ goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);},
1968
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
1969
+ goLineDown: function(cm) {cm.moveV(1, "line");},
1970
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
1971
+ goPageDown: function(cm) {cm.moveV(1, "page");},
1972
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
1973
+ goCharRight: function(cm) {cm.moveH(1, "char");},
1974
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
1975
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
1976
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
1977
+ goWordRight: function(cm) {cm.moveH(1, "word");},
1978
+ delCharLeft: function(cm) {cm.deleteH(-1, "char");},
1979
+ delCharRight: function(cm) {cm.deleteH(1, "char");},
1980
+ delWordLeft: function(cm) {cm.deleteH(-1, "word");},
1981
+ delWordRight: function(cm) {cm.deleteH(1, "word");},
1982
+ indentAuto: function(cm) {cm.indentSelection("smart");},
1983
+ indentMore: function(cm) {cm.indentSelection("add");},
1984
+ indentLess: function(cm) {cm.indentSelection("subtract");},
1985
+ insertTab: function(cm) {cm.replaceSelection("\t", "end");},
1986
+ transposeChars: function(cm) {
1987
+ var cur = cm.getCursor(), line = cm.getLine(cur.line);
1988
+ if (cur.ch > 0 && cur.ch < line.length - 1)
1989
+ cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
1990
+ {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
1991
+ },
1992
+ newlineAndIndent: function(cm) {
1993
+ cm.replaceSelection("\n", "end");
1994
+ cm.indentLine(cm.getCursor().line);
1995
+ },
1996
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
1997
+ };
1998
+
1999
+ var keyMap = CodeMirror.keyMap = {};
2000
+ keyMap.basic = {
2001
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
2002
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
2003
+ "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "insertTab", "Shift-Tab": "indentAuto",
2004
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
2005
+ };
2006
+ // Note that the save and find-related commands aren't defined by
2007
+ // default. Unknown commands are simply ignored.
2008
+ keyMap.pcDefault = {
2009
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
2010
+ "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
2011
+ "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
2012
+ "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
2013
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
2014
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
2015
+ fallthrough: "basic"
2016
+ };
2017
+ keyMap.macDefault = {
2018
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
2019
+ "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
2020
+ "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
2021
+ "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
2022
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
2023
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore",
2024
+ fallthrough: ["basic", "emacsy"]
2025
+ };
2026
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
2027
+ keyMap.emacsy = {
2028
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
2029
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
2030
+ "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft",
2031
+ "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
2032
+ };
2033
+
2034
+ function getKeyMap(val) {
2035
+ if (typeof val == "string") return keyMap[val];
2036
+ else return val;
2037
+ }
2038
+ function lookupKey(name, extraMap, map, handle) {
2039
+ function lookup(map) {
2040
+ map = getKeyMap(map);
2041
+ var found = map[name];
2042
+ if (found != null && handle(found)) return true;
2043
+ if (map.catchall) return handle(map.catchall);
2044
+ var fallthrough = map.fallthrough;
2045
+ if (fallthrough == null) return false;
2046
+ if (Object.prototype.toString.call(fallthrough) != "[object Array]")
2047
+ return lookup(fallthrough);
2048
+ for (var i = 0, e = fallthrough.length; i < e; ++i) {
2049
+ if (lookup(fallthrough[i])) return true;
2050
+ }
2051
+ return false;
2052
+ }
2053
+ if (extraMap && lookup(extraMap)) return true;
2054
+ return lookup(map);
2055
+ }
2056
+ function isModifierKey(event) {
2057
+ var name = keyNames[e_prop(event, "keyCode")];
2058
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
2059
+ }
2060
+
2061
+ CodeMirror.fromTextArea = function(textarea, options) {
2062
+ if (!options) options = {};
2063
+ options.value = textarea.value;
2064
+ if (!options.tabindex && textarea.tabindex)
2065
+ options.tabindex = textarea.tabindex;
2066
+ if (options.autofocus == null && textarea.getAttribute("autofocus") != null)
2067
+ options.autofocus = true;
2068
+
2069
+ function save() {textarea.value = instance.getValue();}
2070
+ if (textarea.form) {
2071
+ // Deplorable hack to make the submit method do the right thing.
2072
+ var rmSubmit = connect(textarea.form, "submit", save, true);
2073
+ if (typeof textarea.form.submit == "function") {
2074
+ var realSubmit = textarea.form.submit;
2075
+ function wrappedSubmit() {
2076
+ save();
2077
+ textarea.form.submit = realSubmit;
2078
+ textarea.form.submit();
2079
+ textarea.form.submit = wrappedSubmit;
2080
+ }
2081
+ textarea.form.submit = wrappedSubmit;
2082
+ }
2083
+ }
2084
+
2085
+ textarea.style.display = "none";
2086
+ var instance = CodeMirror(function(node) {
2087
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
2088
+ }, options);
2089
+ instance.save = save;
2090
+ instance.getTextArea = function() { return textarea; };
2091
+ instance.toTextArea = function() {
2092
+ save();
2093
+ textarea.parentNode.removeChild(instance.getWrapperElement());
2094
+ textarea.style.display = "";
2095
+ if (textarea.form) {
2096
+ rmSubmit();
2097
+ if (typeof textarea.form.submit == "function")
2098
+ textarea.form.submit = realSubmit;
2099
+ }
2100
+ };
2101
+ return instance;
2102
+ };
2103
+
2104
+ // Utility functions for working with state. Exported because modes
2105
+ // sometimes need to do this.
2106
+ function copyState(mode, state) {
2107
+ if (state === true) return state;
2108
+ if (mode.copyState) return mode.copyState(state);
2109
+ var nstate = {};
2110
+ for (var n in state) {
2111
+ var val = state[n];
2112
+ if (val instanceof Array) val = val.concat([]);
2113
+ nstate[n] = val;
2114
+ }
2115
+ return nstate;
2116
+ }
2117
+ CodeMirror.copyState = copyState;
2118
+ function startState(mode, a1, a2) {
2119
+ return mode.startState ? mode.startState(a1, a2) : true;
2120
+ }
2121
+ CodeMirror.startState = startState;
2122
+
2123
+ // The character stream used by a mode's parser.
2124
+ function StringStream(string, tabSize) {
2125
+ this.pos = this.start = 0;
2126
+ this.string = string;
2127
+ this.tabSize = tabSize || 8;
2128
+ }
2129
+ StringStream.prototype = {
2130
+ eol: function() {return this.pos >= this.string.length;},
2131
+ sol: function() {return this.pos == 0;},
2132
+ peek: function() {return this.string.charAt(this.pos);},
2133
+ next: function() {
2134
+ if (this.pos < this.string.length)
2135
+ return this.string.charAt(this.pos++);
2136
+ },
2137
+ eat: function(match) {
2138
+ var ch = this.string.charAt(this.pos);
2139
+ if (typeof match == "string") var ok = ch == match;
2140
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
2141
+ if (ok) {++this.pos; return ch;}
2142
+ },
2143
+ eatWhile: function(match) {
2144
+ var start = this.pos;
2145
+ while (this.eat(match)){}
2146
+ return this.pos > start;
2147
+ },
2148
+ eatSpace: function() {
2149
+ var start = this.pos;
2150
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
2151
+ return this.pos > start;
2152
+ },
2153
+ skipToEnd: function() {this.pos = this.string.length;},
2154
+ skipTo: function(ch) {
2155
+ var found = this.string.indexOf(ch, this.pos);
2156
+ if (found > -1) {this.pos = found; return true;}
2157
+ },
2158
+ backUp: function(n) {this.pos -= n;},
2159
+ column: function() {return countColumn(this.string, this.start, this.tabSize);},
2160
+ indentation: function() {return countColumn(this.string, null, this.tabSize);},
2161
+ match: function(pattern, consume, caseInsensitive) {
2162
+ if (typeof pattern == "string") {
2163
+ function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
2164
+ if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
2165
+ if (consume !== false) this.pos += pattern.length;
2166
+ return true;
2167
+ }
2168
+ }
2169
+ else {
2170
+ var match = this.string.slice(this.pos).match(pattern);
2171
+ if (match && consume !== false) this.pos += match[0].length;
2172
+ return match;
2173
+ }
2174
+ },
2175
+ current: function(){return this.string.slice(this.start, this.pos);}
2176
+ };
2177
+ CodeMirror.StringStream = StringStream;
2178
+
2179
+ function MarkedText(from, to, className, marker) {
2180
+ this.from = from; this.to = to; this.style = className; this.marker = marker;
2181
+ }
2182
+ MarkedText.prototype = {
2183
+ attach: function(line) { this.marker.set.push(line); },
2184
+ detach: function(line) {
2185
+ var ix = indexOf(this.marker.set, line);
2186
+ if (ix > -1) this.marker.set.splice(ix, 1);
2187
+ },
2188
+ split: function(pos, lenBefore) {
2189
+ if (this.to <= pos && this.to != null) return null;
2190
+ var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore;
2191
+ var to = this.to == null ? null : this.to - pos + lenBefore;
2192
+ return new MarkedText(from, to, this.style, this.marker);
2193
+ },
2194
+ dup: function() { return new MarkedText(null, null, this.style, this.marker); },
2195
+ clipTo: function(fromOpen, from, toOpen, to, diff) {
2196
+ if (fromOpen && to > this.from && (to < this.to || this.to == null))
2197
+ this.from = null;
2198
+ else if (this.from != null && this.from >= from)
2199
+ this.from = Math.max(to, this.from) + diff;
2200
+ if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null))
2201
+ this.to = null;
2202
+ else if (this.to != null && this.to > from)
2203
+ this.to = to < this.to ? this.to + diff : from;
2204
+ },
2205
+ isDead: function() { return this.from != null && this.to != null && this.from >= this.to; },
2206
+ sameSet: function(x) { return this.marker == x.marker; }
2207
+ };
2208
+
2209
+ function Bookmark(pos) {
2210
+ this.from = pos; this.to = pos; this.line = null;
2211
+ }
2212
+ Bookmark.prototype = {
2213
+ attach: function(line) { this.line = line; },
2214
+ detach: function(line) { if (this.line == line) this.line = null; },
2215
+ split: function(pos, lenBefore) {
2216
+ if (pos < this.from) {
2217
+ this.from = this.to = (this.from - pos) + lenBefore;
2218
+ return this;
2219
+ }
2220
+ },
2221
+ isDead: function() { return this.from > this.to; },
2222
+ clipTo: function(fromOpen, from, toOpen, to, diff) {
2223
+ if ((fromOpen || from < this.from) && (toOpen || to > this.to)) {
2224
+ this.from = 0; this.to = -1;
2225
+ } else if (this.from > from) {
2226
+ this.from = this.to = Math.max(to, this.from) + diff;
2227
+ }
2228
+ },
2229
+ sameSet: function(x) { return false; },
2230
+ find: function() {
2231
+ if (!this.line || !this.line.parent) return null;
2232
+ return {line: lineNo(this.line), ch: this.from};
2233
+ },
2234
+ clear: function() {
2235
+ if (this.line) {
2236
+ var found = indexOf(this.line.marked, this);
2237
+ if (found != -1) this.line.marked.splice(found, 1);
2238
+ this.line = null;
2239
+ }
2240
+ }
2241
+ };
2242
+
2243
+ // Line objects. These hold state related to a line, including
2244
+ // highlighting info (the styles array).
2245
+ function Line(text, styles) {
2246
+ this.styles = styles || [text, null];
2247
+ this.text = text;
2248
+ this.height = 1;
2249
+ this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;
2250
+ this.stateAfter = this.parent = this.hidden = null;
2251
+ }
2252
+ Line.inheritMarks = function(text, orig) {
2253
+ var ln = new Line(text), mk = orig && orig.marked;
2254
+ if (mk) {
2255
+ for (var i = 0; i < mk.length; ++i) {
2256
+ if (mk[i].to == null && mk[i].style) {
2257
+ var newmk = ln.marked || (ln.marked = []), mark = mk[i];
2258
+ var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln);
2259
+ }
2260
+ }
2261
+ }
2262
+ return ln;
2263
+ }
2264
+ Line.prototype = {
2265
+ // Replace a piece of a line, keeping the styles around it intact.
2266
+ replace: function(from, to_, text) {
2267
+ var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_;
2268
+ copyStyles(0, from, this.styles, st);
2269
+ if (text) st.push(text, null);
2270
+ copyStyles(to, this.text.length, this.styles, st);
2271
+ this.styles = st;
2272
+ this.text = this.text.slice(0, from) + text + this.text.slice(to);
2273
+ this.stateAfter = null;
2274
+ if (mk) {
2275
+ var diff = text.length - (to - from);
2276
+ for (var i = 0; i < mk.length; ++i) {
2277
+ var mark = mk[i];
2278
+ mark.clipTo(from == null, from || 0, to_ == null, to, diff);
2279
+ if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);}
2280
+ }
2281
+ }
2282
+ },
2283
+ // Split a part off a line, keeping styles and markers intact.
2284
+ split: function(pos, textBefore) {
2285
+ var st = [textBefore, null], mk = this.marked;
2286
+ copyStyles(pos, this.text.length, this.styles, st);
2287
+ var taken = new Line(textBefore + this.text.slice(pos), st);
2288
+ if (mk) {
2289
+ for (var i = 0; i < mk.length; ++i) {
2290
+ var mark = mk[i];
2291
+ var newmark = mark.split(pos, textBefore.length);
2292
+ if (newmark) {
2293
+ if (!taken.marked) taken.marked = [];
2294
+ taken.marked.push(newmark); newmark.attach(taken);
2295
+ if (newmark == mark) mk.splice(i--, 1);
2296
+ }
2297
+ }
2298
+ }
2299
+ return taken;
2300
+ },
2301
+ append: function(line) {
2302
+ var mylen = this.text.length, mk = line.marked, mymk = this.marked;
2303
+ this.text += line.text;
2304
+ copyStyles(0, line.text.length, line.styles, this.styles);
2305
+ if (mymk) {
2306
+ for (var i = 0; i < mymk.length; ++i)
2307
+ if (mymk[i].to == null) mymk[i].to = mylen;
2308
+ }
2309
+ if (mk && mk.length) {
2310
+ if (!mymk) this.marked = mymk = [];
2311
+ outer: for (var i = 0; i < mk.length; ++i) {
2312
+ var mark = mk[i];
2313
+ if (!mark.from) {
2314
+ for (var j = 0; j < mymk.length; ++j) {
2315
+ var mymark = mymk[j];
2316
+ if (mymark.to == mylen && mymark.sameSet(mark)) {
2317
+ mymark.to = mark.to == null ? null : mark.to + mylen;
2318
+ if (mymark.isDead()) {
2319
+ mymark.detach(this);
2320
+ mk.splice(i--, 1);
2321
+ }
2322
+ continue outer;
2323
+ }
2324
+ }
2325
+ }
2326
+ mymk.push(mark);
2327
+ mark.attach(this);
2328
+ mark.from += mylen;
2329
+ if (mark.to != null) mark.to += mylen;
2330
+ }
2331
+ }
2332
+ },
2333
+ fixMarkEnds: function(other) {
2334
+ var mk = this.marked, omk = other.marked;
2335
+ if (!mk) return;
2336
+ for (var i = 0; i < mk.length; ++i) {
2337
+ var mark = mk[i], close = mark.to == null;
2338
+ if (close && omk) {
2339
+ for (var j = 0; j < omk.length; ++j)
2340
+ if (omk[j].sameSet(mark)) {close = false; break;}
2341
+ }
2342
+ if (close) mark.to = this.text.length;
2343
+ }
2344
+ },
2345
+ fixMarkStarts: function() {
2346
+ var mk = this.marked;
2347
+ if (!mk) return;
2348
+ for (var i = 0; i < mk.length; ++i)
2349
+ if (mk[i].from == null) mk[i].from = 0;
2350
+ },
2351
+ addMark: function(mark) {
2352
+ mark.attach(this);
2353
+ if (this.marked == null) this.marked = [];
2354
+ this.marked.push(mark);
2355
+ this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);});
2356
+ },
2357
+ // Run the given mode's parser over a line, update the styles
2358
+ // array, which contains alternating fragments of text and CSS
2359
+ // classes.
2360
+ highlight: function(mode, state, tabSize) {
2361
+ var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0;
2362
+ var changed = false, curWord = st[0], prevWord;
2363
+ if (this.text == "" && mode.blankLine) mode.blankLine(state);
2364
+ while (!stream.eol()) {
2365
+ var style = mode.token(stream, state);
2366
+ var substr = this.text.slice(stream.start, stream.pos);
2367
+ stream.start = stream.pos;
2368
+ if (pos && st[pos-1] == style)
2369
+ st[pos-2] += substr;
2370
+ else if (substr) {
2371
+ if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
2372
+ st[pos++] = substr; st[pos++] = style;
2373
+ prevWord = curWord; curWord = st[pos];
2374
+ }
2375
+ // Give up when line is ridiculously long
2376
+ if (stream.pos > 5000) {
2377
+ st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
2378
+ break;
2379
+ }
2380
+ }
2381
+ if (st.length != pos) {st.length = pos; changed = true;}
2382
+ if (pos && st[pos-2] != prevWord) changed = true;
2383
+ // Short lines with simple highlights return null, and are
2384
+ // counted as changed by the driver because they are likely to
2385
+ // highlight the same way in various contexts.
2386
+ return changed || (st.length < 5 && this.text.length < 10 ? null : false);
2387
+ },
2388
+ // Fetch the parser token for a given character. Useful for hacks
2389
+ // that want to inspect the mode state (say, for completion).
2390
+ getTokenAt: function(mode, state, ch) {
2391
+ var txt = this.text, stream = new StringStream(txt);
2392
+ while (stream.pos < ch && !stream.eol()) {
2393
+ stream.start = stream.pos;
2394
+ var style = mode.token(stream, state);
2395
+ }
2396
+ return {start: stream.start,
2397
+ end: stream.pos,
2398
+ string: stream.current(),
2399
+ className: style || null,
2400
+ state: state};
2401
+ },
2402
+ indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
2403
+ // Produces an HTML fragment for the line, taking selection,
2404
+ // marking, and highlighting into account.
2405
+ getHTML: function(makeTab, endAt) {
2406
+ var html = [], first = true, col = 0;
2407
+ function span(text, style) {
2408
+ if (!text) return;
2409
+ // Work around a bug where, in some compat modes, IE ignores leading spaces
2410
+ if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
2411
+ first = false;
2412
+ if (text.indexOf("\t") == -1) {
2413
+ col += text.length;
2414
+ var escaped = htmlEscape(text);
2415
+ } else {
2416
+ var escaped = "";
2417
+ for (var pos = 0;;) {
2418
+ var idx = text.indexOf("\t", pos);
2419
+ if (idx == -1) {
2420
+ escaped += htmlEscape(text.slice(pos));
2421
+ col += text.length - pos;
2422
+ break;
2423
+ } else {
2424
+ col += idx - pos;
2425
+ var tab = makeTab(col);
2426
+ escaped += htmlEscape(text.slice(pos, idx)) + tab.html;
2427
+ col += tab.width;
2428
+ pos = idx + 1;
2429
+ }
2430
+ }
2431
+ }
2432
+ if (style) html.push('<span class="', style, '">', escaped, "</span>");
2433
+ else html.push(escaped);
2434
+ }
2435
+ var st = this.styles, allText = this.text, marked = this.marked;
2436
+ var len = allText.length;
2437
+ if (endAt != null) len = Math.min(endAt, len);
2438
+ function styleToClass(style) {
2439
+ if (!style) return null;
2440
+ return "cm-" + style.replace(/ +/g, " cm-");
2441
+ }
2442
+
2443
+ if (!allText && endAt == null)
2444
+ span(" ");
2445
+ else if (!marked || !marked.length)
2446
+ for (var i = 0, ch = 0; ch < len; i+=2) {
2447
+ var str = st[i], style = st[i+1], l = str.length;
2448
+ if (ch + l > len) str = str.slice(0, len - ch);
2449
+ ch += l;
2450
+ span(str, styleToClass(style));
2451
+ }
2452
+ else {
2453
+ var pos = 0, i = 0, text = "", style, sg = 0;
2454
+ var nextChange = marked[0].from || 0, marks = [], markpos = 0;
2455
+ function advanceMarks() {
2456
+ var m;
2457
+ while (markpos < marked.length &&
2458
+ ((m = marked[markpos]).from == pos || m.from == null)) {
2459
+ if (m.style != null) marks.push(m);
2460
+ ++markpos;
2461
+ }
2462
+ nextChange = markpos < marked.length ? marked[markpos].from : Infinity;
2463
+ for (var i = 0; i < marks.length; ++i) {
2464
+ var to = marks[i].to || Infinity;
2465
+ if (to == pos) marks.splice(i--, 1);
2466
+ else nextChange = Math.min(to, nextChange);
2467
+ }
2468
+ }
2469
+ var m = 0;
2470
+ while (pos < len) {
2471
+ if (nextChange == pos) advanceMarks();
2472
+ var upto = Math.min(len, nextChange);
2473
+ while (true) {
2474
+ if (text) {
2475
+ var end = pos + text.length;
2476
+ var appliedStyle = style;
2477
+ for (var j = 0; j < marks.length; ++j)
2478
+ appliedStyle = (appliedStyle ? appliedStyle + " " : "") + marks[j].style;
2479
+ span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
2480
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
2481
+ pos = end;
2482
+ }
2483
+ text = st[i++]; style = styleToClass(st[i++]);
2484
+ }
2485
+ }
2486
+ }
2487
+ return html.join("");
2488
+ },
2489
+ cleanUp: function() {
2490
+ this.parent = null;
2491
+ if (this.marked)
2492
+ for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this);
2493
+ }
2494
+ };
2495
+ // Utility used by replace and split above
2496
+ function copyStyles(from, to, source, dest) {
2497
+ for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
2498
+ var part = source[i], end = pos + part.length;
2499
+ if (state == 0) {
2500
+ if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
2501
+ if (end >= from) state = 1;
2502
+ }
2503
+ else if (state == 1) {
2504
+ if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
2505
+ else dest.push(part, source[i+1]);
2506
+ }
2507
+ pos = end;
2508
+ }
2509
+ }
2510
+
2511
+ // Data structure that holds the sequence of lines.
2512
+ function LeafChunk(lines) {
2513
+ this.lines = lines;
2514
+ this.parent = null;
2515
+ for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
2516
+ lines[i].parent = this;
2517
+ height += lines[i].height;
2518
+ }
2519
+ this.height = height;
2520
+ }
2521
+ LeafChunk.prototype = {
2522
+ chunkSize: function() { return this.lines.length; },
2523
+ remove: function(at, n, callbacks) {
2524
+ for (var i = at, e = at + n; i < e; ++i) {
2525
+ var line = this.lines[i];
2526
+ this.height -= line.height;
2527
+ line.cleanUp();
2528
+ if (line.handlers)
2529
+ for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]);
2530
+ }
2531
+ this.lines.splice(at, n);
2532
+ },
2533
+ collapse: function(lines) {
2534
+ lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
2535
+ },
2536
+ insertHeight: function(at, lines, height) {
2537
+ this.height += height;
2538
+ this.lines.splice.apply(this.lines, [at, 0].concat(lines));
2539
+ for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
2540
+ },
2541
+ iterN: function(at, n, op) {
2542
+ for (var e = at + n; at < e; ++at)
2543
+ if (op(this.lines[at])) return true;
2544
+ }
2545
+ };
2546
+ function BranchChunk(children) {
2547
+ this.children = children;
2548
+ var size = 0, height = 0;
2549
+ for (var i = 0, e = children.length; i < e; ++i) {
2550
+ var ch = children[i];
2551
+ size += ch.chunkSize(); height += ch.height;
2552
+ ch.parent = this;
2553
+ }
2554
+ this.size = size;
2555
+ this.height = height;
2556
+ this.parent = null;
2557
+ }
2558
+ BranchChunk.prototype = {
2559
+ chunkSize: function() { return this.size; },
2560
+ remove: function(at, n, callbacks) {
2561
+ this.size -= n;
2562
+ for (var i = 0; i < this.children.length; ++i) {
2563
+ var child = this.children[i], sz = child.chunkSize();
2564
+ if (at < sz) {
2565
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
2566
+ child.remove(at, rm, callbacks);
2567
+ this.height -= oldHeight - child.height;
2568
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
2569
+ if ((n -= rm) == 0) break;
2570
+ at = 0;
2571
+ } else at -= sz;
2572
+ }
2573
+ if (this.size - n < 25) {
2574
+ var lines = [];
2575
+ this.collapse(lines);
2576
+ this.children = [new LeafChunk(lines)];
2577
+ this.children[0].parent = this;
2578
+ }
2579
+ },
2580
+ collapse: function(lines) {
2581
+ for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
2582
+ },
2583
+ insert: function(at, lines) {
2584
+ var height = 0;
2585
+ for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
2586
+ this.insertHeight(at, lines, height);
2587
+ },
2588
+ insertHeight: function(at, lines, height) {
2589
+ this.size += lines.length;
2590
+ this.height += height;
2591
+ for (var i = 0, e = this.children.length; i < e; ++i) {
2592
+ var child = this.children[i], sz = child.chunkSize();
2593
+ if (at <= sz) {
2594
+ child.insertHeight(at, lines, height);
2595
+ if (child.lines && child.lines.length > 50) {
2596
+ while (child.lines.length > 50) {
2597
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
2598
+ var newleaf = new LeafChunk(spilled);
2599
+ child.height -= newleaf.height;
2600
+ this.children.splice(i + 1, 0, newleaf);
2601
+ newleaf.parent = this;
2602
+ }
2603
+ this.maybeSpill();
2604
+ }
2605
+ break;
2606
+ }
2607
+ at -= sz;
2608
+ }
2609
+ },
2610
+ maybeSpill: function() {
2611
+ if (this.children.length <= 10) return;
2612
+ var me = this;
2613
+ do {
2614
+ var spilled = me.children.splice(me.children.length - 5, 5);
2615
+ var sibling = new BranchChunk(spilled);
2616
+ if (!me.parent) { // Become the parent node
2617
+ var copy = new BranchChunk(me.children);
2618
+ copy.parent = me;
2619
+ me.children = [copy, sibling];
2620
+ me = copy;
2621
+ } else {
2622
+ me.size -= sibling.size;
2623
+ me.height -= sibling.height;
2624
+ var myIndex = indexOf(me.parent.children, me);
2625
+ me.parent.children.splice(myIndex + 1, 0, sibling);
2626
+ }
2627
+ sibling.parent = me.parent;
2628
+ } while (me.children.length > 10);
2629
+ me.parent.maybeSpill();
2630
+ },
2631
+ iter: function(from, to, op) { this.iterN(from, to - from, op); },
2632
+ iterN: function(at, n, op) {
2633
+ for (var i = 0, e = this.children.length; i < e; ++i) {
2634
+ var child = this.children[i], sz = child.chunkSize();
2635
+ if (at < sz) {
2636
+ var used = Math.min(n, sz - at);
2637
+ if (child.iterN(at, used, op)) return true;
2638
+ if ((n -= used) == 0) break;
2639
+ at = 0;
2640
+ } else at -= sz;
2641
+ }
2642
+ }
2643
+ };
2644
+
2645
+ function getLineAt(chunk, n) {
2646
+ while (!chunk.lines) {
2647
+ for (var i = 0;; ++i) {
2648
+ var child = chunk.children[i], sz = child.chunkSize();
2649
+ if (n < sz) { chunk = child; break; }
2650
+ n -= sz;
2651
+ }
2652
+ }
2653
+ return chunk.lines[n];
2654
+ }
2655
+ function lineNo(line) {
2656
+ if (line.parent == null) return null;
2657
+ var cur = line.parent, no = indexOf(cur.lines, line);
2658
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
2659
+ for (var i = 0, e = chunk.children.length; ; ++i) {
2660
+ if (chunk.children[i] == cur) break;
2661
+ no += chunk.children[i].chunkSize();
2662
+ }
2663
+ }
2664
+ return no;
2665
+ }
2666
+ function lineAtHeight(chunk, h) {
2667
+ var n = 0;
2668
+ outer: do {
2669
+ for (var i = 0, e = chunk.children.length; i < e; ++i) {
2670
+ var child = chunk.children[i], ch = child.height;
2671
+ if (h < ch) { chunk = child; continue outer; }
2672
+ h -= ch;
2673
+ n += child.chunkSize();
2674
+ }
2675
+ return n;
2676
+ } while (!chunk.lines);
2677
+ for (var i = 0, e = chunk.lines.length; i < e; ++i) {
2678
+ var line = chunk.lines[i], lh = line.height;
2679
+ if (h < lh) break;
2680
+ h -= lh;
2681
+ }
2682
+ return n + i;
2683
+ }
2684
+ function heightAtLine(chunk, n) {
2685
+ var h = 0;
2686
+ outer: do {
2687
+ for (var i = 0, e = chunk.children.length; i < e; ++i) {
2688
+ var child = chunk.children[i], sz = child.chunkSize();
2689
+ if (n < sz) { chunk = child; continue outer; }
2690
+ n -= sz;
2691
+ h += child.height;
2692
+ }
2693
+ return h;
2694
+ } while (!chunk.lines);
2695
+ for (var i = 0; i < n; ++i) h += chunk.lines[i].height;
2696
+ return h;
2697
+ }
2698
+
2699
+ // The history object 'chunks' changes that are made close together
2700
+ // and at almost the same time into bigger undoable units.
2701
+ function History() {
2702
+ this.time = 0;
2703
+ this.done = []; this.undone = [];
2704
+ }
2705
+ History.prototype = {
2706
+ addChange: function(start, added, old) {
2707
+ this.undone.length = 0;
2708
+ var time = +new Date, cur = this.done[this.done.length - 1], last = cur && cur[cur.length - 1];
2709
+ var dtime = time - this.time;
2710
+ if (dtime > 400 || !last) {
2711
+ this.done.push([{start: start, added: added, old: old}]);
2712
+ } else if (last.start > start + old.length || last.start + last.added < start - last.added + last.old.length) {
2713
+ cur.push({start: start, added: added, old: old});
2714
+ } else {
2715
+ var oldoff = 0;
2716
+ if (start < last.start) {
2717
+ for (var i = last.start - start - 1; i >= 0; --i)
2718
+ last.old.unshift(old[i]);
2719
+ oldoff = Math.min(0, added - old.length);
2720
+ last.added += last.start - start + oldoff;
2721
+ last.start = start;
2722
+ } else if (last.start < start) {
2723
+ oldoff = start - last.start;
2724
+ added += oldoff;
2725
+ }
2726
+ for (var i = last.added - oldoff, e = old.length; i < e; ++i)
2727
+ last.old.push(old[i]);
2728
+ if (last.added < added) last.added = added;
2729
+ }
2730
+ this.time = time;
2731
+ }
2732
+ };
2733
+
2734
+ function stopMethod() {e_stop(this);}
2735
+ // Ensure an event has a stop method.
2736
+ function addStop(event) {
2737
+ if (!event.stop) event.stop = stopMethod;
2738
+ return event;
2739
+ }
2740
+
2741
+ function e_preventDefault(e) {
2742
+ if (e.preventDefault) e.preventDefault();
2743
+ else e.returnValue = false;
2744
+ }
2745
+ function e_stopPropagation(e) {
2746
+ if (e.stopPropagation) e.stopPropagation();
2747
+ else e.cancelBubble = true;
2748
+ }
2749
+ function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
2750
+ CodeMirror.e_stop = e_stop;
2751
+ CodeMirror.e_preventDefault = e_preventDefault;
2752
+ CodeMirror.e_stopPropagation = e_stopPropagation;
2753
+
2754
+ function e_target(e) {return e.target || e.srcElement;}
2755
+ function e_button(e) {
2756
+ if (e.which) return e.which;
2757
+ else if (e.button & 1) return 1;
2758
+ else if (e.button & 2) return 3;
2759
+ else if (e.button & 4) return 2;
2760
+ }
2761
+
2762
+ // Allow 3rd-party code to override event properties by adding an override
2763
+ // object to an event object.
2764
+ function e_prop(e, prop) {
2765
+ var overridden = e.override && e.override.hasOwnProperty(prop);
2766
+ return overridden ? e.override[prop] : e[prop];
2767
+ }
2768
+
2769
+ // Event handler registration. If disconnect is true, it'll return a
2770
+ // function that unregisters the handler.
2771
+ function connect(node, type, handler, disconnect) {
2772
+ if (typeof node.addEventListener == "function") {
2773
+ node.addEventListener(type, handler, false);
2774
+ if (disconnect) return function() {node.removeEventListener(type, handler, false);};
2775
+ }
2776
+ else {
2777
+ var wrapHandler = function(event) {handler(event || window.event);};
2778
+ node.attachEvent("on" + type, wrapHandler);
2779
+ if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
2780
+ }
2781
+ }
2782
+ CodeMirror.connect = connect;
2783
+
2784
+ function Delayed() {this.id = null;}
2785
+ Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
2786
+
2787
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
2788
+
2789
+ var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
2790
+ var ie = /MSIE \d/.test(navigator.userAgent);
2791
+ var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
2792
+ var webkit = /WebKit\//.test(navigator.userAgent);
2793
+ var chrome = /Chrome\//.test(navigator.userAgent);
2794
+ var khtml = /KHTML\//.test(navigator.userAgent);
2795
+
2796
+ // Detect drag-and-drop
2797
+ var dragAndDrop = function() {
2798
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
2799
+ // couldn't get it to work yet.
2800
+ if (ie_lt9) return false;
2801
+ var div = document.createElement('div');
2802
+ return "draggable" in div || "dragDrop" in div;
2803
+ }();
2804
+
2805
+ var lineSep = "\n";
2806
+ // Feature-detect whether newlines in textareas are converted to \r\n
2807
+ (function () {
2808
+ var te = document.createElement("textarea");
2809
+ te.value = "foo\nbar";
2810
+ if (te.value.indexOf("\r") > -1) lineSep = "\r\n";
2811
+ }());
2812
+
2813
+ // Counts the column offset in a string, taking tabs into account.
2814
+ // Used mostly to find indentation.
2815
+ function countColumn(string, end, tabSize) {
2816
+ if (end == null) {
2817
+ end = string.search(/[^\s\u00a0]/);
2818
+ if (end == -1) end = string.length;
2819
+ }
2820
+ for (var i = 0, n = 0; i < end; ++i) {
2821
+ if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
2822
+ else ++n;
2823
+ }
2824
+ return n;
2825
+ }
2826
+
2827
+ function computedStyle(elt) {
2828
+ if (elt.currentStyle) return elt.currentStyle;
2829
+ return window.getComputedStyle(elt, null);
2830
+ }
2831
+
2832
+ // Find the position of an element by following the offsetParent chain.
2833
+ // If screen==true, it returns screen (rather than page) coordinates.
2834
+ function eltOffset(node, screen) {
2835
+ var bod = node.ownerDocument.body;
2836
+ var x = 0, y = 0, skipBody = false;
2837
+ for (var n = node; n; n = n.offsetParent) {
2838
+ var ol = n.offsetLeft, ot = n.offsetTop;
2839
+ // Firefox reports weird inverted offsets when the body has a border.
2840
+ if (n == bod) { x += Math.abs(ol); y += Math.abs(ot); }
2841
+ else { x += ol, y += ot; }
2842
+ if (screen && computedStyle(n).position == "fixed")
2843
+ skipBody = true;
2844
+ }
2845
+ var e = screen && !skipBody ? null : bod;
2846
+ for (var n = node.parentNode; n != e; n = n.parentNode)
2847
+ if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
2848
+ return {left: x, top: y};
2849
+ }
2850
+ // Use the faster and saner getBoundingClientRect method when possible.
2851
+ if (document.documentElement.getBoundingClientRect != null) eltOffset = function(node, screen) {
2852
+ // Take the parts of bounding client rect that we are interested in so we are able to edit if need be,
2853
+ // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page)
2854
+ try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; }
2855
+ catch(e) { box = {top: 0, left: 0}; }
2856
+ if (!screen) {
2857
+ // Get the toplevel scroll, working around browser differences.
2858
+ if (window.pageYOffset == null) {
2859
+ var t = document.documentElement || document.body.parentNode;
2860
+ if (t.scrollTop == null) t = document.body;
2861
+ box.top += t.scrollTop; box.left += t.scrollLeft;
2862
+ } else {
2863
+ box.top += window.pageYOffset; box.left += window.pageXOffset;
2864
+ }
2865
+ }
2866
+ return box;
2867
+ };
2868
+
2869
+ // Get a node's text content.
2870
+ function eltText(node) {
2871
+ return node.textContent || node.innerText || node.nodeValue || "";
2872
+ }
2873
+ function selectInput(node) {
2874
+ if (ios) { // Mobile Safari apparently has a bug where select() is broken.
2875
+ node.selectionStart = 0;
2876
+ node.selectionEnd = node.value.length;
2877
+ } else node.select();
2878
+ }
2879
+
2880
+ // Operations on {line, ch} objects.
2881
+ function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2882
+ function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2883
+ function copyPos(x) {return {line: x.line, ch: x.ch};}
2884
+
2885
+ var escapeElement = document.createElement("pre");
2886
+ function htmlEscape(str) {
2887
+ escapeElement.textContent = str;
2888
+ return escapeElement.innerHTML;
2889
+ }
2890
+ // Recent (late 2011) Opera betas insert bogus newlines at the start
2891
+ // of the textContent, so we strip those.
2892
+ if (htmlEscape("a") == "\na")
2893
+ htmlEscape = function(str) {
2894
+ escapeElement.textContent = str;
2895
+ return escapeElement.innerHTML.slice(1);
2896
+ };
2897
+ // Some IEs don't preserve tabs through innerHTML
2898
+ else if (htmlEscape("\t") != "\t")
2899
+ htmlEscape = function(str) {
2900
+ escapeElement.innerHTML = "";
2901
+ escapeElement.appendChild(document.createTextNode(str));
2902
+ return escapeElement.innerHTML;
2903
+ };
2904
+ CodeMirror.htmlEscape = htmlEscape;
2905
+
2906
+ // Used to position the cursor after an undo/redo by finding the
2907
+ // last edited character.
2908
+ function editEnd(from, to) {
2909
+ if (!to) return 0;
2910
+ if (!from) return to.length;
2911
+ for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
2912
+ if (from.charAt(i) != to.charAt(j)) break;
2913
+ return j + 1;
2914
+ }
2915
+
2916
+ function indexOf(collection, elt) {
2917
+ if (collection.indexOf) return collection.indexOf(elt);
2918
+ for (var i = 0, e = collection.length; i < e; ++i)
2919
+ if (collection[i] == elt) return i;
2920
+ return -1;
2921
+ }
2922
+ function isWordChar(ch) {
2923
+ return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase();
2924
+ }
2925
+
2926
+ // See if "".split is the broken IE version, if so, provide an
2927
+ // alternative way to split lines.
2928
+ var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
2929
+ var pos = 0, nl, result = [];
2930
+ while ((nl = string.indexOf("\n", pos)) > -1) {
2931
+ result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
2932
+ pos = nl + 1;
2933
+ }
2934
+ result.push(string.slice(pos));
2935
+ return result;
2936
+ } : function(string){return string.split(/\r?\n/);};
2937
+ CodeMirror.splitLines = splitLines;
2938
+
2939
+ var hasSelection = window.getSelection ? function(te) {
2940
+ try { return te.selectionStart != te.selectionEnd; }
2941
+ catch(e) { return false; }
2942
+ } : function(te) {
2943
+ try {var range = te.ownerDocument.selection.createRange();}
2944
+ catch(e) {}
2945
+ if (!range || range.parentElement() != te) return false;
2946
+ return range.compareEndPoints("StartToEnd", range) != 0;
2947
+ };
2948
+
2949
+ CodeMirror.defineMode("null", function() {
2950
+ return {token: function(stream) {stream.skipToEnd();}};
2951
+ });
2952
+ CodeMirror.defineMIME("text/plain", "null");
2953
+
2954
+ var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
2955
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
2956
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
2957
+ 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 127: "Delete", 186: ";", 187: "=", 188: ",",
2958
+ 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp",
2959
+ 63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right",
2960
+ 63233: "Down", 63302: "Insert", 63272: "Delete"};
2961
+ CodeMirror.keyNames = keyNames;
2962
+ (function() {
2963
+ // Number keys
2964
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
2965
+ // Alphabetic keys
2966
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
2967
+ // Function keys
2968
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
2969
+ })();
2970
+
2971
+ return CodeMirror;
2972
+ })();