~ubuntu-branches/ubuntu/raring/qtwebkit-source/raring-proposed

« back to all changes in this revision

Viewing changes to Source/WebCore/inspector/front-end/cm/codemirror.js

  • Committer: Package Import Robot
  • Author(s): Jonathan Riddell
  • Date: 2013-02-18 14:24:18 UTC
  • Revision ID: package-import@ubuntu.com-20130218142418-eon0jmjg3nj438uy
Tags: upstream-2.3
ImportĀ upstreamĀ versionĀ 2.3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// CodeMirror is the only global var we claim
 
2
window.CodeMirror = (function() {
 
3
  "use strict";
 
4
 
 
5
  // BROWSER SNIFFING
 
6
 
 
7
  // Crude, but necessary to handle a number of hard-to-feature-detect
 
8
  // bugs and behavior differences.
 
9
  var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
 
10
  var ie = /MSIE \d/.test(navigator.userAgent);
 
11
  var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
 
12
  var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
 
13
  var ie_lt10 = /MSIE [1-9]\b/.test(navigator.userAgent);
 
14
  var webkit = /WebKit\//.test(navigator.userAgent);
 
15
  var chrome = /Chrome\//.test(navigator.userAgent);
 
16
  var opera = /Opera\//.test(navigator.userAgent);
 
17
  var safari = /Apple Computer/.test(navigator.vendor);
 
18
  var khtml = /KHTML\//.test(navigator.userAgent);
 
19
  var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
 
20
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
 
21
  var phantom = /PhantomJS/.test(navigator.userAgent);
 
22
 
 
23
  var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
 
24
  var mac = ios || /Mac/.test(navigator.platform);
 
25
  var win = /Win/.test(navigator.platform);
 
26
 
 
27
  // Optimize some code when these features are not used
 
28
  var sawReadOnlySpans = false, sawCollapsedSpans = false;
 
29
 
 
30
  // CONSTRUCTOR
 
31
 
 
32
  function CodeMirror(place, options) {
 
33
    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
 
34
    
 
35
    this.options = options = options || {};
 
36
    // Determine effective options based on given values and defaults.
 
37
    for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
 
38
      options[opt] = defaults[opt];
 
39
    setGuttersForLineNumbers(options);
 
40
 
 
41
    var display = this.display = makeDisplay(place);
 
42
    display.wrapper.CodeMirror = this;
 
43
    updateGutters(this);
 
44
    if (options.autofocus) focusInput(this);
 
45
 
 
46
    var doc = new BranchChunk([new LeafChunk([makeLine("", null, textHeight(display))])]);
 
47
    // The selection. These are always maintained to point at valid
 
48
    // positions. Inverted is used to remember that the user is
 
49
    // selecting bottom-to-top.
 
50
    this.view = {
 
51
      doc: doc,
 
52
      // frontier is the point up to which the content has been parsed,
 
53
      frontier: 0, highlight: new Delayed(),
 
54
      sel: {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false, shift: false},
 
55
      scrollTop: 0, scrollLeft: 0,
 
56
      overwrite: false, focused: false,
 
57
      // Tracks the maximum line length so that
 
58
      // the horizontal scrollbar can be kept
 
59
      // static when scrolling.
 
60
      maxLine: getLine(doc, 0),
 
61
      maxLineLength: 0,
 
62
      maxLineChanged: false,
 
63
      suppressEdits: false,
 
64
      goalColumn: null,
 
65
      cantEdit: false
 
66
    };
 
67
    loadMode(this);
 
68
 
 
69
    // Initialize the content.
 
70
    this.setValue(options.value || "");
 
71
    // Override magic textarea content restore that IE sometimes does
 
72
    // on our hidden textarea on reload
 
73
    if (ie) setTimeout(bind(resetInput, this, true), 20);
 
74
    this.view.history = makeHistory();
 
75
 
 
76
    registerEventHandlers(this);
 
77
    // IE throws unspecified error in certain cases, when
 
78
    // trying to access activeElement before onload
 
79
    var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
 
80
    if (hasFocus || options.autofocus) setTimeout(bind(onFocus, this), 20);
 
81
    else onBlur(this);
 
82
 
 
83
    operation(this, function() {
 
84
      for (var opt in optionHandlers)
 
85
        if (optionHandlers.propertyIsEnumerable(opt))
 
86
          optionHandlers[opt](this, options[opt], Init);
 
87
      for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
 
88
    })();
 
89
  }
 
90
 
 
91
  // DISPLAY CONSTRUCTOR
 
92
 
 
93
  function makeDisplay(place) {
 
94
    var d = {};
 
95
    var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;");
 
96
    input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
 
97
    // Wraps and hides input textarea
 
98
    d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
 
99
    // The actual fake scrollbars.
 
100
    d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
 
101
    d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
 
102
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
 
103
    // DIVs containing the selection and the actual code
 
104
    d.lineDiv = elt("div");
 
105
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
 
106
    // Blinky cursor, and element used to ensure cursor fits at the end of a line
 
107
    d.cursor = elt("pre", "\u00a0", "CodeMirror-cursor");
 
108
    // Secondary cursor, shown when on a 'jump' in bi-directional text
 
109
    d.otherCursor = elt("pre", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
 
110
    // Used to measure text size
 
111
    d.measure = elt("div", null, "CodeMirror-measure");
 
112
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
 
113
    d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
 
114
                         null, "position: relative; outline: none");
 
115
    // Moved around its parent to cover visible view
 
116
    d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
 
117
    d.gutters = elt("div", null, "CodeMirror-gutters");
 
118
    d.lineGutter = null;
 
119
    // Set to the height of the text, causes scrolling
 
120
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
 
121
    // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
 
122
    d.heightForcer = elt("div", "\u00a0", null, "position: absolute; height: " + scrollerCutOff + "px");
 
123
    // Provides scrolling
 
124
    d.scroller = elt("div", [d.sizer, d.heightForcer], "CodeMirror-scroll");
 
125
    d.scroller.setAttribute("tabIndex", "-1");
 
126
    // The element in which the editor lives.
 
127
    d.wrapper = elt("div", [d.gutters, d.inputDiv, d.scrollbarH, d.scrollbarV,
 
128
                            d.scrollbarFiller, d.scroller], "CodeMirror");
 
129
    // Work around IE7 z-index bug
 
130
    if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
 
131
    if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
 
132
 
 
133
    // Needed to hide big blue blinking cursor on Mobile Safari
 
134
    if (ios) input.style.width = "0px";
 
135
    if (!webkit) d.scroller.draggable = true;
 
136
    // Needed to handle Tab key in KHTML
 
137
    if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
 
138
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
 
139
    else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
 
140
 
 
141
    // Current visible range (may be bigger than the view window).
 
142
    d.viewOffset = d.showingFrom = d.showingTo = d.lastSizeC = 0;
 
143
 
 
144
    // Used to only resize the line number gutter when necessary (when
 
145
    // the amount of lines crosses a boundary that makes its width change)
 
146
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
 
147
    // See readInput and resetInput
 
148
    d.prevInput = "";
 
149
    // Set to true when a non-horizontal-scrolling widget is added. As
 
150
    // an optimization, widget aligning is skipped when d is false.
 
151
    d.alignWidgets = false;
 
152
    // Flag that indicates whether we currently expect input to appear
 
153
    // (after some event like 'keypress' or 'input') and are polling
 
154
    // intensively.
 
155
    d.pollingFast = false;
 
156
    // Self-resetting timeout for the poller
 
157
    d.poll = new Delayed();
 
158
    // True when a drag from the editor is active
 
159
    d.draggingText = false;
 
160
 
 
161
    d.cachedCharWidth = d.cachedTextHeight = null;
 
162
    d.measureLineCache = [];
 
163
    d.measureLineCache.pos = 0;
 
164
 
 
165
    // Tracks when resetInput has punted to just putting a short
 
166
    // string instead of the (large) selection.
 
167
    d.inaccurateSelection = false;
 
168
 
 
169
    // Used to adjust overwrite behaviour when a paste has been
 
170
    // detected
 
171
    d.pasteIncoming = false;
 
172
 
 
173
    return d;
 
174
  }
 
175
 
 
176
  // STATE UPDATES
 
177
 
 
178
  // Used to get the editor into a consistent state again when options change.
 
179
 
 
180
  function loadMode(cm) {
 
181
    var doc = cm.view.doc;
 
182
    cm.view.mode = CodeMirror.getMode(cm.options, cm.options.mode);
 
183
    doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
 
184
    cm.view.frontier = 0;
 
185
    startWorker(cm, 100);
 
186
  }
 
187
 
 
188
  function wrappingChanged(cm) {
 
189
    var doc = cm.view.doc, th = textHeight(cm.display);
 
190
    if (cm.options.lineWrapping) {
 
191
      cm.display.wrapper.className += " CodeMirror-wrap";
 
192
      var perLine = cm.display.scroller.clientWidth / charWidth(cm.display) - 3;
 
193
      doc.iter(0, doc.size, function(line) {
 
194
        if (line.height == 0) return;
 
195
        var guess = Math.ceil(line.text.length / perLine) || 1;
 
196
        if (guess != 1) updateLineHeight(line, guess * th);
 
197
      });
 
198
      cm.display.sizer.style.minWidth = "";
 
199
    } else {
 
200
      cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
 
201
      computeMaxLength(cm.view);
 
202
      doc.iter(0, doc.size, function(line) {
 
203
        if (line.height != 0) updateLineHeight(line, th);
 
204
      });
 
205
    }
 
206
    regChange(cm, 0, doc.size);
 
207
  }
 
208
 
 
209
  function keyMapChanged(cm) {
 
210
    var style = keyMap[cm.options.keyMap].style;
 
211
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
 
212
      (style ? " cm-keymap-" + style : "");
 
213
  }
 
214
 
 
215
  function themeChanged(cm) {
 
216
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
 
217
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
 
218
  }
 
219
 
 
220
  function guttersChanged(cm) {
 
221
    updateGutters(cm);
 
222
    updateDisplay(cm, true);
 
223
  }
 
224
 
 
225
  function updateGutters(cm) {
 
226
    var gutters = cm.display.gutters, specs = cm.options.gutters;
 
227
    removeChildren(gutters);
 
228
    for (var i = 0; i < specs.length; ++i) {
 
229
      var gutterClass = specs[i];
 
230
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
 
231
      if (gutterClass == "CodeMirror-linenumbers") {
 
232
        cm.display.lineGutter = gElt;
 
233
        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
 
234
      }
 
235
    }
 
236
    gutters.style.display = i ? "" : "none";
 
237
  }
 
238
 
 
239
  function lineLength(doc, line) {
 
240
    if (line.height == 0) return 0;
 
241
    var len = line.text.length, merged, cur = line;
 
242
    while (merged = collapsedSpanAtStart(cur)) {
 
243
      var found = merged.find();
 
244
      cur = getLine(doc, found.from.line);
 
245
      len += found.from.ch - found.to.ch;
 
246
    }
 
247
    cur = line;
 
248
    while (merged = collapsedSpanAtEnd(cur)) {
 
249
      var found = merged.find();
 
250
      len -= cur.text.length - found.from.ch;
 
251
      cur = getLine(doc, found.to.line);
 
252
      len += cur.text.length - found.to.ch;
 
253
    }
 
254
    return len;
 
255
  }
 
256
 
 
257
  function computeMaxLength(view) {
 
258
    view.maxLine = getLine(view.doc, 0);
 
259
    view.maxLineLength = lineLength(view.doc, view.maxLine);
 
260
    view.maxLineChanged = true;
 
261
    view.doc.iter(1, view.doc.size, function(line) {
 
262
      var len = lineLength(view.doc, line);
 
263
      if (len > view.maxLineLength) {
 
264
        view.maxLineLength = len;
 
265
        view.maxLine = line;
 
266
      }
 
267
    });
 
268
  }
 
269
 
 
270
  // Make sure the gutters options contains the element
 
271
  // "CodeMirror-linenumbers" when the lineNumbers option is true.
 
272
  function setGuttersForLineNumbers(options) {
 
273
    var found = false;
 
274
    for (var i = 0; i < options.gutters.length; ++i) {
 
275
      if (options.gutters[i] == "CodeMirror-linenumbers") {
 
276
        if (options.lineNumbers) found = true;
 
277
        else options.gutters.splice(i--, 1);
 
278
      }
 
279
    }
 
280
    if (!found && options.lineNumbers)
 
281
      options.gutters.push("CodeMirror-linenumbers");
 
282
  }
 
283
 
 
284
  // SCROLLBARS
 
285
 
 
286
  // Re-synchronize the fake scrollbars with the actual size of the
 
287
  // content. Optionally force a scrollTop.
 
288
  function updateScrollbars(d /* display */, docHeight, scrollTop) {
 
289
    d.sizer.style.minHeight = d.heightForcer.style.top = (docHeight + 2 * paddingTop(d)) + "px";
 
290
    var needsH = d.scroller.scrollWidth > d.scroller.clientWidth;
 
291
    var needsV = d.scroller.scrollHeight > d.scroller.clientHeight;
 
292
    if (needsV) {
 
293
      d.scrollbarV.style.display = "block";
 
294
      d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
 
295
      d.scrollbarV.firstChild.style.height = 
 
296
        (d.scroller.scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
 
297
      if (scrollTop != null) {
 
298
        d.scrollbarV.scrollTop = d.scroller.scrollTop = scrollTop;
 
299
        // 'Nudge' the scrollbar to work around a Webkit bug where,
 
300
        // in some situations, we'd end up with a scrollbar that
 
301
        // reported its scrollTop (and looked) as expected, but
 
302
        // *behaved* as if it was still in a previous state (i.e.
 
303
        // couldn't scroll up, even though it appeared to be at the
 
304
        // bottom).
 
305
        if (webkit) setTimeout(function() {
 
306
          if (d.scrollbarV.scrollTop != scrollTop) return;
 
307
          d.scrollbarV.scrollTop = scrollTop + (scrollTop ? -1 : 1);
 
308
          d.scrollbarV.scrollTop = scrollTop;
 
309
        }, 0);
 
310
      }
 
311
    } else d.scrollbarV.style.display = "";
 
312
    if (needsH) {
 
313
      d.scrollbarH.style.display = "block";
 
314
      d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
 
315
      d.scrollbarH.firstChild.style.width =
 
316
        (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
 
317
    } else d.scrollbarH.style.display = "";
 
318
    if (needsH && needsV) {
 
319
      d.scrollbarFiller.style.display = "block";
 
320
      d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
 
321
    } else d.scrollbarFiller.style.display = "";
 
322
 
 
323
    if (mac_geLion && scrollbarWidth(d.measure) === 0)
 
324
      d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
 
325
  }
 
326
 
 
327
  function visibleLines(display, doc, viewPort) {
 
328
    var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
 
329
    if (typeof viewPort == "number") top = viewPort;
 
330
    else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
 
331
    top = Math.floor(top - paddingTop(display));
 
332
    var bottom = Math.ceil(top + height);
 
333
    return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
 
334
  }
 
335
 
 
336
  // LINE NUMBERS
 
337
 
 
338
  function alignVertically(display) {
 
339
    if (!display.alignWidgets && !display.gutters.firstChild) return;
 
340
    var l = compensateForHScroll(display) + "px";
 
341
    for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
 
342
      for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
 
343
    }
 
344
  }
 
345
 
 
346
  function maybeUpdateLineNumberWidth(cm) {
 
347
    if (!cm.options.lineNumbers) return false;
 
348
    var doc = cm.view.doc, last = lineNumberFor(cm.options, doc.size - 1), display = cm.display;
 
349
    if (last.length != display.lineNumChars) {
 
350
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
 
351
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
 
352
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
 
353
      display.lineGutter.style.width = "";
 
354
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
 
355
      display.lineNumWidth = display.lineNumInnerWidth + padding;
 
356
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
 
357
      display.lineGutter.style.width = display.lineNumWidth + "px";
 
358
      return true;
 
359
    }
 
360
    return false;
 
361
  }
 
362
 
 
363
  function lineNumberFor(options, i) {
 
364
    return String(options.lineNumberFormatter(i + options.firstLineNumber));
 
365
  }
 
366
  function compensateForHScroll(display) {
 
367
    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
 
368
  }
 
369
 
 
370
  // DISPLAY DRAWING
 
371
 
 
372
  function updateDisplay(cm, changes, viewPort) {
 
373
    var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo;
 
374
    var updated = updateDisplayInner(cm, changes, viewPort);
 
375
    if (updated) {
 
376
      signalLater(cm, cm, "update", cm);
 
377
      if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
 
378
        signalLater(cm, cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
 
379
    }
 
380
    updateSelection(cm);
 
381
    updateScrollbars(cm.display, cm.view.doc.height, typeof viewPort == "number" ? viewPort : null);
 
382
    return updated;
 
383
  }
 
384
 
 
385
  // Uses a set of changes plus the current scroll position to
 
386
  // determine which DOM updates have to be made, and makes the
 
387
  // updates.
 
388
  function updateDisplayInner(cm, changes, viewPort) {
 
389
    var display = cm.display, doc = cm.view.doc;
 
390
    if (!display.wrapper.clientWidth) {
 
391
      display.showingFrom = display.showingTo = display.viewOffset = 0;
 
392
      return;
 
393
    }
 
394
 
 
395
    // Compute the new visible window
 
396
    // If scrollTop is specified, use that to determine which lines
 
397
    // to render instead of the current scrollbar position.
 
398
    var visible = visibleLines(display, doc, viewPort);
 
399
    // Bail out if the visible area is already rendered and nothing changed.
 
400
    if (changes !== true && changes.length == 0 &&
 
401
        visible.from > display.showingFrom && visible.to < display.showingTo)
 
402
      return;
 
403
 
 
404
    if (changes && maybeUpdateLineNumberWidth(cm))
 
405
      changes = true;
 
406
    display.sizer.style.marginLeft = display.scrollbarH.style.left = display.gutters.offsetWidth + "px";
 
407
 
 
408
    // When merged lines are present, the line that needs to be
 
409
    // redrawn might not be the one that was changed.
 
410
    if (changes !== true && sawCollapsedSpans)
 
411
      for (var i = 0; i < changes.length; ++i) {
 
412
        var ch = changes[i], merged;
 
413
        while (merged = collapsedSpanAtStart(getLine(doc, ch.from))) {
 
414
          var from = merged.find().from.line;
 
415
          if (ch.diff) ch.diff -= ch.from - from;
 
416
          ch.from = from;
 
417
        }
 
418
      }
 
419
 
 
420
    // Used to determine which lines need their line numbers updated
 
421
    var positionsChangedFrom = changes === true ? 0 : Infinity;
 
422
    if (cm.options.lineNumbers && changes && changes !== true)
 
423
      for (var i = 0; i < changes.length; ++i)
 
424
        if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
 
425
 
 
426
    var from = Math.max(visible.from - cm.options.viewportMargin, 0);
 
427
    var to = Math.min(doc.size, visible.to + cm.options.viewportMargin);
 
428
    if (display.showingFrom < from && from - display.showingFrom < 20) from = display.showingFrom;
 
429
    if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(doc.size, display.showingTo);
 
430
 
 
431
    // Create a range of theoretically intact lines, and punch holes
 
432
    // in that using the change info.
 
433
    var intact = changes === true ? [] :
 
434
      computeIntact([{from: display.showingFrom, to: display.showingTo, domStart: 0}], changes);
 
435
    // Clip off the parts that won't be visible
 
436
    var intactLines = 0;
 
437
    for (var i = 0; i < intact.length; ++i) {
 
438
      var range = intact[i];
 
439
      if (range.from < from) {range.domStart += (from - range.from); range.from = from;}
 
440
      if (range.to > to) range.to = to;
 
441
      if (range.from >= range.to) intact.splice(i--, 1);
 
442
      else intactLines += range.to - range.from;
 
443
    }
 
444
    if (intactLines == to - from && from == display.showingFrom && to == display.showingTo)
 
445
      return;
 
446
    intact.sort(function(a, b) {return a.domStart - b.domStart;});
 
447
 
 
448
    if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
 
449
    patchDisplay(cm, from, to, intact, positionsChangedFrom);
 
450
    display.lineDiv.style.display = "";
 
451
 
 
452
    var different = from != display.showingFrom || to != display.showingTo ||
 
453
      display.lastSizeC != display.wrapper.clientHeight;
 
454
    // This is just a bogus formula that detects when the editor is
 
455
    // resized or the font size changes.
 
456
    if (different) display.lastSizeC = display.wrapper.clientHeight;
 
457
    display.showingFrom = from; display.showingTo = to;
 
458
    display.viewOffset = heightAtLine(cm, getLine(doc, from));
 
459
    startWorker(cm, 100);
 
460
 
 
461
    // Since this is all rather error prone, it is honoured with the
 
462
    // only assertion in the whole file.
 
463
    if (display.lineDiv.childNodes.length != display.showingTo - display.showingFrom)
 
464
      throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (display.showingTo - display.showingFrom) +
 
465
                      " nodes=" + display.lineDiv.childNodes.length);
 
466
 
 
467
    // Update line heights for visible lines based on actual DOM
 
468
    // sizes
 
469
    var curNode = display.lineDiv.firstChild, relativeTo = curNode.offsetTop;
 
470
    doc.iter(display.showingFrom, display.showingTo, function(line) {
 
471
      // Work around bizarro IE7 bug where, sometimes, our curNode
 
472
      // is magically replaced with a new node in the DOM, leaving
 
473
      // us with a reference to an orphan (nextSibling-less) node.
 
474
      if (!curNode) return;
 
475
      if (!lineIsHidden(line)) {
 
476
        var end = curNode.offsetHeight + curNode.offsetTop;
 
477
        var height = end - relativeTo, diff = line.height - height;
 
478
        if (height < 2) height = textHeight(display);
 
479
        relativeTo = end;
 
480
        if (diff > .001 || diff < -.001)
 
481
          updateLineHeight(line, height);
 
482
      }
 
483
      curNode = curNode.nextSibling;
 
484
    });
 
485
 
 
486
    // Position the mover div to align with the current virtual scroll position
 
487
    display.mover.style.top = display.viewOffset + "px";
 
488
    return true;
 
489
  }
 
490
 
 
491
  function computeIntact(intact, changes) {
 
492
    for (var i = 0, l = changes.length || 0; i < l; ++i) {
 
493
      var change = changes[i], intact2 = [], diff = change.diff || 0;
 
494
      for (var j = 0, l2 = intact.length; j < l2; ++j) {
 
495
        var range = intact[j];
 
496
        if (change.to <= range.from && change.diff)
 
497
          intact2.push({from: range.from + diff, to: range.to + diff,
 
498
                        domStart: range.domStart});
 
499
        else if (change.to <= range.from || change.from >= range.to)
 
500
          intact2.push(range);
 
501
        else {
 
502
          if (change.from > range.from)
 
503
            intact2.push({from: range.from, to: change.from, domStart: range.domStart});
 
504
          if (change.to < range.to)
 
505
            intact2.push({from: change.to + diff, to: range.to + diff,
 
506
                          domStart: range.domStart + (change.to - range.from)});
 
507
        }
 
508
      }
 
509
      intact = intact2;
 
510
    }
 
511
    return intact;
 
512
  }
 
513
 
 
514
  function getDimensions(cm) {
 
515
    var d = cm.display, left = {}, width = {};
 
516
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
 
517
      left[cm.options.gutters[i]] = n.offsetLeft;
 
518
      width[cm.options.gutters[i]] = n.offsetWidth;
 
519
    }
 
520
    return {fixedPos: compensateForHScroll(d),
 
521
            gutterTotalWidth: d.gutters.offsetWidth,
 
522
            gutterLeft: left,
 
523
            gutterWidth: width,
 
524
            wrapperWidth: d.wrapper.clientWidth};
 
525
  }
 
526
 
 
527
  function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
 
528
    function killNode(node) {
 
529
      var tmp = node.nextSibling;
 
530
      node.parentNode.removeChild(node);
 
531
      return tmp;
 
532
    }
 
533
    var dims = getDimensions(cm);
 
534
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
 
535
    // The first pass removes the DOM nodes that aren't intact.
 
536
    if (!intact.length) {
 
537
      // old IE does bad things to nodes when .innerHTML = "" is used on a parent
 
538
      // we still need widgets and markers intact to add back to the new content later
 
539
      if (ie_lt10) for (var ld = display.lineDiv, tmp = ld.firstChild; tmp; tmp = ld.firstChild) ld.removeChild(tmp);
 
540
      else removeChildren(display.lineDiv);
 
541
    } else {
 
542
      var domPos = 0, curNode = display.lineDiv.firstChild, n;
 
543
      for (var i = 0; i < intact.length; ++i) {
 
544
        var cur = intact[i];
 
545
        while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;}
 
546
        for (var j = cur.from, e = cur.to; j < e; ++j) {
 
547
          if (lineNumbers && updateNumbersFrom <= j && curNode.firstChild)
 
548
            setTextContent(curNode.firstChild.firstChild, lineNumberFor(cm.options, j));
 
549
          curNode = curNode.nextSibling; domPos++;
 
550
        }
 
551
      }
 
552
      while (curNode) curNode = killNode(curNode);
 
553
    }
 
554
    // This pass fills in the lines that actually changed.
 
555
    var nextIntact = intact.shift(), curNode = display.lineDiv.firstChild;
 
556
    var j = from;
 
557
 
 
558
    cm.view.doc.iter(from, to, function(line) {
 
559
      if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
 
560
      if (!nextIntact || nextIntact.from > j)
 
561
        display.lineDiv.insertBefore(buildLineElement(cm, line, j, dims), curNode);
 
562
      else
 
563
        curNode = curNode.nextSibling;
 
564
      ++j;
 
565
    });
 
566
  }
 
