~jstys-z/helioviewer.org/timeline

« back to all changes in this revision

Viewing changes to timeline/Highstock-1.3.10/exporting-server/java/highcharts-export/highcharts-export-web/src/main/webapp/resources/lib/codemirror/codemirror.js

  • Committer: Jeff Stys
  • Date: 2014-04-21 12:46:26 UTC
  • Revision ID: jstys@sesda3.com-20140421124626-2332pb2dyjc33jxi
Proof-of-concept version of Data Coverage Timeline using Highchart/Highstock javascript library.  Changes to getDataCoverage API in order to feed the necessary data to the Timeline

Show diffs side-by-side

added added

removed removed

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