feather_cms 0.0.1

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