567
 
 
568
  function buildLineElement(cm, line, lineNo, dims) {
 
569
    if (line.height == 0) return elt("div");
 
570
 
 
571
    var lineElement = line.height == 0 ? elt("div") : lineContent(cm, line);
 
572
    var markers = line.gutterMarkers, display = cm.display;
 
573
 
 
574
    if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass &&
 
575
        (!line.widgets || !line.widgets.length)) return lineElement;
 
576
 
 
577
    // Lines with gutter elements or a background class need
 
578
    // to be wrapped again, and have the extra elements added
 
579
    // to the wrapper div
 
580
 
 
581
    var wrap = elt("div", null, line.wrapClass, "position: relative");
 
582
    if (cm.options.lineNumbers || markers) {
 
583
      var gutterWrap = wrap.appendChild(elt("div", null, null, "position: absolute; left: " +
 
584
                                            dims.fixedPos + "px"));
 
585
      wrap.alignable = [gutterWrap];
 
586
      if (cm.options.lineNumbers)
 
587
        gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineNo),
 
588
                                   "CodeMirror-linenumber CodeMirror-gutter-elt",
 
589
                                   "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
 
590
                                   + display.lineNumInnerWidth + "px"));
 
591
      if (markers)
 
592
        for (var k = 0; k < cm.options.gutters.length; ++k) {
 
593
          var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
 
594
          if (found) {
 
595
            gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
 
596
                                       dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
 
597
          }
 
598
        }
 
599
    }
 
600
    // Kludge to make sure the styled element lies behind the selection (by z-index)
 
601
    if (line.bgClass)
 
602
      wrap.appendChild(elt("div", "\u00a0", line.bgClass + " CodeMirror-linebackground"));
 
603
    wrap.appendChild(lineElement);
 
604
    if (line.widgets)
 
605
      for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
 
606
        var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
 
607
        node.widget = widget;
 
608
        if (widget.noHScroll) {
 
609
          (wrap.alignable || (wrap.alignable = [])).push(node);
 
610
          var width = dims.wrapperWidth;
 
611
          node.style.left = dims.fixedPos + "px";
 
612
          if (!widget.coverGutter) {
 
613
            width -= dims.gutterTotalWidth;
 
614
            node.style.paddingLeft = dims.gutterTotalWidth + "px";
 
615
          }
 
616
          node.style.width = width + "px";
 
617
        }
 
618
        if (widget.coverGutter) {
 
619
          node.style.zIndex = 5;
 
620
          node.style.position = "relative";
 
621
          if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
 
622
        }
 
623
        if (widget.above)
 
624
          wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
 
625
        else
 
626
          wrap.appendChild(node);
 
627
      }
 
628
 
 
629
    if (ie_lt8) wrap.style.zIndex = 2;
 
630
    return wrap;
 
631
  }
 
632
 
 
633
  // SELECTION / CURSOR
 
634
 
 
635
  function selHead(view) {
 
636
    return view.sel.inverted ? view.sel.from : view.sel.to;
 
637
  }
 
638
 
 
639
  function updateSelection(cm) {
 
640
    var headPos = posEq(cm.view.sel.from, cm.view.sel.to) ?
 
641
      updateSelectionCursor(cm) :
 
642
      updateSelectionRange(cm);
 
643
    var display = cm.display;
 
644
    // Move the hidden textarea near the cursor to prevent scrolling artifacts
 
645
    var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
 
646
    display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
 
647
                                                      headPos.top + lineOff.top - wrapOff.top)) + "px";
 
648
    display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
 
649
                                                       headPos.left + lineOff.left - wrapOff.left)) + "px";
 
650
  }
 
651
 
 
652
  // No selection, plain cursor
 
653
  function updateSelectionCursor(cm) {
 
654
    var display = cm.display, pos = cursorCoords(cm, cm.view.sel.from, "div");
 
655
    display.cursor.style.left = pos.left + "px";
 
656
    display.cursor.style.top = pos.top + "px";
 
657
    display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
 
658
    display.cursor.style.display = "";
 
659
    display.selectionDiv.style.display = "none";
 
660
 
 
661
    if (pos.other) {
 
662
      display.otherCursor.style.display = "";
 
663
      display.otherCursor.style.left = pos.other.left + "px";
 
664
      display.otherCursor.style.top = pos.other.top + "px";
 
665
      display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
 
666
    } else { display.otherCursor.style.display = "none"; }
 
667
    return pos;
 
668
  }
 
669
 
 
670
  // Highlight selection
 
671
  function updateSelectionRange(cm) {
 
672
    var display = cm.display, doc = cm.view.doc, sel = cm.view.sel;
 
673
    var fragment = document.createDocumentFragment();
 
674
    var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
 
675
 
 
676
    function add(left, top, width, bottom) {
 
677
      if (top < 0) top = 0;
 
678
      fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
 
679
                               "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
 
680
                               "px; height: " + (bottom - top) + "px"));
 
681
    }
 
682
 
 
683
    function drawForLine(line, fromArg, toArg, retTop) {
 
684
      var lineObj = getLine(doc, line);
 
685
      var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity;
 
686
      function coords(ch) {
 
687
        return charCoords(cm, {line: line, ch: ch}, "div", lineObj);
 
688
      }
 
689
 
 
690
      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
 
691
        var leftPos = coords(dir == "rtl" ? to - 1 : from);
 
692
        var rightPos = coords(dir == "rtl" ? from : to - 1);
 
693
        var left = leftPos.left, right = rightPos.right;
 
694
        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
 
695
          add(left, leftPos.top, null, leftPos.bottom);
 
696
          left = pl;
 
697
          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
 
698
        }
 
699
        if (toArg == null && to == lineLen) right = clientWidth;
 
700
        if (fromArg == null && from == 0) left = pl;
 
701
        rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal);
 
702
        if (left < pl + 1) left = pl;
 
703
        add(left, rightPos.top, right - left, rightPos.bottom);
 
704
      });
 
705
      return rVal;
 
706
    }
 
707
 
 
708
    if (sel.from.line == sel.to.line) {
 
709
      drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
 
710
    } else {
 
711
      var fromObj = getLine(doc, sel.from.line);
 
712
      var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine;
 
713
      while (merged = collapsedSpanAtEnd(cur)) {
 
714
        var found = merged.find();
 
715
        path.push(found.from.ch, found.to.line, found.to.ch);
 
716
        if (found.to.line == sel.to.line) {
 
717
          path.push(sel.to.ch);
 
718
          singleLine = true;
 
719
          break;
 
720
        }
 
721
        cur = getLine(doc, found.to.line);
 
722
      }
 
723
 
 
724
      // This is a single, merged line
 
725
      if (singleLine) {
 
726
        for (var i = 0; i < path.length; i += 3)
 
727
          drawForLine(path[i], path[i+1], path[i+2]);
 
728
      } else {
 
729
        var middleTop, middleBot, toObj = getLine(doc, sel.to.line);
 
730
        if (sel.from.ch)
 
731
          // Draw the first line of selection.
 
732
          middleTop = drawForLine(sel.from.line, sel.from.ch, null, false);
 
733
        else
 
734
          // Simply include it in the middle block.
 
735
          middleTop = heightAtLine(cm, fromObj) - display.viewOffset;
 
736
 
 
737
        if (!sel.to.ch)
 
738
          middleBot = heightAtLine(cm, toObj) - display.viewOffset;
 
739
        else
 
740
          middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true);
 
741
 
 
742
        if (middleTop < middleBot) add(pl, middleTop, null, middleBot);
 
743
      }
 
744
    }
 
745
 
 
746
    removeChildrenAndAdd(display.selectionDiv, fragment);
 
747
    display.cursor.style.display = display.otherCursor.style.display = "none";
 
748
    display.selectionDiv.style.display = "";
 
749
    return cursorCoords(cm, selHead(cm.view), "div");
 
750
  }
 
751
 
 
752
  // Cursor-blinking
 
753
  function restartBlink(cm) {
 
754
    var display = cm.display;
 
755
    clearInterval(display.blinker);
 
756
    var on = true;
 
757
    display.cursor.style.visibility = display.otherCursor.style.visibility = "";
 
758
    display.blinker = setInterval(function() {
 
759
      display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
 
760
    }, cm.options.cursorBlinkRate);
 
761
  }
 
762
 
 
763
  // HIGHLIGHT WORKER
 
764
 
 
765
  function startWorker(cm, time) {
 
766
    if (cm.view.frontier < cm.display.showingTo)
 
767
      cm.view.highlight.set(time, bind(highlightWorker, cm));
 
768
  }
 
769
 
 
770
  function highlightWorker(cm) {
 
771
    var view = cm.view, doc = view.doc;
 
772
    if (view.frontier >= cm.display.showingTo) return;
 
773
    var end = +new Date + cm.options.workTime;
 
774
    var state = copyState(view.mode, getStateBefore(cm, view.frontier));
 
775
    var changed = [], prevChange;
 
776
    doc.iter(view.frontier, Math.min(doc.size, cm.display.showingTo + 500), function(line) {
 
777
      if (view.frontier >= cm.display.showingFrom) { // Visible
 
778
        if (highlightLine(cm, line, state) && view.frontier >= cm.display.showingFrom) {
 
779
          if (prevChange && prevChange.end == view.frontier) prevChange.end++;
 
780
          else changed.push(prevChange = {start: view.frontier, end: view.frontier + 1});
 
781
        }
 
782
        line.stateAfter = copyState(view.mode, state);
 
783
      } else {
 
784
        processLine(cm, line, state);
 
785
        line.stateAfter = view.frontier % 5 == 0 ? copyState(view.mode, state) : null;
 
786
      }
 
787
      ++view.frontier;
 
788
      if (+new Date > end) {
 
789
        startWorker(cm, cm.options.workDelay);
 
790
        return true;
 
791
      }
 
792
    });
 
793
    if (changed.length)
 
794
      operation(cm, function() {
 
795
        for (var i = 0; i < changed.length; ++i)
 
796
          regChange(this, changed[i].start, changed[i].end);
 
797
      })();
 
798
  }
 
799
 
 
800
  // Finds the line to start with when starting a parse. Tries to
 
801
  // find a line with a stateAfter, so that it can start with a
 
802
  // valid state. If that fails, it returns the line with the
 
803
  // smallest indentation, which tends to need the least context to
 
804
  // parse correctly.
 
805
  function findStartLine(cm, n) {
 
806
    var minindent, minline, doc = cm.view.doc;
 
807
    for (var search = n, lim = n - 100; search > lim; --search) {
 
808
      if (search == 0) return 0;
 
809
      var line = getLine(doc, search-1);
 
810
      if (line.stateAfter) return search;
 
811
      var indented = countColumn(line.text, null, cm.options.tabSize);
 
812
      if (minline == null || minindent > indented) {
 
813
        minline = search - 1;
 
814
        minindent = indented;
 
815
      }
 
816
    }
 
817
    return minline;
 
818
  }
 
819
 
 
820
  function getStateBefore(cm, n) {
 
821
    var view = cm.view;
 
822
    var pos = findStartLine(cm, n), state = pos && getLine(view.doc, pos-1).stateAfter;
 
823
    if (!state) state = startState(view.mode);
 
824
    else state = copyState(view.mode, state);
 
825
    view.doc.iter(pos, n, function(line) {
 
826
      processLine(cm, line, state);
 
827
      var save = pos == n - 1 || pos % 5 == 0 || pos >= view.showingFrom && pos < view.showingTo;
 
828
      line.stateAfter = save ? copyState(view.mode, state) : null;
 
829
      ++pos;
 
830
    });
 
831
    return state;
 
832
  }
 
833
 
 
834
  // POSITION MEASUREMENT
 
835
  
 
836
  function paddingTop(display) {return display.lineSpace.offsetTop;}
 
837
  function paddingLeft(display) {
 
838
    var e = removeChildrenAndAdd(display.measure, elt("pre")).appendChild(elt("span", "x"));
 
839
    return e.offsetLeft;
 
840
  }
 
841
 
 
842
  function measureChar(cm, line, ch, data) {
 
843
    var data = data || measureLine(cm, line);
 
844
    var dir = -1, len = line.text.length;
 
845
    for (var pos = ch;; pos += dir) {
 
846
      var r = data[pos];
 
847
      if (r) break;
 
848
      if (dir < 0 && pos == 0) dir = 1;
 
849
    }
 
850
    return {left: pos < ch ? r.right : r.left,
 
851
            right: pos > ch ? r.left : r.right,
 
852
            top: r.top, bottom: r.bottom};
 
853
  }
 
854
 
 
855
  function measureLine(cm, line) {
 
856
    // First look in the cache
 
857
    var display = cm.display, cache = cm.display.measureLineCache;
 
858
    for (var i = 0; i < cache.length; ++i) {
 
859
      var memo = cache[i];
 
860
      if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
 
861
          display.scroller.clientWidth == memo.width)
 
862
        return memo.measure;
 
863
    }
 
864
    
 
865
    var measure = measureLineInner(cm, line);
 
866
    // Store result in the cache
 
867
    var memo = {text: line.text, width: display.scroller.clientWidth,
 
868
                markedSpans: line.markedSpans, measure: measure};
 
869
    if (cache.length == 16) cache[++cache.pos % 16] = memo;
 
870
    else cache.push(memo);
 
871
    return measure;
 
872
  }
 
873
 
 
874
  function measureLineInner(cm, line) {
 
875
    var display = cm.display, measure = emptyArray(line.text.length);
 
876
    var pre = lineContent(cm, line, measure);
 
877
    removeChildrenAndAdd(display.measure, pre);
 
878
 
 
879
    var outer = display.lineDiv.getBoundingClientRect();
 
880
    var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
 
881
    for (var i = 0, elt; i < measure.length; ++i) if (elt = measure[i]) {
 
882
      var size = measure[i].getBoundingClientRect();
 
883
      var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot);
 
884
      for (var j = 0; j < vranges.length; j += 2) {
 
885
        var rtop = vranges[j], rbot = vranges[j+1];
 
886
        if (rtop > bot || rbot < top) continue;
 
887
        if (rtop <= top && rbot >= bot ||
 
888
            top <= rtop && bot >= rbot ||
 
889
            Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
 
890
          vranges[j] = Math.min(top, rtop);
 
891
          vranges[j+1] = Math.max(bot, rbot);
 
892
          break;
 
893
        }
 
894
      }
 
895
      if (j == vranges.length) vranges.push(top, bot);
 
896
      data[i] = {left: size.left - outer.left, right: size.right - outer.left, top: j};
 
897
    }
 
898
    for (var i = 0, elt; i < data.length; ++i) if (elt = data[i]) {
 
899
      var vr = elt.top;
 
900
      elt.top = vranges[vr]; elt.bottom = vranges[vr+1];
 
901
    }
 
902
    return data;
 
903
  }
 
904
 
 
905
  // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
 
906
  function intoCoordSystem(cm, lineObj, pos, rect, context) {
 
907
    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
 
908
      var size = lineObj.widgets[i].node.offsetHeight;
 
909
      rect.top += size; rect.bottom += size;
 
910
    }
 
911
    if (context == "line") return rect;
 
912
    if (!context) context = "local";
 
913
    var yOff = heightAtLine(cm, lineObj);
 
914
    if (context != "local") yOff -= cm.display.viewOffset;
 
915
    if (context == "page") {
 
916
      var lOff = cm.display.lineSpace.getBoundingClientRect();
 
917
      yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop);
 
918
      var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft);
 
919
      rect.left += xOff; rect.right += xOff;
 
920
    }
 
921
    rect.top += yOff; rect.bottom += yOff;
 
922
    return rect;
 
923
  }
 
924
 
 
925
  function charCoords(cm, pos, context, lineObj) {
 
926
    if (!lineObj) lineObj = getLine(cm.view.doc, pos.line);
 
927
    return intoCoordSystem(cm, lineObj, pos, measureChar(cm, lineObj, pos.ch), context);
 
928
  }
 
929
 
 
930
  function cursorCoords(cm, pos, context, lineObj, measurement) {
 
931
    lineObj = lineObj || getLine(cm.view.doc, pos.line);
 
932
    if (!measurement) measurement = measureLine(cm, lineObj);
 
933
    function get(ch, right) {
 
934
      var m = measureChar(cm, lineObj, ch, measurement);
 
935
      if (right) m.left = m.right; else m.right = m.left;
 
936
      return intoCoordSystem(cm, lineObj, pos, m, context);
 
937
    }
 
938
    var order = getOrder(lineObj), ch = pos.ch;
 
939
    if (!order) return get(ch);
 
940
    var main, other, linedir = order[0].level;
 
941
    for (var i = 0; i < order.length; ++i) {
 
942
      var part = order[i], rtl = part.level % 2, nb, here;
 
943
      if (part.from < ch && part.to > ch) return get(ch, rtl);
 
944
      var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to;
 
945
      if (left == ch) {
 
946
        // Opera and IE return bogus offsets and widths for edges
 
947
        // where the direction flips, but only for the side with the
 
948
        // lower level. So we try to use the side with the higher
 
949
        // level.
 
950
        if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true);
 
951
        else here = get(rtl && part.from != part.to ? ch - 1 : ch);
 
952
        if (rtl == linedir) main = here; else other = here;
 
953
      } else if (right == ch) {
 
954
        var nb = i < order.length - 1 && order[i+1];
 
955
        if (!rtl && nb && nb.from == nb.to) continue;
 
956
        if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from);
 
957
        else here = get(rtl ? ch : ch - 1, true);
 
958
        if (rtl == linedir) main = here; else other = here;
 
959
      }
 
960
    }
 
961
    if (linedir && !ch) other = get(order[0].to - 1);
 
962
    if (!main) return other;
 
963
    if (other) main.other = other;
 
964
    return main;
 
965
  }
 
966
 
 
967
  // Coords must be lineSpace-local
 
968
  function coordsChar(cm, x, y) {
 
969
    var doc = cm.view.doc;
 
970
    y += cm.display.viewOffset;
 
971
    if (y < 0) return {line: 0, ch: 0, outside: true};
 
972
    var lineNo = lineAtHeight(doc, y);
 
973
    if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length};
 
974
    if (x < 0) x = 0;
 
975
 
 
976
    for (;;) {
 
977
      var lineObj = getLine(doc, lineNo);
 
978
      var found = coordsCharInner(cm, lineObj, lineNo, x, y);
 
979
      var merged = collapsedSpanAtEnd(lineObj);
 
980
      if (merged && found.ch == lineRight(lineObj))
 
981
        lineNo = merged.find().to.line;
 
982
      else
 
983
        return found;
 
984
    }
 
985
  }
 
986
 
 
987
  function coordsCharInner(cm, lineObj, lineNo, x, y) {
 
988
    var doc = cm.view.doc;
 
989
    var innerOff = y - heightAtLine(cm, lineObj);
 
990
    var wrongLine = false, cWidth = cm.display.wrapper.clientWidth;
 
991
    var measurement = measureLine(cm, lineObj);
 
992
 
 
993
    function getX(ch) {
 
994
      var sp = cursorCoords(cm, {line: lineNo, ch: ch}, "line",
 
995
                            lineObj, measurement);
 
996
      wrongLine = true;
 
997
      if (innerOff > sp.bottom) return Math.max(0, sp.left - cWidth);
 
998
      else if (innerOff < sp.top) return sp.left + cWidth;
 
999
      else wrongLine = false;
 
1000
      return sp.left;
 
1001
    }
 
1002
 
 
1003
    var bidi = getOrder(lineObj), dist = lineObj.text.length;
 
1004
    var from = lineLeft(lineObj), to = lineRight(lineObj), fromX = paddingLeft(cm.display), toX;
 
1005
    if (!bidi) {
 
1006
      // Guess a suitable upper bound for our search.
 
1007
      var estimated = Math.min(to, Math.ceil((x + Math.floor(innerOff / textHeight(cm.display)) *
 
1008
                                              cWidth * .9) / charWidth(cm.display)));
 
1009
      for (;;) {
 
1010
        var estX = getX(estimated);
 
1011
        if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
 
1012
        else {toX = estX; to = estimated; break;}
 
1013
      }
 
1014
      // Try to guess a suitable lower bound as well.
 
1015
      estimated = Math.floor(to * 0.8); estX = getX(estimated);
 
1016
      if (estX < x) {from = estimated; fromX = estX;}
 
1017
      dist = to - from;
 
1018
    } else toX = getX(to);
 
1019
    if (x > toX) return {line: lineNo, ch: to, outside: wrongLine};
 
1020
    // Do a binary search between these bounds.
 
1021
    for (;;) {
 
1022
      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
 
1023
        var after = x - fromX < toX - x, ch = after ? from : to;
 
1024
        while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
 
1025
        return {line: lineNo, ch: ch, after: after, outside: wrongLine};
 
1026
      }
 
1027
      var step = Math.ceil(dist / 2), middle = from + step;
 
1028
      if (bidi) {
 
1029
        middle = from;
 
1030
        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
 
1031
      }
 
1032
      var middleX = getX(middle);
 
1033
      if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; dist -= step;}
 
1034
      else {from = middle; fromX = middleX; dist = step;}
 
1035
    }
 
1036
  }
 
1037
 
 
1038
  var measureText;
 
1039
  function textHeight(display) {
 
1040
    if (display.cachedTextHeight != null) return display.cachedTextHeight;
 
1041
    if (measureText == null) {
 
1042
      measureText = elt("pre");
 
1043
      // Measure a bunch of lines, for browsers that compute
 
1044
      // fractional heights.
 
1045
      for (var i = 0; i < 49; ++i) {
 
1046
        measureText.appendChild(document.createTextNode("x"));
 
1047
        measureText.appendChild(elt("br"));
 
1048
      }
 
1049
      measureText.appendChild(document.createTextNode("x"));
 
1050
    }
 
1051
    removeChildrenAndAdd(display.measure, measureText);
 
1052
    var height = measureText.offsetHeight / 50;
 
1053
    if (height > 3) display.cachedTextHeight = height;
 
1054
    removeChildren(display.measure);
 
1055
    return height || 1;
 
1056
  }
 
1057
 
 
1058
  function charWidth(display) {
 
1059
    if (display.cachedCharWidth != null) return display.cachedCharWidth;
 
1060
    var anchor = elt("span", "x");
 
1061
    var pre = elt("pre", [anchor]);
 
1062
    removeChildrenAndAdd(display.measure, pre);
 
1063
    var width = anchor.offsetWidth;
 
1064
    if (width > 2) display.cachedCharWidth = width;
 
1065
    return width || 10;
 
1066
  }
 
1067
 
 
1068
  // OPERATIONS
 
1069
 
 
1070
  // Operations are used to wrap changes in such a way that each
 
1071
  // change won't have to update the cursor and display (which would
 
1072
  // be awkward, slow, and error-prone), but instead updates are
 
1073
  // batched and then all combined and executed at once.
 
1074
 
 
1075
  function startOperation(cm) {
 
1076
    if (cm.curOp) ++cm.curOp.depth;
 
1077
    else cm.curOp = {
 
1078
      // Nested operations delay update until the outermost one
 
1079
      // finishes.
 
1080
      depth: 1,
 
1081
      // An array of ranges of lines that have to be updated. See
 
1082
      // updateDisplay.
 
1083
      changes: [],
 
1084
      delayedCallbacks: [],
 
1085
      updateInput: null,
 
1086
      userSelChange: null,
 
1087
      textChanged: null,
 
1088
      selectionChanged: false,
 
1089
      updateMaxLine: false
 
1090
    };
 
1091
  }
 
1092
 
 
1093
  function endOperation(cm) {
 
1094
    var op = cm.curOp;
 
1095
    if (--op.depth) return;
 
1096
    cm.curOp = null;
 
1097
    var view = cm.view, display = cm.display;
 
1098
    if (op.updateMaxLine) computeMaxLength(view);
 
1099
    if (view.maxLineChanged && !cm.options.lineWrapping) {
 
1100
      var width = measureChar(cm, view.maxLine, view.maxLine.text.length).right;
 
1101
      display.sizer.style.minWidth = (width + 3 + scrollerCutOff) + "px";
 
1102
      view.maxLineChanged = false;
 
1103
    }
 
1104
    var newScrollPos, updated;
 
1105
    if (op.selectionChanged) {
 
1106
      var coords = cursorCoords(cm, selHead(view));
 
1107
      newScrollPos = calculateScrollPos(display, coords.left, coords.top, coords.left, coords.bottom);
 
1108
    }
 
1109
    if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null)
 
