sparql-doc 0.0.3

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