1110
      updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop);
 
1111
    if (!updated && op.selectionChanged) updateSelection(cm);
 
1112
    if (newScrollPos) scrollCursorIntoView(cm);
 
1113
    if (op.selectionChanged) restartBlink(cm);
 
1114
 
 
1115
    if (view.focused && op.updateInput)
 
1116
      resetInput(cm, op.userSelChange);
 
1117
 
 
1118
    if (op.textChanged)
 
1119
      signal(cm, "change", cm, op.textChanged);
 
1120
    if (op.selectionChanged) signal(cm, "cursorActivity", cm);
 
1121
    for (var i = 0; i < op.delayedCallbacks.length; ++i) op.delayedCallbacks[i](cm);
 
1122
  }
 
1123
 
 
1124
  // Wraps a function in an operation. Returns the wrapped function.
 
1125
  function operation(cm1, f) {
 
1126
    return function() {
 
1127
      var cm = cm1 || this;
 
1128
      startOperation(cm);
 
1129
      try {var result = f.apply(cm, arguments);}
 
1130
      finally {endOperation(cm);}
 
1131
      return result;
 
1132
    };
 
1133
  }
 
1134
 
 
1135
  function regChange(cm, from, to, lendiff) {
 
1136
    cm.curOp.changes.push({from: from, to: to, diff: lendiff});
 
1137
  }
 
1138
 
 
1139
  // INPUT HANDLING
 
1140
 
 
1141
  function slowPoll(cm) {
 
1142
    if (cm.view.pollingFast) return;
 
1143
    cm.display.poll.set(cm.options.pollInterval, function() {
 
1144
      readInput(cm);
 
1145
      if (cm.view.focused) slowPoll(cm);
 
1146
    });
 
1147
  }
 
1148
 
 
1149
  function fastPoll(cm) {
 
1150
    var missed = false;
 
1151
    cm.display.pollingFast = true;
 
1152
    function p() {
 
1153
      var changed = readInput(cm);
 
1154
      if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
 
1155
      else {cm.display.pollingFast = false; slowPoll(cm);}
 
1156
    }
 
1157
    cm.display.poll.set(20, p);
 
1158
  }
 
1159
 
 
1160
  // prevInput is a hack to work with IME. If we reset the textarea
 
1161
  // on every change, that breaks IME. So we look for changes
 
1162
  // compared to the previous content instead. (Modern browsers have
 
1163
  // events that indicate IME taking place, but these are not widely
 
1164
  // supported or compatible enough yet to rely on.)
 
1165
  function readInput(cm) {
 
1166
    var input = cm.display.input, prevInput = cm.display.prevInput, view = cm.view, sel = view.sel;
 
1167
    if (!view.focused || hasSelection(input) || isReadOnly(cm)) return false;
 
1168
    var text = input.value;
 
1169
    if (text == prevInput && posEq(sel.from, sel.to)) return false;
 
1170
    startOperation(cm);
 
1171
    view.sel.shift = null;
 
1172
    var same = 0, l = Math.min(prevInput.length, text.length);
 
1173
    while (same < l && prevInput[same] == text[same]) ++same;
 
1174
    if (same < prevInput.length)
 
1175
      sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)};
 
1176
    else if (view.overwrite && posEq(sel.from, sel.to) && !cm.display.pasteIncoming)
 
1177
      sel.to = {line: sel.to.line, ch: Math.min(getLine(cm.view.doc, sel.to.line).text.length, sel.to.ch + (text.length - same))};
 
1178
    var updateInput = cm.curOp.updateInput;
 
1179
    cm.replaceSelection(text.slice(same), "end");
 
1180
    cm.curOp.updateInput = updateInput;
 
1181
    if (text.length > 1000) { input.value = cm.display.prevInput = ""; }
 
1182
    else cm.display.prevInput = text;
 
1183
    endOperation(cm);
 
1184
    cm.display.pasteIncoming = false;
 
1185
    return true;
 
1186
  }
 
1187
 
 
1188
  function resetInput(cm, user) {
 
1189
    var view = cm.view, minimal, selected;
 
1190
    if (!posEq(view.sel.from, view.sel.to)) {
 
1191
      cm.display.prevInput = "";
 
1192
      minimal = hasCopyEvent &&
 
1193
        (view.sel.to.line - view.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
 
1194
      if (minimal) cm.display.input.value = "-";
 
1195
      else cm.display.input.value = selected || cm.getSelection();
 
1196
      if (view.focused) selectInput(cm.display.input);
 
1197
    } else if (user) cm.display.prevInput = cm.display.input.value = "";
 
1198
    cm.display.inaccurateSelection = minimal;
 
1199
  }
 
1200
 
 
1201
  function focusInput(cm) {
 
1202
    if (cm.options.readOnly != "nocursor") cm.display.input.focus();
 
1203
  }
 
1204
 
 
1205
  function isReadOnly(cm) {
 
1206
    return cm.options.readOnly || cm.view.cantEdit;
 
1207
  }
 
1208
 
 
1209
  // EVENT HANDLERS
 
1210
 
 
1211
  function registerEventHandlers(cm) {
 
1212
    var d = cm.display;
 
1213
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
 
1214
    on(d.gutters, "mousedown", operation(cm, clickInGutter));
 
1215
    on(d.scroller, "dblclick", operation(cm, e_preventDefault));
 
1216
    on(d.lineSpace, "selectstart", function(e) {
 
1217
      if (!mouseEventInWidget(d, e)) e_preventDefault(e);
 
1218
    });
 
1219
    // Gecko browsers fire contextmenu *after* opening the menu, at
 
1220
    // which point we can't mess with it anymore. Context menu is
 
1221
    // handled in onMouseDown for Gecko.
 
1222
    if (!gecko) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
 
1223
 
 
1224
    on(d.scroller, "scroll", function() {
 
1225
      setScrollTop(cm, d.scroller.scrollTop);
 
1226
      setScrollLeft(cm, d.scroller.scrollLeft);
 
1227
      signal(cm, "scroll", cm);
 
1228
    });
 
1229
    on(d.scrollbarV, "scroll", function() {
 
1230
      setScrollTop(cm, d.scrollbarV.scrollTop);
 
1231
    });
 
1232
    on(d.scrollbarH, "scroll", function() {
 
1233
      setScrollLeft(cm, d.scrollbarH.scrollLeft);
 
1234
    });
 
1235
 
 
1236
    on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
 
1237
    on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
 
1238
 
 
1239
    function reFocus() { if (cm.view.focused) setTimeout(bind(focusInput, cm), 0); }
 
1240
    on(d.scrollbarH, "mousedown", reFocus);
 
1241
    on(d.scrollbarV, "mousedown", reFocus);
 
1242
    // Prevent wrapper from ever scrolling
 
1243
    on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
 
1244
    on(window, "resize", function resizeHandler() {
 
1245
      // Might be a text scaling operation, clear size caches.
 
1246
      d.cachedCharWidth = d.cachedTextHeight = null;
 
1247
      d.measureLineCache.length = d.measureLineCache.pos = 0;
 
1248
      if (d.wrapper.parentNode) updateDisplay(cm, true);
 
1249
      else off(window, "resize", resizeHandler);
 
1250
    });
 
1251
 
 
1252
    on(d.input, "keyup", operation(cm, function(e) {
 
1253
      if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
 
1254
      if (e_prop(e, "keyCode") == 16) cm.view.sel.shift = null;
 
1255
    }));
 
1256
    on(d.input, "input", bind(fastPoll, cm));
 
1257
    on(d.input, "keydown", operation(cm, onKeyDown));
 
1258
    on(d.input, "keypress", operation(cm, onKeyPress));
 
1259
    on(d.input, "focus", bind(onFocus, cm));
 
1260
    on(d.input, "blur", bind(onBlur, cm));
 
1261
 
 
1262
    function drag_(e) {
 
1263
      if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
 
1264
      e_stop(e);
 
1265
    }
 
1266
    if (cm.options.dragDrop) {
 
1267
      on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
 
1268
      on(d.scroller, "dragenter", drag_);
 
1269
      on(d.scroller, "dragover", drag_);
 
1270
      on(d.scroller, "drop", operation(cm, onDrop));
 
1271
    }
 
1272
    on(d.scroller, "paste", function(){focusInput(cm); fastPoll(cm);});
 
1273
    on(d.input, "paste", function() {
 
1274
      d.pasteIncoming = true;
 
1275
      fastPoll(cm);
 
1276
    });
 
1277
 
 
1278
    function prepareCopy() {
 
1279
      if (d.inaccurateSelection) {
 
1280
        d.prevInput = "";
 
1281
        d.inaccurateSelection = false;
 
1282
        d.input.value = cm.getSelection();
 
1283
        selectInput(d.input);
 
1284
      }
 
1285
    }
 
1286
    on(d.input, "cut", prepareCopy);
 
1287
    on(d.input, "copy", prepareCopy);
 
1288
 
 
1289
    // Needed to handle Tab key in KHTML
 
1290
    if (khtml) on(d.sizer, "mouseup", function() {
 
1291
        if (document.activeElement == d.input) d.input.blur();
 
1292
        focusInput(cm);
 
1293
    });
 
1294
  }
 
1295
 
 
1296
  function mouseEventInWidget(display, e) {
 
1297
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode)
 
1298
      if (/\bCodeMirror-(?:line)?widget\b/.test(n.className) ||
 
1299
          n.parentNode == display.sizer && n != display.mover) return true;
 
1300
  }
 
1301
 
 
1302
  function posFromMouse(cm, e, liberal) {
 
1303
    var display = cm.display;
 
1304
    if (!liberal) {
 
1305
      var target = e_target(e);
 
1306
      if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
 
1307
          target == display.scrollbarV || target == display.scrollbarV.firstChild ||
 
1308
          target == display.scrollbarFiller) return null;
 
1309
    }
 
1310
    var x, y, space = display.lineSpace.getBoundingClientRect();
 
1311
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
 
1312
    try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
 
1313
    return coordsChar(cm, x - space.left, y - space.top);
 
1314
  }
 
1315
 
 
1316
  var lastClick, lastDoubleClick;
 
1317
  function onMouseDown(e) {
 
1318
    var cm = this, display = cm.display, view = cm.view, sel = view.sel, doc = view.doc;
 
1319
    setShift(cm.view, e_prop(e, "shiftKey"));
 
1320
 
 
1321
    if (mouseEventInWidget(display, e)) {
 
1322
      if (!webkit) {
 
1323
        display.scroller.draggable = false;
 
1324
        setTimeout(function(){display.scroller.draggable = true;}, 100);
 
1325
      }
 
1326
      return;
 
1327
    }
 
1328
    if (clickInGutter.call(cm, e)) return;
 
1329
    var start = posFromMouse(cm, e);
 
1330
 
 
1331
    switch (e_button(e)) {
 
1332
    case 3:
 
1333
      if (gecko) onContextMenu.call(cm, cm, e);
 
1334
      return;
 
1335
    case 2:
 
1336
      if (start) setSelectionUser(cm, start, start);
 
1337
      setTimeout(bind(focusInput, cm), 20);
 
1338
      e_preventDefault(e);
 
1339
      return;
 
1340
    }
 
1341
    // For button 1, if it was clicked inside the editor
 
1342
    // (posFromMouse returning non-null), we have to adjust the
 
1343
    // selection.
 
1344
    if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
 
1345
 
 
1346
    if (!view.focused) onFocus(cm);
 
1347
 
 
1348
    var now = +new Date, type = "single";
 
1349
    if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
 
1350
      type = "triple";
 
1351
      e_preventDefault(e);
 
1352
      setTimeout(bind(focusInput, cm), 20);
 
1353
      selectLine(cm, start.line);
 
1354
    } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
 
1355
      type = "double";
 
1356
      lastDoubleClick = {time: now, pos: start};
 
1357
      e_preventDefault(e);
 
1358
      var word = findWordAt(getLine(doc, start.line).text, start);
 
1359
      setSelectionUser(cm, word.from, word.to);
 
1360
    } else { lastClick = {time: now, pos: start}; }
 
1361
 
 
1362
    var last = start;
 
1363
    if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
 
1364
        !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
 
1365
      var dragEnd = operation(cm, function(e2) {
 
1366
        if (webkit) display.scroller.draggable = false;
 
1367
        view.draggingText = false;
 
1368
        off(document, "mouseup", dragEnd);
 
1369
        off(display.scroller, "drop", dragEnd);
 
1370
        if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
 
1371
          e_preventDefault(e2);
 
1372
          setSelectionUser(cm, start, start);
 
1373
          focusInput(cm);
 
1374
        }
 
1375
      });
 
1376
      // Let the drag handler handle this.
 
1377
      if (webkit) display.scroller.draggable = true;
 
1378
      view.draggingText = dragEnd;
 
1379
      // IE's approach to draggable
 
1380
      if (display.scroller.dragDrop) display.scroller.dragDrop();
 
1381
      on(document, "mouseup", dragEnd);
 
1382
      on(display.scroller, "drop", dragEnd);
 
1383
      return;
 
1384
    }
 
1385
    e_preventDefault(e);
 
1386
    if (type == "single") setSelectionUser(cm, start, start);
 
1387
 
 
1388
    var startstart = sel.from, startend = sel.to;
 
1389
 
 
1390
    function doSelect(cur) {
 
1391
      if (type == "single") {
 
1392
        setSelectionUser(cm, start, cur);
 
1393
      } else if (type == "double") {
 
1394
        var word = findWordAt(getLine(doc, cur.line).text, cur);
 
1395
        if (posLess(cur, startstart)) setSelectionUser(cm, word.from, startend);
 
1396
        else setSelectionUser(cm, startstart, word.to);
 
1397
      } else if (type == "triple") {
 
1398
        if (posLess(cur, startstart)) setSelectionUser(cm, startend, clipPos(doc, {line: cur.line, ch: 0}));
 
1399
        else setSelectionUser(cm, startstart, clipPos(doc, {line: cur.line + 1, ch: 0}));
 
1400
      }
 
1401
    }
 
1402
 
 
1403
    var editorSize = display.wrapper.getBoundingClientRect();
 
1404
    // Used to ensure timeout re-tries don't fire when another extend
 
1405
    // happened in the meantime (clearTimeout isn't reliable -- at
 
1406
    // least on Chrome, the timeouts still happen even when cleared,
 
1407
    // if the clear happens after their scheduled firing time).
 
1408
    var counter = 0;
 
1409
 
 
1410
    function extend(e) {
 
1411
      var curCount = ++counter;
 
1412
      var cur = posFromMouse(cm, e, true);
 
1413
      if (!cur) return;
 
1414
      if (!posEq(cur, last)) {
 
1415
        if (!view.focused) onFocus(cm);
 
1416
        last = cur;
 
1417
        doSelect(cur);
 
1418
        var visible = visibleLines(display, doc);
 
1419
        if (cur.line >= visible.to || cur.line < visible.from)
 
1420
          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
 
1421
      } else {
 
1422
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
 
1423
        if (outside) setTimeout(operation(cm, function() {
 
1424
          if (counter != curCount) return;
 
1425
          display.scroller.scrollTop += outside;
 
1426
          extend(e);
 
1427
        }), 50);
 
1428
      }
 
1429
    }
 
1430
 
 
1431
    function done(e) {
 
1432
      counter = Infinity;
 
1433
      var cur = posFromMouse(cm, e);
 
1434
      if (cur) doSelect(cur);
 
1435
      e_preventDefault(e);
 
1436
      focusInput(cm);
 
1437
      off(document, "mousemove", move);
 
1438
      off(document, "mouseup", up);
 
1439
    }
 
1440
 
 
1441
    var move = operation(cm, function(e) {
 
1442
      e_preventDefault(e);
 
1443
      if (!ie && !e_button(e)) done(e);
 
1444
      else extend(e);
 
1445
    });
 
1446
    var up = operation(cm, done);
 
1447
    on(document, "mousemove", move);
 
1448
    on(document, "mouseup", up);
 
1449
  }
 
1450
 
 
1451
  function onDrop(e) {
 
1452
    var cm = this;
 
1453
    if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
 
1454
    e_preventDefault(e);
 
1455
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
 
1456
    if (!pos || isReadOnly(cm)) return;
 
1457
    if (files && files.length && window.FileReader && window.File) {
 
1458
      var n = files.length, text = Array(n), read = 0;
 
1459
      var loadFile = function(file, i) {
 
1460
        var reader = new FileReader;
 
1461
        reader.onload = function() {
 
1462
          text[i] = reader.result;
 
1463
          if (++read == n) {
 
1464
            pos = clipPos(cm.view.doc, pos);
 
1465
            operation(cm, function() {
 
1466
              var end = replaceRange(cm, text.join(""), pos, pos);
 
1467
              setSelectionUser(cm, pos, end);
 
1468
            })();
 
1469
          }
 
1470
        };
 
1471
        reader.readAsText(file);
 
1472
      };
 
1473
      for (var i = 0; i < n; ++i) loadFile(files[i], i);
 
1474
    } else {
 
1475
      // Don't do a replace if the drop happened inside of the selected text.
 
1476
      if (cm.view.draggingText && !(posLess(pos, cm.view.sel.from) || posLess(cm.view.sel.to, pos))) {
 
1477
        cm.view.draggingText(e);
 
1478
        if (ie) setTimeout(bind(focusInput, cm), 50);
 
1479
        return;
 
1480
      }
 
1481
      try {
 
1482
        var text = e.dataTransfer.getData("Text");
 
1483
        if (text) {
 
1484
          compoundChange(cm, function() {
 
1485
            var curFrom = cm.view.sel.from, curTo = cm.view.sel.to;
 
1486
            setSelectionUser(cm, pos, pos);
 
1487
            if (cm.view.draggingText) replaceRange(cm, "", curFrom, curTo);
 
1488
            cm.replaceSelection(text);
 
1489
            focusInput(cm);
 
1490
            onFocus(cm);
 
1491
          });
 
1492
        }
 
1493
      }
 
1494
      catch(e){}
 
1495
    }
 
1496
  }
 
1497
 
 
1498
  function clickInGutter(e) {
 
1499
    var cm = this, display = cm.display;
 
1500
    try { var mX = e.clientX, mY = e.clientY; }
 
1501
    catch(e) { return false; }
 
1502
    
 
1503
    if (mX >= Math.floor(display.gutters.getBoundingClientRect().right)) return false;
 
1504
    e_preventDefault(e);
 
1505
    if (!hasHandler(cm, "gutterClick")) return true;
 
1506
 
 
1507
    var lineBox = display.lineDiv.getBoundingClientRect();
 
1508
    if (mY > lineBox.bottom) return true;
 
1509
    mY -= lineBox.top - display.viewOffset;
 
1510
 
 
1511
    for (var i = 0; i < cm.options.gutters.length; ++i) {
 
1512
      var g = display.gutters.childNodes[i];
 
1513
      if (g && g.getBoundingClientRect().right >= mX) {
 
1514
        var line = lineAtHeight(cm.view.doc, mY);
 
1515
        var gutter = cm.options.gutters[i];
 
1516
        signalLater(cm, cm, "gutterClick", cm, line, gutter, e);
 
1517
        break;
 
1518
      }
 
1519
    }
 
1520
    return true;
 
1521
  }
 
1522
 
 
1523
  function onDragStart(cm, e) {
 
1524
    var txt = cm.getSelection();
 
1525
    e.dataTransfer.setData("Text", txt);
 
1526
 
 
1527
    // Use dummy image instead of default browsers image.
 
1528
    if (e.dataTransfer.setDragImage)
 
1529
      e.dataTransfer.setDragImage(elt('img'), 0, 0);
 
1530
  }
 
1531
 
 
1532
  function setScrollTop(cm, val) {
 
1533
    if (Math.abs(cm.view.scrollTop - val) < 2) return;
 
1534
    cm.view.scrollTop = val;
 
1535
    if (!gecko) updateDisplay(cm, [], val);
 
1536
    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
 
1537
    if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
 
1538
    if (gecko) updateDisplay(cm, []);
 
1539
  }
 
1540
  function setScrollLeft(cm, val) {
 
1541
    if (Math.abs(cm.view.scrollLeft - val) < 2) return;
 
1542
    cm.view.scrollLeft = val;
 
1543
    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
 
1544
    if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
 
1545
    alignVertically(cm.display);
 
1546
  }
 
1547
 
 
1548
  // Since the delta values reported on mouse wheel events are
 
1549
  // unstandardized between browsers and even browser versions, and
 
1550
  // generally horribly unpredictable, this code starts by measuring
 
1551
  // the scroll effect that the first few mouse wheel events have,
 
1552
  // and, from that, detects the way it can convert deltas to pixel
 
1553
  // offsets afterwards.
 
1554
  //
 
1555
  // The reason we want to know the amount a wheel event will scroll
 
1556
  // is that it gives us a chance to update the display before the
 
1557
  // actual scrolling happens, reducing flickering.
 
1558
 
 
1559
  var wheelSamples = 0, wheelDX, wheelDY, wheelStartX, wheelStartY, wheelPixelsPerUnit = null;
 
1560
  // Fill in a browser-detected starting value on browsers where we
 
1561
  // know one. These don't have to be accurate -- the result of them
 
1562
  // being wrong would just be a slight flicker on the first wheel
 
1563
  // scroll (if it is large enough).
 
1564
  if (ie) wheelPixelsPerUnit = -.53;
 
1565
  else if (gecko) wheelPixelsPerUnit = 15;
 
1566
  else if (chrome) wheelPixelsPerUnit = -.7;
 
1567
  else if (safari) wheelPixelsPerUnit = -1/3;
 
1568
 
 
1569
  function onScrollWheel(cm, e) {
 
1570
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
 
1571
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
 
1572
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
 
1573
    else if (dy == null) dy = e.wheelDelta;
 
1574
 
 
1575
    var scroll = cm.display.scroller;
 
1576
    if (wheelPixelsPerUnit != null) {
 
1577
      var pixels = dy * wheelPixelsPerUnit;
 
1578
      var top = cm.view.scrollTop, bot = top + cm.display.wrapper.clientHeight;
 
1579
      if (pixels < 0) top = Math.max(0, top + pixels);
 
1580
      else bot = Math.min(cm.view.doc.height, bot + pixels);
 
1581
      updateDisplay(cm, [], {top: top, bottom: bot});
 
1582
    }
 
1583
    if (wheelSamples < 20) {
 
1584
      if (wheelStartX == null) {
 
1585
        wheelStartX = scroll.scrollLeft; wheelStartY = scroll.scrollTop;
 
1586
        wheelDX = dx; wheelDY = dy;
 
1587
        setTimeout(function() {
 
1588
          var movedX = scroll.scrollLeft - wheelStartX;
 
1589
          var movedY = scroll.scrollTop - wheelStartY;
 
1590
          var sample = (movedY && wheelDY && movedY / wheelDY) ||
 
1591
            (movedX && wheelDX && movedX / wheelDX);
 
1592
          wheelStartX = wheelStartY = null;
 
1593
          if (!sample) return;
 
1594
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
 
1595
          ++wheelSamples;
 
1596
        }, 200);
 
1597
      } else {
 
1598
        wheelDX += dx; wheelDY += dy;
 
1599
      }
 
1600
    }
 
1601
  }
 
1602
 
 
1603
  function doHandleBinding(cm, bound, dropShift) {
 
1604
    if (typeof bound == "string") {
 
1605
      bound = commands[bound];
 
1606
      if (!bound) return false;
 
1607
    }
 
1608
    var view = cm.view, prevShift = view.sel.shift;
 
1609
    try {
 
1610
      if (isReadOnly(cm)) view.suppressEdits = true;
 
1611
      if (dropShift) view.sel.shift = null;
 
1612
      bound(cm);
 
1613
    } catch(e) {
 
1614
      if (e != Pass) throw e;
 
1615
      return false;
 
1616
    } finally {
 
1617
      view.sel.shift = prevShift;
 
1618
      view.suppressEdits = false;
 
1619
    }
 
1620
    return true;
 
1621
  }
 
1622
 
 
1623
  var maybeTransition;
 
1624
  function handleKeyBinding(cm, e) {
 
1625
    // Handle auto keymap transitions
 
1626
    var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
 
1627
    clearTimeout(maybeTransition);
 
1628
    if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
 
1629
      if (getKeyMap(cm.options.keyMap) == startMap)
 
1630
        cm.options.keyMap = (next.call ? next.call(null, cm) : next);
 
1631
    }, 50);
 
1632
 
 
1633
    var name = keyNames[e_prop(e, "keyCode")], handled = false;
 
1634
    var flipCtrlCmd = opera && mac;
 
1635
    if (name == null || e.altGraphKey) return false;
 
1636
    if (e_prop(e, "altKey")) name = "Alt-" + name;
 
1637
    if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name;
 
1638
    if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name;
 
1639
 
 
1640
    var stopped = false;
 
1641
    function stop() { stopped = true; }
 
1642
 
 
1643
    if (e_prop(e, "shiftKey")) {
 
1644
      handled = lookupKey("Shift-" + name, cm.options.extraKeys, cm.options.keyMap,
 
1645
                          function(b) {return doHandleBinding(cm, b, true);}, stop)
 
1646
        || lookupKey(name, cm.options.extraKeys, cm.options.keyMap, function(b) {
 
1647
          if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b);
 
1648
        }, stop);
 
1649
    } else {
 
1650
      handled = lookupKey(name, cm.options.extraKeys, cm.options.keyMap,
 
1651
                          function(b) { return doHandleBinding(cm, b); }, stop);
 
1652
    }
 
1653
    if (stopped) handled = false;
 
1654
    if (handled) {
 
1655
      e_preventDefault(e);
 
1656
      restartBlink(cm);
 
1657
      if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
 
1658
    }
 
1659
    return handled;
 
1660
  }
 
1661
 
 
1662
  function handleCharBinding(cm, e, ch) {
 
1663
    var handled = lookupKey("'" + ch + "'", cm.options.extraKeys, cm.options.keyMap,
 
1664
                            function(b) { return doHandleBinding(cm, b, true); });
 
1665
    if (handled) {
 
1666
      e_preventDefault(e);
 
1667
      restartBlink(cm);
 
1668
    }
 
1669
    return handled;
 
1670
  }
 
1671
 
 
1672
  var lastStoppedKey = null;
 
1673
  function onKeyDown(e) {
 
1674
    var cm = this;
 
1675
    if (!cm.view.focused) onFocus(cm);
 
1676
    if (ie && e.keyCode == 27) { e.returnValue = false; }
 
1677
    if (cm.display.pollingFast) { if (readInput(cm)) cm.display.pollingFast = false; }
 
1678
    if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
 
1679
    var code = e_prop(e, "keyCode");
 
1680
    // IE does strange things with escape.
 
1681
    setShift(cm.view, code == 16 || e_prop(e, "shiftKey"));
 
1682
    // First give onKeyEvent option a chance to handle this.
 
1683
    var handled = handleKeyBinding(cm, e);
 
1684
    if (opera) {
 
1685
      lastStoppedKey = handled ? code : null;
 
1686
      // Opera has no cut event... we try to at least catch the key combo
 
1687
      if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey"))
 
1688
        cm.replaceSelection("");
 
1689
    }
 
1690
  }
 
1691
 
 
1692
  function onKeyPress(e) {
 
1693
    var cm = this;
 
1694
    if (cm.display.pollingFast) readInput(cm);
 
1695
    if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
 
1696
    var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
 
1697
    if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
 
1698
    if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
 
1699
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
 
1700
    if (this.options.electricChars && this.view.mode.electricChars &&
 
1701
        this.options.smartIndent && !isReadOnly(this) &&
 
1702
        this.view.mode.electricChars.indexOf(ch) > -1)
 
1703
      setTimeout(operation(cm, function() {indentLine(cm, cm.view.sel.to.line, "smart");}), 75);
 
1704
    if (handleCharBinding(cm, e, ch)) return;
 
1705
    fastPoll(cm);
 
1706
  }
 
1707
 
 
1708
  function onFocus(cm) {
 
1709
    if (cm.options.readOnly == "nocursor") return;
 
1710
    if (!cm.view.focused) {
 
1711
      signal(cm, "focus", cm);
 
1712
      cm.view.focused = true;
 
1713
      if (cm.display.scroller.className.search(/\bCodeMirror-focused\b/) == -1)
 
1714
        cm.display.scroller.className += " CodeMirror-focused";
 
1715
      resetInput(cm, true);
 
1716
    }
 
1717
    slowPoll(cm);
 
1718
    restartBlink(cm);
 
1719
  }
 
1720
  function onBlur(cm) {
 
1721
    if (cm.view.focused) {
 
1722
      signal(cm, "blur", cm);
 
1723
      cm.view.focused = false;
 
1724
      cm.display.scroller.className = cm.display.scroller.className.replace(" CodeMirror-focused", "");
 
1725
    }
 
1726
    clearInterval(cm.display.blinker);
 
1727
    setTimeout(function() {if (!cm.view.focused) cm.view.sel.shift = null;}, 150);
 
1728
  }
 
1729
 
 
1730
  var detectingSelectAll;
 
1731
  function onContextMenu(cm, e) {
 
1732
    var display = cm.display, sel = cm.view.sel;
 
1733
    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
 
1734
    if (!pos || opera) return; // Opera is difficult.
 
1735
    if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
 
1736
      operation(cm, setSelection)(cm, pos, pos);
 
1737
 
 
1738
    var oldCSS = display.input.style.cssText;
 
1739
    display.inputDiv.style.position = "absolute";
 
1740
    display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
 
1741
      "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
 
1742
      "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
 
1743
    focusInput(cm);
 
1744
    resetInput(cm, true);
 
1745
    // Adds "Select all" to context menu in FF
 
1746
    if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
 
1747
 
 
1748
    function rehide() {
 
1749
      display.inputDiv.style.position = "relative";
 
1750
      display.input.style.cssText = oldCSS;
 
1751
      if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
 
1752
      slowPoll(cm);
 
1753
 
 
1754
      // Try to detect the user choosing select-all 
 
1755
      if (display.input.selectionStart != null) {
 
1756
        clearTimeout(detectingSelectAll);
 
1757
        var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0;
 
1758
        display.prevInput = " ";
 
1759
        display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
 
1760
        detectingSelectAll = setTimeout(function poll(){
 
1761
          if (display.prevInput == " " && display.input.selectionStart == 0)
 
1762
            operation(cm, commands.selectAll)(cm);
 
1763
          else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
 
1764
          else resetInput(cm);
 
1765
        }, 200);
 
1766
      }
 
1767
    }
 
1768
 
 
1769
    if (gecko) {
 
1770
      e_stop(e);
 
1771
      on(window, "mouseup", function mouseup() {
 
1772
        off(window, "mouseup", mouseup);
 
1773
        setTimeout(rehide, 20);
 
1774
      });
 
1775
    } else {
 
1776
      setTimeout(rehide, 50);
 
1777
    }
 
1778
  }
 
1779
 
 
1780
  // UPDATING
 
1781
 
 
1782
  // Replace the range from from to to by the strings in newText.
 
1783
  // Afterwards, set the selection to selFrom, selTo.
 
1784
  function updateDoc(cm, from, to, newText, selUpdate) {
 
1785
    // Possibly split or suppress the update based on the presence
 
1786
    // of read-only spans in its range.
 
1787
    var split = sawReadOnlySpans &&
 
1788
      removeReadOnlyRanges(cm.view.doc, from, to);
 
1789
    if (split) {
 
1790
      for (var i = split.length - 1; i >= 1; --i)
 
1791
        updateDocInner(cm, split[i].from, split[i].to, [""]);
 
1792
      if (split.length)
 
1793
        return updateDocInner(cm, split[0].from, split[0].to, newText, selUpdate);
 
1794
    } else {
 
1795
      return updateDocInner(cm, from, to, newText, selUpdate);
 
1796
    }
 
1797
  }
 
1798
 
 
1799
  function updateDocInner(cm, from, to, newText, selUpdate) {
 
1800
    if (cm.view.suppressEdits) return;
 
1801
 
 
1802
    var view = cm.view, doc = view.doc, old = [];
 
1803
    doc.iter(from.line, to.line + 1, function(line) {
 
1804
      old.push(newHL(line.text, line.markedSpans));
 
1805
    });
 
1806
    if (view.history) {
 
1807
      addChange(view.history, from.line, newText.length, old);
 
1808
      while (view.history.done.length > cm.options.undoDepth) view.history.done.shift();
 
1809
    }
 
1810
    var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
 
1811
    return updateDocNoUndo(cm, from, to, lines, selUpdate);
 
1812
  }
 
1813
 
 
1814
  function unredoHelper(cm, from, to, dir) {
 
1815
    var doc = cm.view.doc, hist = cm.view.history;
 
1816
    if (!from.length) return;
 
1817
    var set = from.pop(), out = [];
 
1818
    for (var i = set.length - 1; i >= 0; i -= 1) {
 
1819
      hist.dirtyCounter += dir;
 
1820
      var change = set[i];
 
1821
      var replaced = [], end = change.start + change.added;
 
1822
      doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); });
 
1823
      out.push({start: change.start, added: change.old.length, old: replaced});
 
1824
      var pos = {line: change.start + change.old.length - 1,
 
1825
                 ch: editEnd(hlText(lst(replaced)), hlText(lst(change.old)))};
 
1826
      updateDocNoUndo(cm, {line: change.start, ch: 0}, {line: end - 1, ch: getLine(doc, end-1).text.length},
 
1827
                      change.old, pos);
 
1828
    }
 
1829
    to.push(out);
 
1830
  }
 
1831
 
 
1832
  function updateDocNoUndo(cm, from, to, lines, selUpdate) {
 
1833
    var view = cm.view, doc = view.doc, display = cm.display;
 
1834
    if (view.suppressEdits) return;
 
1835
 
 
1836
    var nlines = to.line - from.line, firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
 
1837
    var recomputeMaxLength = false, checkWidthStart = from.line;
 
1838
    if (!cm.options.lineWrapping) {
 
1839
      for (var cur = firstLine, merged; merged = collapsedSpanAtStart(cur);) {
 
1840
        checkWidthStart = merged.find().from.line;
 
1841
        cur = getLine(doc, checkWidthStart);
 
1842
      }
 
1843
      doc.iter(checkWidthStart, to.line + 1, function(line) {
 
1844
        if (lineLength(doc, line) == view.maxLineLength) {
 
1845
          recomputeMaxLength = true;
 
1846
          return true;
 
1847
        }
 
1848
      });
 
1849
    }
 
1850
 
 
1851
    var lastHL = lst(lines), th = textHeight(display);
 
1852
 
 
1853
    // First adjust the line structure
 
1854
    if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") {
 
1855
      // This is a whole-line replace. Treated specially to make
 
1856
      // sure line objects move the way they are supposed to.
 
1857
      var added = [], prevLine = null;
 
1858
      for (var i = 0, e = lines.length - 1; i < e; ++i)
 
1859
        added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
 
1860
      updateLine(cm, lastLine, lastLine.text, hlSpans(lastHL));
 
1861
      if (nlines) doc.remove(from.line, nlines, cm);
 
1862
      if (added.length) doc.insert(from.line, added);
 
1863
    } else if (firstLine == lastLine) {
 
1864
      if (lines.length == 1) {
 
1865
        updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) +
 
1866
                   firstLine.text.slice(to.ch), hlSpans(lines[0]));
 
1867
      } else {
 
1868
        for (var added = [], i = 1, e = lines.length - 1; i < e; ++i)
 
1869
          added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
 
1870
        added.push(makeLine(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL), th));
 
1871
        updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
 
1872
        doc.insert(from.line + 1, added);
 
1873
      }
 
1874
    } else if (lines.length == 1) {
 
1875
      updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) +
 
1876
                 lastLine.text.slice(to.ch), hlSpans(lines[0]));
 
1877
      doc.remove(from.line + 1, nlines, cm);
 
1878
    } else {
 
1879
      var added = [];
 
1880
      updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
 
1881
      updateLine(cm, lastLine, hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL));
 
1882
      for (var i = 1, e = lines.length - 1; i < e; ++i)
 
1883
        added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
 
1884
      if (nlines > 1) doc.remove(from.line + 1, nlines - 1, cm);
 
1885
      doc.insert(from.line + 1, added);
 
1886
    }
 
1887
 
 
1888
    if (cm.options.lineWrapping) {
 
1889
      var perLine = Math.max(5, display.scroller.clientWidth / charWidth(display) - 3);
 
1890
      doc.iter(from.line, from.line + lines.length, function(line) {
 
1891
        if (line.height == 0) return;
 
1892
        var guess = (Math.ceil(line.text.length / perLine) || 1) * th;
 
1893
        if (guess != line.height) updateLineHeight(line, guess);
 
1894
      });
 
1895
    } else {
 
1896
      doc.iter(checkWidthStart, from.line + lines.length, function(line) {
 
1897
        var len = lineLength(doc, line);
 
1898
        if (len > view.maxLineLength) {
 
1899
          view.maxLine = line;
 
1900
          view.maxLineLength = len;
 
1901
          view.maxLineChanged = true;
 
1902
          recomputeMaxLength = false;
 
1903
        }
 
1904
      });
 
1905
      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
 
1906
    }
 
1907
 
 
1908
    // Adjust frontier, schedule worker
 
1909
    view.frontier = Math.min(view.frontier, from.line);
 
1910
    startWorker(cm, 400);
 
1911
 
 
1912
    var lendiff = lines.length - nlines - 1;
 
1913
    // Remember that these lines changed, for updating the display
 
1914
    regChange(cm, from.line, to.line + 1, lendiff);
 
1915
    if (hasHandler(cm, "change")) {
 
1916
      // Normalize lines to contain only strings, since that's what
 
1917
      // the change event handler expects
 
1918
      for (var i = 0; i < lines.length; ++i)
 
1919
        if (typeof lines[i] != "string") lines[i] = lines[i].text;
 
1920
      var changeObj = {from: from, to: to, text: lines};
 
1921
      if (cm.curOp.textChanged) {
 
1922
        for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
 
1923
        cur.next = changeObj;
 
1924
      } else cm.curOp.textChanged = changeObj;
 
1925
    }
 
1926
 
 
1927
    // Update the selection
 
1928
    var newSelFrom, newSelTo, end = {line: from.line + lines.length - 1,
 
1929
                                     ch: hlText(lastHL).length  + (lines.length == 1 ? from.ch : 0)};
 
1930
    if (typeof selUpdate == "object" && selUpdate.line != null) {
 
1931
      newSelFrom = newSelTo = selUpdate;
 
1932
    } else if (selUpdate == "end") {
 
1933
      newSelFrom = newSelTo = end;
 
1934
    } else if (selUpdate == "start") {
 
1935
      newSelFrom = newSelTo = from;
 
1936
    } else if (selUpdate == "around") {
 
1937
      newSelFrom = from; newSelTo = end;
 
1938
    } else {
 
1939
      var adjustPos = function(pos) {
 
1940
        if (posLess(pos, from)) return pos;
 
1941
        if (!posLess(to, pos)) return end;
 
1942
        var line = pos.line + lendiff;
 
1943
        var ch = pos.ch;
 
1944
        if (pos.line == to.line)
 
1945
          ch += hlText(lastHL).length - (to.ch - (to.line == from.line ? from.ch : 0));
 
1946
        return {line: line, ch: ch};
 
1947
      };
 
1948
      newSelFrom = adjustPos(view.sel.from);
 
1949
      newSelTo = adjustPos(view.sel.to);
 
1950
    }
 
1951
    setSelection(cm, newSelFrom, newSelTo, null, true);
 
1952
    return end;
 
1953
  }
 
1954
 
 
1955
  function replaceRange(cm, code, from, to) {
 
1956
    if (!to) to = from;
 
1957
    if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
 
1958
    code = splitLines(code);
 
1959
    function adjustPos(pos) {
 
1960
      if (posLess(pos, from)) return pos;
 
1961
      if (!posLess(to, pos)) return end;
 
1962
      var line = pos.line + code.length - (to.line - from.line) - 1;
 
1963
      var ch = pos.ch;
 
1964
      if (pos.line == to.line)
 
1965
        ch += lst(code).length - (to.ch - (to.line == from.line ? from.ch : 0));
 
1966
      return {line: line, ch: ch};
 
1967
    }
 
1968
    return updateDoc(cm, from, to, code);
 
1969
  }
 
1970
 
 
1971
  // SELECTION
 
1972
 
 
1973
  function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
 
1974
  function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
 
1975
  function copyPos(x) {return {line: x.line, ch: x.ch};}
 
1976
 
 
1977
  function clipLine(doc, n) {return Math.max(0, Math.min(n, doc.size-1));}
 
1978
  function clipPos(doc, pos) {
 
1979
    if (pos.line < 0) return {line: 0, ch: 0};
 
1980
    if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc, doc.size-1).text.length};
 
1981
    var ch = pos.ch, linelen = getLine(doc, pos.line).text.length;
 
1982
    if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
 
1983
    else if (ch < 0) return {line: pos.line, ch: 0};
 
1984
    else return pos;
 
1985
  }
 
1986
  function isLine(doc, l) {return l >= 0 && l < doc.size;}
 
1987
 
 
1988
  function setShift(view, val) {
 
1989
    if (val) view.sel.shift = view.sel.shift || selHead(view);
 
1990
    else view.sel.shift = null;
 
1991
  }
 
1992
  function setSelectionUser(cm, from, to, bias) {
 
1993
    var view = cm.view, sh = view.sel.shift;
 
1994
    if (sh) {
 
1995
      sh = clipPos(view.doc, sh);
 
1996
      if (posLess(sh, from)) from = sh;
 
1997
      else if (posLess(to, sh)) to = sh;
 
1998
    }
 
1999
    setSelection(cm, from, to, bias);
 
2000
    cm.curOp.userSelChange = true;
 
2001
  }
 
2002
 
 
2003
  // Update the selection. Last two args are only used by
 
2004
  // updateDoc, since they have to be expressed in the line
 
2005
  // numbers before the update.
 
2006
  function setSelection(cm, from, to, bias, checkAtomic) {
 
2007
    cm.curOp.updateInput = true;
 
2008
    var sel = cm.view.sel, doc = cm.view.doc;
 
2009
    cm.view.goalColumn = null;
 
2010
    if (!checkAtomic && posEq(sel.from, from) && posEq(sel.to, to)) return;
 
2011
    if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
 
2012
 
 
2013
    // Skip over atomic spans.
 
2014
    if (checkAtomic || !posEq(from, sel.from))
 
2015
      from = skipAtomic(cm, from, bias, checkAtomic != "push");
 
2016
    if (checkAtomic || !posEq(to, sel.to))
 
2017
      to = skipAtomic(cm, to, bias, checkAtomic != "push");
 
2018
 
 
2019
    if (posEq(from, to)) sel.inverted = false;
 
2020
    else if (posEq(from, sel.to)) sel.inverted = false;
 
2021
    else if (posEq(to, sel.from)) sel.inverted = true;
 
2022
 
 
2023
    if (cm.options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
 
2024
      var head = selHead(cm.view);
 
2025
      if (head.line != sel.from.line && sel.from.line < doc.size) {
 
2026
        var oldLine = getLine(doc, sel.from.line);
 
2027
        if (/^\s+$/.test(oldLine.text))
 
2028
          setTimeout(operation(cm, function() {
 
2029
            if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
 
2030
              var no = lineNo(oldLine);
 
2031
              replaceRange(cm, "", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
 
2032
            }
 
2033
          }, 10));
 
2034
      }
 
2035
    }
 
2036
 
 
2037
    sel.from = from; sel.to = to;
 
2038
    cm.curOp.selectionChanged = true;
 
2039
  }
 
2040
 
 
2041
  function reCheckSelection(cm) {
 
2042
    setSelection(cm, cm.view.sel.from, cm.view.sel.to, null, "push");
 
2043
  }
 
2044
 
 
2045
  function skipAtomic(cm, pos, bias, mayClear) {
 
2046
    var doc = cm.view.doc, flipped = false, curPos = pos;
 
2047
    var dir = bias || 1;
 
2048
    cm.view.cantEdit = false;
 
2049
    search: for (;;) {
 
2050
      var line = getLine(doc, curPos.line), toClear;
 
2051
      if (line.markedSpans) {
 
2052
        for (var i = 0; i < line.markedSpans.length; ++i) {
 
2053
          var sp = line.markedSpans[i], m = sp.marker;
 
2054
          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
 
2055
              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
 
2056
            if (mayClear && m.clearOnEnter) {
 
2057
              (toClear || (toClear = [])).push(m);
 
2058
              continue;
 
2059
            } else if (!m.atomic) continue;
 
2060
            var newPos = m.find()[dir < 0 ? "from" : "to"];
 
2061
            if (posEq(newPos, curPos)) {
 
2062
              newPos.ch += dir;
 
2063
              if (newPos.ch < 0) {
 
2064
                if (newPos.line) newPos = clipPos(doc, {line: newPos.line - 1});
 
2065
                else newPos = null;
 
2066
              } else if (newPos.ch > line.text.length) {
 
2067
                if (newPos.line < doc.size - 1) newPos = {line: newPos.line + 1, ch: 0};
 
2068
                else newPos = null;
 
2069
              }
 
2070
              if (!newPos) {
 
2071
                if (flipped) {
 
2072
                  // Driven in a corner -- no valid cursor position found at all
 
2073
                  // -- try again *with* clearing, if we didn't already
 
2074
                  if (!mayClear) return skipAtomic(cm, pos, bias, true);
 
2075
                  // Otherwise, turn off editing until further notice, and return the start of the doc
 
2076
                  cm.view.cantEdit = true;
 
2077
                  return {line: 0, ch: 0};
 
2078
                }
 
2079
                flipped = true; newPos = pos; dir = -dir;
 
2080
              }
 
2081
            }
 
2082
            curPos = newPos;
 
2083
            continue search;
 
2084
          }
 
2085
        }
 
2086
        if (toClear) for (var i = 0; i < toClear.length; ++i) toClear[i].clear();
 
2087
      }
 
2088
      return curPos;
 
2089
    }
 
2090
  }
 
2091
 
 
2092
  // SCROLLING
 
2093
 
 
2094
  function scrollCursorIntoView(cm) {
 
2095
    var view = cm.view, coords = cursorCoords(cm, selHead(view));
 
2096
    scrollIntoView(cm.display, coords.left, coords.top, coords.left, coords.bottom);
 
2097
    if (!view.focused) return;
 
2098
    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
 
2099
    if (coords.top + box.top < 0) doScroll = true;
 
2100
    else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
 
2101
    if (doScroll != null && !phantom) {
 
2102
      var hidden = display.cursor.style.display == "none";
 
2103
      if (hidden) {
 
2104
        display.cursor.style.display = "";
 
2105
        display.cursor.style.left = coords.left + "px";
 
2106
        display.cursor.style.top = (coords.top - display.viewOffset) + "px";
 
2107
      }
 
2108
      display.cursor.scrollIntoView(doScroll);
 
2109
      if (hidden) display.cursor.style.display = "none";
 
2110
    }
 
2111
  }
 
2112
 
 
2113
  function scrollIntoView(display, x1, y1, x2, y2) {
 
2114
    var scrollPos = calculateScrollPos(display, x1, y1, x2, y2);
 
2115
    if (scrollPos.scrollLeft != null) {display.scrollbarH.scrollLeft = display.scroller.scrollLeft = scrollPos.scrollLeft;}
 
2116
    if (scrollPos.scrollTop != null) {display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos.scrollTop;}
 
2117
  }
 
2118
 
 
2119
  function calculateScrollPos(display, x1, y1, x2, y2) {
 
2120
    var pt = paddingTop(display);
 
2121
    y1 += pt; y2 += pt;
 
2122
    var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
 
2123
    var docBottom = display.scroller.scrollHeight - scrollerCutOff;
 
2124
    var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
 
2125
    if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
 
2126
    else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2 - screen);
 
2127
 
 
2128
    var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
 
2129
    x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
 
2130
    var gutterw = display.gutters.offsetWidth;
 
2131
    var atLeft = x1 < gutterw + 10;
 
2132
    if (x1 < screenleft + gutterw || atLeft) {
 
2133
      if (atLeft) x1 = 0;
 
2134
      result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
 
2135
    } else if (x2 > screenw + screenleft - 3) {
 
2136
      result.scrollLeft = x2 + 10 - screenw;
 
2137
    }
 
2138
    return result;
 
2139
  }
 
2140
 
 
2141
  // API UTILITIES
 
2142
 
 
2143
  function indentLine(cm, n, how) {
 
2144
    var doc = cm.view.doc;
 
2145
    if (!how) how = "add";
 
2146
    if (how == "smart") {
 
2147
      if (!cm.view.mode.indent) how = "prev";
 
2148
      else var state = getStateBefore(cm, n);
 
2149
    }
 
2150
 
 
2151
    var tabSize = cm.options.tabSize;
 
2152
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
 
2153
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
 
2154
    if (how == "smart") {
 
2155
      indentation = cm.view.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
 
2156
      if (indentation == Pass) how = "prev";
 
2157
    }
 
2158
    if (how == "prev") {
 
2159
      if (n) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
 
2160
      else indentation = 0;
 
2161
    }
 
2162
    else if (how == "add") indentation = curSpace + cm.options.indentUnit;
 
2163
    else if (how == "subtract") indentation = curSpace - cm.options.indentUnit;
 
2164
    indentation = Math.max(0, indentation);
 
2165
    var diff = indentation - curSpace;
 
2166
 
 
2167
    var indentString = "", pos = 0;
 
2168
    if (cm.options.indentWithTabs)
 
2169
      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
 
2170
    if (pos < indentation) indentString += spaceStr(indentation - pos);
 
2171
 
 
2172
    if (indentString != curSpaceString)
 
2173
      replaceRange(cm, indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
 
2174
    line.stateAfter = null;
 
2175
  }
 
2176
 
 
2177
  function changeLine(cm, handle, op) {
 
2178
    var no = handle, line = handle, doc = cm.view.doc;
 
2179
    if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
 
2180
    else no = lineNo(handle);
 
2181
    if (no == null) return null;
 
2182
    if (op(line, no)) regChange(cm, no, no + 1);
 
2183
    else return null;
 
2184
    return line;
 
2185
  }
 
2186
 
 
2187
  function findPosH(cm, dir, unit, visually) {
 
2188
    var doc = cm.view.doc, end = selHead(cm.view), line = end.line, ch = end.ch;
 
2189
    var lineObj = getLine(doc, line);
 
2190
    function findNextLine() {
 
2191
      var l = line + dir;
 
2192
      if (l < 0 || l == doc.size) return false;
 
2193
      line = l;
 
2194
      return lineObj = getLine(doc, l);
 
2195
    }
 
2196
    function moveOnce(boundToLine) {
 
2197
      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
 
2198
      if (next == null) {
 
2199
        if (!boundToLine && findNextLine()) {
 
2200
          if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
 
2201
          else ch = dir < 0 ? lineObj.text.length : 0;
 
2202
        } else return false;
 
2203
      } else ch = next;
 
2204
      return true;
 
2205
    }
 
2206
    if (unit == "char") moveOnce();
 
2207
    else if (unit == "column") moveOnce(true);
 
2208
    else if (unit == "word") {
 
2209
      var sawWord = false;
 
2210
      for (;;) {
 
2211
        if (dir < 0) if (!moveOnce()) break;
 
2212
        if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
 
2213
        else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
 
2214
        if (dir > 0) if (!moveOnce()) break;
 
2215
      }
 
2216
    }
 
2217
    return skipAtomic(cm, {line: line, ch: ch}, dir, true);
 
2218
  }
 
2219
 
 
2220
  function findWordAt(line, pos) {
 
2221
    var start = pos.ch, end = pos.ch;
 
2222
    if (line) {
 
2223
      if (pos.after === false || end == line.length) --start; else ++end;
 
2224
      var startChar = line.charAt(start);
 
2225
      var check = isWordChar(startChar) ? isWordChar :
 
2226
        /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} :
 
2227
      function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
 
2228
      while (start > 0 && check(line.charAt(start - 1))) --start;
 
2229
      while (end < line.length && check(line.charAt(end))) ++end;
 
2230
    }
 
2231
    return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}};
 
2232
  }
 
2233
 
 
2234
  function selectLine(cm, line) {
 
2235
    setSelectionUser(cm, {line: line, ch: 0}, clipPos(cm.view.doc, {line: line + 1, ch: 0}));
 
2236
  }
 
2237
 
 
2238
  // PROTOTYPE
 
2239
 
 
2240
  // The publicly visible API. Note that operation(null, f) means
 
2241
  // 'wrap f in an operation, performed on its `this` parameter'
 
2242
 
 
2243
  CodeMirror.prototype = {
 
2244
    getValue: function(lineSep) {
 
2245
      var text = [], doc = this.view.doc;
 
2246
      doc.iter(0, doc.size, function(line) { text.push(line.text); });
 
2247
      return text.join(lineSep || "\n");
 
2248
    },
 
2249
 
 
2250
    setValue: operation(null, function(code) {
 
2251
      var doc = this.view.doc, top = {line: 0, ch: 0}, lastLen = getLine(doc, doc.size-1).text.length;
 
2252
      updateDocInner(this, top, {line: doc.size - 1, ch: lastLen}, splitLines(code), top, top);
 
2253
    }),
 
2254
 
 
2255
    getSelection: function(lineSep) { return this.getRange(this.view.sel.from, this.view.sel.to, lineSep); },
 
2256
 
 
2257
    replaceSelection: operation(null, function(code, collapse) {
 
2258
      var sel = this.view.sel;
 
2259
      updateDoc(this, sel.from, sel.to, splitLines(code), collapse || "around");
 
2260
    }),
 
2261
 
 
2262
    focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
 
2263
 
 
2264
    setOption: function(option, value) {
 
2265
      var options = this.options, old = options[option];
 
2266
      if (options[option] == value && option != "mode") return;
 
2267
      options[option] = value;
 
2268
      if (optionHandlers.hasOwnProperty(option))
 
2269
        operation(this, optionHandlers[option])(this, value, old);
 
2270
    },
 
2271
 
 
2272
    getOption: function(option) {return this.options[option];},
 
2273
 
 
2274
    getMode: function() {return this.view.mode;},
 
2275
 
 
2276
    undo: operation(null, function() {
 
2277
      var hist = this.view.history;
 
2278
      unredoHelper(this, hist.done, hist.undone, -1);
 
2279
    }),
 
2280
    redo: operation(null, function() {
 
2281
      var hist = this.view.history;
 
2282
      unredoHelper(this, hist.undone, hist.done, 1);
 
2283
    }),
 
2284
 
 
2285
    indentLine: operation(null, function(n, dir) {
 
2286
      if (typeof dir != "string") {
 
2287
        if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
 
2288
        else dir = dir ? "add" : "subtract";
 
2289
      }
 
2290
      if (isLine(this.view.doc, n)) indentLine(this, n, dir);
 
2291
    }),
 
2292
 
 
2293
    indentSelection: operation(null, function(how) {
 
2294
      var sel = this.view.sel;
 
2295
      if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
 
2296
      var e = sel.to.line - (sel.to.ch ? 0 : 1);
 
2297
      for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
 
2298
    }),
 
2299
 
 
2300
    historySize: function() {
 
2301
      var hist = this.view.history;
 
2302
      return {undo: hist.done.length, redo: hist.undone.length};
 
2303
    },
 
2304
 
 
2305
    clearHistory: function() {this.view.history = makeHistory();},
 
2306
 
 
2307
    markClean: function() {
 
2308
      this.view.history.dirtyCounter = 0;
 
2309
      this.view.history.closed = true;
 
2310
    },
 
2311
 
 
2312
    isClean: function () {return this.view.history.dirtyCounter == 0;},
 
2313
      
 
2314
    getHistory: function() {
 
2315
      var hist = this.view.history;
 
2316
      function cp(arr) {
 
2317
        for (var i = 0, nw = [], nwelt; i < arr.length; ++i) {
 
2318
          nw.push(nwelt = []);
 
2319
          for (var j = 0, elt = arr[i]; j < elt.length; ++j) {
 
2320
            var old = [], cur = elt[j];
 
2321
            nwelt.push({start: cur.start, added: cur.added, old: old});
 
2322
            for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k]));
 
2323
          }
 
2324
        }
 
2325
        return nw;
 
2326
      }
 
2327
      return {done: cp(hist.done), undone: cp(hist.undone)};
 
2328
    },
 
2329
 
 
2330
    setHistory: function(histData) {
 
2331
      var hist = this.view.history = makeHistory();
 
2332
      hist.done = histData.done;
 
2333
      hist.undone = histData.undone;
 
2334
    },
 
2335
 
 
2336
    getTokenAt: function(pos) {
 
2337
      var doc = this.view.doc;
 
2338
      pos = clipPos(doc, pos);
 
2339
      return getTokenAt(this, getLine(doc, pos.line), getStateBefore(this, pos.line), pos.ch);
 
2340
    },
 
2341
 
 
2342
    getStateAfter: function(line) {
 
2343
      var doc = this.view.doc;
 
2344
      line = clipLine(doc, line == null ? doc.size - 1: line);
 
2345
      return getStateBefore(this, line + 1);
 
2346
    },
 
2347
 
 
2348
    cursorCoords: function(start, mode) {
 
2349
      var pos, sel = this.view.sel;
 
2350
      if (start == null) start = sel.inverted;
 
2351
      if (typeof start == "object") pos = clipPos(this.view.doc, start);
 
2352
      else pos = start ? sel.from : sel.to;
 
2353
      return cursorCoords(this, pos, mode || "page");
 
2354
    },
 
2355
 
 
2356
    charCoords: function(pos, mode) {
 
2357
      return charCoords(this, clipPos(this.view.doc, pos), mode || "page");
 
2358
    },
 
2359
 
 
2360
    coordsChar: function(coords) {
 
2361
      var off = this.display.lineSpace.getBoundingClientRect();
 
2362
      return coordsChar(this, coords.left - off.left, coords.top - off.top);
 
2363
    },
 
2364
 
 
2365
    defaultTextHeight: function() { return textHeight(this.display); },
 
2366
 
 
2367
    markText: operation(null, function(from, to, options) {
 
2368
      return markText(this, clipPos(this.view.doc, from), clipPos(this.view.doc, to),
 
2369
                      options, "range");
 
2370
    }),
 
2371
 
 
2372
    setBookmark: operation(null, function(pos, widget) {
 
2373
      pos = clipPos(this.view.doc, pos);
 
2374
      return markText(this, pos, pos, widget ? {replacedWith: widget} : {}, "bookmark");
 
2375
    }),
 
2376
 
 
2377
    findMarksAt: function(pos) {
 
2378
      var doc = this.view.doc;
 
2379
      pos = clipPos(doc, pos);
 
2380
      var markers = [], spans = getLine(doc, pos.line).markedSpans;
 
2381
      if (spans) for (var i = 0; i < spans.length; ++i) {
 
2382
        var span = spans[i];
 
2383
        if ((span.from == null || span.from <= pos.ch) &&
 
2384
            (span.to == null || span.to >= pos.ch))
 
2385
          markers.push(span.marker);
 
2386
      }
 
2387
      return markers;
 
2388
    },
 
2389
 
 
2390
    setGutterMarker: operation(null, function(line, gutterID, value) {
 
2391
      return changeLine(this, line, function(line) {
 
2392
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
 
2393
        markers[gutterID] = value;
 
2394
        if (!value && isEmpty(markers)) line.gutterMarkers = null;
 
2395
        return true;
 
2396
      });
 
2397
    }),
 
2398
 
 
2399
    clearGutter: operation(null, function(gutterID) {
 
2400
      var i = 0, cm = this, doc = cm.view.doc;
 
2401
      doc.iter(0, doc.size, function(line) {
 
2402
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
 
2403
          line.gutterMarkers[gutterID] = null;
 
2404
          regChange(cm, i, i + 1);
 
2405
          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
 
2406
        }
 
2407
        ++i;
 
2408
      });
 
2409
    }),
 
2410
 
 
2411
    addLineClass: operation(null, function(handle, where, cls) {
 
2412
      return changeLine(this, handle, function(line) {
 
2413
        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
 
2414
        if (!line[prop]) line[prop] = cls;
 
2415
        else if (new RegExp("\\b" + cls + "\\b").test(line[prop])) return false;
 
2416
        else line[prop] += " " + cls;
 
2417
        return true;
 
2418
      });
 
2419
    }),
 
2420
 
 
2421
    removeLineClass: operation(null, function(handle, where, cls) {
 
2422
      return changeLine(this, handle, function(line) {
 
2423
        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
 
2424
        var cur = line[prop];
 
2425
        if (!cur) return false;
 
2426
        else if (cls == null) line[prop] = null;
 
2427
        else {
 
2428
          var upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), "");
 
2429
          if (upd == cur) return false;
 
2430
          line[prop] = upd || null;
 
2431
        }
 
2432
        return true;
 
2433
      });
 
2434
    }),
 
2435
 
 
2436
    addLineWidget: operation(null, function addLineWidget(handle, node, options) {
 
2437
      var widget = options || {};
 
2438
      widget.node = node;
 
2439
      if (widget.noHScroll) this.display.alignWidgets = true;
 
2440
      changeLine(this, handle, function(line) {
 
2441
        (line.widgets || (line.widgets = [])).push(widget);
 
2442
        widget.line = line;
 
2443
        return true;
 
2444
      });
 
2445
      return widget;
 
2446
    }),
 
2447
 
 
2448
    removeLineWidget: operation(null, function(widget) {
 
2449
      var ws = widget.line.widgets, no = lineNo(widget.line);
 
2450
      if (no == null) return;
 
2451
      for (var i = 0; i < ws.length; ++i) if (ws[i] == widget) ws.splice(i--, 1);
 
2452
      regChange(this, no, no + 1);
 
2453
    }),
 
2454
 
 
2455
    lineInfo: function(line) {
 
2456
      if (typeof line == "number") {
 
2457
        if (!isLine(this.view.doc, line)) return null;
 
2458
        var n = line;
 
2459
        line = getLine(this.view.doc, line);
 
2460
        if (!line) return null;
 
2461
      } else {
 
2462
        var n = lineNo(line);
 
2463
        if (n == null) return null;
 
2464
      }
 
2465
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
 
2466
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
 
2467
              widgets: line.widgets};
 
2468
    },
 
2469
 
 
2470
    getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
 
2471
 
 
2472
    addWidget: function(pos, node, scroll, vert, horiz) {
 
2473
      var display = this.display;
 
2474
      pos = cursorCoords(this, clipPos(this.view.doc, pos));
 
2475
      var top = pos.top, left = pos.left;
 
2476
      node.style.position = "absolute";
 
2477
      display.sizer.appendChild(node);
 
2478
      if (vert == "over") top = pos.top;
 
2479
      else if (vert == "near") {
 
2480
        var vspace = Math.max(display.wrapper.clientHeight, this.view.doc.height),
 
2481
        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
 
2482
        if (pos.bottom + node.offsetHeight > vspace && pos.top > node.offsetHeight)
 
2483
          top = pos.top - node.offsetHeight;
 
2484
        if (left + node.offsetWidth > hspace)
 
2485
          left = hspace - node.offsetWidth;
 
2486
      }
 
2487
      node.style.top = (top + paddingTop(display)) + "px";
 
2488
      node.style.left = node.style.right = "";
 
2489
      if (horiz == "right") {
 
2490
        left = display.sizer.clientWidth - node.offsetWidth;
 
2491
        node.style.right = "0px";
 
2492
      } else {
 
2493
        if (horiz == "left") left = 0;
 
2494
        else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
 
2495
        node.style.left = left + "px";
 
2496
      }
 
2497
      if (scroll)
 
2498
        scrollIntoView(display, left, top, left + node.offsetWidth, top + node.offsetHeight);
 
2499
    },
 
2500
 
 
2501
    lineCount: function() {return this.view.doc.size;},
 
2502
 
 
2503
    clipPos: function(pos) {return clipPos(this.view.doc, pos);},
 
2504
 
 
2505
    getCursor: function(start) {
 
2506
      var sel = this.view.sel;
 
2507
      if (start == null) start = sel.inverted;
 
2508
      return copyPos(start ? sel.from : sel.to);
 
2509
    },
 
2510
 
 
2511
    somethingSelected: function() {return !posEq(this.view.sel.from, this.view.sel.to);},
 
2512
 
 
2513
    setCursor: operation(null, function(line, ch, user) {
 
2514
      var pos = typeof line == "number" ? {line: line, ch: ch || 0} : line;
 
2515
      (user ? setSelectionUser : setSelection)(this, pos, pos);
 
2516
    }),
 
2517
 
 
2518
    setSelection: operation(null, function(from, to, user) {
 
2519
      var doc = this.view.doc;
 
2520
      (user ? setSelectionUser : setSelection)(this, clipPos(doc, from), clipPos(doc, to || from));
 
2521
    }),
 
2522
 
 
2523
    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
 
2524
 
 
2525
    getLineHandle: function(line) {
 
2526
      var doc = this.view.doc;
 
2527
      if (isLine(doc, line)) return getLine(doc, line);
 
2528
    },
 
2529
 
 
2530
    getLineNumber: function(line) {return lineNo(line);},
 
2531
 
 
2532
    setLine: operation(null, function(line, text) {
 
2533
      if (isLine(this.view.doc, line))
 
2534
        replaceRange(this, text, {line: line, ch: 0}, {line: line, ch: getLine(this.view.doc, line).text.length});
 
2535
    }),
 
2536
 
 
2537
    removeLine: operation(null, function(line) {
 
2538
      if (isLine(this.view.doc, line))
 
2539
        replaceRange(this, "", {line: line, ch: 0}, clipPos(this.view.doc, {line: line+1, ch: 0}));
 
2540
    }),
 
2541
 
 
2542
    replaceRange: operation(null, function(code, from, to) {
 
2543
      var doc = this.view.doc;
 
2544
      from = clipPos(doc, from);
 
2545
      to = to ? clipPos(doc, to) : from;
 
2546
      return replaceRange(this, code, from, to);
 
2547
    }),
 
2548
 
 
2549
    getRange: function(from, to, lineSep) {
 
2550
      var doc = this.view.doc;
 
2551
      from = clipPos(doc, from); to = clipPos(doc, to);
 
2552
      var l1 = from.line, l2 = to.line;
 
2553
      if (l1 == l2) return getLine(doc, l1).text.slice(from.ch, to.ch);
 
2554
      var code = [getLine(doc, l1).text.slice(from.ch)];
 
2555
      doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
 
2556
      code.push(getLine(doc, l2).text.slice(0, to.ch));
 
2557
      return code.join(lineSep || "\n");
 
2558
    },
 
2559
 
 
2560
    triggerOnKeyDown: operation(null, onKeyDown),
 
2561
 
 
2562
    execCommand: function(cmd) {return commands[cmd](this);},
 
2563
 
 
2564
    // Stuff used by commands, probably not much use to outside code.
 
2565
    moveH: operation(null, function(dir, unit) {
 
2566
      var sel = this.view.sel, pos = dir < 0 ? sel.from : sel.to;
 
2567
      if (sel.shift || posEq(sel.from, sel.to)) pos = findPosH(this, dir, unit, true);
 
2568
      setSelectionUser(this, pos, pos, dir);
 
2569
    }),
 
2570
 
 
2571
    deleteH: operation(null, function(dir, unit) {
 
2572
      var sel = this.view.sel;
 
2573
      if (!posEq(sel.from, sel.to)) replaceRange(this, "", sel.from, sel.to);
 
2574
      else replaceRange(this, "", sel.from, findPosH(this, dir, unit, false));
 
2575
      this.curOp.userSelChange = true;
 
2576
    }),
 
2577
 
 
2578
    moveV: operation(null, function(dir, unit) {
 
2579
      var view = this.view, doc = view.doc, display = this.display;
 
2580
      var dist = 0, cur = selHead(view), pos = cursorCoords(this, cur, "div");
 
2581
      var x = pos.left, y;
 
2582
      if (view.goalColumn != null) x = view.goalColumn;
 
2583
      if (unit == "page") {
 
2584
        var pageSize = Math.min(display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
 
2585
        y = pos.top + dir * pageSize;
 
2586
      } else if (unit == "line") {
 
2587
        y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
 
2588
      }
 
2589
      do {
 
2590
        var target = coordsChar(this, x, y);
 
2591
        y += dir * 5;
 
2592
      } while (target.outside && (dir < 0 ? y > 0 : y < doc.height));
 
2593
 
 
2594
      if (unit == "page") display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top;
 
2595
      setSelectionUser(this, target, target, dir);
 
2596
      view.goalColumn = x;
 
2597
    }),
 
2598
 
 
2599
    toggleOverwrite: function() {
 
2600
      if (this.view.overwrite = !this.view.overwrite)
 
2601
        this.display.cursor.className += " CodeMirror-overwrite";
 
2602
      else
 
2603
        this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
 
2604
    },
 
2605
 
 
2606
    posFromIndex: function(off) {
 
2607
      var lineNo = 0, ch, doc = this.view.doc;
 
2608
      doc.iter(0, doc.size, function(line) {
 
2609
        var sz = line.text.length + 1;
 
2610
        if (sz > off) { ch = off; return true; }
 
2611
        off -= sz;
 
2612
        ++lineNo;
 
2613
      });
 
2614
      return clipPos(doc, {line: lineNo, ch: ch});
 
2615
    },
 
2616
    indexFromPos: function (coords) {
 
2617
      if (coords.line < 0 || coords.ch < 0) return 0;
 
2618
      var index = coords.ch;
 
2619
      this.view.doc.iter(0, coords.line, function (line) {
 
2620
        index += line.text.length + 1;
 
2621
      });
 
2622
      return index;
 
2623
    },
 
2624
 
 
2625
    scrollTo: function(x, y) {
 
2626
      if (x != null) this.display.scrollbarH.scrollLeft = this.display.scroller.scrollLeft = x;
 
2627
      if (y != null) this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = y;
 
2628
      updateDisplay(this, []);
 
2629
    },
 
2630
    getScrollInfo: function() {
 
2631
      var scroller = this.display.scroller, co = scrollerCutOff;
 
2632
      return {left: scroller.scrollLeft, top: scroller.scrollTop,
 
2633
              height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
 
2634
              clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
 
2635
    },
 
2636
 
 
2637
    scrollIntoView: function(pos) {
 
2638
      pos = pos ? clipPos(this.view.doc, pos) : selHead(this.view);
 
2639
      var coords = cursorCoords(this, pos);
 
2640
      scrollIntoView(this.display, coords.left, coords.top, coords.left, coords.bottom);
 
2641
    },
 
2642
 
 
2643
    setSize: function(width, height) {
 
2644
      function interpret(val) {
 
2645
        return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
 
2646
      }
 
2647
      if (width != null) this.display.wrapper.style.width = interpret(width);
 
2648
      if (height != null) this.display.wrapper.style.height = interpret(height);
 
2649
      this.refresh();
 
2650
    },
 
2651
 
 
2652
    on: function(type, f) {on(this, type, f);},
 
2653
    off: function(type, f) {off(this, type, f);},
 
2654
 
 
2655
    operation: function(f){return operation(this, f)();},
 
2656
    compoundChange: function(f){return compoundChange(this, f);},
 
2657
 
 
2658
    refresh: function(){
 
2659
      updateDisplay(this, true, this.view.scrollTop);
 
2660
      if (this.display.scrollbarV.scrollHeight > this.view.scrollTop)
 
2661
        this.display.scrollbarV.scrollTop = this.view.scrollTop;
 
2662
    },
 
2663
 
 
2664
    getInputField: function(){return this.display.input;},
 
2665
    getWrapperElement: function(){return this.display.wrapper;},
 
2666
    getScrollerElement: function(){return this.display.scroller;},
 
2667
    getGutterElement: function(){return this.display.gutters;}
 
2668
  };
 
2669
 
 
2670
  // OPTION DEFAULTS
 
2671
 
 
2672
  var optionHandlers = CodeMirror.optionHandlers = {};
 
2673
 
 
2674
  // The default configuration options.
 
2675
  var defaults = CodeMirror.defaults = {};
 
2676
 
 
2677
  function option(name, deflt, handle, notOnInit) {
 
2678
    CodeMirror.defaults[name] = deflt;
 
2679
    if (handle) optionHandlers[name] =
 
2680
      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
 
2681
  }
 
2682
 
 
2683
  var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
 
2684
 
 
2685
  // These two are, on init, called from the constructor because they
 
2686
  // have to be initialized before the editor can start at all.
 
2687
  option("value", "", function(cm, val) {cm.setValue(val);}, true);
 
2688
  option("mode", null, loadMode, true);
 
2689
 
 
2690
  option("indentUnit", 2, loadMode, true);
 
2691
  option("indentWithTabs", false);
 
2692
  option("smartIndent", true);
 
2693
  option("tabSize", 4, function(cm) {loadMode(cm); updateDisplay(cm, true);}, true);
 
2694
  option("electricChars", true);
 
2695
  option("autoClearEmptyLines", false);
 
2696
 
 
2697
  option("theme", "default", function(cm, val, old) {
 
2698
    themeChanged(cm);
 
2699
    if (old != Init) guttersChanged(cm);
 
2700
  });
 
2701
  option("keyMap", "default", keyMapChanged);
 
2702
  option("extraKeys", null);
 
2703
 
 
2704
  option("onKeyEvent", null);
 
2705
  option("onDragEvent", null);
 
2706
 
 
2707
  option("lineWrapping", false, wrappingChanged);
 
2708
  option("gutters", [], function(cm) {
 
2709
    setGuttersForLineNumbers(cm.options);
 
2710
    guttersChanged(cm);
 
2711
  }, true);
 
2712
  option("lineNumbers", false, function(cm) {
 
2713
    setGuttersForLineNumbers(cm.options);
 
2714
    guttersChanged(cm);
 
2715
  }, true);
 
2716
  option("firstLineNumber", 1, guttersChanged, false);
 
2717
  option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, false);
 
2718
  
 
2719
  option("readOnly", false, function(cm, val) {
 
2720
    if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
 
2721
    else if (!val) resetInput(cm, true);
 
2722
  });
 
2723
  option("dragDrop", true);
 
2724
 
 
2725
  option("cursorBlinkRate", 530);
 
2726
  option("cursorHeight", 1);
 
2727
  option("workTime", 100);
 
2728
  option("workDelay", 100);
 
2729
  option("flattenSpans", true);
 
2730
  option("pollInterval", 100);
 
2731
  option("undoDepth", 40);
 
2732
  option("viewportMargin", 10, function(cm){cm.refresh();}, true);
 
2733
 
 
2734
  option("tabindex", null, function(cm, val) {
 
2735
    cm.display.input.tabIndex = val || "";
 
2736
  });
 
2737
  option("autofocus", null);
 
2738
 
 
2739
  // MODE DEFINITION AND QUERYING
 
2740
 
 
2741
  // Known modes, by name and by MIME
 
2742
  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
 
2743
 
 
2744
  CodeMirror.defineMode = function(name, mode) {
 
2745
    if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
 
2746
    if (arguments.length > 2) {
 
2747
      mode.dependencies = [];
 
2748
      for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
 
2749
    }
 
2750
    modes[name] = mode;
 
2751
  };
 
2752
 
 
2753
  CodeMirror.defineMIME = function(mime, spec) {
 
2754
    mimeModes[mime] = spec;
 
2755
  };
 
2756
 
 
2757
  CodeMirror.resolveMode = function(spec) {
 
2758
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
 
2759
      spec = mimeModes[spec];
 
2760
    else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
 
2761
      return CodeMirror.resolveMode("application/xml");
 
2762
    if (typeof spec == "string") return {name: spec};
 
2763
    else return spec || {name: "null"};
 
2764
  };
 
2765
 
 
2766
  CodeMirror.getMode = function(options, spec) {
 
2767
    var spec = CodeMirror.resolveMode(spec);
 
2768
    var mfactory = modes[spec.name];
 
2769
    if (!mfactory) return CodeMirror.getMode(options, "text/plain");
 
2770
    var modeObj = mfactory(options, spec);
 
2771
    if (modeExtensions.hasOwnProperty(spec.name)) {
 
2772
      var exts = modeExtensions[spec.name];
 
2773
      for (var prop in exts) if (exts.hasOwnProperty(prop)) modeObj[prop] = exts[prop];
 
2774
    }
 
2775
    modeObj.name = spec.name;
 
2776
    return modeObj;
 
2777
  };
 
2778
 
 
2779
  CodeMirror.defineMode("null", function() {
 
2780
    return {token: function(stream) {stream.skipToEnd();}};
 
2781
  });
 
2782
  CodeMirror.defineMIME("text/plain", "null");
 
2783
 
 
2784
  var modeExtensions = CodeMirror.modeExtensions = {};
 
2785
  CodeMirror.extendMode = function(mode, properties) {
 
2786
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
 
2787
    for (var prop in properties) if (properties.hasOwnProperty(prop))
 
2788
      exts[prop] = properties[prop];
 
2789
  };
 
2790
 
 
2791
  // EXTENSIONS
 
2792
 
 
2793
  CodeMirror.defineExtension = function(name, func) {
 
2794
    CodeMirror.prototype[name] = func;
 
2795
  };
 
2796
 
 
2797
  CodeMirror.defineOption = option;
 
2798
 
 
2799
  var initHooks = [];
 
2800
  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
 
2801
 
 
2802
  // MODE STATE HANDLING
 
2803
 
 
2804
  // Utility functions for working with state. Exported because modes
 
2805
  // sometimes need to do this.
 
2806
  function copyState(mode, state) {
 
2807
    if (state === true) return state;
 
2808
    if (mode.copyState) return mode.copyState(state);
 
2809
    var nstate = {};
 
2810
    for (var n in state) {
 
2811
      var val = state[n];
 
2812
      if (val instanceof Array) val = val.concat([]);
 
2813
      nstate[n] = val;
 
2814
    }
 
2815
    return nstate;
 
2816
  }
 
2817
  CodeMirror.copyState = copyState;
 
2818
 
 
2819
  function startState(mode, a1, a2) {
 
2820
    return mode.startState ? mode.startState(a1, a2) : true;
 
2821
  }
 
2822
  CodeMirror.startState = startState;
 
2823
 
 
2824
  CodeMirror.innerMode = function(mode, state) {
 
2825
    while (mode.innerMode) {
 
2826
      var info = mode.innerMode(state);
 
2827
      state = info.state;
 
2828
      mode = info.mode;
 
2829
    }
 
2830
    return info || {mode: mode, state: state};
 
2831
  };
 
2832
 
 
2833
  // STANDARD COMMANDS
 
2834
 
 
2835
  var commands = CodeMirror.commands = {
 
2836
    selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
 
2837
    killLine: function(cm) {
 
2838
      var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
 
2839
      if (!sel && cm.getLine(from.line).length == from.ch)
 
2840
        cm.replaceRange("", from, {line: from.line + 1, ch: 0});
 
2841
      else cm.replaceRange("", from, sel ? to : {line: from.line});
 
2842
    },
 
2843
    deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});},
 
2844
    undo: function(cm) {cm.undo();},
 
2845
    redo: function(cm) {cm.redo();},
 
2846
    goDocStart: function(cm) {cm.setCursor(0, 0, true);},
 
2847
    goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);},
 
2848
    goLineStart: function(cm) {
 
2849
      cm.setCursor(lineStart(cm, cm.getCursor().line), null, true);
 
2850
    },
 
2851
    goLineStartSmart: function(cm) {
 
2852
      var cur = cm.getCursor(), start = lineStart(cm, cur.line);
 
2853
      var line = cm.getLineHandle(start.line);
 
2854
      var order = getOrder(line);
 
2855
      if (!order || order[0].level == 0) {
 
2856
        var firstNonWS = Math.max(0, line.text.search(/\S/));
 
2857
        var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
 
2858
        cm.setCursor(start.line, inWS ? 0 : firstNonWS, true);
 
2859
      } else cm.setCursor(start, null, true);
 
2860
    },
 
2861
    goLineEnd: function(cm) {
 
2862
      cm.setCursor(lineEnd(cm, cm.getCursor().line), null, true);
 
2863
    },
 
2864
    goLineUp: function(cm) {cm.moveV(-1, "line");},
 
2865
    goLineDown: function(cm) {cm.moveV(1, "line");},
 
2866
    goPageUp: function(cm) {cm.moveV(-1, "page");},
 
2867
    goPageDown: function(cm) {cm.moveV(1, "page");},
 
2868
    goCharLeft: function(cm) {cm.moveH(-1, "char");},
 
2869
    goCharRight: function(cm) {cm.moveH(1, "char");},
 
2870
    goColumnLeft: function(cm) {cm.moveH(-1, "column");},
 
2871
    goColumnRight: function(cm) {cm.moveH(1, "column");},
 
2872
    goWordLeft: function(cm) {cm.moveH(-1, "word");},
 
2873
    goWordRight: function(cm) {cm.moveH(1, "word");},
 
2874
    delCharBefore: function(cm) {cm.deleteH(-1, "char");},
 
2875
    delCharAfter: function(cm) {cm.deleteH(1, "char");},
 
2876
    delWordBefore: function(cm) {cm.deleteH(-1, "word");},
 
2877
    delWordAfter: function(cm) {cm.deleteH(1, "word");},
 
2878
    indentAuto: function(cm) {cm.indentSelection("smart");},
 
2879
    indentMore: function(cm) {cm.indentSelection("add");},
 
2880
    indentLess: function(cm) {cm.indentSelection("subtract");},
 
2881
    insertTab: function(cm) {cm.replaceSelection("\t", "end");},
 
2882
    defaultTab: function(cm) {
 
2883
      if (cm.somethingSelected()) cm.indentSelection("add");
 
2884
      else cm.replaceSelection("\t", "end");
 
2885
    },
 
2886
    transposeChars: function(cm) {
 
2887
      var cur = cm.getCursor(), line = cm.getLine(cur.line);
 
2888
      if (cur.ch > 0 && cur.ch < line.length - 1)
 
2889
        cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
 
2890
                        {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
 
2891
    },
 
2892
    newlineAndIndent: function(cm) {
 
2893
      cm.replaceSelection("\n", "end");
 
2894
      cm.indentLine(cm.getCursor().line);
 
2895
    },
 
2896
    toggleOverwrite: function(cm) {cm.toggleOverwrite();}
 
2897
  };
 
2898
 
 
2899
  // STANDARD KEYMAPS
 
2900
 
 
2901
  var keyMap = CodeMirror.keyMap = {};
 
2902
  keyMap.basic = {
 
2903
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
 
2904
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
 
2905
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
 
2906
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
 
2907
  };
 
2908
  // Note that the save and find-related commands aren't defined by
 
2909
  // default. Unknown commands are simply ignored.
 
2910
  keyMap.pcDefault = {
 
2911
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
 
2912
    "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
 
2913
    "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
 
2914
    "Ctrl-Backspace": "delWordBefore", "Ctrl-Delete": "delWordAfter", "Ctrl-S": "save", "Ctrl-F": "find",
 
2915
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
 
2916
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
 
2917
    fallthrough: "basic"
 
2918
  };
 
2919
  keyMap.macDefault = {
 
2920
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
 
2921
    "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
 
2922
    "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordBefore",
 
2923
    "Ctrl-Alt-Backspace": "delWordAfter", "Alt-Delete": "delWordAfter", "Cmd-S": "save", "Cmd-F": "find",
 
2924
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
 
2925
    "Cmd-[": "indentLess", "Cmd-]": "indentMore",
 
2926
    fallthrough: ["basic", "emacsy"]
 
2927
  };
 
2928
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
 
2929
  keyMap.emacsy = {
 
2930
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
 
2931
    "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
 
2932
    "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
 
2933
    "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
 
2934
  };
 
2935
 
 
2936
  // KEYMAP DISPATCH
 
2937
 
 
2938
  function getKeyMap(val) {
 
2939
    if (typeof val == "string") return keyMap[val];
 
2940
    else return val;
 
2941
  }
 
2942
 
 
2943
  function lookupKey(name, extraMap, map, handle, stop) {
 
2944
    function lookup(map) {
 
2945
      map = getKeyMap(map);
 
2946
      var found = map[name];
 
2947
      if (found === false) {
 
2948
        if (stop) stop();
 
2949
        return true;
 
2950
      }
 
2951
      if (found != null && handle(found)) return true;
 
2952
      if (map.nofallthrough) {
 
2953
        if (stop) stop();
 
2954
        return true;
 
2955
      }
 
2956
      var fallthrough = map.fallthrough;
 
2957
      if (fallthrough == null) return false;
 
2958
      if (Object.prototype.toString.call(fallthrough) != "[object Array]")
 
2959
        return lookup(fallthrough);
 
2960
      for (var i = 0, e = fallthrough.length; i < e; ++i) {
 
2961
        if (lookup(fallthrough[i])) return true;
 
2962
      }
 
2963
      return false;
 
2964
    }
 
2965
    if (extraMap && lookup(extraMap)) return true;
 
2966
    return lookup(map);
 
2967
  }
 
2968
  function isModifierKey(event) {
 
2969
    var name = keyNames[e_prop(event, "keyCode")];
 
2970
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
 
2971
  }
 
2972
  CodeMirror.isModifierKey = isModifierKey;
 
2973
 
 
2974
  // FROMTEXTAREA
 
2975
 
 
2976
  CodeMirror.fromTextArea = function(textarea, options) {
 
2977
    if (!options) options = {};
 
2978
    options.value = textarea.value;
 
2979
    if (!options.tabindex && textarea.tabindex)
 
2980
      options.tabindex = textarea.tabindex;
 
2981
    // Set autofocus to true if this textarea is focused, or if it has
 
2982
    // autofocus and no other element is focused.
 
2983
    if (options.autofocus == null) {
 
2984
      var hasFocus = document.body;
 
2985
      // doc.activeElement occasionally throws on IE
 
2986
      try { hasFocus = document.activeElement; } catch(e) {}
 
2987
      options.autofocus = hasFocus == textarea ||
 
2988
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
 
2989
    }
 
2990
 
 
2991
    function save() {textarea.value = cm.getValue();}
 
2992
    if (textarea.form) {
 
2993
      // Deplorable hack to make the submit method do the right thing.
 
2994
      on(textarea.form, "submit", save);
 
2995
      if (typeof textarea.form.submit == "function") {
 
2996
        var realSubmit = textarea.form.submit;
 
2997
        textarea.form.submit = function wrappedSubmit() {
 
2998
          save();
 
2999
          textarea.form.submit = realSubmit;
 
3000
          textarea.form.submit();
 
3001
          textarea.form.submit = wrappedSubmit;
 
3002
        };
 
3003
      }
 
3004
    }
 
3005
 
 
3006
    textarea.style.display = "none";
 
3007
    var cm = CodeMirror(function(node) {
 
3008
      textarea.parentNode.insertBefore(node, textarea.nextSibling);
 
3009
    }, options);
 
3010
    cm.save = save;
 
3011
    cm.getTextArea = function() { return textarea; };
 
3012
    cm.toTextArea = function() {
 
3013
      save();
 
3014
      textarea.parentNode.removeChild(cm.getWrapperElement());
 
3015
      textarea.style.display = "";
 
3016
      if (textarea.form) {
 
3017
        off(textarea.form, "submit", save);
 
3018
        if (typeof textarea.form.submit == "function")
 
3019
          textarea.form.submit = realSubmit;
 
3020
      }
 
3021
    };
 
3022
    return cm;
 
3023
  };
 
3024
 
 
3025
  // STRING STREAM
 
3026
 
 
3027
  // Fed to the mode parsers, provides helper functions to make
 
3028
  // parsers more succinct.
 
3029
 
 
3030
  // The character stream used by a mode's parser.
 
3031
  function StringStream(string, tabSize) {
 
3032
    this.pos = this.start = 0;
 
3033
    this.string = string;
 
3034
    this.tabSize = tabSize || 8;
 
3035
  }
 
3036
 
 
3037
  StringStream.prototype = {
 
3038
    eol: function() {return this.pos >= this.string.length;},
 
3039
    sol: function() {return this.pos == 0;},
 
3040
    peek: function() {return this.string.charAt(this.pos) || undefined;},
 
3041
    next: function() {
 
3042
      if (this.pos < this.string.length)
 
3043
        return this.string.charAt(this.pos++);
 
3044
    },
 
3045
    eat: function(match) {
 
3046
      var ch = this.string.charAt(this.pos);
 
3047
      if (typeof match == "string") var ok = ch == match;
 
3048
      else var ok = ch && (match.test ? match.test(ch) : match(ch));
 
3049
      if (ok) {++this.pos; return ch;}
 
3050
    },
 
3051
    eatWhile: function(match) {
 
3052
      var start = this.pos;
 
3053
      while (this.eat(match)){}
 
3054
      return this.pos > start;
 
3055
    },
 
3056
    eatSpace: function() {
 
3057
      var start = this.pos;
 
3058
      while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
 
3059
      return this.pos > start;
 
3060
    },
 
3061
    skipToEnd: function() {this.pos = this.string.length;},
 
3062
    skipTo: function(ch) {
 
3063
      var found = this.string.indexOf(ch, this.pos);
 
3064
      if (found > -1) {this.pos = found; return true;}
 
3065
    },
 
3066
    backUp: function(n) {this.pos -= n;},
 
3067
    column: function() {return countColumn(this.string, this.start, this.tabSize);},
 
3068
    indentation: function() {return countColumn(this.string, null, this.tabSize);},
 
3069
    match: function(pattern, consume, caseInsensitive) {
 
3070
      if (typeof pattern == "string") {
 
3071
        var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
 
3072
        if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
 
3073
          if (consume !== false) this.pos += pattern.length;
 
3074
          return true;
 
3075
        }
 
3076
      } else {
 
3077
        var match = this.string.slice(this.pos).match(pattern);
 
3078
        if (match && match.index > 0) return null;
 
3079
        if (match && consume !== false) this.pos += match[0].length;
 
3080
        return match;
 
3081
      }
 
3082
    },
 
3083
    current: function(){return this.string.slice(this.start, this.pos);}
 
3084
  };
 
3085
  CodeMirror.StringStream = StringStream;
 
3086
 
 
3087
  // TEXTMARKERS
 
3088
 
 
3089
  function TextMarker(cm, type) {
 
3090
    this.lines = [];
 
3091
    this.type = type;
 
3092
    this.cm = cm;
 
3093
  }
 
3094
 
 
3095
  TextMarker.prototype.clear = function() {
 
3096
    if (this.explicitlyCleared) return;
 
3097
    startOperation(this.cm);
 
3098
    var min = null, max = null;
 
3099
    for (var i = 0; i < this.lines.length; ++i) {
 
3100
      var line = this.lines[i];
 
3101
      var span = getMarkedSpanFor(line.markedSpans, this);
 
3102
      if (span.to != null) max = lineNo(line);
 
3103
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
 
3104
      if (span.from != null)
 
3105
        min = lineNo(line);
 
3106
      else if (this.collapsed && !lineIsHidden(line))
 
3107
        updateLineHeight(line, textHeight(this.cm.display));
 
3108
    }
 
3109
    if (min != null) regChange(this.cm, min, max + 1);
 
3110
    this.lines.length = 0;
 
3111
    this.explicitlyCleared = true;
 
3112
    if (this.collapsed && this.cm.view.cantEdit) {
 
3113
      this.cm.view.cantEdit = false;
 
3114
      reCheckSelection(this.cm);
 
3115
    }
 
3116
    endOperation(this.cm);
 
3117
    signalLater(this.cm, this, "clear");
 
3118
  };
 
3119
 
 
3120
  TextMarker.prototype.find = function() {
 
3121
    var from, to;
 
3122
    for (var i = 0; i < this.lines.length; ++i) {
 
3123
      var line = this.lines[i];
 
3124
      var span = getMarkedSpanFor(line.markedSpans, this);
 
3125
      if (span.from != null || span.to != null) {
 
3126
        var found = lineNo(line);
 
3127
        if (span.from != null) from = {line: found, ch: span.from};
 
3128
        if (span.to != null) to = {line: found, ch: span.to};
 
3129
      }
 
3130
    }
 
3131
    if (this.type == "bookmark") return from;
 
3132
    return from && {from: from, to: to};
 
3133
  };
 
3134
 
 
3135
  function markText(cm, from, to, options, type) {
 
3136
    var doc = cm.view.doc;
 
3137
    var marker = new TextMarker(cm, type);
 
3138
    if (type == "range" && !posLess(from, to)) return marker;
 
3139
    if (options) for (var opt in options) if (options.hasOwnProperty(opt))
 
3140
      marker[opt] = options[opt];
 
3141
    if (marker.replacedWith) {
 
3142
      marker.collapsed = true;
 
3143
      marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
 
3144
    }
 
3145
    if (marker.collapsed) sawCollapsedSpans = true;
 
3146
 
 
3147
    var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd;
 
3148
    doc.iter(curLine, to.line + 1, function(line) {
 
3149
      var span = {from: null, to: null, marker: marker};
 
3150
      size += line.text.length;
 
3151
      if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
 
3152
      if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
 
3153
      if (marker.collapsed) {
 
3154
        if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
 
3155
        if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
 
3156
        else updateLineHeight(line, 0);
 
3157
      }
 
3158
      addMarkedSpan(line, span);
 
3159
      if (marker.collapsed && curLine == from.line && lineIsHidden(line))
 
3160
        updateLineHeight(line, 0);
 
3161
      ++curLine;
 
3162
    });
 
3163
 
 
3164
    if (marker.readOnly) {
 
3165
      sawReadOnlySpans = true;
 
3166
      if (cm.view.history.done.length || cm.view.history.undone.length)
 
3167
        cm.clearHistory();
 
3168
    }
 
3169
    if (marker.collapsed) {
 
3170
      if (collapsedAtStart != collapsedAtEnd)
 
3171
        throw new Error("Inserting collapsed marker overlapping an existing one");
 
3172
      marker.size = size;
 
3173
      marker.atomic = true;
 
3174
    }
 
3175
    if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed)
 
3176
      regChange(cm, from.line, to.line + 1);
 
3177
    if (marker.atomic) reCheckSelection(cm);
 
3178
    return marker;
 
3179
  }
 
3180
 
 
3181
  // TEXTMARKER SPANS
 
3182
 
 
3183
  function getMarkedSpanFor(spans, marker) {
 
3184
    if (spans) for (var i = 0; i < spans.length; ++i) {
 
3185
      var span = spans[i];
 
3186
      if (span.marker == marker) return span;
 
3187
    }
 
3188
  }
 
3189
  function removeMarkedSpan(spans, span) {
 
3190
    for (var r, i = 0; i < spans.length; ++i)
 
3191
      if (spans[i] != span) (r || (r = [])).push(spans[i]);
 
3192
    return r;
 
3193
  }
 
3194
  function addMarkedSpan(line, span) {
 
3195
    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
 
3196
    span.marker.lines.push(line);
 
3197
  }
 
3198
 
 
3199
  function markedSpansBefore(old, startCh) {
 
3200
    if (old) for (var i = 0, nw; i < old.length; ++i) {
 
3201
      var span = old[i], marker = span.marker;
 
3202
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
 
3203
      if (startsBefore || marker.type == "bookmark" && span.from == startCh) {
 
3204
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
 
3205
        (nw || (nw = [])).push({from: span.from,
 
3206
                                to: endsAfter ? null : span.to,
 
3207
                                marker: marker});
 
3208
      }
 
3209
    }
 
3210
    return nw;
 
3211
  }
 
3212
 
 
3213
  function markedSpansAfter(old, startCh, endCh) {
 
3214
    if (old) for (var i = 0, nw; i < old.length; ++i) {
 
3215
      var span = old[i], marker = span.marker;
 
3216
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
 
3217
      if (endsAfter || marker.type == "bookmark" && span.from == endCh && span.from != startCh) {
 
3218
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
 
3219
        (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
 
3220
                                to: span.to == null ? null : span.to - endCh,
 
3221
                                marker: marker});
 
3222
      }
 
3223
    }
 
3224
    return nw;
 
3225
  }
 
3226
 
 
3227
  function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) {
 
3228
    if (!oldFirst && !oldLast) return newText;
 
3229
    // Get the spans that 'stick out' on both sides
 
3230
    var first = markedSpansBefore(oldFirst, startCh);
 
3231
    var last = markedSpansAfter(oldLast, startCh, endCh);
 
3232
 
 
3233
    // Next, merge those two ends
 
3234
    var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0);
 
3235
    if (first) {
 
3236
      // Fix up .to properties of first
 
3237
      for (var i = 0; i < first.length; ++i) {
 
3238
        var span = first[i];
 
3239
        if (span.to == null) {
 
3240
          var found = getMarkedSpanFor(last, span.marker);
 
3241
          if (!found) span.to = startCh;
 
3242
          else if (sameLine) span.to = found.to == null ? null : found.to + offset;
 
3243
        }
 
3244
      }
 
3245
    }
 
3246
    if (last) {
 
3247
      // Fix up .from in last (or move them into first in case of sameLine)
 
3248
      for (var i = 0; i < last.length; ++i) {
 
3249
        var span = last[i];
 
3250
        if (span.to != null) span.to += offset;
 
3251
        if (span.from == null) {
 
3252
          var found = getMarkedSpanFor(first, span.marker);
 
3253
          if (!found) {
 
3254
            span.from = offset;
 
3255
            if (sameLine) (first || (first = [])).push(span);
 
3256
          }
 
3257
        } else {
 
3258
          span.from += offset;
 
3259
          if (sameLine) (first || (first = [])).push(span);
 
3260
        }
 
3261
      }
 
3262
    }
 
3263
 
 
3264
    var newMarkers = [newHL(newText[0], first)];
 
3265
    if (!sameLine) {
 
3266
      // Fill gap with whole-line-spans
 
3267
      var gap = newText.length - 2, gapMarkers;
 
3268
      if (gap > 0 && first)
 
3269
        for (var i = 0; i < first.length; ++i)
 
3270
          if (first[i].to == null)
 
3271
            (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
 
3272
      for (var i = 0; i < gap; ++i)
 
3273
        newMarkers.push(newHL(newText[i+1], gapMarkers));
 
3274
      newMarkers.push(newHL(lst(newText), last));
 
3275
    }
 
3276
    return newMarkers;
 
3277
  }
 
3278
 
 
3279
  function removeReadOnlyRanges(doc, from, to) {
 
3280
    var markers = null;
 
3281
    doc.iter(from.line, to.line + 1, function(line) {
 
3282
      if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
 
3283
        var mark = line.markedSpans[i].marker;
 
3284
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
 
3285
          (markers || (markers = [])).push(mark);
 
3286
      }
 
3287
    });
 
3288
    if (!markers) return null;
 
3289
    var parts = [{from: from, to: to}];
 
3290
    for (var i = 0; i < markers.length; ++i) {
 
3291
      var m = markers[i].find();
 
3292
      for (var j = 0; j < parts.length; ++j) {
 
3293
        var p = parts[j];
 
3294
        if (!posLess(m.from, p.to) || posLess(m.to, p.from)) continue;
 
3295
        var newParts = [j, 1];
 
3296
        if (posLess(p.from, m.from)) newParts.push({from: p.from, to: m.from});
 
3297
        if (posLess(m.to, p.to)) newParts.push({from: m.to, to: p.to});
 
3298
        parts.splice.apply(parts, newParts);
 
3299
        j += newParts.length - 1;
 
3300
      }
 
3301
    }
 
3302
    return parts;
 
3303
  }
 
3304
 
 
3305
  function collapsedSpanAt(line, ch) {
 
3306
    var sps = sawCollapsedSpans && line.markedSpans, found;
 
3307
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
 
3308
      sp = sps[i];
 
3309
      if (!sp.marker.collapsed) continue;
 
3310
      if ((sp.from == null || sp.from < ch) &&
 
3311
          (sp.to == null || sp.to > ch) &&
 
3312
          (!found || found.width < sp.marker.width))
 
3313
        found = sp.marker;
 
3314
    }
 
3315
    return found;
 
3316
  }
 
3317
  function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
 
3318
  function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
 
3319
 
 
3320
  function lineIsHidden(line) {
 
3321
    var sps = sawCollapsedSpans && line.markedSpans;
 
3322
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
 
3323
      sp = sps[i];
 
3324
      if (!sp.marker.collapsed) continue;
 
3325
      if (sp.from == null) return true;
 
3326
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(line, sp))
 
3327
        return true;
 
3328
    }
 
3329
  }
 
3330
  window.lineIsHidden = lineIsHidden;
 
3331
  function lineIsHiddenInner(line, span) {
 
3332
    if (span.to == null || span.marker.inclusiveRight && span.to == line.text.length)
 
3333
      return true;
 
3334
    for (var sp, i = 0; i < line.markedSpans.length; ++i) {
 
3335
      sp = line.markedSpans[i];
 
3336
      if (sp.marker.collapsed && sp.from == span.to &&
 
3337
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
 
3338
          lineIsHiddenInner(line, sp)) return true;
 
3339
    }
 
3340
  }
 
3341
 
 
3342
  // hl stands for history-line, a data structure that can be either a
 
3343
  // string (line without markers) or a {text, markedSpans} object.
 
3344
  function hlText(val) { return typeof val == "string" ? val : val.text; }
 
3345
  function hlSpans(val) {
 
3346
    if (typeof val == "string") return null;
 
3347
    var spans = val.markedSpans, out = null;
 
3348
    for (var i = 0; i < spans.length; ++i) {
 
3349
      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
 
3350
      else if (out) out.push(spans[i]);
 
3351
    }
 
3352
    return !out ? spans : out.length ? out : null;
 
3353
  }
 
3354
  function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; }
 
3355
 
 
3356
  function detachMarkedSpans(line) {
 
3357
    var spans = line.markedSpans;
 
3358
    if (!spans) return;
 
3359
    for (var i = 0; i < spans.length; ++i) {
 
3360
      var lines = spans[i].marker.lines;
 
3361
      var ix = indexOf(lines, line);
 
3362
      lines.splice(ix, 1);
 
3363
    }
 
3364
    line.markedSpans = null;
 
3365
  }
 
3366
 
 
3367
  function attachMarkedSpans(line, spans) {
 
3368
    if (!spans) return;
 
3369
    for (var i = 0; i < spans.length; ++i)
 
3370
      var marker = spans[i].marker.lines.push(line);
 
3371
    line.markedSpans = spans;
 
3372
  }
 
3373
 
 
3374
  // LINE DATA STRUCTURE
 
3375
 
 
3376
  // Line objects. These hold state related to a line, including
 
3377
  // highlighting info (the styles array).
 
3378
  function makeLine(text, markedSpans, height) {
 
3379
    var line = {text: text, height: height};
 
3380
    attachMarkedSpans(line, markedSpans);
 
3381
    if (markedSpans && collapsedSpanAtStart(line)) line.height = 0;
 
3382
    return line;
 
3383
  }
 
3384
 
 
3385
  function updateLine(cm, line, text, markedSpans) {
 
3386
    line.text = text;
 
3387
    line.stateAfter = line.styles = null;
 
3388
    if (line.order != null) line.order = null;
 
3389
    detachMarkedSpans(line);
 
3390
    attachMarkedSpans(line, markedSpans);
 
3391
    var hidden = collapsedSpanAtStart(line);
 
3392
    if (hidden) line.height = 0;
 
3393
    else if (!line.height) line.height = textHeight(cm.display);
 
3394
    signalLater(cm, line, "change");
 
3395
  }
 
3396
 
 
3397
  function cleanUpLine(line) {
 
3398
    line.parent = null;
 
3399
    detachMarkedSpans(line);
 
3400
  }
 
3401
 
 
3402
  // Run the given mode's parser over a line, update the styles
 
3403
  // array, which contains alternating fragments of text and CSS
 
3404
  // classes.
 
3405
  function highlightLine(cm, line, state) {
 
3406
    var mode = cm.view.mode, flattenSpans = cm.options.flattenSpans;
 
3407
    var changed = !line.styles, pos = 0, curText = "", curStyle = null;
 
3408
    var stream = new StringStream(line.text, cm.options.tabSize), st = line.styles || (line.styles = []);
 
3409
    if (line.text == "" && mode.blankLine) mode.blankLine(state);
 
3410
    while (!stream.eol()) {
 
3411
      var style = mode.token(stream, state), substr = stream.current();
 
3412
      stream.start = stream.pos;
 
3413
      if (!flattenSpans || curStyle != style) {
 
3414
        if (curText) {
 
3415
          changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1];
 
3416
          st[pos++] = curText; st[pos++] = curStyle;
 
3417
        }
 
3418
        curText = substr; curStyle = style;
 
3419
      } else curText = curText + substr;
 
3420
      // Give up when line is ridiculously long
 
3421
      if (stream.pos > 5000) break;
 
3422
    }
 
3423
    if (curText) {
 
3424
      changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1];
 
3425
      st[pos++] = curText; st[pos++] = curStyle;
 
3426
    }
 
3427
    if (stream.pos > 5000) { st[pos++] = line.text.slice(stream.pos); st[pos++] = null; }
 
3428
    if (pos != st.length) { st.length = pos; changed = true; }
 
3429
    return changed;
 
3430
  }
 
3431
 
 
3432
  // Lightweight form of highlight -- proceed over this line and
 
3433
  // update state, but don't save a style array.
 
3434
  function processLine(cm, line, state) {
 
3435
    var mode = cm.view.mode;
 
3436
    var stream = new StringStream(line.text, cm.options.tabSize);
 
3437
    if (line.text == "" && mode.blankLine) mode.blankLine(state);
 
3438
    while (!stream.eol() && stream.pos <= 5000) {
 
3439
      mode.token(stream, state);
 
3440
      stream.start = stream.pos;
 
3441
    }
 
3442
  }
 
3443
 
 
3444
  // Fetch the parser token for a given character. Useful for hacks
 
3445
  // that want to inspect the mode state (say, for completion).
 
3446
  function getTokenAt(cm, line, state, ch) {
 
3447
    var mode = cm.view.mode;
 
3448
    var txt = line.text, stream = new StringStream(txt, cm.options.tabSize);
 
3449
    while (stream.pos < ch && !stream.eol()) {
 
3450
      stream.start = stream.pos;
 
3451
      var style = mode.token(stream, state);
 
3452
    }
 
3453
    return {start: stream.start,
 
3454
            end: stream.pos,
 
3455
            string: stream.current(),
 
3456
            className: style || null,
 
3457
            state: state};
 
3458
  }
 
3459
 
 
3460
  var styleToClassCache = {};
 
3461
  function styleToClass(style) {
 
3462
    if (!style) return null;
 
3463
    return styleToClassCache[style] ||
 
3464
      (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
 
3465
  }
 
3466
 
 
3467
  function lineContent(cm, realLine, measure) {
 
3468
    var merged, line = realLine, lineBefore, sawBefore;
 
3469
    while (merged = collapsedSpanAtStart(line)) {
 
3470
      line = getLine(cm.view.doc, merged.find().from.line);
 
3471
      if (!lineBefore) lineBefore = line;
 
3472
    }
 
3473
 
 
3474
    var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure,
 
3475
                   measure: null, addedOne: false, cm: cm};
 
3476
    if (line.textClass) builder.pre.className = line.textClass;
 
3477
 
 
3478
    do {
 
3479
      if (!line.styles)
 
3480
        highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
 
3481
      builder.measure = line == realLine && measure;
 
3482
      builder.pos = 0;
 
3483
      builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
 
3484
      if (measure && sawBefore && line != realLine && !builder.addedOne) {
 
3485
        measure[0] = builder.pre.appendChild(elt("span", "\u200b"));
 
3486
        builder.addedOne = true;
 
3487
      }
 
3488
      var next = insertLineContent(line, builder);
 
3489
      sawBefore = line == lineBefore;
 
3490
      if (next) line = getLine(cm.view.doc, next.to.line);
 
3491
    } while (next);
 
3492
 
 
3493
    if (measure && !builder.addedOne)
 
3494
      measure[0] = builder.pre.appendChild(elt("span", "\u200b"));
 
3495
    if (!builder.pre.firstChild && !lineIsHidden(realLine))
 
3496
      builder.pre.appendChild(document.createTextNode("\u00a0"));
 
3497
 
 
3498
    return builder.pre;
 
3499
  }
 
3500
 
 
3501
  var tokenSpecialChars = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g;
 
3502
  function buildToken(builder, text, style, startStyle, endStyle) {
 
3503
    if (!text) return;
 
3504
    if (!tokenSpecialChars.test(text)) {
 
3505
      builder.col += text.length;
 
3506
      var content = document.createTextNode(text);
 
3507
    } else {
 
3508
      var content = document.createDocumentFragment(), pos = 0;
 
3509
      while (true) {
 
3510
        tokenSpecialChars.lastIndex = pos;
 
3511
        var m = tokenSpecialChars.exec(text);
 
3512
        var skipped = m ? m.index - pos : text.length - pos;
 
3513
        if (skipped) {
 
3514
          content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
 
3515
          builder.col += skipped;
 
3516
        }
 
3517
        if (!m) break;
 
3518
        pos += skipped + 1;
 
3519
        if (m[0] == "\t") {
 
3520
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
 
3521
          content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
 
3522
          builder.col += tabWidth;
 
3523
        } else {
 
3524
          var token = elt("span", "\u2022", "cm-invalidchar");
 
3525
          token.title = "\\u" + m[0].charCodeAt(0).toString(16);
 
3526
          content.appendChild(token);
 
3527
          builder.col += 1;
 
3528
        }
 
3529
      }
 
3530
    }
 
3531
    if (style || startStyle || endStyle || builder.measure) {
 
3532
      var fullStyle = style || "";
 
3533
      if (startStyle) fullStyle += startStyle;
 
3534
      if (endStyle) fullStyle += endStyle;
 
3535
      return builder.pre.appendChild(elt("span", [content], fullStyle));
 
3536
    }
 
3537
    builder.pre.appendChild(content);
 
3538
  }
 
3539
 
 
3540
  function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
 
3541
    for (var i = 0; i < text.length; ++i) {
 
3542
      if (i && i < text.length - 1 &&
 
3543
          builder.cm.options.lineWrapping &&
 
3544
          spanAffectsWrapping.test(text.slice(i - 1, i + 1)))
 
3545
        builder.pre.appendChild(elt("wbr"));
 
3546
      builder.measure[builder.pos++] =
 
3547
        buildToken(builder, text.charAt(i), style,
 
3548
                   i == 0 && startStyle, i == text.length - 1 && endStyle);
 
3549
    }
 
3550
    if (text.length) builder.addedOne = true;
 
3551
  }
 
3552
 
 
3553
  function buildCollapsedSpan(builder, size, widget) {
 
3554
    if (widget) {
 
3555
      if (!builder.display) widget = widget.cloneNode(true);
 
3556
      builder.pre.appendChild(widget);
 
3557
      if (builder.measure && size) {
 
3558
        builder.measure[builder.pos] = widget;
 
3559
        builder.addedOne = true;
 
3560
      }
 
3561
    }
 
3562
    builder.pos += size;
 
3563
  }
 
3564
 
 
3565
  // Outputs a number of spans to make up a line, taking highlighting
 
3566
  // and marked text into account.
 
3567
  function insertLineContent(line, builder) {
 
3568
    var st = line.styles, spans = line.markedSpans;
 
3569
    if (!spans) {
 
3570
      for (var i = 0; i < st.length; i+=2)
 
3571
        builder.addToken(builder, st[i], styleToClass(st[i+1]));
 
3572
      return;
 
3573
    }
 
3574
 
 
3575
    var allText = line.text, len = allText.length;
 
3576
    var pos = 0, i = 0, text = "", style;
 
3577
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed;
 
3578
    for (;;) {
 
3579
      if (nextChange == pos) { // Update current marker set
 
3580
        spanStyle = spanEndStyle = spanStartStyle = "";
 
3581
        collapsed = null; nextChange = Infinity;
 
3582
        var foundBookmark = null;
 
3583
        for (var j = 0; j < spans.length; ++j) {
 
3584
          var sp = spans[j], m = sp.marker;
 
3585
          if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
 
3586
            if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
 
3587
            if (m.className) spanStyle += " " + m.className;
 
3588
            if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
 
3589
            if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
 
3590
            if (m.collapsed && (!collapsed || collapsed.marker.width < m.width))
 
3591
              collapsed = sp;
 
3592
          } else if (sp.from > pos && nextChange > sp.from) {
 
3593
            nextChange = sp.from;
 
3594
          }
 
3595
          if (m.type == "bookmark" && sp.from == pos && m.replacedWith)
 
3596
            foundBookmark = m.replacedWith;
 
3597
        }
 
3598
        if (collapsed && (collapsed.from || 0) == pos) {
 
3599
          buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
 
3600
                             collapsed.from != null && collapsed.marker.replacedWith);
 
3601
          if (collapsed.to == null) return collapsed.marker.find();
 
3602
        }
 
3603
        if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
 
3604
      }
 
3605
      if (pos >= len) break;
 
3606
 
 
3607
      var upto = Math.min(len, nextChange);
 
3608
      while (true) {
 
3609
        if (text) {
 
3610
          var end = pos + text.length;
 
3611
          if (!collapsed) {
 
3612
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
 
3613
            builder.addToken(builder, tokenText, style + spanStyle,
 
3614
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "");
 
3615
          }
 
3616
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
 
3617
          pos = end;
 
3618
          spanStartStyle = "";
 
3619
        }
 
3620
        text = st[i++]; style = styleToClass(st[i++]);
 
3621
      }
 
3622
    }
 
3623
  }
 
3624
 
 
3625
  // DOCUMENT DATA STRUCTURE
 
3626
 
 
3627
  function LeafChunk(lines) {
 
3628
    this.lines = lines;
 
3629
    this.parent = null;
 
3630
    for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
 
3631
      lines[i].parent = this;
 
3632
      height += lines[i].height;
 
3633
    }
 
3634
    this.height = height;
 
3635
  }
 
3636
 
 
3637
  LeafChunk.prototype = {
 
3638
    chunkSize: function() { return this.lines.length; },
 
3639
    remove: function(at, n, cm) {
 
3640
      for (var i = at, e = at + n; i < e; ++i) {
 
3641
        var line = this.lines[i];
 
3642
        this.height -= line.height;
 
3643
        cleanUpLine(line);
 
3644
        signalLater(cm, line, "delete");
 
3645
      }
 
3646
      this.lines.splice(at, n);
 
3647
    },
 
3648
    collapse: function(lines) {
 
3649
      lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
 
3650
    },
 
3651
    insertHeight: function(at, lines, height) {
 
3652
      this.height += height;
 
3653
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
 
3654
      for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
 
3655
    },
 
3656
    iterN: function(at, n, op) {
 
3657
      for (var e = at + n; at < e; ++at)
 
3658
        if (op(this.lines[at])) return true;
 
3659
    }
 
3660
  };
 
3661
 
 
3662
  function BranchChunk(children) {
 
3663
    this.children = children;
 
3664
    var size = 0, height = 0;
 
3665
    for (var i = 0, e = children.length; i < e; ++i) {
 
3666
      var ch = children[i];
 
3667
      size += ch.chunkSize(); height += ch.height;
 
3668
      ch.parent = this;
 
3669
    }
 
3670
    this.size = size;
 
3671
    this.height = height;
 
3672
    this.parent = null;
 
3673
  }
 
3674
 
 
3675
  BranchChunk.prototype = {
 
3676
    chunkSize: function() { return this.size; },
 
3677
    remove: function(at, n, callbacks) {
 
3678
      this.size -= n;
 
3679
      for (var i = 0; i < this.children.length; ++i) {
 
3680
        var child = this.children[i], sz = child.chunkSize();
 
3681
        if (at < sz) {
 
3682
          var rm = Math.min(n, sz - at), oldHeight = child.height;
 
3683
          child.remove(at, rm, callbacks);
 
3684
          this.height -= oldHeight - child.height;
 
3685
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
 
3686
          if ((n -= rm) == 0) break;
 
3687
          at = 0;
 
3688
        } else at -= sz;
 
3689
      }
 
3690
      if (this.size - n < 25) {
 
3691
        var lines = [];
 
3692
        this.collapse(lines);
 
3693
        this.children = [new LeafChunk(lines)];
 
3694
        this.children[0].parent = this;
 
3695
      }
 
3696
    },
 
3697
    collapse: function(lines) {
 
3698
      for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
 
3699
    },
 
3700
    insert: function(at, lines) {
 
3701
      var height = 0;
 
3702
      for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
 
3703
      this.insertHeight(at, lines, height);
 
3704
    },
 
3705
    insertHeight: function(at, lines, height) {
 
3706
      this.size += lines.length;
 
3707
      this.height += height;
 
3708
      for (var i = 0, e = this.children.length; i < e; ++i) {
 
3709
        var child = this.children[i], sz = child.chunkSize();
 
3710
        if (at <= sz) {
 
3711
          child.insertHeight(at, lines, height);
 
3712
          if (child.lines && child.lines.length > 50) {
 
3713
            while (child.lines.length > 50) {
 
3714
              var spilled = child.lines.splice(child.lines.length - 25, 25);
 
3715
              var newleaf = new LeafChunk(spilled);
 
3716
              child.height -= newleaf.height;
 
3717
              this.children.splice(i + 1, 0, newleaf);
 
3718
              newleaf.parent = this;
 
3719
            }
 
3720
            this.maybeSpill();
 
3721
          }
 
3722
          break;
 
3723
        }
 
3724
        at -= sz;
 
3725
      }
 
3726
    },
 
3727
    maybeSpill: function() {
 
3728
      if (this.children.length <= 10) return;
 
3729
      var me = this;
 
3730
      do {
 
3731
        var spilled = me.children.splice(me.children.length - 5, 5);
 
3732
        var sibling = new BranchChunk(spilled);
 
3733
        if (!me.parent) { // Become the parent node
 
3734
          var copy = new BranchChunk(me.children);
 
3735
          copy.parent = me;
 
3736
          me.children = [copy, sibling];
 
3737
          me = copy;
 
3738
        } else {
 
3739
          me.size -= sibling.size;
 
3740
          me.height -= sibling.height;
 
3741
          var myIndex = indexOf(me.parent.children, me);
 
3742
          me.parent.children.splice(myIndex + 1, 0, sibling);
 
3743
        }
 
3744
        sibling.parent = me.parent;
 
3745
      } while (me.children.length > 10);
 
3746
      me.parent.maybeSpill();
 
3747
    },
 
3748
    iter: function(from, to, op) { this.iterN(from, to - from, op); },
 
3749
    iterN: function(at, n, op) {
 
3750
      for (var i = 0, e = this.children.length; i < e; ++i) {
 
3751
        var child = this.children[i], sz = child.chunkSize();
 
3752
        if (at < sz) {
 
3753
          var used = Math.min(n, sz - at);
 
3754
          if (child.iterN(at, used, op)) return true;
 
3755
          if ((n -= used) == 0) break;
 
3756
          at = 0;
 
3757
        } else at -= sz;
 
3758
      }
 
3759
    }
 
3760
  };
 
3761
 
 
3762
  // LINE UTILITIES
 
3763
 
 
3764
  function lineDoc(line) {
 
3765
    for (var d = line.parent; d && d.parent; d = d.parent) {}
 
3766
    return d;
 
3767
  }
 
3768
 
 
3769
  function getLine(chunk, n) {
 
3770
    while (!chunk.lines) {
 
3771
      for (var i = 0;; ++i) {
 
3772
        var child = chunk.children[i], sz = child.chunkSize();
 
3773
        if (n < sz) { chunk = child; break; }
 
3774
        n -= sz;
 
3775
      }
 
3776
    }
 
3777
    return chunk.lines[n];
 
3778
  }
 
3779
 
 
3780
  function updateLineHeight(line, height) {
 
3781
    var diff = height - line.height;
 
3782
    for (var n = line; n; n = n.parent) n.height += diff;
 
3783
  }
 
3784
 
 
3785
  function lineNo(line) {
 
3786
    if (line.parent == null) return null;
 
3787
    var cur = line.parent, no = indexOf(cur.lines, line);
 
3788
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
 
3789
      for (var i = 0, e = chunk.children.length; ; ++i) {
 
3790
        if (chunk.children[i] == cur) break;
 
3791
        no += chunk.children[i].chunkSize();
 
3792
      }
 
3793
    }
 
3794
    return no;
 
3795
  }
 
3796
 
 
3797
  function lineAtHeight(chunk, h) {
 
3798
    var n = 0;
 
3799
    outer: do {
 
3800
      for (var i = 0, e = chunk.children.length; i < e; ++i) {
 
3801
        var child = chunk.children[i], ch = child.height;
 
3802
        if (h < ch) { chunk = child; continue outer; }
 
3803
        h -= ch;
 
3804
        n += child.chunkSize();
 
3805
      }
 
3806
      return n;
 
3807
    } while (!chunk.lines);
 
3808
    for (var i = 0, e = chunk.lines.length; i < e; ++i) {
 
3809
      var line = chunk.lines[i], lh = line.height;
 
3810
      if (h < lh) break;
 
3811
      h -= lh;
 
3812
    }
 
3813
    return n + i;
 
3814
  }
 
3815
 
 
3816
  function heightAtLine(cm, lineObj) {
 
3817
    var merged;
 
3818
    while (merged = collapsedSpanAtStart(lineObj))
 
3819
      lineObj = getLine(cm.view.doc, merged.find().from.line);
 
3820
 
 
3821
    var h = 0, chunk = lineObj.parent;
 
3822
    for (var i = 0; i < chunk.lines.length; ++i) {
 
3823
      var line = chunk.lines[i];
 
3824
      if (line == lineObj) break;
 
3825
      else h += line.height;
 
3826
    }
 
3827
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
 
3828
      for (var i = 0; i < p.children.length; ++i) {
 
3829
        var cur = p.children[i];
 
3830
        if (cur == chunk) break;
 
3831
        else h += cur.height;
 
3832
      }
 
3833
    }
 
3834
    return h;
 
3835
  }
 
3836
 
 
3837
  function getOrder(line) {
 
3838
    var order = line.order;
 
3839
    if (order == null) order = line.order = bidiOrdering(line.text);
 
3840
    return order;
 
3841
  }
 
3842
 
 
3843
  // HISTORY
 
3844
 
 
3845
  // The history object 'chunks' changes that are made close together
 
3846
  // and at almost the same time into bigger undoable units.
 
3847
  function makeHistory() {
 
3848
    return {time: 0, done: [], undone: [],
 
3849
            compound: 0, closed: false, dirtyCounter: 0};
 
3850
  }
 
3851
 
 
3852
  function addChange(history, start, added, old) {
 
3853
    history.undone.length = 0;
 
3854
    var time = +new Date, cur = lst(history.done), last = cur && lst(cur);
 
3855
    var dtime = time - history.time;
 
3856
    
 
3857
    function updateDirty() {
 
3858
      if (history.dirtyCounter < 0) {
 
3859
          // The user has made a change after undoing past the last clean state. 
 
3860
          // We can never get back to a clean state now until markClean() is called.
 
3861
          history.dirtyCounter = NaN;
 
3862
      }
 
3863
      history.dirtyCounter++;
 
3864
    }
 
3865
 
 
3866
    if (cur && !history.closed && history.compound) {
 
3867
      updateDirty();
 
3868
      cur.push({start: start, added: added, old: old});
 
3869
    } else if (dtime > 400 || !last || history.closed ||
 
3870
               last.start > start + old.length || last.start + last.added < start) {
 
3871
      updateDirty();
 
3872
      history.done.push([{start: start, added: added, old: old}]);
 
3873
      history.closed = false;
 
3874
    } else {
 
3875
      var startBefore = Math.max(0, last.start - start),
 
3876
      endAfter = Math.max(0, (start + old.length) - (last.start + last.added));
 
3877
      for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]);
 
3878
      for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]);
 
3879
      if (startBefore) last.start = start;
 
3880
      last.added += added - (old.length - startBefore - endAfter);
 
3881
    }
 
3882
    history.time = time;
 
3883
  }
 
3884
 
 
3885
  function compoundChange(cm, f) {
 
3886
    var hist = cm.view.history;
 
3887
    if (!hist.compound++) hist.closed = true;
 
3888
    try { return f(); }
 
3889
    finally { if (!--hist.compound) hist.closed = true; }
 
3890
  }
 
3891
 
 
3892
  // EVENT OPERATORS
 
3893
 
 
3894
  function stopMethod() {e_stop(this);}
 
3895
  // Ensure an event has a stop method.
 
3896
  function addStop(event) {
 
3897
    if (!event.stop) event.stop = stopMethod;
 
3898
    return event;
 
3899
  }
 
3900
 
 
3901
  function e_preventDefault(e) {
 
3902
    if (e.preventDefault) e.preventDefault();
 
3903
    else e.returnValue = false;
 
3904
  }
 
3905
  function e_stopPropagation(e) {
 
3906
    if (e.stopPropagation) e.stopPropagation();
 
3907
    else e.cancelBubble = true;
 
3908
  }
 
3909
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
 
3910
  CodeMirror.e_stop = e_stop;
 
3911
  CodeMirror.e_preventDefault = e_preventDefault;
 
3912
  CodeMirror.e_stopPropagation = e_stopPropagation;
 
3913
 
 
3914
  function e_target(e) {return e.target || e.srcElement;}
 
3915
  function e_button(e) {
 
3916
    var b = e.which;
 
3917
    if (b == null) {
 
3918
      if (e.button & 1) b = 1;
 
3919
      else if (e.button & 2) b = 3;
 
3920
      else if (e.button & 4) b = 2;
 
3921
    }
 
3922
    if (mac && e.ctrlKey && b == 1) b = 3;
 
3923
    return b;
 
3924
  }
 
3925
 
 
3926
  // Allow 3rd-party code to override event properties by adding an override
 
3927
  // object to an event object.
 
3928
  function e_prop(e, prop) {
 
3929
    var overridden = e.override && e.override.hasOwnProperty(prop);
 
3930
    return overridden ? e.override[prop] : e[prop];
 
3931
  }
 
3932
 
 
3933
  // EVENT HANDLING
 
3934
 
 
3935
  function on(emitter, type, f) {
 
3936
    if (emitter.addEventListener)
 
3937
      emitter.addEventListener(type, f, false);
 
3938
    else if (emitter.attachEvent)
 
3939
      emitter.attachEvent("on" + type, f);
 
3940
    else {
 
3941
      var map = emitter._handlers || (emitter._handlers = {});
 
3942
      var arr = map[type] || (map[type] = []);
 
3943
      arr.push(f);
 
3944
    }
 
3945
  }
 
3946
 
 
3947
  function off(emitter, type, f) {
 
3948
    if (emitter.removeEventListener)
 
3949
      emitter.removeEventListener(type, f, false);
 
3950
    else if (emitter.detachEvent)
 
3951
      emitter.detachEvent("on" + type, f);
 
3952
    else {
 
3953
      var arr = emitter._handlers && emitter._handlers[type];
 
3954
      if (!arr) return;
 
3955
      for (var i = 0; i < arr.length; ++i)
 
3956
        if (arr[i] == f) { arr.splice(i, 1); break; }
 
3957
    }
 
3958
  }
 
3959
 
 
3960
  function signal(emitter, type /*, values...*/) {
 
3961
    var arr = emitter._handlers && emitter._handlers[type];
 
3962
    if (!arr) return;
 
3963
    var args = Array.prototype.slice.call(arguments, 2);
 
3964
    for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
 
3965
  }
 
3966
 
 
3967
  function signalLater(cm, emitter, type /*, values...*/) {
 
3968
    var arr = emitter._handlers && emitter._handlers[type];
 
3969
    if (!arr) return;
 
3970
    var args = Array.prototype.slice.call(arguments, 3), flist = cm.curOp && cm.curOp.delayedCallbacks;
 
3971
    function bnd(f) {return function(){f.apply(null, args);};};
 
3972
    for (var i = 0; i < arr.length; ++i)
 
3973
      if (flist) flist.push(bnd(arr[i]));
 
3974
      else arr[i].apply(null, args);
 
3975
  }
 
3976
 
 
3977
  function hasHandler(emitter, type) {
 
3978
    var arr = emitter._handlers && emitter._handlers[type];
 
3979
    return arr && arr.length > 0;
 
3980
  }
 
3981
 
 
3982
  CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
 
3983
 
 
3984
  // MISC UTILITIES
 
3985
 
 
3986
  // Number of pixels added to scroller and sizer to hide scrollbar
 
3987
  var scrollerCutOff = 30;
 
3988
 
 
3989
  // Returned or thrown by various protocols to signal 'I'm not
 
3990
  // handling this'.
 
3991
  var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
 
3992
 
 
3993
  function Delayed() {this.id = null;}
 
3994
  Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
 
3995
 
 
3996
  // Counts the column offset in a string, taking tabs into account.
 
3997
  // Used mostly to find indentation.
 
3998
  function countColumn(string, end, tabSize) {
 
3999
    if (end == null) {
 
4000
      end = string.search(/[^\s\u00a0]/);
 
4001
      if (end == -1) end = string.length;
 
4002
    }
 
4003
    for (var i = 0, n = 0; i < end; ++i) {
 
4004
      if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
 
4005
      else ++n;
 
4006
    }
 
4007
    return n;
 
4008
  }
 
4009
  CodeMirror.countColumn = countColumn;
 
4010
 
 
4011
  var spaceStrs = [""];
 
4012
  function spaceStr(n) {
 
4013
    while (spaceStrs.length <= n)
 
4014
      spaceStrs.push(lst(spaceStrs) + " ");
 
4015
    return spaceStrs[n];
 
4016
  }
 
4017
 
 
4018
  function lst(arr) { return arr[arr.length-1]; }
 
4019
 
 
4020
  function selectInput(node) {
 
4021
    if (ios) { // Mobile Safari apparently has a bug where select() is broken.
 
4022
      node.selectionStart = 0;
 
4023
      node.selectionEnd = node.value.length;
 
4024
    } else node.select();
 
4025
  }
 
4026
 
 
4027
  // Used to position the cursor after an undo/redo by finding the
 
4028
  // last edited character.
 
4029
  function editEnd(from, to) {
 
4030
    if (!to) return 0;
 
4031
    if (!from) return to.length;
 
4032
    for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
 
4033
      if (from.charAt(i) != to.charAt(j)) break;
 
4034
    return j + 1;
 
4035
  }
 
4036
 
 
4037
  function indexOf(collection, elt) {
 
4038
    if (collection.indexOf) return collection.indexOf(elt);
 
4039
    for (var i = 0, e = collection.length; i < e; ++i)
 
4040
      if (collection[i] == elt) return i;
 
4041
    return -1;
 
4042
  }
 
4043
 
 
4044
  function emptyArray(size) {
 
4045
    for (var a = [], i = 0; i < size; ++i) a.push(undefined);
 
4046
    return a;
 
4047
  }
 
4048
 
 
4049
  function bind(f) {
 
4050
    var args = Array.prototype.slice.call(arguments, 1);
 
4051
    return function(){return f.apply(null, args);};
 
4052
  }
 
4053
 
 
4054
  var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/;
 
4055
  function isWordChar(ch) {
 
4056
    return /\w/.test(ch) || ch > "\x80" &&
 
4057
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
 
4058
  }
 
4059
 
 
4060
  function isEmpty(obj) {
 
4061
    var c = 0;
 
4062
    for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) ++c;
 
4063
    return !c;
 
4064
  }
 
4065
 
 
4066
  var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F]/;
 
4067
 
 
4068
  // DOM UTILITIES
 
4069
 
 
4070
  function elt(tag, content, className, style) {
 
4071
    var e = document.createElement(tag);
 
4072
    if (className) e.className = className;
 
4073
    if (style) e.style.cssText = style;
 
4074
    if (typeof content == "string") setTextContent(e, content);
 
4075
    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
 
4076
    return e;
 
4077
  }
 
4078
 
 
4079
  function removeChildren(e) {
 
4080
    e.innerHTML = "";
 
4081
    return e;
 
4082
  }
 
4083
 
 
4084
  function removeChildrenAndAdd(parent, e) {
 
4085
    return removeChildren(parent).appendChild(e);
 
4086
  }
 
4087
 
 
4088
  function setTextContent(e, str) {
 
4089
    if (ie_lt9) {
 
4090
      e.innerHTML = "";
 
4091
      e.appendChild(document.createTextNode(str));
 
4092
    } else e.textContent = str;
 
4093
  }
 
4094
 
 
4095
  // FEATURE DETECTION
 
4096
 
 
4097
  // Detect drag-and-drop
 
4098
  var dragAndDrop = function() {
 
4099
    // There is *some* kind of drag-and-drop support in IE6-8, but I
 
4100
    // couldn't get it to work yet.
 
4101
    if (ie_lt9) return false;
 
4102
    var div = elt('div');
 
4103
    return "draggable" in div || "dragDrop" in div;
 
4104
  }();
 
4105
 
 
4106
  // Feature-detect whether newlines in textareas are converted to \r\n
 
4107
  var lineSep = function () {
 
4108
    var te = elt("textarea");
 
4109
    te.value = "foo\nbar";
 
4110
    if (te.value.indexOf("\r") > -1) return "\r\n";
 
4111
    return "\n";
 
4112
  }();
 
4113
 
 
4114
  // For a reason I have yet to figure out, some browsers disallow
 
4115
  // word wrapping between certain characters *only* if a new inline
 
4116
  // element is started between them. This makes it hard to reliably
 
4117
  // measure the position of things, since that requires inserting an
 
4118
  // extra span. This terribly fragile set of regexps matches the
 
4119
  // character combinations that suffer from this phenomenon on the
 
4120
  // various browsers.
 
4121
  var spanAffectsWrapping = /^$/; // Won't match any two-character string
 
4122
  if (gecko) spanAffectsWrapping = /$'/;
 
4123
  else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
 
4124
  else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/;
 
4125
 
 
4126
  var knownScrollbarWidth;
 
4127
  function scrollbarWidth(measure) {
 
4128
    if (knownScrollbarWidth != null) return knownScrollbarWidth;
 
4129
    var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
 
4130
    removeChildrenAndAdd(measure, test);
 
4131
    if (test.offsetWidth)
 
4132
      knownScrollbarWidth = test.offsetHeight - test.clientHeight;
 
4133
    return knownScrollbarWidth || 0;
 
4134
  }
 
4135
 
 
4136
  // See if "".split is the broken IE version, if so, provide an
 
4137
  // alternative way to split lines.
 
4138
  var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
 
4139
    var pos = 0, result = [], l = string.length;
 
4140
    while (pos <= l) {
 
4141
      var nl = string.indexOf("\n", pos);
 
4142
      if (nl == -1) nl = string.length;
 
4143
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
 
4144
      var rt = line.indexOf("\r");
 
4145
      if (rt != -1) {
 
4146
        result.push(line.slice(0, rt));
 
4147
        pos += rt + 1;
 
4148
      } else {
 
4149
        result.push(line);
 
4150
        pos = nl + 1;
 
4151
      }
 
4152
    }
 
4153
    return result;
 
4154
  } : function(string){return string.split(/\r\n?|\n/);};
 
4155
  CodeMirror.splitLines = splitLines;
 
4156
 
 
4157
  var hasSelection = window.getSelection ? function(te) {
 
4158
    try { return te.selectionStart != te.selectionEnd; }
 
4159
    catch(e) { return false; }
 
4160
  } : function(te) {
 
4161
    try {var range = te.ownerDocument.selection.createRange();}
 
4162
    catch(e) {}
 
4163
    if (!range || range.parentElement() != te) return false;
 
4164
    return range.compareEndPoints("StartToEnd", range) != 0;
 
4165
  };
 
4166
 
 
4167
  var hasCopyEvent = (function() {
 
4168
    var e = elt("div");
 
4169
    if ("oncopy" in e) return true;
 
4170
    e.setAttribute("oncopy", "return;");
 
4171
    return typeof e.oncopy == 'function';
 
4172
  })();
 
4173
 
 
4174
  // KEY NAMING
 
4175
 
 
4176
  var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
 
4177
                  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
 
4178
                  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
 
4179
                  46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
 
4180
                  186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
 
4181
                  221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
 
4182
                  63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
 
4183
  CodeMirror.keyNames = keyNames;
 
4184
  (function() {
 
4185
    // Number keys
 
4186
    for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
 
4187
    // Alphabetic keys
 
4188
    for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
 
4189
    // Function keys
 
4190
    for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
 
4191
  })();
 
4192
 
 
4193
  // BIDI HELPERS
 
4194
 
 
4195
  function iterateBidiSections(order, from, to, f) {
 
4196
    if (!order) return f(from, to, "ltr");
 
4197
    for (var i = 0; i < order.length; ++i) {
 
4198
      var part = order[i];
 
4199
      if (part.from < to && part.to > from)
 
4200
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
 
4201
    }
 
4202
  }
 
4203
 
 
4204
  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
 
4205
  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
 
4206
 
 
4207
  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
 
4208
  function lineRight(line) {
 
4209
    var order = getOrder(line);
 
4210
    if (!order) return line.text.length;
 
4211
    return bidiRight(lst(order));
 
4212
  }
 
4213
 
 
4214
  function lineStart(cm, lineNo) {
 
4215
    var merged, line;
 
4216
    while (merged = collapsedSpanAtStart(line = getLine(cm.view.doc, lineNo)))
 
4217
      lineNo = merged.find().from.line;
 
4218
    var order = getOrder(line);
 
4219
    var ch = !order ? 0 : order[0].level % 2 ? lineRight(line) : lineLeft(line);
 
4220
    return {line: lineNo, ch: ch};
 
4221
  }
 
4222
  function lineEnd(cm, lineNo) {
 
4223
    var merged, line;
 
4224
    while (merged = collapsedSpanAtEnd(line = getLine(cm.view.doc, lineNo)))
 
4225
      lineNo = merged.find().to.line;
 
4226
    var order = getOrder(line);
 
4227
    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
 
4228
    return {line: lineNo, ch: ch};
 
4229
  }
 
4230
 
 
4231
  // This is somewhat involved. It is needed in order to move
 
4232
  // 'visually' through bi-directional text -- i.e., pressing left
 
4233
  // should make the cursor go left, even when in RTL text. The
 
4234
  // tricky part is the 'jumps', where RTL and LTR text touch each
 
4235
  // other. This often requires the cursor offset to move more than
 
4236
  // one unit, in order to visually move one unit.
 
4237
  function moveVisually(line, start, dir, byUnit) {
 
4238
    var bidi = getOrder(line);
 
4239
    if (!bidi) return moveLogically(line, start, dir, byUnit);
 
4240
    var moveOneUnit = byUnit ? function(pos, dir) {
 
4241
      do pos += dir;
 
4242
      while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
 
4243
      return pos;
 
4244
    } : function(pos, dir) { return pos + dir; };
 
4245
    var linedir = bidi[0].level;
 
4246
    for (var i = 0; i < bidi.length; ++i) {
 
4247
      var part = bidi[i], sticky = part.level % 2 == linedir;
 
4248
      if ((part.from < start && part.to > start) ||
 
4249
          (sticky && (part.from == start || part.to == start))) break;
 
4250
    }
 
4251
    var target = moveOneUnit(start, part.level % 2 ? -dir : dir);
 
4252
 
 
4253
    while (target != null) {
 
4254
      if (part.level % 2 == linedir) {
 
4255
        if (target < part.from || target > part.to) {
 
4256
          part = bidi[i += dir];
 
4257
          target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1));
 
4258
        } else break;
 
4259
      } else {
 
4260
        if (target == bidiLeft(part)) {
 
4261
          part = bidi[--i];
 
4262
          target = part && bidiRight(part);
 
4263
        } else if (target == bidiRight(part)) {
 
4264
          part = bidi[++i];
 
4265
          target = part && bidiLeft(part);
 
4266
        } else break;
 
4267
      }
 
4268
    }
 
4269
 
 
4270
    return target < 0 || target > line.text.length ? null : target;
 
4271
  }
 
4272
 
 
4273
  function moveLogically(line, start, dir, byUnit) {
 
4274
    var target = start + dir;
 
4275
    if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
 
4276
    return target < 0 || target > line.text.length ? null : target;
 
4277
  }
 
4278
 
 
4279
  // Bidirectional ordering algorithm
 
4280
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
 
4281
  // that this (partially) implements.
 
4282
 
 
4283
  // One-char codes used for character types:
 
4284
  // L (L):   Left-to-Right
 
4285
  // R (R):   Right-to-Left
 
4286
  // r (AL):  Right-to-Left Arabic
 
4287
  // 1 (EN):  European Number
 
4288
  // + (ES):  European Number Separator
 
4289
  // % (ET):  European Number Terminator
 
4290
  // n (AN):  Arabic Number
 
4291
  // , (CS):  Common Number Separator
 
4292
  // m (NSM): Non-Spacing Mark
 
4293
  // b (BN):  Boundary Neutral
 
4294
  // s (B):   Paragraph Separator
 
4295
  // t (S):   Segment Separator
 
4296
  // w (WS):  Whitespace
 
4297
  // N (ON):  Other Neutrals
 
4298
 
 
4299
  // Returns null if characters are ordered as they appear
 
4300
  // (left-to-right), or an array of sections ({from, to, level}
 
4301
  // objects) in the order in which they occur visually.
 
4302
  var bidiOrdering = (function() {
 
4303
    // Character types for codepoints 0 to 0xff
 
4304
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
 
4305
    // Character types for codepoints 0x600 to 0x6ff
 
4306
    var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
 
4307
    function charType(code) {
 
4308
      var type = "L";
 
4309
      if (code <= 0xff) return lowTypes.charAt(code);
 
4310
      else if (0x590 <= code && code <= 0x5f4) return "R";
 
4311
      else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
 
4312
      else if (0x700 <= code && code <= 0x8ac) return "r";
 
4313
      else return "L";
 
4314
    }
 
4315
 
 
4316
    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
 
4317
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
 
4318
 
 
4319
    return function charOrdering(str) {
 
4320
      if (!bidiRE.test(str)) return false;
 
4321
      var len = str.length, types = [], startType = null;
 
4322
      for (var i = 0, type; i < len; ++i) {
 
4323
        types.push(type = charType(str.charCodeAt(i)));
 
4324
        if (startType == null) {
 
4325
          if (type == "L") startType = "L";
 
4326
          else if (type == "R" || type == "r") startType = "R";
 
4327
        }
 
4328
      }
 
4329
      if (startType == null) startType = "L";
 
4330
 
 
4331
      // W1. Examine each non-spacing mark (NSM) in the level run, and
 
4332
      // change the type of the NSM to the type of the previous
 
4333
      // character. If the NSM is at the start of the level run, it will
 
4334
      // get the type of sor.
 
4335
      for (var i = 0, prev = startType; i < len; ++i) {
 
4336
        var type = types[i];
 
4337
        if (type == "m") types[i] = prev;
 
4338
        else prev = type;
 
4339
      }
 
4340
 
 
4341
      // W2. Search backwards from each instance of a European number
 
4342
      // until the first strong type (R, L, AL, or sor) is found. If an
 
4343
      // AL is found, change the type of the European number to Arabic
 
4344
      // number.
 
4345
      // W3. Change all ALs to R.
 
4346
      for (var i = 0, cur = startType; i < len; ++i) {
 
4347
        var type = types[i];
 
4348
        if (type == "1" && cur == "r") types[i] = "n";
 
4349
        else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
 
4350
      }
 
4351
 
 
4352
      // W4. A single European separator between two European numbers
 
4353
      // changes to a European number. A single common separator between
 
4354
      // two numbers of the same type changes to that type.
 
4355
      for (var i = 1, prev = types[0]; i < len - 1; ++i) {
 
4356
        var type = types[i];
 
4357
        if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
 
4358
        else if (type == "," && prev == types[i+1] &&
 
4359
                 (prev == "1" || prev == "n")) types[i] = prev;
 
4360
        prev = type;
 
4361
      }
 
4362
 
 
4363
      // W5. A sequence of European terminators adjacent to European
 
4364
      // numbers changes to all European numbers.
 
4365
      // W6. Otherwise, separators and terminators change to Other
 
4366
      // Neutral.
 
4367
      for (var i = 0; i < len; ++i) {
 
4368
        var type = types[i];
 
4369
        if (type == ",") types[i] = "N";
 
4370
        else if (type == "%") {
 
4371
          for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
 
4372
          var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
 
4373
          for (var j = i; j < end; ++j) types[j] = replace;
 
4374
          i = end - 1;
 
4375
        }
 
4376
      }
 
4377
 
 
4378
      // W7. Search backwards from each instance of a European number
 
4379
      // until the first strong type (R, L, or sor) is found. If an L is
 
4380
      // found, then change the type of the European number to L.
 
4381
      for (var i = 0, cur = startType; i < len; ++i) {
 
4382
        var type = types[i];
 
4383
        if (cur == "L" && type == "1") types[i] = "L";
 
4384
        else if (isStrong.test(type)) cur = type;
 
4385
      }
 
4386
 
 
4387
      // N1. A sequence of neutrals takes the direction of the
 
4388
      // surrounding strong text if the text on both sides has the same
 
4389
      // direction. European and Arabic numbers act as if they were R in
 
4390
      // terms of their influence on neutrals. Start-of-level-run (sor)
 
4391
      // and end-of-level-run (eor) are used at level run boundaries.
 
4392
      // N2. Any remaining neutrals take the embedding direction.
 
4393
      for (var i = 0; i < len; ++i) {
 
4394
        if (isNeutral.test(types[i])) {
 
4395
          for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
 
4396
          var before = (i ? types[i-1] : startType) == "L";
 
4397
          var after = (end < len - 1 ? types[end] : startType) == "L";
 
4398
          var replace = before || after ? "L" : "R";
 
4399
          for (var j = i; j < end; ++j) types[j] = replace;
 
4400
          i = end - 1;
 
4401
        }
 
4402
      }
 
4403
 
 
4404
      // Here we depart from the documented algorithm, in order to avoid
 
4405
      // building up an actual levels array. Since there are only three
 
4406
      // levels (0, 1, 2) in an implementation that doesn't take
 
4407
      // explicit embedding into account, we can build up the order on
 
4408
      // the fly, without following the level-based algorithm.
 
4409
      var order = [], m;
 
4410
      for (var i = 0; i < len;) {
 
4411
        if (countsAsLeft.test(types[i])) {
 
4412
          var start = i;
 
4413
          for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
 
4414
          order.push({from: start, to: i, level: 0});
 
4415
        } else {
 
4416
          var pos = i, at = order.length;
 
4417
          for (++i; i < len && types[i] != "L"; ++i) {}
 
4418
          for (var j = pos; j < i;) {
 
4419
            if (countsAsNum.test(types[j])) {
 
4420
              if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
 
4421
              var nstart = j;
 
4422
              for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
 
4423
              order.splice(at, 0, {from: nstart, to: j, level: 2});
 
4424
              pos = j;
 
4425
            } else ++j;
 
4426
          }
 
4427
          if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
 
4428
        }
 
4429
      }
 
4430
      if (order[0].level == 1 && (m = str.match(/^\s+/))) {
 
4431
        order[0].from = m[0].length;
 
4432
        order.unshift({from: 0, to: m[0].length, level: 0});
 
4433
      }
 
4434
      if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
 
4435
        lst(order).to -= m[0].length;
 
4436
        order.push({from: len - m[0].length, to: len, level: 0});
 
4437
      }
 
4438
      if (order[0].level != lst(order).level)
 
4439
        order.push({from: len, to: len, level: order[0].level});
 
4440
 
 
4441
      return order;
 
4442
    };
 
4443
  })();
 
4444
 
 
4445
  // THE END
 
4446
 
 
4447
  CodeMirror.version = "3.0 B2";
 
4448
 
 
4449
  return CodeMirror;
 
4450
})();