Subversion-Projekte lars-tiefland.ci

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
776 lars 1
// CodeMirror, copyright (c) by Marijn Haverbeke and others
2
// Distributed under an MIT license: http://codemirror.net/LICENSE
3
 
4
// This is CodeMirror (http://codemirror.net), a code editor
5
// implemented in JavaScript on top of the browser's DOM.
6
//
7
// You can find some technical background for some of the code below
8
// at http://marijnhaverbeke.nl/blog/#cm-internals .
9
 
10
(function(mod) {
11
  if (typeof exports == "object" && typeof module == "object") // CommonJS
12
    module.exports = mod();
13
  else if (typeof define == "function" && define.amd) // AMD
14
    return define([], mod);
15
  else // Plain browser env
16
    this.CodeMirror = mod();
17
})(function() {
18
  "use strict";
19
 
20
  // BROWSER SNIFFING
21
 
22
  // Kludges for bugs and behavior differences that can't be feature
23
  // detected are enabled based on userAgent etc sniffing.
24
 
25
  var gecko = /gecko\/\d/i.test(navigator.userAgent);
26
  var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
27
  var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
28
  var ie = ie_upto10 || ie_11up;
29
  var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
30
  var webkit = /WebKit\//.test(navigator.userAgent);
31
  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
32
  var chrome = /Chrome\//.test(navigator.userAgent);
33
  var presto = /Opera\//.test(navigator.userAgent);
34
  var safari = /Apple Computer/.test(navigator.vendor);
35
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
36
  var phantom = /PhantomJS/.test(navigator.userAgent);
37
 
38
  var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
39
  // This is woefully incomplete. Suggestions for alternative methods welcome.
40
  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
41
  var mac = ios || /Mac/.test(navigator.platform);
42
  var windows = /win/i.test(navigator.platform);
43
 
44
  var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
45
  if (presto_version) presto_version = Number(presto_version[1]);
46
  if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
47
  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
48
  var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
49
  var captureRightClick = gecko || (ie && ie_version >= 9);
50
 
51
  // Optimize some code when these features are not used.
52
  var sawReadOnlySpans = false, sawCollapsedSpans = false;
53
 
54
  // EDITOR CONSTRUCTOR
55
 
56
  // A CodeMirror instance represents an editor. This is the object
57
  // that user code is usually dealing with.
58
 
59
  function CodeMirror(place, options) {
60
    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
61
 
62
    this.options = options = options ? copyObj(options) : {};
63
    // Determine effective options based on given values and defaults.
64
    copyObj(defaults, options, false);
65
    setGuttersForLineNumbers(options);
66
 
67
    var doc = options.value;
68
    if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
69
    this.doc = doc;
70
 
71
    var input = new CodeMirror.inputStyles[options.inputStyle](this);
72
    var display = this.display = new Display(place, doc, input);
73
    display.wrapper.CodeMirror = this;
74
    updateGutters(this);
75
    themeChanged(this);
76
    if (options.lineWrapping)
77
      this.display.wrapper.className += " CodeMirror-wrap";
78
    if (options.autofocus && !mobile) display.input.focus();
79
    initScrollbars(this);
80
 
81
    this.state = {
82
      keyMaps: [],  // stores maps added by addKeyMap
83
      overlays: [], // highlighting overlays, as added by addOverlay
84
      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
85
      overwrite: false,
86
      delayingBlurEvent: false,
87
      focused: false,
88
      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
89
      pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
90
      selectingText: false,
91
      draggingText: false,
92
      highlight: new Delayed(), // stores highlight worker timeout
93
      keySeq: null,  // Unfinished key sequence
94
      specialChars: null
95
    };
96
 
97
    var cm = this;
98
 
99
    // Override magic textarea content restore that IE sometimes does
100
    // on our hidden textarea on reload
101
    if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
102
 
103
    registerEventHandlers(this);
104
    ensureGlobalHandlers();
105
 
106
    startOperation(this);
107
    this.curOp.forceUpdate = true;
108
    attachDoc(this, doc);
109
 
110
    if ((options.autofocus && !mobile) || cm.hasFocus())
111
      setTimeout(bind(onFocus, this), 20);
112
    else
113
      onBlur(this);
114
 
115
    for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
116
      optionHandlers[opt](this, options[opt], Init);
117
    maybeUpdateLineNumberWidth(this);
118
    if (options.finishInit) options.finishInit(this);
119
    for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
120
    endOperation(this);
121
    // Suppress optimizelegibility in Webkit, since it breaks text
122
    // measuring on line wrapping boundaries.
123
    if (webkit && options.lineWrapping &&
124
        getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
125
      display.lineDiv.style.textRendering = "auto";
126
  }
127
 
128
  // DISPLAY CONSTRUCTOR
129
 
130
  // The display handles the DOM integration, both for input reading
131
  // and content drawing. It holds references to DOM nodes and
132
  // display-related state.
133
 
134
  function Display(place, doc, input) {
135
    var d = this;
136
    this.input = input;
137
 
138
    // Covers bottom-right square when both scrollbars are present.
139
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
140
    d.scrollbarFiller.setAttribute("cm-not-content", "true");
141
    // Covers bottom of gutter when coverGutterNextToScrollbar is on
142
    // and h scrollbar is present.
143
    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
144
    d.gutterFiller.setAttribute("cm-not-content", "true");
145
    // Will contain the actual code, positioned to cover the viewport.
146
    d.lineDiv = elt("div", null, "CodeMirror-code");
147
    // Elements are added to these to represent selection and cursors.
148
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
149
    d.cursorDiv = elt("div", null, "CodeMirror-cursors");
150
    // A visibility: hidden element used to find the size of things.
151
    d.measure = elt("div", null, "CodeMirror-measure");
152
    // When lines outside of the viewport are measured, they are drawn in this.
153
    d.lineMeasure = elt("div", null, "CodeMirror-measure");
154
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
155
    d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
156
                      null, "position: relative; outline: none");
157
    // Moved around its parent to cover visible view.
158
    d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
159
    // Set to the height of the document, allowing scrolling.
160
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
161
    d.sizerWidth = null;
162
    // Behavior of elts with overflow: auto and padding is
163
    // inconsistent across browsers. This is used to ensure the
164
    // scrollable area is big enough.
165
    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
166
    // Will contain the gutters, if any.
167
    d.gutters = elt("div", null, "CodeMirror-gutters");
168
    d.lineGutter = null;
169
    // Actual scrollable element.
170
    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
171
    d.scroller.setAttribute("tabIndex", "-1");
172
    // The element in which the editor lives.
173
    d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
174
 
175
    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
176
    if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
177
    if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
178
 
179
    if (place) {
180
      if (place.appendChild) place.appendChild(d.wrapper);
181
      else place(d.wrapper);
182
    }
183
 
184
    // Current rendered range (may be bigger than the view window).
185
    d.viewFrom = d.viewTo = doc.first;
186
    d.reportedViewFrom = d.reportedViewTo = doc.first;
187
    // Information about the rendered lines.
188
    d.view = [];
189
    d.renderedView = null;
190
    // Holds info about a single rendered line when it was rendered
191
    // for measurement, while not in view.
192
    d.externalMeasured = null;
193
    // Empty space (in pixels) above the view
194
    d.viewOffset = 0;
195
    d.lastWrapHeight = d.lastWrapWidth = 0;
196
    d.updateLineNumbers = null;
197
 
198
    d.nativeBarWidth = d.barHeight = d.barWidth = 0;
199
    d.scrollbarsClipped = false;
200
 
201
    // Used to only resize the line number gutter when necessary (when
202
    // the amount of lines crosses a boundary that makes its width change)
203
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
204
    // Set to true when a non-horizontal-scrolling line widget is
205
    // added. As an optimization, line widget aligning is skipped when
206
    // this is false.
207
    d.alignWidgets = false;
208
 
209
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
210
 
211
    // Tracks the maximum line length so that the horizontal scrollbar
212
    // can be kept static when scrolling.
213
    d.maxLine = null;
214
    d.maxLineLength = 0;
215
    d.maxLineChanged = false;
216
 
217
    // Used for measuring wheel scrolling granularity
218
    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
219
 
220
    // True when shift is held down.
221
    d.shift = false;
222
 
223
    // Used to track whether anything happened since the context menu
224
    // was opened.
225
    d.selForContextMenu = null;
226
 
227
    d.activeTouch = null;
228
 
229
    input.init(d);
230
  }
231
 
232
  // STATE UPDATES
233
 
234
  // Used to get the editor into a consistent state again when options change.
235
 
236
  function loadMode(cm) {
237
    cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
238
    resetModeState(cm);
239
  }
240
 
241
  function resetModeState(cm) {
242
    cm.doc.iter(function(line) {
243
      if (line.stateAfter) line.stateAfter = null;
244
      if (line.styles) line.styles = null;
245
    });
246
    cm.doc.frontier = cm.doc.first;
247
    startWorker(cm, 100);
248
    cm.state.modeGen++;
249
    if (cm.curOp) regChange(cm);
250
  }
251
 
252
  function wrappingChanged(cm) {
253
    if (cm.options.lineWrapping) {
254
      addClass(cm.display.wrapper, "CodeMirror-wrap");
255
      cm.display.sizer.style.minWidth = "";
256
      cm.display.sizerWidth = null;
257
    } else {
258
      rmClass(cm.display.wrapper, "CodeMirror-wrap");
259
      findMaxLine(cm);
260
    }
261
    estimateLineHeights(cm);
262
    regChange(cm);
263
    clearCaches(cm);
264
    setTimeout(function(){updateScrollbars(cm);}, 100);
265
  }
266
 
267
  // Returns a function that estimates the height of a line, to use as
268
  // first approximation until the line becomes visible (and is thus
269
  // properly measurable).
270
  function estimateHeight(cm) {
271
    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
272
    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
273
    return function(line) {
274
      if (lineIsHidden(cm.doc, line)) return 0;
275
 
276
      var widgetsHeight = 0;
277
      if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
278
        if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
279
      }
280
 
281
      if (wrapping)
282
        return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
283
      else
284
        return widgetsHeight + th;
285
    };
286
  }
287
 
288
  function estimateLineHeights(cm) {
289
    var doc = cm.doc, est = estimateHeight(cm);
290
    doc.iter(function(line) {
291
      var estHeight = est(line);
292
      if (estHeight != line.height) updateLineHeight(line, estHeight);
293
    });
294
  }
295
 
296
  function themeChanged(cm) {
297
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
298
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
299
    clearCaches(cm);
300
  }
301
 
302
  function guttersChanged(cm) {
303
    updateGutters(cm);
304
    regChange(cm);
305
    setTimeout(function(){alignHorizontally(cm);}, 20);
306
  }
307
 
308
  // Rebuild the gutter elements, ensure the margin to the left of the
309
  // code matches their width.
310
  function updateGutters(cm) {
311
    var gutters = cm.display.gutters, specs = cm.options.gutters;
312
    removeChildren(gutters);
313
    for (var i = 0; i < specs.length; ++i) {
314
      var gutterClass = specs[i];
315
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
316
      if (gutterClass == "CodeMirror-linenumbers") {
317
        cm.display.lineGutter = gElt;
318
        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
319
      }
320
    }
321
    gutters.style.display = i ? "" : "none";
322
    updateGutterSpace(cm);
323
  }
324
 
325
  function updateGutterSpace(cm) {
326
    var width = cm.display.gutters.offsetWidth;
327
    cm.display.sizer.style.marginLeft = width + "px";
328
  }
329
 
330
  // Compute the character length of a line, taking into account
331
  // collapsed ranges (see markText) that might hide parts, and join
332
  // other lines onto it.
333
  function lineLength(line) {
334
    if (line.height == 0) return 0;
335
    var len = line.text.length, merged, cur = line;
336
    while (merged = collapsedSpanAtStart(cur)) {
337
      var found = merged.find(0, true);
338
      cur = found.from.line;
339
      len += found.from.ch - found.to.ch;
340
    }
341
    cur = line;
342
    while (merged = collapsedSpanAtEnd(cur)) {
343
      var found = merged.find(0, true);
344
      len -= cur.text.length - found.from.ch;
345
      cur = found.to.line;
346
      len += cur.text.length - found.to.ch;
347
    }
348
    return len;
349
  }
350
 
351
  // Find the longest line in the document.
352
  function findMaxLine(cm) {
353
    var d = cm.display, doc = cm.doc;
354
    d.maxLine = getLine(doc, doc.first);
355
    d.maxLineLength = lineLength(d.maxLine);
356
    d.maxLineChanged = true;
357
    doc.iter(function(line) {
358
      var len = lineLength(line);
359
      if (len > d.maxLineLength) {
360
        d.maxLineLength = len;
361
        d.maxLine = line;
362
      }
363
    });
364
  }
365
 
366
  // Make sure the gutters options contains the element
367
  // "CodeMirror-linenumbers" when the lineNumbers option is true.
368
  function setGuttersForLineNumbers(options) {
369
    var found = indexOf(options.gutters, "CodeMirror-linenumbers");
370
    if (found == -1 && options.lineNumbers) {
371
      options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
372
    } else if (found > -1 && !options.lineNumbers) {
373
      options.gutters = options.gutters.slice(0);
374
      options.gutters.splice(found, 1);
375
    }
376
  }
377
 
378
  // SCROLLBARS
379
 
380
  // Prepare DOM reads needed to update the scrollbars. Done in one
381
  // shot to minimize update/measure roundtrips.
382
  function measureForScrollbars(cm) {
383
    var d = cm.display, gutterW = d.gutters.offsetWidth;
384
    var docH = Math.round(cm.doc.height + paddingVert(cm.display));
385
    return {
386
      clientHeight: d.scroller.clientHeight,
387
      viewHeight: d.wrapper.clientHeight,
388
      scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
389
      viewWidth: d.wrapper.clientWidth,
390
      barLeft: cm.options.fixedGutter ? gutterW : 0,
391
      docHeight: docH,
392
      scrollHeight: docH + scrollGap(cm) + d.barHeight,
393
      nativeBarWidth: d.nativeBarWidth,
394
      gutterWidth: gutterW
395
    };
396
  }
397
 
398
  function NativeScrollbars(place, scroll, cm) {
399
    this.cm = cm;
400
    var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
401
    var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
402
    place(vert); place(horiz);
403
 
404
    on(vert, "scroll", function() {
405
      if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
406
    });
407
    on(horiz, "scroll", function() {
408
      if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
409
    });
410
 
411
    this.checkedOverlay = false;
412
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
413
    if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
414
  }
415
 
416
  NativeScrollbars.prototype = copyObj({
417
    update: function(measure) {
418
      var needsH = measure.scrollWidth > measure.clientWidth + 1;
419
      var needsV = measure.scrollHeight > measure.clientHeight + 1;
420
      var sWidth = measure.nativeBarWidth;
421
 
422
      if (needsV) {
423
        this.vert.style.display = "block";
424
        this.vert.style.bottom = needsH ? sWidth + "px" : "0";
425
        var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
426
        // A bug in IE8 can cause this value to be negative, so guard it.
427
        this.vert.firstChild.style.height =
428
          Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
429
      } else {
430
        this.vert.style.display = "";
431
        this.vert.firstChild.style.height = "0";
432
      }
433
 
434
      if (needsH) {
435
        this.horiz.style.display = "block";
436
        this.horiz.style.right = needsV ? sWidth + "px" : "0";
437
        this.horiz.style.left = measure.barLeft + "px";
438
        var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
439
        this.horiz.firstChild.style.width =
440
          (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
441
      } else {
442
        this.horiz.style.display = "";
443
        this.horiz.firstChild.style.width = "0";
444
      }
445
 
446
      if (!this.checkedOverlay && measure.clientHeight > 0) {
447
        if (sWidth == 0) this.overlayHack();
448
        this.checkedOverlay = true;
449
      }
450
 
451
      return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
452
    },
453
    setScrollLeft: function(pos) {
454
      if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
455
    },
456
    setScrollTop: function(pos) {
457
      if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
458
    },
459
    overlayHack: function() {
460
      var w = mac && !mac_geMountainLion ? "12px" : "18px";
461
      this.horiz.style.minHeight = this.vert.style.minWidth = w;
462
      var self = this;
463
      var barMouseDown = function(e) {
464
        if (e_target(e) != self.vert && e_target(e) != self.horiz)
465
          operation(self.cm, onMouseDown)(e);
466
      };
467
      on(this.vert, "mousedown", barMouseDown);
468
      on(this.horiz, "mousedown", barMouseDown);
469
    },
470
    clear: function() {
471
      var parent = this.horiz.parentNode;
472
      parent.removeChild(this.horiz);
473
      parent.removeChild(this.vert);
474
    }
475
  }, NativeScrollbars.prototype);
476
 
477
  function NullScrollbars() {}
478
 
479
  NullScrollbars.prototype = copyObj({
480
    update: function() { return {bottom: 0, right: 0}; },
481
    setScrollLeft: function() {},
482
    setScrollTop: function() {},
483
    clear: function() {}
484
  }, NullScrollbars.prototype);
485
 
486
  CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
487
 
488
  function initScrollbars(cm) {
489
    if (cm.display.scrollbars) {
490
      cm.display.scrollbars.clear();
491
      if (cm.display.scrollbars.addClass)
492
        rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
493
    }
494
 
495
    cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
496
      cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
497
      // Prevent clicks in the scrollbars from killing focus
498
      on(node, "mousedown", function() {
499
        if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
500
      });
501
      node.setAttribute("cm-not-content", "true");
502
    }, function(pos, axis) {
503
      if (axis == "horizontal") setScrollLeft(cm, pos);
504
      else setScrollTop(cm, pos);
505
    }, cm);
506
    if (cm.display.scrollbars.addClass)
507
      addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
508
  }
509
 
510
  function updateScrollbars(cm, measure) {
511
    if (!measure) measure = measureForScrollbars(cm);
512
    var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
513
    updateScrollbarsInner(cm, measure);
514
    for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
515
      if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
516
        updateHeightsInViewport(cm);
517
      updateScrollbarsInner(cm, measureForScrollbars(cm));
518
      startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
519
    }
520
  }
521
 
522
  // Re-synchronize the fake scrollbars with the actual size of the
523
  // content.
524
  function updateScrollbarsInner(cm, measure) {
525
    var d = cm.display;
526
    var sizes = d.scrollbars.update(measure);
527
 
528
    d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
529
    d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
530
 
531
    if (sizes.right && sizes.bottom) {
532
      d.scrollbarFiller.style.display = "block";
533
      d.scrollbarFiller.style.height = sizes.bottom + "px";
534
      d.scrollbarFiller.style.width = sizes.right + "px";
535
    } else d.scrollbarFiller.style.display = "";
536
    if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
537
      d.gutterFiller.style.display = "block";
538
      d.gutterFiller.style.height = sizes.bottom + "px";
539
      d.gutterFiller.style.width = measure.gutterWidth + "px";
540
    } else d.gutterFiller.style.display = "";
541
  }
542
 
543
  // Compute the lines that are visible in a given viewport (defaults
544
  // the the current scroll position). viewport may contain top,
545
  // height, and ensure (see op.scrollToPos) properties.
546
  function visibleLines(display, doc, viewport) {
547
    var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
548
    top = Math.floor(top - paddingTop(display));
549
    var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
550
 
551
    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
552
    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
553
    // forces those lines into the viewport (if possible).
554
    if (viewport && viewport.ensure) {
555
      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
556
      if (ensureFrom < from) {
557
        from = ensureFrom;
558
        to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
559
      } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
560
        from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
561
        to = ensureTo;
562
      }
563
    }
564
    return {from: from, to: Math.max(to, from + 1)};
565
  }
566
 
567
  // LINE NUMBERS
568
 
569
  // Re-align line numbers and gutter marks to compensate for
570
  // horizontal scrolling.
571
  function alignHorizontally(cm) {
572
    var display = cm.display, view = display.view;
573
    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
574
    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
575
    var gutterW = display.gutters.offsetWidth, left = comp + "px";
576
    for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
577
      if (cm.options.fixedGutter && view[i].gutter)
578
        view[i].gutter.style.left = left;
579
      var align = view[i].alignable;
580
      if (align) for (var j = 0; j < align.length; j++)
581
        align[j].style.left = left;
582
    }
583
    if (cm.options.fixedGutter)
584
      display.gutters.style.left = (comp + gutterW) + "px";
585
  }
586
 
587
  // Used to ensure that the line number gutter is still the right
588
  // size for the current document size. Returns true when an update
589
  // is needed.
590
  function maybeUpdateLineNumberWidth(cm) {
591
    if (!cm.options.lineNumbers) return false;
592
    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
593
    if (last.length != display.lineNumChars) {
594
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
595
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
596
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
597
      display.lineGutter.style.width = "";
598
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
599
      display.lineNumWidth = display.lineNumInnerWidth + padding;
600
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
601
      display.lineGutter.style.width = display.lineNumWidth + "px";
602
      updateGutterSpace(cm);
603
      return true;
604
    }
605
    return false;
606
  }
607
 
608
  function lineNumberFor(options, i) {
609
    return String(options.lineNumberFormatter(i + options.firstLineNumber));
610
  }
611
 
612
  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
613
  // but using getBoundingClientRect to get a sub-pixel-accurate
614
  // result.
615
  function compensateForHScroll(display) {
616
    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
617
  }
618
 
619
  // DISPLAY DRAWING
620
 
621
  function DisplayUpdate(cm, viewport, force) {
622
    var display = cm.display;
623
 
624
    this.viewport = viewport;
625
    // Store some values that we'll need later (but don't want to force a relayout for)
626
    this.visible = visibleLines(display, cm.doc, viewport);
627
    this.editorIsHidden = !display.wrapper.offsetWidth;
628
    this.wrapperHeight = display.wrapper.clientHeight;
629
    this.wrapperWidth = display.wrapper.clientWidth;
630
    this.oldDisplayWidth = displayWidth(cm);
631
    this.force = force;
632
    this.dims = getDimensions(cm);
633
    this.events = [];
634
  }
635
 
636
  DisplayUpdate.prototype.signal = function(emitter, type) {
637
    if (hasHandler(emitter, type))
638
      this.events.push(arguments);
639
  };
640
  DisplayUpdate.prototype.finish = function() {
641
    for (var i = 0; i < this.events.length; i++)
642
      signal.apply(null, this.events[i]);
643
  };
644
 
645
  function maybeClipScrollbars(cm) {
646
    var display = cm.display;
647
    if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
648
      display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
649
      display.heightForcer.style.height = scrollGap(cm) + "px";
650
      display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
651
      display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
652
      display.scrollbarsClipped = true;
653
    }
654
  }
655
 
656
  // Does the actual updating of the line display. Bails out
657
  // (returning false) when there is nothing to be done and forced is
658
  // false.
659
  function updateDisplayIfNeeded(cm, update) {
660
    var display = cm.display, doc = cm.doc;
661
 
662
    if (update.editorIsHidden) {
663
      resetView(cm);
664
      return false;
665
    }
666
 
667
    // Bail out if the visible area is already rendered and nothing changed.
668
    if (!update.force &&
669
        update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
670
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
671
        display.renderedView == display.view && countDirtyView(cm) == 0)
672
      return false;
673
 
674
    if (maybeUpdateLineNumberWidth(cm)) {
675
      resetView(cm);
676
      update.dims = getDimensions(cm);
677
    }
678
 
679
    // Compute a suitable new viewport (from & to)
680
    var end = doc.first + doc.size;
681
    var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
682
    var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
683
    if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
684
    if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
685
    if (sawCollapsedSpans) {
686
      from = visualLineNo(cm.doc, from);
687
      to = visualLineEndNo(cm.doc, to);
688
    }
689
 
690
    var different = from != display.viewFrom || to != display.viewTo ||
691
      display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
692
    adjustView(cm, from, to);
693
 
694
    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
695
    // Position the mover div to align with the current scroll position
696
    cm.display.mover.style.top = display.viewOffset + "px";
697
 
698
    var toUpdate = countDirtyView(cm);
699
    if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
700
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
701
      return false;
702
 
703
    // For big changes, we hide the enclosing element during the
704
    // update, since that speeds up the operations on most browsers.
705
    var focused = activeElt();
706
    if (toUpdate > 4) display.lineDiv.style.display = "none";
707
    patchDisplay(cm, display.updateLineNumbers, update.dims);
708
    if (toUpdate > 4) display.lineDiv.style.display = "";
709
    display.renderedView = display.view;
710
    // There might have been a widget with a focused element that got
711
    // hidden or updated, if so re-focus it.
712
    if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
713
 
714
    // Prevent selection and cursors from interfering with the scroll
715
    // width and height.
716
    removeChildren(display.cursorDiv);
717
    removeChildren(display.selectionDiv);
718
    display.gutters.style.height = display.sizer.style.minHeight = 0;
719
 
720
    if (different) {
721
      display.lastWrapHeight = update.wrapperHeight;
722
      display.lastWrapWidth = update.wrapperWidth;
723
      startWorker(cm, 400);
724
    }
725
 
726
    display.updateLineNumbers = null;
727
 
728
    return true;
729
  }
730
 
731
  function postUpdateDisplay(cm, update) {
732
    var viewport = update.viewport;
733
    for (var first = true;; first = false) {
734
      if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
735
        // Clip forced viewport to actual scrollable area.
736
        if (viewport && viewport.top != null)
737
          viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
738
        // Updated line heights might result in the drawn area not
739
        // actually covering the viewport. Keep looping until it does.
740
        update.visible = visibleLines(cm.display, cm.doc, viewport);
741
        if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
742
          break;
743
      }
744
      if (!updateDisplayIfNeeded(cm, update)) break;
745
      updateHeightsInViewport(cm);
746
      var barMeasure = measureForScrollbars(cm);
747
      updateSelection(cm);
748
      setDocumentHeight(cm, barMeasure);
749
      updateScrollbars(cm, barMeasure);
750
    }
751
 
752
    update.signal(cm, "update", cm);
753
    if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
754
      update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
755
      cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
756
    }
757
  }
758
 
759
  function updateDisplaySimple(cm, viewport) {
760
    var update = new DisplayUpdate(cm, viewport);
761
    if (updateDisplayIfNeeded(cm, update)) {
762
      updateHeightsInViewport(cm);
763
      postUpdateDisplay(cm, update);
764
      var barMeasure = measureForScrollbars(cm);
765
      updateSelection(cm);
766
      setDocumentHeight(cm, barMeasure);
767
      updateScrollbars(cm, barMeasure);
768
      update.finish();
769
    }
770
  }
771
 
772
  function setDocumentHeight(cm, measure) {
773
    cm.display.sizer.style.minHeight = measure.docHeight + "px";
774
    var total = measure.docHeight + cm.display.barHeight;
775
    cm.display.heightForcer.style.top = total + "px";
776
    cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
777
  }
778
 
779
  // Read the actual heights of the rendered lines, and update their
780
  // stored heights to match.
781
  function updateHeightsInViewport(cm) {
782
    var display = cm.display;
783
    var prevBottom = display.lineDiv.offsetTop;
784
    for (var i = 0; i < display.view.length; i++) {
785
      var cur = display.view[i], height;
786
      if (cur.hidden) continue;
787
      if (ie && ie_version < 8) {
788
        var bot = cur.node.offsetTop + cur.node.offsetHeight;
789
        height = bot - prevBottom;
790
        prevBottom = bot;
791
      } else {
792
        var box = cur.node.getBoundingClientRect();
793
        height = box.bottom - box.top;
794
      }
795
      var diff = cur.line.height - height;
796
      if (height < 2) height = textHeight(display);
797
      if (diff > .001 || diff < -.001) {
798
        updateLineHeight(cur.line, height);
799
        updateWidgetHeight(cur.line);
800
        if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
801
          updateWidgetHeight(cur.rest[j]);
802
      }
803
    }
804
  }
805
 
806
  // Read and store the height of line widgets associated with the
807
  // given line.
808
  function updateWidgetHeight(line) {
809
    if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
810
      line.widgets[i].height = line.widgets[i].node.offsetHeight;
811
  }
812
 
813
  // Do a bulk-read of the DOM positions and sizes needed to draw the
814
  // view, so that we don't interleave reading and writing to the DOM.
815
  function getDimensions(cm) {
816
    var d = cm.display, left = {}, width = {};
817
    var gutterLeft = d.gutters.clientLeft;
818
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
819
      left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
820
      width[cm.options.gutters[i]] = n.clientWidth;
821
    }
822
    return {fixedPos: compensateForHScroll(d),
823
            gutterTotalWidth: d.gutters.offsetWidth,
824
            gutterLeft: left,
825
            gutterWidth: width,
826
            wrapperWidth: d.wrapper.clientWidth};
827
  }
828
 
829
  // Sync the actual display DOM structure with display.view, removing
830
  // nodes for lines that are no longer in view, and creating the ones
831
  // that are not there yet, and updating the ones that are out of
832
  // date.
833
  function patchDisplay(cm, updateNumbersFrom, dims) {
834
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
835
    var container = display.lineDiv, cur = container.firstChild;
836
 
837
    function rm(node) {
838
      var next = node.nextSibling;
839
      // Works around a throw-scroll bug in OS X Webkit
840
      if (webkit && mac && cm.display.currentWheelTarget == node)
841
        node.style.display = "none";
842
      else
843
        node.parentNode.removeChild(node);
844
      return next;
845
    }
846
 
847
    var view = display.view, lineN = display.viewFrom;
848
    // Loop over the elements in the view, syncing cur (the DOM nodes
849
    // in display.lineDiv) with the view as we go.
850
    for (var i = 0; i < view.length; i++) {
851
      var lineView = view[i];
852
      if (lineView.hidden) {
853
      } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
854
        var node = buildLineElement(cm, lineView, lineN, dims);
855
        container.insertBefore(node, cur);
856
      } else { // Already drawn
857
        while (cur != lineView.node) cur = rm(cur);
858
        var updateNumber = lineNumbers && updateNumbersFrom != null &&
859
          updateNumbersFrom <= lineN && lineView.lineNumber;
860
        if (lineView.changes) {
861
          if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
862
          updateLineForChanges(cm, lineView, lineN, dims);
863
        }
864
        if (updateNumber) {
865
          removeChildren(lineView.lineNumber);
866
          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
867
        }
868
        cur = lineView.node.nextSibling;
869
      }
870
      lineN += lineView.size;
871
    }
872
    while (cur) cur = rm(cur);
873
  }
874
 
875
  // When an aspect of a line changes, a string is added to
876
  // lineView.changes. This updates the relevant part of the line's
877
  // DOM structure.
878
  function updateLineForChanges(cm, lineView, lineN, dims) {
879
    for (var j = 0; j < lineView.changes.length; j++) {
880
      var type = lineView.changes[j];
881
      if (type == "text") updateLineText(cm, lineView);
882
      else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
883
      else if (type == "class") updateLineClasses(lineView);
884
      else if (type == "widget") updateLineWidgets(cm, lineView, dims);
885
    }
886
    lineView.changes = null;
887
  }
888
 
889
  // Lines with gutter elements, widgets or a background class need to
890
  // be wrapped, and have the extra elements added to the wrapper div
891
  function ensureLineWrapped(lineView) {
892
    if (lineView.node == lineView.text) {
893
      lineView.node = elt("div", null, null, "position: relative");
894
      if (lineView.text.parentNode)
895
        lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
896
      lineView.node.appendChild(lineView.text);
897
      if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
898
    }
899
    return lineView.node;
900
  }
901
 
902
  function updateLineBackground(lineView) {
903
    var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
904
    if (cls) cls += " CodeMirror-linebackground";
905
    if (lineView.background) {
906
      if (cls) lineView.background.className = cls;
907
      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
908
    } else if (cls) {
909
      var wrap = ensureLineWrapped(lineView);
910
      lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
911
    }
912
  }
913
 
914
  // Wrapper around buildLineContent which will reuse the structure
915
  // in display.externalMeasured when possible.
916
  function getLineContent(cm, lineView) {
917
    var ext = cm.display.externalMeasured;
918
    if (ext && ext.line == lineView.line) {
919
      cm.display.externalMeasured = null;
920
      lineView.measure = ext.measure;
921
      return ext.built;
922
    }
923
    return buildLineContent(cm, lineView);
924
  }
925
 
926
  // Redraw the line's text. Interacts with the background and text
927
  // classes because the mode may output tokens that influence these
928
  // classes.
929
  function updateLineText(cm, lineView) {
930
    var cls = lineView.text.className;
931
    var built = getLineContent(cm, lineView);
932
    if (lineView.text == lineView.node) lineView.node = built.pre;
933
    lineView.text.parentNode.replaceChild(built.pre, lineView.text);
934
    lineView.text = built.pre;
935
    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
936
      lineView.bgClass = built.bgClass;
937
      lineView.textClass = built.textClass;
938
      updateLineClasses(lineView);
939
    } else if (cls) {
940
      lineView.text.className = cls;
941
    }
942
  }
943
 
944
  function updateLineClasses(lineView) {
945
    updateLineBackground(lineView);
946
    if (lineView.line.wrapClass)
947
      ensureLineWrapped(lineView).className = lineView.line.wrapClass;
948
    else if (lineView.node != lineView.text)
949
      lineView.node.className = "";
950
    var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
951
    lineView.text.className = textClass || "";
952
  }
953
 
954
  function updateLineGutter(cm, lineView, lineN, dims) {
955
    if (lineView.gutter) {
956
      lineView.node.removeChild(lineView.gutter);
957
      lineView.gutter = null;
958
    }
959
    if (lineView.gutterBackground) {
960
      lineView.node.removeChild(lineView.gutterBackground);
961
      lineView.gutterBackground = null;
962
    }
963
    if (lineView.line.gutterClass) {
964
      var wrap = ensureLineWrapped(lineView);
965
      lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
966
                                      "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
967
                                      "px; width: " + dims.gutterTotalWidth + "px");
968
      wrap.insertBefore(lineView.gutterBackground, lineView.text);
969
    }
970
    var markers = lineView.line.gutterMarkers;
971
    if (cm.options.lineNumbers || markers) {
972
      var wrap = ensureLineWrapped(lineView);
973
      var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
974
                                             (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
975
      cm.display.input.setUneditable(gutterWrap);
976
      wrap.insertBefore(gutterWrap, lineView.text);
977
      if (lineView.line.gutterClass)
978
        gutterWrap.className += " " + lineView.line.gutterClass;
979
      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
980
        lineView.lineNumber = gutterWrap.appendChild(
981
          elt("div", lineNumberFor(cm.options, lineN),
982
              "CodeMirror-linenumber CodeMirror-gutter-elt",
983
              "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
984
              + cm.display.lineNumInnerWidth + "px"));
985
      if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
986
        var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
987
        if (found)
988
          gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
989
                                     dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
990
      }
991
    }
992
  }
993
 
994
  function updateLineWidgets(cm, lineView, dims) {
995
    if (lineView.alignable) lineView.alignable = null;
996
    for (var node = lineView.node.firstChild, next; node; node = next) {
997
      var next = node.nextSibling;
998
      if (node.className == "CodeMirror-linewidget")
999
        lineView.node.removeChild(node);
1000
    }
1001
    insertLineWidgets(cm, lineView, dims);
1002
  }
1003
 
1004
  // Build a line's DOM representation from scratch
1005
  function buildLineElement(cm, lineView, lineN, dims) {
1006
    var built = getLineContent(cm, lineView);
1007
    lineView.text = lineView.node = built.pre;
1008
    if (built.bgClass) lineView.bgClass = built.bgClass;
1009
    if (built.textClass) lineView.textClass = built.textClass;
1010
 
1011
    updateLineClasses(lineView);
1012
    updateLineGutter(cm, lineView, lineN, dims);
1013
    insertLineWidgets(cm, lineView, dims);
1014
    return lineView.node;
1015
  }
1016
 
1017
  // A lineView may contain multiple logical lines (when merged by
1018
  // collapsed spans). The widgets for all of them need to be drawn.
1019
  function insertLineWidgets(cm, lineView, dims) {
1020
    insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
1021
    if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
1022
      insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
1023
  }
1024
 
1025
  function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
1026
    if (!line.widgets) return;
1027
    var wrap = ensureLineWrapped(lineView);
1028
    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
1029
      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
1030
      if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
1031
      positionLineWidget(widget, node, lineView, dims);
1032
      cm.display.input.setUneditable(node);
1033
      if (allowAbove && widget.above)
1034
        wrap.insertBefore(node, lineView.gutter || lineView.text);
1035
      else
1036
        wrap.appendChild(node);
1037
      signalLater(widget, "redraw");
1038
    }
1039
  }
1040
 
1041
  function positionLineWidget(widget, node, lineView, dims) {
1042
    if (widget.noHScroll) {
1043
      (lineView.alignable || (lineView.alignable = [])).push(node);
1044
      var width = dims.wrapperWidth;
1045
      node.style.left = dims.fixedPos + "px";
1046
      if (!widget.coverGutter) {
1047
        width -= dims.gutterTotalWidth;
1048
        node.style.paddingLeft = dims.gutterTotalWidth + "px";
1049
      }
1050
      node.style.width = width + "px";
1051
    }
1052
    if (widget.coverGutter) {
1053
      node.style.zIndex = 5;
1054
      node.style.position = "relative";
1055
      if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
1056
    }
1057
  }
1058
 
1059
  // POSITION OBJECT
1060
 
1061
  // A Pos instance represents a position within the text.
1062
  var Pos = CodeMirror.Pos = function(line, ch) {
1063
    if (!(this instanceof Pos)) return new Pos(line, ch);
1064
    this.line = line; this.ch = ch;
1065
  };
1066
 
1067
  // Compare two positions, return 0 if they are the same, a negative
1068
  // number when a is less, and a positive number otherwise.
1069
  var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
1070
 
1071
  function copyPos(x) {return Pos(x.line, x.ch);}
1072
  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
1073
  function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
1074
 
1075
  // INPUT HANDLING
1076
 
1077
  function ensureFocus(cm) {
1078
    if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
1079
  }
1080
 
1081
  function isReadOnly(cm) {
1082
    return cm.options.readOnly || cm.doc.cantEdit;
1083
  }
1084
 
1085
  // This will be set to an array of strings when copying, so that,
1086
  // when pasting, we know what kind of selections the copied text
1087
  // was made out of.
1088
  var lastCopied = null;
1089
 
1090
  function applyTextInput(cm, inserted, deleted, sel, origin) {
1091
    var doc = cm.doc;
1092
    cm.display.shift = false;
1093
    if (!sel) sel = doc.sel;
1094
 
1095
    var paste = cm.state.pasteIncoming || origin == "paste";
1096
    var textLines = doc.splitLines(inserted), multiPaste = null;
1097
    // When pasing N lines into N selections, insert one line per selection
1098
    if (paste && sel.ranges.length > 1) {
1099
      if (lastCopied && lastCopied.join("\n") == inserted) {
1100
        if (sel.ranges.length % lastCopied.length == 0) {
1101
          multiPaste = [];
1102
          for (var i = 0; i < lastCopied.length; i++)
1103
            multiPaste.push(doc.splitLines(lastCopied[i]));
1104
        }
1105
      } else if (textLines.length == sel.ranges.length) {
1106
        multiPaste = map(textLines, function(l) { return [l]; });
1107
      }
1108
    }
1109
 
1110
    // Normal behavior is to insert the new text into every selection
1111
    for (var i = sel.ranges.length - 1; i >= 0; i--) {
1112
      var range = sel.ranges[i];
1113
      var from = range.from(), to = range.to();
1114
      if (range.empty()) {
1115
        if (deleted && deleted > 0) // Handle deletion
1116
          from = Pos(from.line, from.ch - deleted);
1117
        else if (cm.state.overwrite && !paste) // Handle overwrite
1118
          to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
1119
      }
1120
      var updateInput = cm.curOp.updateInput;
1121
      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
1122
                         origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
1123
      makeChange(cm.doc, changeEvent);
1124
      signalLater(cm, "inputRead", cm, changeEvent);
1125
    }
1126
    if (inserted && !paste)
1127
      triggerElectric(cm, inserted);
1128
 
1129
    ensureCursorVisible(cm);
1130
    cm.curOp.updateInput = updateInput;
1131
    cm.curOp.typing = true;
1132
    cm.state.pasteIncoming = cm.state.cutIncoming = false;
1133
  }
1134
 
1135
  function handlePaste(e, cm) {
1136
    var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
1137
    if (pasted) {
1138
      e.preventDefault();
1139
      if (!isReadOnly(cm) && !cm.options.disableInput)
1140
        runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
1141
      return true;
1142
    }
1143
  }
1144
 
1145
  function triggerElectric(cm, inserted) {
1146
    // When an 'electric' character is inserted, immediately trigger a reindent
1147
    if (!cm.options.electricChars || !cm.options.smartIndent) return;
1148
    var sel = cm.doc.sel;
1149
 
1150
    for (var i = sel.ranges.length - 1; i >= 0; i--) {
1151
      var range = sel.ranges[i];
1152
      if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
1153
      var mode = cm.getModeAt(range.head);
1154
      var indented = false;
1155
      if (mode.electricChars) {
1156
        for (var j = 0; j < mode.electricChars.length; j++)
1157
          if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
1158
            indented = indentLine(cm, range.head.line, "smart");
1159
            break;
1160
          }
1161
      } else if (mode.electricInput) {
1162
        if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
1163
          indented = indentLine(cm, range.head.line, "smart");
1164
      }
1165
      if (indented) signalLater(cm, "electricInput", cm, range.head.line);
1166
    }
1167
  }
1168
 
1169
  function copyableRanges(cm) {
1170
    var text = [], ranges = [];
1171
    for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
1172
      var line = cm.doc.sel.ranges[i].head.line;
1173
      var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
1174
      ranges.push(lineRange);
1175
      text.push(cm.getRange(lineRange.anchor, lineRange.head));
1176
    }
1177
    return {text: text, ranges: ranges};
1178
  }
1179
 
1180
  function disableBrowserMagic(field) {
1181
    field.setAttribute("autocorrect", "off");
1182
    field.setAttribute("autocapitalize", "off");
1183
    field.setAttribute("spellcheck", "false");
1184
  }
1185
 
1186
  // TEXTAREA INPUT STYLE
1187
 
1188
  function TextareaInput(cm) {
1189
    this.cm = cm;
1190
    // See input.poll and input.reset
1191
    this.prevInput = "";
1192
 
1193
    // Flag that indicates whether we expect input to appear real soon
1194
    // now (after some event like 'keypress' or 'input') and are
1195
    // polling intensively.
1196
    this.pollingFast = false;
1197
    // Self-resetting timeout for the poller
1198
    this.polling = new Delayed();
1199
    // Tracks when input.reset has punted to just putting a short
1200
    // string into the textarea instead of the full selection.
1201
    this.inaccurateSelection = false;
1202
    // Used to work around IE issue with selection being forgotten when focus moves away from textarea
1203
    this.hasSelection = false;
1204
    this.composing = null;
1205
  };
1206
 
1207
  function hiddenTextarea() {
1208
    var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
1209
    var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
1210
    // The textarea is kept positioned near the cursor to prevent the
1211
    // fact that it'll be scrolled into view on input from scrolling
1212
    // our fake cursor out of view. On webkit, when wrap=off, paste is
1213
    // very slow. So make the area wide instead.
1214
    if (webkit) te.style.width = "1000px";
1215
    else te.setAttribute("wrap", "off");
1216
    // If border: 0; -- iOS fails to open keyboard (issue #1287)
1217
    if (ios) te.style.border = "1px solid black";
1218
    disableBrowserMagic(te);
1219
    return div;
1220
  }
1221
 
1222
  TextareaInput.prototype = copyObj({
1223
    init: function(display) {
1224
      var input = this, cm = this.cm;
1225
 
1226
      // Wraps and hides input textarea
1227
      var div = this.wrapper = hiddenTextarea();
1228
      // The semihidden textarea that is focused when the editor is
1229
      // focused, and receives input.
1230
      var te = this.textarea = div.firstChild;
1231
      display.wrapper.insertBefore(div, display.wrapper.firstChild);
1232
 
1233
      // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
1234
      if (ios) te.style.width = "0px";
1235
 
1236
      on(te, "input", function() {
1237
        if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
1238
        input.poll();
1239
      });
1240
 
1241
      on(te, "paste", function(e) {
1242
        if (handlePaste(e, cm)) return true;
1243
 
1244
        cm.state.pasteIncoming = true;
1245
        input.fastPoll();
1246
      });
1247
 
1248
      function prepareCopyCut(e) {
1249
        if (cm.somethingSelected()) {
1250
          lastCopied = cm.getSelections();
1251
          if (input.inaccurateSelection) {
1252
            input.prevInput = "";
1253
            input.inaccurateSelection = false;
1254
            te.value = lastCopied.join("\n");
1255
            selectInput(te);
1256
          }
1257
        } else if (!cm.options.lineWiseCopyCut) {
1258
          return;
1259
        } else {
1260
          var ranges = copyableRanges(cm);
1261
          lastCopied = ranges.text;
1262
          if (e.type == "cut") {
1263
            cm.setSelections(ranges.ranges, null, sel_dontScroll);
1264
          } else {
1265
            input.prevInput = "";
1266
            te.value = ranges.text.join("\n");
1267
            selectInput(te);
1268
          }
1269
        }
1270
        if (e.type == "cut") cm.state.cutIncoming = true;
1271
      }
1272
      on(te, "cut", prepareCopyCut);
1273
      on(te, "copy", prepareCopyCut);
1274
 
1275
      on(display.scroller, "paste", function(e) {
1276
        if (eventInWidget(display, e)) return;
1277
        cm.state.pasteIncoming = true;
1278
        input.focus();
1279
      });
1280
 
1281
      // Prevent normal selection in the editor (we handle our own)
1282
      on(display.lineSpace, "selectstart", function(e) {
1283
        if (!eventInWidget(display, e)) e_preventDefault(e);
1284
      });
1285
 
1286
      on(te, "compositionstart", function() {
1287
        var start = cm.getCursor("from");
1288
        input.composing = {
1289
          start: start,
1290
          range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
1291
        };
1292
      });
1293
      on(te, "compositionend", function() {
1294
        if (input.composing) {
1295
          input.poll();
1296
          input.composing.range.clear();
1297
          input.composing = null;
1298
        }
1299
      });
1300
    },
1301
 
1302
    prepareSelection: function() {
1303
      // Redraw the selection and/or cursor
1304
      var cm = this.cm, display = cm.display, doc = cm.doc;
1305
      var result = prepareSelection(cm);
1306
 
1307
      // Move the hidden textarea near the cursor to prevent scrolling artifacts
1308
      if (cm.options.moveInputWithCursor) {
1309
        var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1310
        var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1311
        result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1312
                                            headPos.top + lineOff.top - wrapOff.top));
1313
        result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1314
                                             headPos.left + lineOff.left - wrapOff.left));
1315
      }
1316
 
1317
      return result;
1318
    },
1319
 
1320
    showSelection: function(drawn) {
1321
      var cm = this.cm, display = cm.display;
1322
      removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
1323
      removeChildrenAndAdd(display.selectionDiv, drawn.selection);
1324
      if (drawn.teTop != null) {
1325
        this.wrapper.style.top = drawn.teTop + "px";
1326
        this.wrapper.style.left = drawn.teLeft + "px";
1327
      }
1328
    },
1329
 
1330
    // Reset the input to correspond to the selection (or to be empty,
1331
    // when not typing and nothing is selected)
1332
    reset: function(typing) {
1333
      if (this.contextMenuPending) return;
1334
      var minimal, selected, cm = this.cm, doc = cm.doc;
1335
      if (cm.somethingSelected()) {
1336
        this.prevInput = "";
1337
        var range = doc.sel.primary();
1338
        minimal = hasCopyEvent &&
1339
          (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
1340
        var content = minimal ? "-" : selected || cm.getSelection();
1341
        this.textarea.value = content;
1342
        if (cm.state.focused) selectInput(this.textarea);
1343
        if (ie && ie_version >= 9) this.hasSelection = content;
1344
      } else if (!typing) {
1345
        this.prevInput = this.textarea.value = "";
1346
        if (ie && ie_version >= 9) this.hasSelection = null;
1347
      }
1348
      this.inaccurateSelection = minimal;
1349
    },
1350
 
1351
    getField: function() { return this.textarea; },
1352
 
1353
    supportsTouch: function() { return false; },
1354
 
1355
    focus: function() {
1356
      if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
1357
        try { this.textarea.focus(); }
1358
        catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
1359
      }
1360
    },
1361
 
1362
    blur: function() { this.textarea.blur(); },
1363
 
1364
    resetPosition: function() {
1365
      this.wrapper.style.top = this.wrapper.style.left = 0;
1366
    },
1367
 
1368
    receivedFocus: function() { this.slowPoll(); },
1369
 
1370
    // Poll for input changes, using the normal rate of polling. This
1371
    // runs as long as the editor is focused.
1372
    slowPoll: function() {
1373
      var input = this;
1374
      if (input.pollingFast) return;
1375
      input.polling.set(this.cm.options.pollInterval, function() {
1376
        input.poll();
1377
        if (input.cm.state.focused) input.slowPoll();
1378
      });
1379
    },
1380
 
1381
    // When an event has just come in that is likely to add or change
1382
    // something in the input textarea, we poll faster, to ensure that
1383
    // the change appears on the screen quickly.
1384
    fastPoll: function() {
1385
      var missed = false, input = this;
1386
      input.pollingFast = true;
1387
      function p() {
1388
        var changed = input.poll();
1389
        if (!changed && !missed) {missed = true; input.polling.set(60, p);}
1390
        else {input.pollingFast = false; input.slowPoll();}
1391
      }
1392
      input.polling.set(20, p);
1393
    },
1394
 
1395
    // Read input from the textarea, and update the document to match.
1396
    // When something is selected, it is present in the textarea, and
1397
    // selected (unless it is huge, in which case a placeholder is
1398
    // used). When nothing is selected, the cursor sits after previously
1399
    // seen text (can be empty), which is stored in prevInput (we must
1400
    // not reset the textarea when typing, because that breaks IME).
1401
    poll: function() {
1402
      var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
1403
      // Since this is called a *lot*, try to bail out as cheaply as
1404
      // possible when it is clear that nothing happened. hasSelection
1405
      // will be the case when there is a lot of text in the textarea,
1406
      // in which case reading its value would be expensive.
1407
      if (this.contextMenuPending || !cm.state.focused ||
1408
          (hasSelection(input) && !prevInput && !this.composing) ||
1409
          isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
1410
        return false;
1411
 
1412
      var text = input.value;
1413
      // If nothing changed, bail.
1414
      if (text == prevInput && !cm.somethingSelected()) return false;
1415
      // Work around nonsensical selection resetting in IE9/10, and
1416
      // inexplicable appearance of private area unicode characters on
1417
      // some key combos in Mac (#2689).
1418
      if (ie && ie_version >= 9 && this.hasSelection === text ||
1419
          mac && /[\uf700-\uf7ff]/.test(text)) {
1420
        cm.display.input.reset();
1421
        return false;
1422
      }
1423
 
1424
      if (cm.doc.sel == cm.display.selForContextMenu) {
1425
        var first = text.charCodeAt(0);
1426
        if (first == 0x200b && !prevInput) prevInput = "\u200b";
1427
        if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
1428
      }
1429
      // Find the part of the input that is actually new
1430
      var same = 0, l = Math.min(prevInput.length, text.length);
1431
      while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1432
 
1433
      var self = this;
1434
      runInOp(cm, function() {
1435
        applyTextInput(cm, text.slice(same), prevInput.length - same,
1436
                       null, self.composing ? "*compose" : null);
1437
 
1438
        // Don't leave long text in the textarea, since it makes further polling slow
1439
        if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
1440
        else self.prevInput = text;
1441
 
1442
        if (self.composing) {
1443
          self.composing.range.clear();
1444
          self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
1445
                                             {className: "CodeMirror-composing"});
1446
        }
1447
      });
1448
      return true;
1449
    },
1450
 
1451
    ensurePolled: function() {
1452
      if (this.pollingFast && this.poll()) this.pollingFast = false;
1453
    },
1454
 
1455
    onKeyPress: function() {
1456
      if (ie && ie_version >= 9) this.hasSelection = null;
1457
      this.fastPoll();
1458
    },
1459
 
1460
    onContextMenu: function(e) {
1461
      var input = this, cm = input.cm, display = cm.display, te = input.textarea;
1462
      var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
1463
      if (!pos || presto) return; // Opera is difficult.
1464
 
1465
      // Reset the current text selection only if the click is done outside of the selection
1466
      // and 'resetSelectionOnContextMenu' option is true.
1467
      var reset = cm.options.resetSelectionOnContextMenu;
1468
      if (reset && cm.doc.sel.contains(pos) == -1)
1469
        operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
1470
 
1471
      var oldCSS = te.style.cssText;
1472
      input.wrapper.style.position = "absolute";
1473
      te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1474
        "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
1475
        (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
1476
        "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1477
      if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
1478
      display.input.focus();
1479
      if (webkit) window.scrollTo(null, oldScrollY);
1480
      display.input.reset();
1481
      // Adds "Select all" to context menu in FF
1482
      if (!cm.somethingSelected()) te.value = input.prevInput = " ";
1483
      input.contextMenuPending = true;
1484
      display.selForContextMenu = cm.doc.sel;
1485
      clearTimeout(display.detectingSelectAll);
1486
 
1487
      // Select-all will be greyed out if there's nothing to select, so
1488
      // this adds a zero-width space so that we can later check whether
1489
      // it got selected.
1490
      function prepareSelectAllHack() {
1491
        if (te.selectionStart != null) {
1492
          var selected = cm.somethingSelected();
1493
          var extval = "\u200b" + (selected ? te.value : "");
1494
          te.value = "\u21da"; // Used to catch context-menu undo
1495
          te.value = extval;
1496
          input.prevInput = selected ? "" : "\u200b";
1497
          te.selectionStart = 1; te.selectionEnd = extval.length;
1498
          // Re-set this, in case some other handler touched the
1499
          // selection in the meantime.
1500
          display.selForContextMenu = cm.doc.sel;
1501
        }
1502
      }
1503
      function rehide() {
1504
        input.contextMenuPending = false;
1505
        input.wrapper.style.position = "relative";
1506
        te.style.cssText = oldCSS;
1507
        if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
1508
 
1509
        // Try to detect the user choosing select-all
1510
        if (te.selectionStart != null) {
1511
          if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
1512
          var i = 0, poll = function() {
1513
            if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
1514
                te.selectionEnd > 0 && input.prevInput == "\u200b")
1515
              operation(cm, commands.selectAll)(cm);
1516
            else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
1517
            else display.input.reset();
1518
          };
1519
          display.detectingSelectAll = setTimeout(poll, 200);
1520
        }
1521
      }
1522
 
1523
      if (ie && ie_version >= 9) prepareSelectAllHack();
1524
      if (captureRightClick) {
1525
        e_stop(e);
1526
        var mouseup = function() {
1527
          off(window, "mouseup", mouseup);
1528
          setTimeout(rehide, 20);
1529
        };
1530
        on(window, "mouseup", mouseup);
1531
      } else {
1532
        setTimeout(rehide, 50);
1533
      }
1534
    },
1535
 
1536
    setUneditable: nothing,
1537
 
1538
    needsContentAttribute: false
1539
  }, TextareaInput.prototype);
1540
 
1541
  // CONTENTEDITABLE INPUT STYLE
1542
 
1543
  function ContentEditableInput(cm) {
1544
    this.cm = cm;
1545
    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
1546
    this.polling = new Delayed();
1547
    this.gracePeriod = false;
1548
  }
1549
 
1550
  ContentEditableInput.prototype = copyObj({
1551
    init: function(display) {
1552
      var input = this, cm = input.cm;
1553
      var div = input.div = display.lineDiv;
1554
      div.contentEditable = "true";
1555
      disableBrowserMagic(div);
1556
 
1557
      on(div, "paste", function(e) { handlePaste(e, cm); })
1558
 
1559
      on(div, "compositionstart", function(e) {
1560
        var data = e.data;
1561
        input.composing = {sel: cm.doc.sel, data: data, startData: data};
1562
        if (!data) return;
1563
        var prim = cm.doc.sel.primary();
1564
        var line = cm.getLine(prim.head.line);
1565
        var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
1566
        if (found > -1 && found <= prim.head.ch)
1567
          input.composing.sel = simpleSelection(Pos(prim.head.line, found),
1568
                                                Pos(prim.head.line, found + data.length));
1569
      });
1570
      on(div, "compositionupdate", function(e) {
1571
        input.composing.data = e.data;
1572
      });
1573
      on(div, "compositionend", function(e) {
1574
        var ours = input.composing;
1575
        if (!ours) return;
1576
        if (e.data != ours.startData && !/\u200b/.test(e.data))
1577
          ours.data = e.data;
1578
        // Need a small delay to prevent other code (input event,
1579
        // selection polling) from doing damage when fired right after
1580
        // compositionend.
1581
        setTimeout(function() {
1582
          if (!ours.handled)
1583
            input.applyComposition(ours);
1584
          if (input.composing == ours)
1585
            input.composing = null;
1586
        }, 50);
1587
      });
1588
 
1589
      on(div, "touchstart", function() {
1590
        input.forceCompositionEnd();
1591
      });
1592
 
1593
      on(div, "input", function() {
1594
        if (input.composing) return;
1595
        if (!input.pollContent())
1596
          runInOp(input.cm, function() {regChange(cm);});
1597
      });
1598
 
1599
      function onCopyCut(e) {
1600
        if (cm.somethingSelected()) {
1601
          lastCopied = cm.getSelections();
1602
          if (e.type == "cut") cm.replaceSelection("", null, "cut");
1603
        } else if (!cm.options.lineWiseCopyCut) {
1604
          return;
1605
        } else {
1606
          var ranges = copyableRanges(cm);
1607
          lastCopied = ranges.text;
1608
          if (e.type == "cut") {
1609
            cm.operation(function() {
1610
              cm.setSelections(ranges.ranges, 0, sel_dontScroll);
1611
              cm.replaceSelection("", null, "cut");
1612
            });
1613
          }
1614
        }
1615
        // iOS exposes the clipboard API, but seems to discard content inserted into it
1616
        if (e.clipboardData && !ios) {
1617
          e.preventDefault();
1618
          e.clipboardData.clearData();
1619
          e.clipboardData.setData("text/plain", lastCopied.join("\n"));
1620
        } else {
1621
          // Old-fashioned briefly-focus-a-textarea hack
1622
          var kludge = hiddenTextarea(), te = kludge.firstChild;
1623
          cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
1624
          te.value = lastCopied.join("\n");
1625
          var hadFocus = document.activeElement;
1626
          selectInput(te);
1627
          setTimeout(function() {
1628
            cm.display.lineSpace.removeChild(kludge);
1629
            hadFocus.focus();
1630
          }, 50);
1631
        }
1632
      }
1633
      on(div, "copy", onCopyCut);
1634
      on(div, "cut", onCopyCut);
1635
    },
1636
 
1637
    prepareSelection: function() {
1638
      var result = prepareSelection(this.cm, false);
1639
      result.focus = this.cm.state.focused;
1640
      return result;
1641
    },
1642
 
1643
    showSelection: function(info) {
1644
      if (!info || !this.cm.display.view.length) return;
1645
      if (info.focus) this.showPrimarySelection();
1646
      this.showMultipleSelections(info);
1647
    },
1648
 
1649
    showPrimarySelection: function() {
1650
      var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
1651
      var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
1652
      var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
1653
      if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
1654
          cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
1655
          cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
1656
        return;
1657
 
1658
      var start = posToDOM(this.cm, prim.from());
1659
      var end = posToDOM(this.cm, prim.to());
1660
      if (!start && !end) return;
1661
 
1662
      var view = this.cm.display.view;
1663
      var old = sel.rangeCount && sel.getRangeAt(0);
1664
      if (!start) {
1665
        start = {node: view[0].measure.map[2], offset: 0};
1666
      } else if (!end) { // FIXME dangerously hacky
1667
        var measure = view[view.length - 1].measure;
1668
        var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
1669
        end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
1670
      }
1671
 
1672
      try { var rng = range(start.node, start.offset, end.offset, end.node); }
1673
      catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
1674
      if (rng) {
1675
        sel.removeAllRanges();
1676
        sel.addRange(rng);
1677
        if (old && sel.anchorNode == null) sel.addRange(old);
1678
        else if (gecko) this.startGracePeriod();
1679
      }
1680
      this.rememberSelection();
1681
    },
1682
 
1683
    startGracePeriod: function() {
1684
      var input = this;
1685
      clearTimeout(this.gracePeriod);
1686
      this.gracePeriod = setTimeout(function() {
1687
        input.gracePeriod = false;
1688
        if (input.selectionChanged())
1689
          input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
1690
      }, 20);
1691
    },
1692
 
1693
    showMultipleSelections: function(info) {
1694
      removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
1695
      removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
1696
    },
1697
 
1698
    rememberSelection: function() {
1699
      var sel = window.getSelection();
1700
      this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
1701
      this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
1702
    },
1703
 
1704
    selectionInEditor: function() {
1705
      var sel = window.getSelection();
1706
      if (!sel.rangeCount) return false;
1707
      var node = sel.getRangeAt(0).commonAncestorContainer;
1708
      return contains(this.div, node);
1709
    },
1710
 
1711
    focus: function() {
1712
      if (this.cm.options.readOnly != "nocursor") this.div.focus();
1713
    },
1714
    blur: function() { this.div.blur(); },
1715
    getField: function() { return this.div; },
1716
 
1717
    supportsTouch: function() { return true; },
1718
 
1719
    receivedFocus: function() {
1720
      var input = this;
1721
      if (this.selectionInEditor())
1722
        this.pollSelection();
1723
      else
1724
        runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
1725
 
1726
      function poll() {
1727
        if (input.cm.state.focused) {
1728
          input.pollSelection();
1729
          input.polling.set(input.cm.options.pollInterval, poll);
1730
        }
1731
      }
1732
      this.polling.set(this.cm.options.pollInterval, poll);
1733
    },
1734
 
1735
    selectionChanged: function() {
1736
      var sel = window.getSelection();
1737
      return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
1738
        sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
1739
    },
1740
 
1741
    pollSelection: function() {
1742
      if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
1743
        var sel = window.getSelection(), cm = this.cm;
1744
        this.rememberSelection();
1745
        var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
1746
        var head = domToPos(cm, sel.focusNode, sel.focusOffset);
1747
        if (anchor && head) runInOp(cm, function() {
1748
          setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
1749
          if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
1750
        });
1751
      }
1752
    },
1753
 
1754
    pollContent: function() {
1755
      var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
1756
      var from = sel.from(), to = sel.to();
1757
      if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
1758
 
1759
      var fromIndex;
1760
      if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
1761
        var fromLine = lineNo(display.view[0].line);
1762
        var fromNode = display.view[0].node;
1763
      } else {
1764
        var fromLine = lineNo(display.view[fromIndex].line);
1765
        var fromNode = display.view[fromIndex - 1].node.nextSibling;
1766
      }
1767
      var toIndex = findViewIndex(cm, to.line);
1768
      if (toIndex == display.view.length - 1) {
1769
        var toLine = display.viewTo - 1;
1770
        var toNode = display.lineDiv.lastChild;
1771
      } else {
1772
        var toLine = lineNo(display.view[toIndex + 1].line) - 1;
1773
        var toNode = display.view[toIndex + 1].node.previousSibling;
1774
      }
1775
 
1776
      var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
1777
      var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
1778
      while (newText.length > 1 && oldText.length > 1) {
1779
        if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
1780
        else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
1781
        else break;
1782
      }
1783
 
1784
      var cutFront = 0, cutEnd = 0;
1785
      var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1786
      while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
1787
        ++cutFront;
1788
      var newBot = lst(newText), oldBot = lst(oldText);
1789
      var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
1790
                               oldBot.length - (oldText.length == 1 ? cutFront : 0));
1791
      while (cutEnd < maxCutEnd &&
1792
             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
1793
        ++cutEnd;
1794
 
1795
      newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
1796
      newText[0] = newText[0].slice(cutFront);
1797
 
1798
      var chFrom = Pos(fromLine, cutFront);
1799
      var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
1800
      if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
1801
        replaceRange(cm.doc, newText, chFrom, chTo, "+input");
1802
        return true;
1803
      }
1804
    },
1805
 
1806
    ensurePolled: function() {
1807
      this.forceCompositionEnd();
1808
    },
1809
    reset: function() {
1810
      this.forceCompositionEnd();
1811
    },
1812
    forceCompositionEnd: function() {
1813
      if (!this.composing || this.composing.handled) return;
1814
      this.applyComposition(this.composing);
1815
      this.composing.handled = true;
1816
      this.div.blur();
1817
      this.div.focus();
1818
    },
1819
    applyComposition: function(composing) {
1820
      if (composing.data && composing.data != composing.startData)
1821
        operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
1822
    },
1823
 
1824
    setUneditable: function(node) {
1825
      node.setAttribute("contenteditable", "false");
1826
    },
1827
 
1828
    onKeyPress: function(e) {
1829
      e.preventDefault();
1830
      operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
1831
    },
1832
 
1833
    onContextMenu: nothing,
1834
    resetPosition: nothing,
1835
 
1836
    needsContentAttribute: true
1837
  }, ContentEditableInput.prototype);
1838
 
1839
  function posToDOM(cm, pos) {
1840
    var view = findViewForLine(cm, pos.line);
1841
    if (!view || view.hidden) return null;
1842
    var line = getLine(cm.doc, pos.line);
1843
    var info = mapFromLineView(view, line, pos.line);
1844
 
1845
    var order = getOrder(line), side = "left";
1846
    if (order) {
1847
      var partPos = getBidiPartAt(order, pos.ch);
1848
      side = partPos % 2 ? "right" : "left";
1849
    }
1850
    var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
1851
    result.offset = result.collapse == "right" ? result.end : result.start;
1852
    return result;
1853
  }
1854
 
1855
  function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
1856
 
1857
  function domToPos(cm, node, offset) {
1858
    var lineNode;
1859
    if (node == cm.display.lineDiv) {
1860
      lineNode = cm.display.lineDiv.childNodes[offset];
1861
      if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
1862
      node = null; offset = 0;
1863
    } else {
1864
      for (lineNode = node;; lineNode = lineNode.parentNode) {
1865
        if (!lineNode || lineNode == cm.display.lineDiv) return null;
1866
        if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
1867
      }
1868
    }
1869
    for (var i = 0; i < cm.display.view.length; i++) {
1870
      var lineView = cm.display.view[i];
1871
      if (lineView.node == lineNode)
1872
        return locateNodeInLineView(lineView, node, offset);
1873
    }
1874
  }
1875
 
1876
  function locateNodeInLineView(lineView, node, offset) {
1877
    var wrapper = lineView.text.firstChild, bad = false;
1878
    if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
1879
    if (node == wrapper) {
1880
      bad = true;
1881
      node = wrapper.childNodes[offset];
1882
      offset = 0;
1883
      if (!node) {
1884
        var line = lineView.rest ? lst(lineView.rest) : lineView.line;
1885
        return badPos(Pos(lineNo(line), line.text.length), bad);
1886
      }
1887
    }
1888
 
1889
    var textNode = node.nodeType == 3 ? node : null, topNode = node;
1890
    if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
1891
      textNode = node.firstChild;
1892
      if (offset) offset = textNode.nodeValue.length;
1893
    }
1894
    while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
1895
    var measure = lineView.measure, maps = measure.maps;
1896
 
1897
    function find(textNode, topNode, offset) {
1898
      for (var i = -1; i < (maps ? maps.length : 0); i++) {
1899
        var map = i < 0 ? measure.map : maps[i];
1900
        for (var j = 0; j < map.length; j += 3) {
1901
          var curNode = map[j + 2];
1902
          if (curNode == textNode || curNode == topNode) {
1903
            var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
1904
            var ch = map[j] + offset;
1905
            if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
1906
            return Pos(line, ch);
1907
          }
1908
        }
1909
      }
1910
    }
1911
    var found = find(textNode, topNode, offset);
1912
    if (found) return badPos(found, bad);
1913
 
1914
    // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
1915
    for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
1916
      found = find(after, after.firstChild, 0);
1917
      if (found)
1918
        return badPos(Pos(found.line, found.ch - dist), bad);
1919
      else
1920
        dist += after.textContent.length;
1921
    }
1922
    for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
1923
      found = find(before, before.firstChild, -1);
1924
      if (found)
1925
        return badPos(Pos(found.line, found.ch + dist), bad);
1926
      else
1927
        dist += after.textContent.length;
1928
    }
1929
  }
1930
 
1931
  function domTextBetween(cm, from, to, fromLine, toLine) {
1932
    var text = "", closing = false, lineSep = cm.doc.lineSeparator();
1933
    function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
1934
    function walk(node) {
1935
      if (node.nodeType == 1) {
1936
        var cmText = node.getAttribute("cm-text");
1937
        if (cmText != null) {
1938
          if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
1939
          text += cmText;
1940
          return;
1941
        }
1942
        var markerID = node.getAttribute("cm-marker"), range;
1943
        if (markerID) {
1944
          var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
1945
          if (found.length && (range = found[0].find()))
1946
            text += getBetween(cm.doc, range.from, range.to).join(lineSep);
1947
          return;
1948
        }
1949
        if (node.getAttribute("contenteditable") == "false") return;
1950
        for (var i = 0; i < node.childNodes.length; i++)
1951
          walk(node.childNodes[i]);
1952
        if (/^(pre|div|p)$/i.test(node.nodeName))
1953
          closing = true;
1954
      } else if (node.nodeType == 3) {
1955
        var val = node.nodeValue;
1956
        if (!val) return;
1957
        if (closing) {
1958
          text += lineSep;
1959
          closing = false;
1960
        }
1961
        text += val;
1962
      }
1963
    }
1964
    for (;;) {
1965
      walk(from);
1966
      if (from == to) break;
1967
      from = from.nextSibling;
1968
    }
1969
    return text;
1970
  }
1971
 
1972
  CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
1973
 
1974
  // SELECTION / CURSOR
1975
 
1976
  // Selection objects are immutable. A new one is created every time
1977
  // the selection changes. A selection is one or more non-overlapping
1978
  // (and non-touching) ranges, sorted, and an integer that indicates
1979
  // which one is the primary selection (the one that's scrolled into
1980
  // view, that getCursor returns, etc).
1981
  function Selection(ranges, primIndex) {
1982
    this.ranges = ranges;
1983
    this.primIndex = primIndex;
1984
  }
1985
 
1986
  Selection.prototype = {
1987
    primary: function() { return this.ranges[this.primIndex]; },
1988
    equals: function(other) {
1989
      if (other == this) return true;
1990
      if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
1991
      for (var i = 0; i < this.ranges.length; i++) {
1992
        var here = this.ranges[i], there = other.ranges[i];
1993
        if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
1994
      }
1995
      return true;
1996
    },
1997
    deepCopy: function() {
1998
      for (var out = [], i = 0; i < this.ranges.length; i++)
1999
        out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
2000
      return new Selection(out, this.primIndex);
2001
    },
2002
    somethingSelected: function() {
2003
      for (var i = 0; i < this.ranges.length; i++)
2004
        if (!this.ranges[i].empty()) return true;
2005
      return false;
2006
    },
2007
    contains: function(pos, end) {
2008
      if (!end) end = pos;
2009
      for (var i = 0; i < this.ranges.length; i++) {
2010
        var range = this.ranges[i];
2011
        if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
2012
          return i;
2013
      }
2014
      return -1;
2015
    }
2016
  };
2017
 
2018
  function Range(anchor, head) {
2019
    this.anchor = anchor; this.head = head;
2020
  }
2021
 
2022
  Range.prototype = {
2023
    from: function() { return minPos(this.anchor, this.head); },
2024
    to: function() { return maxPos(this.anchor, this.head); },
2025
    empty: function() {
2026
      return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
2027
    }
2028
  };
2029
 
2030
  // Take an unsorted, potentially overlapping set of ranges, and
2031
  // build a selection out of it. 'Consumes' ranges array (modifying
2032
  // it).
2033
  function normalizeSelection(ranges, primIndex) {
2034
    var prim = ranges[primIndex];
2035
    ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
2036
    primIndex = indexOf(ranges, prim);
2037
    for (var i = 1; i < ranges.length; i++) {
2038
      var cur = ranges[i], prev = ranges[i - 1];
2039
      if (cmp(prev.to(), cur.from()) >= 0) {
2040
        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
2041
        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
2042
        if (i <= primIndex) --primIndex;
2043
        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
2044
      }
2045
    }
2046
    return new Selection(ranges, primIndex);
2047
  }
2048
 
2049
  function simpleSelection(anchor, head) {
2050
    return new Selection([new Range(anchor, head || anchor)], 0);
2051
  }
2052
 
2053
  // Most of the external API clips given positions to make sure they
2054
  // actually exist within the document.
2055
  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2056
  function clipPos(doc, pos) {
2057
    if (pos.line < doc.first) return Pos(doc.first, 0);
2058
    var last = doc.first + doc.size - 1;
2059
    if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2060
    return clipToLen(pos, getLine(doc, pos.line).text.length);
2061
  }
2062
  function clipToLen(pos, linelen) {
2063
    var ch = pos.ch;
2064
    if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2065
    else if (ch < 0) return Pos(pos.line, 0);
2066
    else return pos;
2067
  }
2068
  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2069
  function clipPosArray(doc, array) {
2070
    for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
2071
    return out;
2072
  }
2073
 
2074
  // SELECTION UPDATES
2075
 
2076
  // The 'scroll' parameter given to many of these indicated whether
2077
  // the new cursor position should be scrolled into view after
2078
  // modifying the selection.
2079
 
2080
  // If shift is held or the extend flag is set, extends a range to
2081
  // include a given position (and optionally a second position).
2082
  // Otherwise, simply returns the range between the given positions.
2083
  // Used for cursor motion and such.
2084
  function extendRange(doc, range, head, other) {
2085
    if (doc.cm && doc.cm.display.shift || doc.extend) {
2086
      var anchor = range.anchor;
2087
      if (other) {
2088
        var posBefore = cmp(head, anchor) < 0;
2089
        if (posBefore != (cmp(other, anchor) < 0)) {
2090
          anchor = head;
2091
          head = other;
2092
        } else if (posBefore != (cmp(head, other) < 0)) {
2093
          head = other;
2094
        }
2095
      }
2096
      return new Range(anchor, head);
2097
    } else {
2098
      return new Range(other || head, head);
2099
    }
2100
  }
2101
 
2102
  // Extend the primary selection range, discard the rest.
2103
  function extendSelection(doc, head, other, options) {
2104
    setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
2105
  }
2106
 
2107
  // Extend all selections (pos is an array of selections with length
2108
  // equal the number of selections)
2109
  function extendSelections(doc, heads, options) {
2110
    for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
2111
      out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
2112
    var newSel = normalizeSelection(out, doc.sel.primIndex);
2113
    setSelection(doc, newSel, options);
2114
  }
2115
 
2116
  // Updates a single range in the selection.
2117
  function replaceOneSelection(doc, i, range, options) {
2118
    var ranges = doc.sel.ranges.slice(0);
2119
    ranges[i] = range;
2120
    setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
2121
  }
2122
 
2123
  // Reset the selection to a single range.
2124
  function setSimpleSelection(doc, anchor, head, options) {
2125
    setSelection(doc, simpleSelection(anchor, head), options);
2126
  }
2127
 
2128
  // Give beforeSelectionChange handlers a change to influence a
2129
  // selection update.
2130
  function filterSelectionChange(doc, sel) {
2131
    var obj = {
2132
      ranges: sel.ranges,
2133
      update: function(ranges) {
2134
        this.ranges = [];
2135
        for (var i = 0; i < ranges.length; i++)
2136
          this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
2137
                                     clipPos(doc, ranges[i].head));
2138
      }
2139
    };
2140
    signal(doc, "beforeSelectionChange", doc, obj);
2141
    if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2142
    if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
2143
    else return sel;
2144
  }
2145
 
2146
  function setSelectionReplaceHistory(doc, sel, options) {
2147
    var done = doc.history.done, last = lst(done);
2148
    if (last && last.ranges) {
2149
      done[done.length - 1] = sel;
2150
      setSelectionNoUndo(doc, sel, options);
2151
    } else {
2152
      setSelection(doc, sel, options);
2153
    }
2154
  }
2155
 
2156
  // Set a new selection.
2157
  function setSelection(doc, sel, options) {
2158
    setSelectionNoUndo(doc, sel, options);
2159
    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
2160
  }
2161
 
2162
  function setSelectionNoUndo(doc, sel, options) {
2163
    if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
2164
      sel = filterSelectionChange(doc, sel);
2165
 
2166
    var bias = options && options.bias ||
2167
      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
2168
    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
2169
 
2170
    if (!(options && options.scroll === false) && doc.cm)
2171
      ensureCursorVisible(doc.cm);
2172
  }
2173
 
2174
  function setSelectionInner(doc, sel) {
2175
    if (sel.equals(doc.sel)) return;
2176
 
2177
    doc.sel = sel;
2178
 
2179
    if (doc.cm) {
2180
      doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
2181
      signalCursorActivity(doc.cm);
2182
    }
2183
    signalLater(doc, "cursorActivity", doc);
2184
  }
2185
 
2186
  // Verify that the selection does not partially select any atomic
2187
  // marked ranges.
2188
  function reCheckSelection(doc) {
2189
    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
2190
  }
2191
 
2192
  // Return a selection that does not partially select any atomic
2193
  // ranges.
2194
  function skipAtomicInSelection(doc, sel, bias, mayClear) {
2195
    var out;
2196
    for (var i = 0; i < sel.ranges.length; i++) {
2197
      var range = sel.ranges[i];
2198
      var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
2199
      var newHead = skipAtomic(doc, range.head, bias, mayClear);
2200
      if (out || newAnchor != range.anchor || newHead != range.head) {
2201
        if (!out) out = sel.ranges.slice(0, i);
2202
        out[i] = new Range(newAnchor, newHead);
2203
      }
2204
    }
2205
    return out ? normalizeSelection(out, sel.primIndex) : sel;
2206
  }
2207
 
2208
  // Ensure a given position is not inside an atomic range.
2209
  function skipAtomic(doc, pos, bias, mayClear) {
2210
    var flipped = false, curPos = pos;
2211
    var dir = bias || 1;
2212
    doc.cantEdit = false;
2213
    search: for (;;) {
2214
      var line = getLine(doc, curPos.line);
2215
      if (line.markedSpans) {
2216
        for (var i = 0; i < line.markedSpans.length; ++i) {
2217
          var sp = line.markedSpans[i], m = sp.marker;
2218
          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2219
              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2220
            if (mayClear) {
2221
              signal(m, "beforeCursorEnter");
2222
              if (m.explicitlyCleared) {
2223
                if (!line.markedSpans) break;
2224
                else {--i; continue;}
2225
              }
2226
            }
2227
            if (!m.atomic) continue;
2228
            var newPos = m.find(dir < 0 ? -1 : 1);
2229
            if (cmp(newPos, curPos) == 0) {
2230
              newPos.ch += dir;
2231
              if (newPos.ch < 0) {
2232
                if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2233
                else newPos = null;
2234
              } else if (newPos.ch > line.text.length) {
2235
                if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2236
                else newPos = null;
2237
              }
2238
              if (!newPos) {
2239
                if (flipped) {
2240
                  // Driven in a corner -- no valid cursor position found at all
2241
                  // -- try again *with* clearing, if we didn't already
2242
                  if (!mayClear) return skipAtomic(doc, pos, bias, true);
2243
                  // Otherwise, turn off editing until further notice, and return the start of the doc
2244
                  doc.cantEdit = true;
2245
                  return Pos(doc.first, 0);
2246
                }
2247
                flipped = true; newPos = pos; dir = -dir;
2248
              }
2249
            }
2250
            curPos = newPos;
2251
            continue search;
2252
          }
2253
        }
2254
      }
2255
      return curPos;
2256
    }
2257
  }
2258
 
2259
  // SELECTION DRAWING
2260
 
2261
  function updateSelection(cm) {
2262
    cm.display.input.showSelection(cm.display.input.prepareSelection());
2263
  }
2264
 
2265
  function prepareSelection(cm, primary) {
2266
    var doc = cm.doc, result = {};
2267
    var curFragment = result.cursors = document.createDocumentFragment();
2268
    var selFragment = result.selection = document.createDocumentFragment();
2269
 
2270
    for (var i = 0; i < doc.sel.ranges.length; i++) {
2271
      if (primary === false && i == doc.sel.primIndex) continue;
2272
      var range = doc.sel.ranges[i];
2273
      var collapsed = range.empty();
2274
      if (collapsed || cm.options.showCursorWhenSelecting)
2275
        drawSelectionCursor(cm, range.head, curFragment);
2276
      if (!collapsed)
2277
        drawSelectionRange(cm, range, selFragment);
2278
    }
2279
    return result;
2280
  }
2281
 
2282
  // Draws a cursor for the given range
2283
  function drawSelectionCursor(cm, head, output) {
2284
    var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
2285
 
2286
    var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
2287
    cursor.style.left = pos.left + "px";
2288
    cursor.style.top = pos.top + "px";
2289
    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
2290
 
2291
    if (pos.other) {
2292
      // Secondary cursor, shown when on a 'jump' in bi-directional text
2293
      var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
2294
      otherCursor.style.display = "";
2295
      otherCursor.style.left = pos.other.left + "px";
2296
      otherCursor.style.top = pos.other.top + "px";
2297
      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
2298
    }
2299
  }
2300
 
2301
  // Draws the given range as a highlighted selection
2302
  function drawSelectionRange(cm, range, output) {
2303
    var display = cm.display, doc = cm.doc;
2304
    var fragment = document.createDocumentFragment();
2305
    var padding = paddingH(cm.display), leftSide = padding.left;
2306
    var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
2307
 
2308
    function add(left, top, width, bottom) {
2309
      if (top < 0) top = 0;
2310
      top = Math.round(top);
2311
      bottom = Math.round(bottom);
2312
      fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
2313
                               "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
2314
                               "px; height: " + (bottom - top) + "px"));
2315
    }
2316
 
2317
    function drawForLine(line, fromArg, toArg) {
2318
      var lineObj = getLine(doc, line);
2319
      var lineLen = lineObj.text.length;
2320
      var start, end;
2321
      function coords(ch, bias) {
2322
        return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
2323
      }
2324
 
2325
      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
2326
        var leftPos = coords(from, "left"), rightPos, left, right;
2327
        if (from == to) {
2328
          rightPos = leftPos;
2329
          left = right = leftPos.left;
2330
        } else {
2331
          rightPos = coords(to - 1, "right");
2332
          if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
2333
          left = leftPos.left;
2334
          right = rightPos.right;
2335
        }
2336
        if (fromArg == null && from == 0) left = leftSide;
2337
        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
2338
          add(left, leftPos.top, null, leftPos.bottom);
2339
          left = leftSide;
2340
          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
2341
        }
2342
        if (toArg == null && to == lineLen) right = rightSide;
2343
        if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
2344
          start = leftPos;
2345
        if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
2346
          end = rightPos;
2347
        if (left < leftSide + 1) left = leftSide;
2348
        add(left, rightPos.top, right - left, rightPos.bottom);
2349
      });
2350
      return {start: start, end: end};
2351
    }
2352
 
2353
    var sFrom = range.from(), sTo = range.to();
2354
    if (sFrom.line == sTo.line) {
2355
      drawForLine(sFrom.line, sFrom.ch, sTo.ch);
2356
    } else {
2357
      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
2358
      var singleVLine = visualLine(fromLine) == visualLine(toLine);
2359
      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
2360
      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
2361
      if (singleVLine) {
2362
        if (leftEnd.top < rightStart.top - 2) {
2363
          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
2364
          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
2365
        } else {
2366
          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
2367
        }
2368
      }
2369
      if (leftEnd.bottom < rightStart.top)
2370
        add(leftSide, leftEnd.bottom, null, rightStart.top);
2371
    }
2372
 
2373
    output.appendChild(fragment);
2374
  }
2375
 
2376
  // Cursor-blinking
2377
  function restartBlink(cm) {
2378
    if (!cm.state.focused) return;
2379
    var display = cm.display;
2380
    clearInterval(display.blinker);
2381
    var on = true;
2382
    display.cursorDiv.style.visibility = "";
2383
    if (cm.options.cursorBlinkRate > 0)
2384
      display.blinker = setInterval(function() {
2385
        display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
2386
      }, cm.options.cursorBlinkRate);
2387
    else if (cm.options.cursorBlinkRate < 0)
2388
      display.cursorDiv.style.visibility = "hidden";
2389
  }
2390
 
2391
  // HIGHLIGHT WORKER
2392
 
2393
  function startWorker(cm, time) {
2394
    if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
2395
      cm.state.highlight.set(time, bind(highlightWorker, cm));
2396
  }
2397
 
2398
  function highlightWorker(cm) {
2399
    var doc = cm.doc;
2400
    if (doc.frontier < doc.first) doc.frontier = doc.first;
2401
    if (doc.frontier >= cm.display.viewTo) return;
2402
    var end = +new Date + cm.options.workTime;
2403
    var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
2404
    var changedLines = [];
2405
 
2406
    doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
2407
      if (doc.frontier >= cm.display.viewFrom) { // Visible
2408
        var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
2409
        var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
2410
        line.styles = highlighted.styles;
2411
        var oldCls = line.styleClasses, newCls = highlighted.classes;
2412
        if (newCls) line.styleClasses = newCls;
2413
        else if (oldCls) line.styleClasses = null;
2414
        var ischange = !oldStyles || oldStyles.length != line.styles.length ||
2415
          oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
2416
        for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
2417
        if (ischange) changedLines.push(doc.frontier);
2418
        line.stateAfter = tooLong ? state : copyState(doc.mode, state);
2419
      } else {
2420
        if (line.text.length <= cm.options.maxHighlightLength)
2421
          processLine(cm, line.text, state);
2422
        line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
2423
      }
2424
      ++doc.frontier;
2425
      if (+new Date > end) {
2426
        startWorker(cm, cm.options.workDelay);
2427
        return true;
2428
      }
2429
    });
2430
    if (changedLines.length) runInOp(cm, function() {
2431
      for (var i = 0; i < changedLines.length; i++)
2432
        regLineChange(cm, changedLines[i], "text");
2433
    });
2434
  }
2435
 
2436
  // Finds the line to start with when starting a parse. Tries to
2437
  // find a line with a stateAfter, so that it can start with a
2438
  // valid state. If that fails, it returns the line with the
2439
  // smallest indentation, which tends to need the least context to
2440
  // parse correctly.
2441
  function findStartLine(cm, n, precise) {
2442
    var minindent, minline, doc = cm.doc;
2443
    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
2444
    for (var search = n; search > lim; --search) {
2445
      if (search <= doc.first) return doc.first;
2446
      var line = getLine(doc, search - 1);
2447
      if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
2448
      var indented = countColumn(line.text, null, cm.options.tabSize);
2449
      if (minline == null || minindent > indented) {
2450
        minline = search - 1;
2451
        minindent = indented;
2452
      }
2453
    }
2454
    return minline;
2455
  }
2456
 
2457
  function getStateBefore(cm, n, precise) {
2458
    var doc = cm.doc, display = cm.display;
2459
    if (!doc.mode.startState) return true;
2460
    var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
2461
    if (!state) state = startState(doc.mode);
2462
    else state = copyState(doc.mode, state);
2463
    doc.iter(pos, n, function(line) {
2464
      processLine(cm, line.text, state);
2465
      var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
2466
      line.stateAfter = save ? copyState(doc.mode, state) : null;
2467
      ++pos;
2468
    });
2469
    if (precise) doc.frontier = pos;
2470
    return state;
2471
  }
2472
 
2473
  // POSITION MEASUREMENT
2474
 
2475
  function paddingTop(display) {return display.lineSpace.offsetTop;}
2476
  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
2477
  function paddingH(display) {
2478
    if (display.cachedPaddingH) return display.cachedPaddingH;
2479
    var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2480
    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2481
    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2482
    if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
2483
    return data;
2484
  }
2485
 
2486
  function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
2487
  function displayWidth(cm) {
2488
    return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
2489
  }
2490
  function displayHeight(cm) {
2491
    return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
2492
  }
2493
 
2494
  // Ensure the lineView.wrapping.heights array is populated. This is
2495
  // an array of bottom offsets for the lines that make up a drawn
2496
  // line. When lineWrapping is on, there might be more than one
2497
  // height.
2498
  function ensureLineHeights(cm, lineView, rect) {
2499
    var wrapping = cm.options.lineWrapping;
2500
    var curWidth = wrapping && displayWidth(cm);
2501
    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2502
      var heights = lineView.measure.heights = [];
2503
      if (wrapping) {
2504
        lineView.measure.width = curWidth;
2505
        var rects = lineView.text.firstChild.getClientRects();
2506
        for (var i = 0; i < rects.length - 1; i++) {
2507
          var cur = rects[i], next = rects[i + 1];
2508
          if (Math.abs(cur.bottom - next.bottom) > 2)
2509
            heights.push((cur.bottom + next.top) / 2 - rect.top);
2510
        }
2511
      }
2512
      heights.push(rect.bottom - rect.top);
2513
    }
2514
  }
2515
 
2516
  // Find a line map (mapping character offsets to text nodes) and a
2517
  // measurement cache for the given line number. (A line view might
2518
  // contain multiple lines when collapsed ranges are present.)
2519
  function mapFromLineView(lineView, line, lineN) {
2520
    if (lineView.line == line)
2521
      return {map: lineView.measure.map, cache: lineView.measure.cache};
2522
    for (var i = 0; i < lineView.rest.length; i++)
2523
      if (lineView.rest[i] == line)
2524
        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
2525
    for (var i = 0; i < lineView.rest.length; i++)
2526
      if (lineNo(lineView.rest[i]) > lineN)
2527
        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
2528
  }
2529
 
2530
  // Render a line into the hidden node display.externalMeasured. Used
2531
  // when measurement is needed for a line that's not in the viewport.
2532
  function updateExternalMeasurement(cm, line) {
2533
    line = visualLine(line);
2534
    var lineN = lineNo(line);
2535
    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2536
    view.lineN = lineN;
2537
    var built = view.built = buildLineContent(cm, view);
2538
    view.text = built.pre;
2539
    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2540
    return view;
2541
  }
2542
 
2543
  // Get a {top, bottom, left, right} box (in line-local coordinates)
2544
  // for a given character.
2545
  function measureChar(cm, line, ch, bias) {
2546
    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
2547
  }
2548
 
2549
  // Find a line view that corresponds to the given line number.
2550
  function findViewForLine(cm, lineN) {
2551
    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2552
      return cm.display.view[findViewIndex(cm, lineN)];
2553
    var ext = cm.display.externalMeasured;
2554
    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2555
      return ext;
2556
  }
2557
 
2558
  // Measurement can be split in two steps, the set-up work that
2559
  // applies to the whole line, and the measurement of the actual
2560
  // character. Functions like coordsChar, that need to do a lot of
2561
  // measurements in a row, can thus ensure that the set-up work is
2562
  // only done once.
2563
  function prepareMeasureForLine(cm, line) {
2564
    var lineN = lineNo(line);
2565
    var view = findViewForLine(cm, lineN);
2566
    if (view && !view.text) {
2567
      view = null;
2568
    } else if (view && view.changes) {
2569
      updateLineForChanges(cm, view, lineN, getDimensions(cm));
2570
      cm.curOp.forceUpdate = true;
2571
    }
2572
    if (!view)
2573
      view = updateExternalMeasurement(cm, line);
2574
 
2575
    var info = mapFromLineView(view, line, lineN);
2576
    return {
2577
      line: line, view: view, rect: null,
2578
      map: info.map, cache: info.cache, before: info.before,
2579
      hasHeights: false
2580
    };
2581
  }
2582
 
2583
  // Given a prepared measurement object, measures the position of an
2584
  // actual character (or fetches it from the cache).
2585
  function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2586
    if (prepared.before) ch = -1;
2587
    var key = ch + (bias || ""), found;
2588
    if (prepared.cache.hasOwnProperty(key)) {
2589
      found = prepared.cache[key];
2590
    } else {
2591
      if (!prepared.rect)
2592
        prepared.rect = prepared.view.text.getBoundingClientRect();
2593
      if (!prepared.hasHeights) {
2594
        ensureLineHeights(cm, prepared.view, prepared.rect);
2595
        prepared.hasHeights = true;
2596
      }
2597
      found = measureCharInner(cm, prepared, ch, bias);
2598
      if (!found.bogus) prepared.cache[key] = found;
2599
    }
2600
    return {left: found.left, right: found.right,
2601
            top: varHeight ? found.rtop : found.top,
2602
            bottom: varHeight ? found.rbottom : found.bottom};
2603
  }
2604
 
2605
  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2606
 
2607
  function nodeAndOffsetInLineMap(map, ch, bias) {
2608
    var node, start, end, collapse;
2609
    // First, search the line map for the text node corresponding to,
2610
    // or closest to, the target character.
2611
    for (var i = 0; i < map.length; i += 3) {
2612
      var mStart = map[i], mEnd = map[i + 1];
2613
      if (ch < mStart) {
2614
        start = 0; end = 1;
2615
        collapse = "left";
2616
      } else if (ch < mEnd) {
2617
        start = ch - mStart;
2618
        end = start + 1;
2619
      } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2620
        end = mEnd - mStart;
2621
        start = end - 1;
2622
        if (ch >= mEnd) collapse = "right";
2623
      }
2624
      if (start != null) {
2625
        node = map[i + 2];
2626
        if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2627
          collapse = bias;
2628
        if (bias == "left" && start == 0)
2629
          while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2630
            node = map[(i -= 3) + 2];
2631
            collapse = "left";
2632
          }
2633
        if (bias == "right" && start == mEnd - mStart)
2634
          while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2635
            node = map[(i += 3) + 2];
2636
            collapse = "right";
2637
          }
2638
        break;
2639
      }
2640
    }
2641
    return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
2642
  }
2643
 
2644
  function measureCharInner(cm, prepared, ch, bias) {
2645
    var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2646
    var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2647
 
2648
    var rect;
2649
    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2650
      for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2651
        while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2652
        while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
2653
        if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
2654
          rect = node.parentNode.getBoundingClientRect();
2655
        } else if (ie && cm.options.lineWrapping) {
2656
          var rects = range(node, start, end).getClientRects();
2657
          if (rects.length)
2658
            rect = rects[bias == "right" ? rects.length - 1 : 0];
2659
          else
2660
            rect = nullRect;
2661
        } else {
2662
          rect = range(node, start, end).getBoundingClientRect() || nullRect;
2663
        }
2664
        if (rect.left || rect.right || start == 0) break;
2665
        end = start;
2666
        start = start - 1;
2667
        collapse = "right";
2668
      }
2669
      if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
2670
    } else { // If it is a widget, simply get the box for the whole widget.
2671
      if (start > 0) collapse = bias = "right";
2672
      var rects;
2673
      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2674
        rect = rects[bias == "right" ? rects.length - 1 : 0];
2675
      else
2676
        rect = node.getBoundingClientRect();
2677
    }
2678
    if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2679
      var rSpan = node.parentNode.getClientRects()[0];
2680
      if (rSpan)
2681
        rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
2682
      else
2683
        rect = nullRect;
2684
    }
2685
 
2686
    var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2687
    var mid = (rtop + rbot) / 2;
2688
    var heights = prepared.view.measure.heights;
2689
    for (var i = 0; i < heights.length - 1; i++)
2690
      if (mid < heights[i]) break;
2691
    var top = i ? heights[i - 1] : 0, bot = heights[i];
2692
    var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2693
                  right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2694
                  top: top, bottom: bot};
2695
    if (!rect.left && !rect.right) result.bogus = true;
2696
    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2697
 
2698
    return result;
2699
  }
2700
 
2701
  // Work around problem with bounding client rects on ranges being
2702
  // returned incorrectly when zoomed on IE10 and below.
2703
  function maybeUpdateRectForZooming(measure, rect) {
2704
    if (!window.screen || screen.logicalXDPI == null ||
2705
        screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2706
      return rect;
2707
    var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2708
    var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2709
    return {left: rect.left * scaleX, right: rect.right * scaleX,
2710
            top: rect.top * scaleY, bottom: rect.bottom * scaleY};
2711
  }
2712
 
2713
  function clearLineMeasurementCacheFor(lineView) {
2714
    if (lineView.measure) {
2715
      lineView.measure.cache = {};
2716
      lineView.measure.heights = null;
2717
      if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
2718
        lineView.measure.caches[i] = {};
2719
    }
2720
  }
2721
 
2722
  function clearLineMeasurementCache(cm) {
2723
    cm.display.externalMeasure = null;
2724
    removeChildren(cm.display.lineMeasure);
2725
    for (var i = 0; i < cm.display.view.length; i++)
2726
      clearLineMeasurementCacheFor(cm.display.view[i]);
2727
  }
2728
 
2729
  function clearCaches(cm) {
2730
    clearLineMeasurementCache(cm);
2731
    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2732
    if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
2733
    cm.display.lineNumChars = null;
2734
  }
2735
 
2736
  function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
2737
  function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
2738
 
2739
  // Converts a {top, bottom, left, right} box from line-local
2740
  // coordinates into another coordinate system. Context may be one of
2741
  // "line", "div" (display.lineDiv), "local"/null (editor), "window",
2742
  // or "page".
2743
  function intoCoordSystem(cm, lineObj, rect, context) {
2744
    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
2745
      var size = widgetHeight(lineObj.widgets[i]);
2746
      rect.top += size; rect.bottom += size;
2747
    }
2748
    if (context == "line") return rect;
2749
    if (!context) context = "local";
2750
    var yOff = heightAtLine(lineObj);
2751
    if (context == "local") yOff += paddingTop(cm.display);
2752
    else yOff -= cm.display.viewOffset;
2753
    if (context == "page" || context == "window") {
2754
      var lOff = cm.display.lineSpace.getBoundingClientRect();
2755
      yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2756
      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2757
      rect.left += xOff; rect.right += xOff;
2758
    }
2759
    rect.top += yOff; rect.bottom += yOff;
2760
    return rect;
2761
  }
2762
 
2763
  // Coverts a box from "div" coords to another coordinate system.
2764
  // Context may be "window", "page", "div", or "local"/null.
2765
  function fromCoordSystem(cm, coords, context) {
2766
    if (context == "div") return coords;
2767
    var left = coords.left, top = coords.top;
2768
    // First move into "page" coordinate system
2769
    if (context == "page") {
2770
      left -= pageScrollX();
2771
      top -= pageScrollY();
2772
    } else if (context == "local" || !context) {
2773
      var localBox = cm.display.sizer.getBoundingClientRect();
2774
      left += localBox.left;
2775
      top += localBox.top;
2776
    }
2777
 
2778
    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2779
    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
2780
  }
2781
 
2782
  function charCoords(cm, pos, context, lineObj, bias) {
2783
    if (!lineObj) lineObj = getLine(cm.doc, pos.line);
2784
    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
2785
  }
2786
 
2787
  // Returns a box for a given cursor position, which may have an
2788
  // 'other' property containing the position of the secondary cursor
2789
  // on a bidi boundary.
2790
  function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2791
    lineObj = lineObj || getLine(cm.doc, pos.line);
2792
    if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
2793
    function get(ch, right) {
2794
      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2795
      if (right) m.left = m.right; else m.right = m.left;
2796
      return intoCoordSystem(cm, lineObj, m, context);
2797
    }
2798
    function getBidi(ch, partPos) {
2799
      var part = order[partPos], right = part.level % 2;
2800
      if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
2801
        part = order[--partPos];
2802
        ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
2803
        right = true;
2804
      } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
2805
        part = order[++partPos];
2806
        ch = bidiLeft(part) - part.level % 2;
2807
        right = false;
2808
      }
2809
      if (right && ch == part.to && ch > part.from) return get(ch - 1);
2810
      return get(ch, right);
2811
    }
2812
    var order = getOrder(lineObj), ch = pos.ch;
2813
    if (!order) return get(ch);
2814
    var partPos = getBidiPartAt(order, ch);
2815
    var val = getBidi(ch, partPos);
2816
    if (bidiOther != null) val.other = getBidi(ch, bidiOther);
2817
    return val;
2818
  }
2819
 
2820
  // Used to cheaply estimate the coordinates for a position. Used for
2821
  // intermediate scroll updates.
2822
  function estimateCoords(cm, pos) {
2823
    var left = 0, pos = clipPos(cm.doc, pos);
2824
    if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
2825
    var lineObj = getLine(cm.doc, pos.line);
2826
    var top = heightAtLine(lineObj) + paddingTop(cm.display);
2827
    return {left: left, right: left, top: top, bottom: top + lineObj.height};
2828
  }
2829
 
2830
  // Positions returned by coordsChar contain some extra information.
2831
  // xRel is the relative x position of the input coordinates compared
2832
  // to the found position (so xRel > 0 means the coordinates are to
2833
  // the right of the character position, for example). When outside
2834
  // is true, that means the coordinates lie outside the line's
2835
  // vertical range.
2836
  function PosWithInfo(line, ch, outside, xRel) {
2837
    var pos = Pos(line, ch);
2838
    pos.xRel = xRel;
2839
    if (outside) pos.outside = true;
2840
    return pos;
2841
  }
2842
 
2843
  // Compute the character position closest to the given coordinates.
2844
  // Input must be lineSpace-local ("div" coordinate system).
2845
  function coordsChar(cm, x, y) {
2846
    var doc = cm.doc;
2847
    y += cm.display.viewOffset;
2848
    if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
2849
    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2850
    if (lineN > last)
2851
      return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2852
    if (x < 0) x = 0;
2853
 
2854
    var lineObj = getLine(doc, lineN);
2855
    for (;;) {
2856
      var found = coordsCharInner(cm, lineObj, lineN, x, y);
2857
      var merged = collapsedSpanAtEnd(lineObj);
2858
      var mergedPos = merged && merged.find(0, true);
2859
      if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2860
        lineN = lineNo(lineObj = mergedPos.to.line);
2861
      else
2862
        return found;
2863
    }
2864
  }
2865
 
2866
  function coordsCharInner(cm, lineObj, lineNo, x, y) {
2867
    var innerOff = y - heightAtLine(lineObj);
2868
    var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
2869
    var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2870
 
2871
    function getX(ch) {
2872
      var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
2873
      wrongLine = true;
2874
      if (innerOff > sp.bottom) return sp.left - adjust;
2875
      else if (innerOff < sp.top) return sp.left + adjust;
2876
      else wrongLine = false;
2877
      return sp.left;
2878
    }
2879
 
2880
    var bidi = getOrder(lineObj), dist = lineObj.text.length;
2881
    var from = lineLeft(lineObj), to = lineRight(lineObj);
2882
    var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
2883
 
2884
    if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
2885
    // Do a binary search between these bounds.
2886
    for (;;) {
2887
      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
2888
        var ch = x < fromX || x - fromX <= toX - x ? from : to;
2889
        var xDiff = x - (ch == from ? fromX : toX);
2890
        while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
2891
        var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
2892
                              xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
2893
        return pos;
2894
      }
2895
      var step = Math.ceil(dist / 2), middle = from + step;
2896
      if (bidi) {
2897
        middle = from;
2898
        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
2899
      }
2900
      var middleX = getX(middle);
2901
      if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
2902
      else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
2903
    }
2904
  }
2905
 
2906
  var measureText;
2907
  // Compute the default text height.
2908
  function textHeight(display) {
2909
    if (display.cachedTextHeight != null) return display.cachedTextHeight;
2910
    if (measureText == null) {
2911
      measureText = elt("pre");
2912
      // Measure a bunch of lines, for browsers that compute
2913
      // fractional heights.
2914
      for (var i = 0; i < 49; ++i) {
2915
        measureText.appendChild(document.createTextNode("x"));
2916
        measureText.appendChild(elt("br"));
2917
      }
2918
      measureText.appendChild(document.createTextNode("x"));
2919
    }
2920
    removeChildrenAndAdd(display.measure, measureText);
2921
    var height = measureText.offsetHeight / 50;
2922
    if (height > 3) display.cachedTextHeight = height;
2923
    removeChildren(display.measure);
2924
    return height || 1;
2925
  }
2926
 
2927
  // Compute the default character width.
2928
  function charWidth(display) {
2929
    if (display.cachedCharWidth != null) return display.cachedCharWidth;
2930
    var anchor = elt("span", "xxxxxxxxxx");
2931
    var pre = elt("pre", [anchor]);
2932
    removeChildrenAndAdd(display.measure, pre);
2933
    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2934
    if (width > 2) display.cachedCharWidth = width;
2935
    return width || 10;
2936
  }
2937
 
2938
  // OPERATIONS
2939
 
2940
  // Operations are used to wrap a series of changes to the editor
2941
  // state in such a way that each change won't have to update the
2942
  // cursor and display (which would be awkward, slow, and
2943
  // error-prone). Instead, display updates are batched and then all
2944
  // combined and executed at once.
2945
 
2946
  var operationGroup = null;
2947
 
2948
  var nextOpId = 0;
2949
  // Start a new operation.
2950
  function startOperation(cm) {
2951
    cm.curOp = {
2952
      cm: cm,
2953
      viewChanged: false,      // Flag that indicates that lines might need to be redrawn
2954
      startHeight: cm.doc.height, // Used to detect need to update scrollbar
2955
      forceUpdate: false,      // Used to force a redraw
2956
      updateInput: null,       // Whether to reset the input textarea
2957
      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
2958
      changeObjs: null,        // Accumulated changes, for firing change events
2959
      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
2960
      cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
2961
      selectionChanged: false, // Whether the selection needs to be redrawn
2962
      updateMaxLine: false,    // Set when the widest line needs to be determined anew
2963
      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
2964
      scrollToPos: null,       // Used to scroll to a specific position
2965
      focus: false,
2966
      id: ++nextOpId           // Unique ID
2967
    };
2968
    if (operationGroup) {
2969
      operationGroup.ops.push(cm.curOp);
2970
    } else {
2971
      cm.curOp.ownsGroup = operationGroup = {
2972
        ops: [cm.curOp],
2973
        delayedCallbacks: []
2974
      };
2975
    }
2976
  }
2977
 
2978
  function fireCallbacksForOps(group) {
2979
    // Calls delayed callbacks and cursorActivity handlers until no
2980
    // new ones appear
2981
    var callbacks = group.delayedCallbacks, i = 0;
2982
    do {
2983
      for (; i < callbacks.length; i++)
2984
        callbacks[i].call(null);
2985
      for (var j = 0; j < group.ops.length; j++) {
2986
        var op = group.ops[j];
2987
        if (op.cursorActivityHandlers)
2988
          while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
2989
            op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
2990
      }
2991
    } while (i < callbacks.length);
2992
  }
2993
 
2994
  // Finish an operation, updating the display and signalling delayed events
2995
  function endOperation(cm) {
2996
    var op = cm.curOp, group = op.ownsGroup;
2997
    if (!group) return;
2998
 
2999
    try { fireCallbacksForOps(group); }
3000
    finally {
3001
      operationGroup = null;
3002
      for (var i = 0; i < group.ops.length; i++)
3003
        group.ops[i].cm.curOp = null;
3004
      endOperations(group);
3005
    }
3006
  }
3007
 
3008
  // The DOM updates done when an operation finishes are batched so
3009
  // that the minimum number of relayouts are required.
3010
  function endOperations(group) {
3011
    var ops = group.ops;
3012
    for (var i = 0; i < ops.length; i++) // Read DOM
3013
      endOperation_R1(ops[i]);
3014
    for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3015
      endOperation_W1(ops[i]);
3016
    for (var i = 0; i < ops.length; i++) // Read DOM
3017
      endOperation_R2(ops[i]);
3018
    for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3019
      endOperation_W2(ops[i]);
3020
    for (var i = 0; i < ops.length; i++) // Read DOM
3021
      endOperation_finish(ops[i]);
3022
  }
3023
 
3024
  function endOperation_R1(op) {
3025
    var cm = op.cm, display = cm.display;
3026
    maybeClipScrollbars(cm);
3027
    if (op.updateMaxLine) findMaxLine(cm);
3028
 
3029
    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3030
      op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3031
                         op.scrollToPos.to.line >= display.viewTo) ||
3032
      display.maxLineChanged && cm.options.lineWrapping;
3033
    op.update = op.mustUpdate &&
3034
      new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3035
  }
3036
 
3037
  function endOperation_W1(op) {
3038
    op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3039
  }
3040
 
3041
  function endOperation_R2(op) {
3042
    var cm = op.cm, display = cm.display;
3043
    if (op.updatedDisplay) updateHeightsInViewport(cm);
3044
 
3045
    op.barMeasure = measureForScrollbars(cm);
3046
 
3047
    // If the max line changed since it was last measured, measure it,
3048
    // and ensure the document's width matches it.
3049
    // updateDisplay_W2 will use these properties to do the actual resizing
3050
    if (display.maxLineChanged && !cm.options.lineWrapping) {
3051
      op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3052
      cm.display.sizerWidth = op.adjustWidthTo;
3053
      op.barMeasure.scrollWidth =
3054
        Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3055
      op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3056
    }
3057
 
3058
    if (op.updatedDisplay || op.selectionChanged)
3059
      op.preparedSelection = display.input.prepareSelection();
3060
  }
3061
 
3062
  function endOperation_W2(op) {
3063
    var cm = op.cm;
3064
 
3065
    if (op.adjustWidthTo != null) {
3066
      cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3067
      if (op.maxScrollLeft < cm.doc.scrollLeft)
3068
        setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
3069
      cm.display.maxLineChanged = false;
3070
    }
3071
 
3072
    if (op.preparedSelection)
3073
      cm.display.input.showSelection(op.preparedSelection);
3074
    if (op.updatedDisplay)
3075
      setDocumentHeight(cm, op.barMeasure);
3076
    if (op.updatedDisplay || op.startHeight != cm.doc.height)
3077
      updateScrollbars(cm, op.barMeasure);
3078
 
3079
    if (op.selectionChanged) restartBlink(cm);
3080
 
3081
    if (cm.state.focused && op.updateInput)
3082
      cm.display.input.reset(op.typing);
3083
    if (op.focus && op.focus == activeElt()) ensureFocus(op.cm);
3084
  }
3085
 
3086
  function endOperation_finish(op) {
3087
    var cm = op.cm, display = cm.display, doc = cm.doc;
3088
 
3089
    if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
3090
 
3091
    // Abort mouse wheel delta measurement, when scrolling explicitly
3092
    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3093
      display.wheelStartX = display.wheelStartY = null;
3094
 
3095
    // Propagate the scroll position to the actual DOM scroller
3096
    if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
3097
      doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
3098
      display.scrollbars.setScrollTop(doc.scrollTop);
3099
      display.scroller.scrollTop = doc.scrollTop;
3100
    }
3101
    if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
3102
      doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
3103
      display.scrollbars.setScrollLeft(doc.scrollLeft);
3104
      display.scroller.scrollLeft = doc.scrollLeft;
3105
      alignHorizontally(cm);
3106
    }
3107
    // If we need to scroll a specific position into view, do so.
3108
    if (op.scrollToPos) {
3109
      var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3110
                                     clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3111
      if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
3112
    }
3113
 
3114
    // Fire events for markers that are hidden/unidden by editing or
3115
    // undoing
3116
    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3117
    if (hidden) for (var i = 0; i < hidden.length; ++i)
3118
      if (!hidden[i].lines.length) signal(hidden[i], "hide");
3119
    if (unhidden) for (var i = 0; i < unhidden.length; ++i)
3120
      if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
3121
 
3122
    if (display.wrapper.offsetHeight)
3123
      doc.scrollTop = cm.display.scroller.scrollTop;
3124
 
3125
    // Fire change events, and delayed event handlers
3126
    if (op.changeObjs)
3127
      signal(cm, "changes", cm, op.changeObjs);
3128
    if (op.update)
3129
      op.update.finish();
3130
  }
3131
 
3132
  // Run the given function in an operation
3133
  function runInOp(cm, f) {
3134
    if (cm.curOp) return f();
3135
    startOperation(cm);
3136
    try { return f(); }
3137
    finally { endOperation(cm); }
3138
  }
3139
  // Wraps a function in an operation. Returns the wrapped function.
3140
  function operation(cm, f) {
3141
    return function() {
3142
      if (cm.curOp) return f.apply(cm, arguments);
3143
      startOperation(cm);
3144
      try { return f.apply(cm, arguments); }
3145
      finally { endOperation(cm); }
3146
    };
3147
  }
3148
  // Used to add methods to editor and doc instances, wrapping them in
3149
  // operations.
3150
  function methodOp(f) {
3151
    return function() {
3152
      if (this.curOp) return f.apply(this, arguments);
3153
      startOperation(this);
3154
      try { return f.apply(this, arguments); }
3155
      finally { endOperation(this); }
3156
    };
3157
  }
3158
  function docMethodOp(f) {
3159
    return function() {
3160
      var cm = this.cm;
3161
      if (!cm || cm.curOp) return f.apply(this, arguments);
3162
      startOperation(cm);
3163
      try { return f.apply(this, arguments); }
3164
      finally { endOperation(cm); }
3165
    };
3166
  }
3167
 
3168
  // VIEW TRACKING
3169
 
3170
  // These objects are used to represent the visible (currently drawn)
3171
  // part of the document. A LineView may correspond to multiple
3172
  // logical lines, if those are connected by collapsed ranges.
3173
  function LineView(doc, line, lineN) {
3174
    // The starting line
3175
    this.line = line;
3176
    // Continuing lines, if any
3177
    this.rest = visualLineContinued(line);
3178
    // Number of logical lines in this visual line
3179
    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
3180
    this.node = this.text = null;
3181
    this.hidden = lineIsHidden(doc, line);
3182
  }
3183
 
3184
  // Create a range of LineView objects for the given lines.
3185
  function buildViewArray(cm, from, to) {
3186
    var array = [], nextPos;
3187
    for (var pos = from; pos < to; pos = nextPos) {
3188
      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
3189
      nextPos = pos + view.size;
3190
      array.push(view);
3191
    }
3192
    return array;
3193
  }
3194
 
3195
  // Updates the display.view data structure for a given change to the
3196
  // document. From and to are in pre-change coordinates. Lendiff is
3197
  // the amount of lines added or subtracted by the change. This is
3198
  // used for changes that span multiple lines, or change the way
3199
  // lines are divided into visual lines. regLineChange (below)
3200
  // registers single-line changes.
3201
  function regChange(cm, from, to, lendiff) {
3202
    if (from == null) from = cm.doc.first;
3203
    if (to == null) to = cm.doc.first + cm.doc.size;
3204
    if (!lendiff) lendiff = 0;
3205
 
3206
    var display = cm.display;
3207
    if (lendiff && to < display.viewTo &&
3208
        (display.updateLineNumbers == null || display.updateLineNumbers > from))
3209
      display.updateLineNumbers = from;
3210
 
3211
    cm.curOp.viewChanged = true;
3212
 
3213
    if (from >= display.viewTo) { // Change after
3214
      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3215
        resetView(cm);
3216
    } else if (to <= display.viewFrom) { // Change before
3217
      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3218
        resetView(cm);
3219
      } else {
3220
        display.viewFrom += lendiff;
3221
        display.viewTo += lendiff;
3222
      }
3223
    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3224
      resetView(cm);
3225
    } else if (from <= display.viewFrom) { // Top overlap
3226
      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3227
      if (cut) {
3228
        display.view = display.view.slice(cut.index);
3229
        display.viewFrom = cut.lineN;
3230
        display.viewTo += lendiff;
3231
      } else {
3232
        resetView(cm);
3233
      }
3234
    } else if (to >= display.viewTo) { // Bottom overlap
3235
      var cut = viewCuttingPoint(cm, from, from, -1);
3236
      if (cut) {
3237
        display.view = display.view.slice(0, cut.index);
3238
        display.viewTo = cut.lineN;
3239
      } else {
3240
        resetView(cm);
3241
      }
3242
    } else { // Gap in the middle
3243
      var cutTop = viewCuttingPoint(cm, from, from, -1);
3244
      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3245
      if (cutTop && cutBot) {
3246
        display.view = display.view.slice(0, cutTop.index)
3247
          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3248
          .concat(display.view.slice(cutBot.index));
3249
        display.viewTo += lendiff;
3250
      } else {
3251
        resetView(cm);
3252
      }
3253
    }
3254
 
3255
    var ext = display.externalMeasured;
3256
    if (ext) {
3257
      if (to < ext.lineN)
3258
        ext.lineN += lendiff;
3259
      else if (from < ext.lineN + ext.size)
3260
        display.externalMeasured = null;
3261
    }
3262
  }
3263
 
3264
  // Register a change to a single line. Type must be one of "text",
3265
  // "gutter", "class", "widget"
3266
  function regLineChange(cm, line, type) {
3267
    cm.curOp.viewChanged = true;
3268
    var display = cm.display, ext = cm.display.externalMeasured;
3269
    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3270
      display.externalMeasured = null;
3271
 
3272
    if (line < display.viewFrom || line >= display.viewTo) return;
3273
    var lineView = display.view[findViewIndex(cm, line)];
3274
    if (lineView.node == null) return;
3275
    var arr = lineView.changes || (lineView.changes = []);
3276
    if (indexOf(arr, type) == -1) arr.push(type);
3277
  }
3278
 
3279
  // Clear the view.
3280
  function resetView(cm) {
3281
    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3282
    cm.display.view = [];
3283
    cm.display.viewOffset = 0;
3284
  }
3285
 
3286
  // Find the view element corresponding to a given line. Return null
3287
  // when the line isn't visible.
3288
  function findViewIndex(cm, n) {
3289
    if (n >= cm.display.viewTo) return null;
3290
    n -= cm.display.viewFrom;
3291
    if (n < 0) return null;
3292
    var view = cm.display.view;
3293
    for (var i = 0; i < view.length; i++) {
3294
      n -= view[i].size;
3295
      if (n < 0) return i;
3296
    }
3297
  }
3298
 
3299
  function viewCuttingPoint(cm, oldN, newN, dir) {
3300
    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3301
    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3302
      return {index: index, lineN: newN};
3303
    for (var i = 0, n = cm.display.viewFrom; i < index; i++)
3304
      n += view[i].size;
3305
    if (n != oldN) {
3306
      if (dir > 0) {
3307
        if (index == view.length - 1) return null;
3308
        diff = (n + view[index].size) - oldN;
3309
        index++;
3310
      } else {
3311
        diff = n - oldN;
3312
      }
3313
      oldN += diff; newN += diff;
3314
    }
3315
    while (visualLineNo(cm.doc, newN) != newN) {
3316
      if (index == (dir < 0 ? 0 : view.length - 1)) return null;
3317
      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3318
      index += dir;
3319
    }
3320
    return {index: index, lineN: newN};
3321
  }
3322
 
3323
  // Force the view to cover a given range, adding empty view element
3324
  // or clipping off existing ones as needed.
3325
  function adjustView(cm, from, to) {
3326
    var display = cm.display, view = display.view;
3327
    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3328
      display.view = buildViewArray(cm, from, to);
3329
      display.viewFrom = from;
3330
    } else {
3331
      if (display.viewFrom > from)
3332
        display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
3333
      else if (display.viewFrom < from)
3334
        display.view = display.view.slice(findViewIndex(cm, from));
3335
      display.viewFrom = from;
3336
      if (display.viewTo < to)
3337
        display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
3338
      else if (display.viewTo > to)
3339
        display.view = display.view.slice(0, findViewIndex(cm, to));
3340
    }
3341
    display.viewTo = to;
3342
  }
3343
 
3344
  // Count the number of lines in the view whose DOM representation is
3345
  // out of date (or nonexistent).
3346
  function countDirtyView(cm) {
3347
    var view = cm.display.view, dirty = 0;
3348
    for (var i = 0; i < view.length; i++) {
3349
      var lineView = view[i];
3350
      if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
3351
    }
3352
    return dirty;
3353
  }
3354
 
3355
  // EVENT HANDLERS
3356
 
3357
  // Attach the necessary event handlers when initializing the editor
3358
  function registerEventHandlers(cm) {
3359
    var d = cm.display;
3360
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
3361
    // Older IE's will not fire a second mousedown for a double click
3362
    if (ie && ie_version < 11)
3363
      on(d.scroller, "dblclick", operation(cm, function(e) {
3364
        if (signalDOMEvent(cm, e)) return;
3365
        var pos = posFromMouse(cm, e);
3366
        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
3367
        e_preventDefault(e);
3368
        var word = cm.findWordAt(pos);
3369
        extendSelection(cm.doc, word.anchor, word.head);
3370
      }));
3371
    else
3372
      on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
3373
    // Some browsers fire contextmenu *after* opening the menu, at
3374
    // which point we can't mess with it anymore. Context menu is
3375
    // handled in onMouseDown for these browsers.
3376
    if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
3377
 
3378
    // Used to suppress mouse event handling when a touch happens
3379
    var touchFinished, prevTouch = {end: 0};
3380
    function finishTouch() {
3381
      if (d.activeTouch) {
3382
        touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
3383
        prevTouch = d.activeTouch;
3384
        prevTouch.end = +new Date;
3385
      }
3386
    };
3387
    function isMouseLikeTouchEvent(e) {
3388
      if (e.touches.length != 1) return false;
3389
      var touch = e.touches[0];
3390
      return touch.radiusX <= 1 && touch.radiusY <= 1;
3391
    }
3392
    function farAway(touch, other) {
3393
      if (other.left == null) return true;
3394
      var dx = other.left - touch.left, dy = other.top - touch.top;
3395
      return dx * dx + dy * dy > 20 * 20;
3396
    }
3397
    on(d.scroller, "touchstart", function(e) {
3398
      if (!isMouseLikeTouchEvent(e)) {
3399
        clearTimeout(touchFinished);
3400
        var now = +new Date;
3401
        d.activeTouch = {start: now, moved: false,
3402
                         prev: now - prevTouch.end <= 300 ? prevTouch : null};
3403
        if (e.touches.length == 1) {
3404
          d.activeTouch.left = e.touches[0].pageX;
3405
          d.activeTouch.top = e.touches[0].pageY;
3406
        }
3407
      }
3408
    });
3409
    on(d.scroller, "touchmove", function() {
3410
      if (d.activeTouch) d.activeTouch.moved = true;
3411
    });
3412
    on(d.scroller, "touchend", function(e) {
3413
      var touch = d.activeTouch;
3414
      if (touch && !eventInWidget(d, e) && touch.left != null &&
3415
          !touch.moved && new Date - touch.start < 300) {
3416
        var pos = cm.coordsChar(d.activeTouch, "page"), range;
3417
        if (!touch.prev || farAway(touch, touch.prev)) // Single tap
3418
          range = new Range(pos, pos);
3419
        else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
3420
          range = cm.findWordAt(pos);
3421
        else // Triple tap
3422
          range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
3423
        cm.setSelection(range.anchor, range.head);
3424
        cm.focus();
3425
        e_preventDefault(e);
3426
      }
3427
      finishTouch();
3428
    });
3429
    on(d.scroller, "touchcancel", finishTouch);
3430
 
3431
    // Sync scrolling between fake scrollbars and real scrollable
3432
    // area, ensure viewport is updated when scrolling.
3433
    on(d.scroller, "scroll", function() {
3434
      if (d.scroller.clientHeight) {
3435
        setScrollTop(cm, d.scroller.scrollTop);
3436
        setScrollLeft(cm, d.scroller.scrollLeft, true);
3437
        signal(cm, "scroll", cm);
3438
      }
3439
    });
3440
 
3441
    // Listen to wheel events in order to try and update the viewport on time.
3442
    on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
3443
    on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
3444
 
3445
    // Prevent wrapper from ever scrolling
3446
    on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
3447
 
3448
    d.dragFunctions = {
3449
      enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
3450
      over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
3451
      start: function(e){onDragStart(cm, e);},
3452
      drop: operation(cm, onDrop),
3453
      leave: function() {clearDragCursor(cm);}
3454
    };
3455
 
3456
    var inp = d.input.getField();
3457
    on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
3458
    on(inp, "keydown", operation(cm, onKeyDown));
3459
    on(inp, "keypress", operation(cm, onKeyPress));
3460
    on(inp, "focus", bind(onFocus, cm));
3461
    on(inp, "blur", bind(onBlur, cm));
3462
  }
3463
 
3464
  function dragDropChanged(cm, value, old) {
3465
    var wasOn = old && old != CodeMirror.Init;
3466
    if (!value != !wasOn) {
3467
      var funcs = cm.display.dragFunctions;
3468
      var toggle = value ? on : off;
3469
      toggle(cm.display.scroller, "dragstart", funcs.start);
3470
      toggle(cm.display.scroller, "dragenter", funcs.enter);
3471
      toggle(cm.display.scroller, "dragover", funcs.over);
3472
      toggle(cm.display.scroller, "dragleave", funcs.leave);
3473
      toggle(cm.display.scroller, "drop", funcs.drop);
3474
    }
3475
  }
3476
 
3477
  // Called when the window resizes
3478
  function onResize(cm) {
3479
    var d = cm.display;
3480
    if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
3481
      return;
3482
    // Might be a text scaling operation, clear size caches.
3483
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
3484
    d.scrollbarsClipped = false;
3485
    cm.setSize();
3486
  }
3487
 
3488
  // MOUSE EVENTS
3489
 
3490
  // Return true when the given mouse event happened in a widget
3491
  function eventInWidget(display, e) {
3492
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
3493
      if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
3494
          (n.parentNode == display.sizer && n != display.mover))
3495
        return true;
3496
    }
3497
  }
3498
 
3499
  // Given a mouse event, find the corresponding position. If liberal
3500
  // is false, it checks whether a gutter or scrollbar was clicked,
3501
  // and returns null if it was. forRect is used by rectangular
3502
  // selections, and tries to estimate a character position even for
3503
  // coordinates beyond the right of the text.
3504
  function posFromMouse(cm, e, liberal, forRect) {
3505
    var display = cm.display;
3506
    if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
3507
 
3508
    var x, y, space = display.lineSpace.getBoundingClientRect();
3509
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3510
    try { x = e.clientX - space.left; y = e.clientY - space.top; }
3511
    catch (e) { return null; }
3512
    var coords = coordsChar(cm, x, y), line;
3513
    if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3514
      var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3515
      coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3516
    }
3517
    return coords;
3518
  }
3519
 
3520
  // A mouse down can be a single click, double click, triple click,
3521
  // start of selection drag, start of text drag, new cursor
3522
  // (ctrl-click), rectangle drag (alt-drag), or xwin
3523
  // middle-click-paste. Or it might be a click on something we should
3524
  // not interfere with, such as a scrollbar or widget.
3525
  function onMouseDown(e) {
3526
    var cm = this, display = cm.display;
3527
    if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
3528
    display.shift = e.shiftKey;
3529
 
3530
    if (eventInWidget(display, e)) {
3531
      if (!webkit) {
3532
        // Briefly turn off draggability, to allow widgets to do
3533
        // normal dragging things.
3534
        display.scroller.draggable = false;
3535
        setTimeout(function(){display.scroller.draggable = true;}, 100);
3536
      }
3537
      return;
3538
    }
3539
    if (clickInGutter(cm, e)) return;
3540
    var start = posFromMouse(cm, e);
3541
    window.focus();
3542
 
3543
    switch (e_button(e)) {
3544
    case 1:
3545
      // #3261: make sure, that we're not starting a second selection
3546
      if (cm.state.selectingText)
3547
        cm.state.selectingText(e);
3548
      else if (start)
3549
        leftButtonDown(cm, e, start);
3550
      else if (e_target(e) == display.scroller)
3551
        e_preventDefault(e);
3552
      break;
3553
    case 2:
3554
      if (webkit) cm.state.lastMiddleDown = +new Date;
3555
      if (start) extendSelection(cm.doc, start);
3556
      setTimeout(function() {display.input.focus();}, 20);
3557
      e_preventDefault(e);
3558
      break;
3559
    case 3:
3560
      if (captureRightClick) onContextMenu(cm, e);
3561
      else delayBlurEvent(cm);
3562
      break;
3563
    }
3564
  }
3565
 
3566
  var lastClick, lastDoubleClick;
3567
  function leftButtonDown(cm, e, start) {
3568
    if (ie) setTimeout(bind(ensureFocus, cm), 0);
3569
    else cm.curOp.focus = activeElt();
3570
 
3571
    var now = +new Date, type;
3572
    if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
3573
      type = "triple";
3574
    } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
3575
      type = "double";
3576
      lastDoubleClick = {time: now, pos: start};
3577
    } else {
3578
      type = "single";
3579
      lastClick = {time: now, pos: start};
3580
    }
3581
 
3582
    var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
3583
    if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
3584
        type == "single" && (contained = sel.contains(start)) > -1 &&
3585
        (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
3586
        (cmp(contained.to(), start) > 0 || start.xRel < 0))
3587
      leftButtonStartDrag(cm, e, start, modifier);
3588
    else
3589
      leftButtonSelect(cm, e, start, type, modifier);
3590
  }
3591
 
3592
  // Start a text drag. When it ends, see if any dragging actually
3593
  // happen, and treat as a click if it didn't.
3594
  function leftButtonStartDrag(cm, e, start, modifier) {
3595
    var display = cm.display, startTime = +new Date;
3596
    var dragEnd = operation(cm, function(e2) {
3597
      if (webkit) display.scroller.draggable = false;
3598
      cm.state.draggingText = false;
3599
      off(document, "mouseup", dragEnd);
3600
      off(display.scroller, "drop", dragEnd);
3601
      if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
3602
        e_preventDefault(e2);
3603
        if (!modifier && +new Date - 200 < startTime)
3604
          extendSelection(cm.doc, start);
3605
        // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
3606
        if (webkit || ie && ie_version == 9)
3607
          setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
3608
        else
3609
          display.input.focus();
3610
      }
3611
    });
3612
    // Let the drag handler handle this.
3613
    if (webkit) display.scroller.draggable = true;
3614
    cm.state.draggingText = dragEnd;
3615
    // IE's approach to draggable
3616
    if (display.scroller.dragDrop) display.scroller.dragDrop();
3617
    on(document, "mouseup", dragEnd);
3618
    on(display.scroller, "drop", dragEnd);
3619
  }
3620
 
3621
  // Normal selection, as opposed to text dragging.
3622
  function leftButtonSelect(cm, e, start, type, addNew) {
3623
    var display = cm.display, doc = cm.doc;
3624
    e_preventDefault(e);
3625
 
3626
    var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
3627
    if (addNew && !e.shiftKey) {
3628
      ourIndex = doc.sel.contains(start);
3629
      if (ourIndex > -1)
3630
        ourRange = ranges[ourIndex];
3631
      else
3632
        ourRange = new Range(start, start);
3633
    } else {
3634
      ourRange = doc.sel.primary();
3635
      ourIndex = doc.sel.primIndex;
3636
    }
3637
 
3638
    if (e.altKey) {
3639
      type = "rect";
3640
      if (!addNew) ourRange = new Range(start, start);
3641
      start = posFromMouse(cm, e, true, true);
3642
      ourIndex = -1;
3643
    } else if (type == "double") {
3644
      var word = cm.findWordAt(start);
3645
      if (cm.display.shift || doc.extend)
3646
        ourRange = extendRange(doc, ourRange, word.anchor, word.head);
3647
      else
3648
        ourRange = word;
3649
    } else if (type == "triple") {
3650
      var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
3651
      if (cm.display.shift || doc.extend)
3652
        ourRange = extendRange(doc, ourRange, line.anchor, line.head);
3653
      else
3654
        ourRange = line;
3655
    } else {
3656
      ourRange = extendRange(doc, ourRange, start);
3657
    }
3658
 
3659
    if (!addNew) {
3660
      ourIndex = 0;
3661
      setSelection(doc, new Selection([ourRange], 0), sel_mouse);
3662
      startSel = doc.sel;
3663
    } else if (ourIndex == -1) {
3664
      ourIndex = ranges.length;
3665
      setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
3666
                   {scroll: false, origin: "*mouse"});
3667
    } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
3668
      setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
3669
                   {scroll: false, origin: "*mouse"});
3670
      startSel = doc.sel;
3671
    } else {
3672
      replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
3673
    }
3674
 
3675
    var lastPos = start;
3676
    function extendTo(pos) {
3677
      if (cmp(lastPos, pos) == 0) return;
3678
      lastPos = pos;
3679
 
3680
      if (type == "rect") {
3681
        var ranges = [], tabSize = cm.options.tabSize;
3682
        var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
3683
        var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
3684
        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
3685
        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
3686
             line <= end; line++) {
3687
          var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
3688
          if (left == right)
3689
            ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
3690
          else if (text.length > leftPos)
3691
            ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
3692
        }
3693
        if (!ranges.length) ranges.push(new Range(start, start));
3694
        setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
3695
                     {origin: "*mouse", scroll: false});
3696
        cm.scrollIntoView(pos);
3697
      } else {
3698
        var oldRange = ourRange;
3699
        var anchor = oldRange.anchor, head = pos;
3700
        if (type != "single") {
3701
          if (type == "double")
3702
            var range = cm.findWordAt(pos);
3703
          else
3704
            var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
3705
          if (cmp(range.anchor, anchor) > 0) {
3706
            head = range.head;
3707
            anchor = minPos(oldRange.from(), range.anchor);
3708
          } else {
3709
            head = range.anchor;
3710
            anchor = maxPos(oldRange.to(), range.head);
3711
          }
3712
        }
3713
        var ranges = startSel.ranges.slice(0);
3714
        ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
3715
        setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
3716
      }
3717
    }
3718
 
3719
    var editorSize = display.wrapper.getBoundingClientRect();
3720
    // Used to ensure timeout re-tries don't fire when another extend
3721
    // happened in the meantime (clearTimeout isn't reliable -- at
3722
    // least on Chrome, the timeouts still happen even when cleared,
3723
    // if the clear happens after their scheduled firing time).
3724
    var counter = 0;
3725
 
3726
    function extend(e) {
3727
      var curCount = ++counter;
3728
      var cur = posFromMouse(cm, e, true, type == "rect");
3729
      if (!cur) return;
3730
      if (cmp(cur, lastPos) != 0) {
3731
        cm.curOp.focus = activeElt();
3732
        extendTo(cur);
3733
        var visible = visibleLines(display, doc);
3734
        if (cur.line >= visible.to || cur.line < visible.from)
3735
          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
3736
      } else {
3737
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
3738
        if (outside) setTimeout(operation(cm, function() {
3739
          if (counter != curCount) return;
3740
          display.scroller.scrollTop += outside;
3741
          extend(e);
3742
        }), 50);
3743
      }
3744
    }
3745
 
3746
    function done(e) {
3747
      cm.state.selectingText = false;
3748
      counter = Infinity;
3749
      e_preventDefault(e);
3750
      display.input.focus();
3751
      off(document, "mousemove", move);
3752
      off(document, "mouseup", up);
3753
      doc.history.lastSelOrigin = null;
3754
    }
3755
 
3756
    var move = operation(cm, function(e) {
3757
      if (!e_button(e)) done(e);
3758
      else extend(e);
3759
    });
3760
    var up = operation(cm, done);
3761
    cm.state.selectingText = up;
3762
    on(document, "mousemove", move);
3763
    on(document, "mouseup", up);
3764
  }
3765
 
3766
  // Determines whether an event happened in the gutter, and fires the
3767
  // handlers for the corresponding event.
3768
  function gutterEvent(cm, e, type, prevent, signalfn) {
3769
    try { var mX = e.clientX, mY = e.clientY; }
3770
    catch(e) { return false; }
3771
    if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
3772
    if (prevent) e_preventDefault(e);
3773
 
3774
    var display = cm.display;
3775
    var lineBox = display.lineDiv.getBoundingClientRect();
3776
 
3777
    if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
3778
    mY -= lineBox.top - display.viewOffset;
3779
 
3780
    for (var i = 0; i < cm.options.gutters.length; ++i) {
3781
      var g = display.gutters.childNodes[i];
3782
      if (g && g.getBoundingClientRect().right >= mX) {
3783
        var line = lineAtHeight(cm.doc, mY);
3784
        var gutter = cm.options.gutters[i];
3785
        signalfn(cm, type, cm, line, gutter, e);
3786
        return e_defaultPrevented(e);
3787
      }
3788
    }
3789
  }
3790
 
3791
  function clickInGutter(cm, e) {
3792
    return gutterEvent(cm, e, "gutterClick", true, signalLater);
3793
  }
3794
 
3795
  // Kludge to work around strange IE behavior where it'll sometimes
3796
  // re-fire a series of drag-related events right after the drop (#1551)
3797
  var lastDrop = 0;
3798
 
3799
  function onDrop(e) {
3800
    var cm = this;
3801
    clearDragCursor(cm);
3802
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
3803
      return;
3804
    e_preventDefault(e);
3805
    if (ie) lastDrop = +new Date;
3806
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
3807
    if (!pos || isReadOnly(cm)) return;
3808
    // Might be a file drop, in which case we simply extract the text
3809
    // and insert it.
3810
    if (files && files.length && window.FileReader && window.File) {
3811
      var n = files.length, text = Array(n), read = 0;
3812
      var loadFile = function(file, i) {
3813
        var reader = new FileReader;
3814
        reader.onload = operation(cm, function() {
3815
          text[i] = reader.result;
3816
          if (++read == n) {
3817
            pos = clipPos(cm.doc, pos);
3818
            var change = {from: pos, to: pos,
3819
                          text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
3820
                          origin: "paste"};
3821
            makeChange(cm.doc, change);
3822
            setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
3823
          }
3824
        });
3825
        reader.readAsText(file);
3826
      };
3827
      for (var i = 0; i < n; ++i) loadFile(files[i], i);
3828
    } else { // Normal drop
3829
      // Don't do a replace if the drop happened inside of the selected text.
3830
      if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
3831
        cm.state.draggingText(e);
3832
        // Ensure the editor is re-focused
3833
        setTimeout(function() {cm.display.input.focus();}, 20);
3834
        return;
3835
      }
3836
      try {
3837
        var text = e.dataTransfer.getData("Text");
3838
        if (text) {
3839
          if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
3840
            var selected = cm.listSelections();
3841
          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
3842
          if (selected) for (var i = 0; i < selected.length; ++i)
3843
            replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
3844
          cm.replaceSelection(text, "around", "paste");
3845
          cm.display.input.focus();
3846
        }
3847
      }
3848
      catch(e){}
3849
    }
3850
  }
3851
 
3852
  function onDragStart(cm, e) {
3853
    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
3854
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
3855
 
3856
    e.dataTransfer.setData("Text", cm.getSelection());
3857
 
3858
    // Use dummy image instead of default browsers image.
3859
    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3860
    if (e.dataTransfer.setDragImage && !safari) {
3861
      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
3862
      img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3863
      if (presto) {
3864
        img.width = img.height = 1;
3865
        cm.display.wrapper.appendChild(img);
3866
        // Force a relayout, or Opera won't use our image for some obscure reason
3867
        img._top = img.offsetTop;
3868
      }
3869
      e.dataTransfer.setDragImage(img, 0, 0);
3870
      if (presto) img.parentNode.removeChild(img);
3871
    }
3872
  }
3873
 
3874
  function onDragOver(cm, e) {
3875
    var pos = posFromMouse(cm, e);
3876
    if (!pos) return;
3877
    var frag = document.createDocumentFragment();
3878
    drawSelectionCursor(cm, pos, frag);
3879
    if (!cm.display.dragCursor) {
3880
      cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
3881
      cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
3882
    }
3883
    removeChildrenAndAdd(cm.display.dragCursor, frag);
3884
  }
3885
 
3886
  function clearDragCursor(cm) {
3887
    if (cm.display.dragCursor) {
3888
      cm.display.lineSpace.removeChild(cm.display.dragCursor);
3889
      cm.display.dragCursor = null;
3890
    }
3891
  }
3892
 
3893
  // SCROLL EVENTS
3894
 
3895
  // Sync the scrollable area and scrollbars, ensure the viewport
3896
  // covers the visible area.
3897
  function setScrollTop(cm, val) {
3898
    if (Math.abs(cm.doc.scrollTop - val) < 2) return;
3899
    cm.doc.scrollTop = val;
3900
    if (!gecko) updateDisplaySimple(cm, {top: val});
3901
    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
3902
    cm.display.scrollbars.setScrollTop(val);
3903
    if (gecko) updateDisplaySimple(cm);
3904
    startWorker(cm, 100);
3905
  }
3906
  // Sync scroller and scrollbar, ensure the gutter elements are
3907
  // aligned.
3908
  function setScrollLeft(cm, val, isScroller) {
3909
    if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
3910
    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3911
    cm.doc.scrollLeft = val;
3912
    alignHorizontally(cm);
3913
    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
3914
    cm.display.scrollbars.setScrollLeft(val);
3915
  }
3916
 
3917
  // Since the delta values reported on mouse wheel events are
3918
  // unstandardized between browsers and even browser versions, and
3919
  // generally horribly unpredictable, this code starts by measuring
3920
  // the scroll effect that the first few mouse wheel events have,
3921
  // and, from that, detects the way it can convert deltas to pixel
3922
  // offsets afterwards.
3923
  //
3924
  // The reason we want to know the amount a wheel event will scroll
3925
  // is that it gives us a chance to update the display before the
3926
  // actual scrolling happens, reducing flickering.
3927
 
3928
  var wheelSamples = 0, wheelPixelsPerUnit = null;
3929
  // Fill in a browser-detected starting value on browsers where we
3930
  // know one. These don't have to be accurate -- the result of them
3931
  // being wrong would just be a slight flicker on the first wheel
3932
  // scroll (if it is large enough).
3933
  if (ie) wheelPixelsPerUnit = -.53;
3934
  else if (gecko) wheelPixelsPerUnit = 15;
3935
  else if (chrome) wheelPixelsPerUnit = -.7;
3936
  else if (safari) wheelPixelsPerUnit = -1/3;
3937
 
3938
  var wheelEventDelta = function(e) {
3939
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
3940
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
3941
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
3942
    else if (dy == null) dy = e.wheelDelta;
3943
    return {x: dx, y: dy};
3944
  };
3945
  CodeMirror.wheelEventPixels = function(e) {
3946
    var delta = wheelEventDelta(e);
3947
    delta.x *= wheelPixelsPerUnit;
3948
    delta.y *= wheelPixelsPerUnit;
3949
    return delta;
3950
  };
3951
 
3952
  function onScrollWheel(cm, e) {
3953
    var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
3954
 
3955
    var display = cm.display, scroll = display.scroller;
3956
    // Quit if there's nothing to scroll here
3957
    if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
3958
          dy && scroll.scrollHeight > scroll.clientHeight)) return;
3959
 
3960
    // Webkit browsers on OS X abort momentum scrolls when the target
3961
    // of the scroll event is removed from the scrollable element.
3962
    // This hack (see related code in patchDisplay) makes sure the
3963
    // element is kept around.
3964
    if (dy && mac && webkit) {
3965
      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
3966
        for (var i = 0; i < view.length; i++) {
3967
          if (view[i].node == cur) {
3968
            cm.display.currentWheelTarget = cur;
3969
            break outer;
3970
          }
3971
        }
3972
      }
3973
    }
3974
 
3975
    // On some browsers, horizontal scrolling will cause redraws to
3976
    // happen before the gutter has been realigned, causing it to
3977
    // wriggle around in a most unseemly way. When we have an
3978
    // estimated pixels/delta value, we just handle horizontal
3979
    // scrolling entirely here. It'll be slightly off from native, but
3980
    // better than glitching out.
3981
    if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
3982
      if (dy)
3983
        setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
3984
      setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
3985
      e_preventDefault(e);
3986
      display.wheelStartX = null; // Abort measurement, if in progress
3987
      return;
3988
    }
3989
 
3990
    // 'Project' the visible viewport to cover the area that is being
3991
    // scrolled into view (if we know enough to estimate it).
3992
    if (dy && wheelPixelsPerUnit != null) {
3993
      var pixels = dy * wheelPixelsPerUnit;
3994
      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
3995
      if (pixels < 0) top = Math.max(0, top + pixels - 50);
3996
      else bot = Math.min(cm.doc.height, bot + pixels + 50);
3997
      updateDisplaySimple(cm, {top: top, bottom: bot});
3998
    }
3999
 
4000
    if (wheelSamples < 20) {
4001
      if (display.wheelStartX == null) {
4002
        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4003
        display.wheelDX = dx; display.wheelDY = dy;
4004
        setTimeout(function() {
4005
          if (display.wheelStartX == null) return;
4006
          var movedX = scroll.scrollLeft - display.wheelStartX;
4007
          var movedY = scroll.scrollTop - display.wheelStartY;
4008
          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4009
            (movedX && display.wheelDX && movedX / display.wheelDX);
4010
          display.wheelStartX = display.wheelStartY = null;
4011
          if (!sample) return;
4012
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4013
          ++wheelSamples;
4014
        }, 200);
4015
      } else {
4016
        display.wheelDX += dx; display.wheelDY += dy;
4017
      }
4018
    }
4019
  }
4020
 
4021
  // KEY EVENTS
4022
 
4023
  // Run a handler that was bound to a key.
4024
  function doHandleBinding(cm, bound, dropShift) {
4025
    if (typeof bound == "string") {
4026
      bound = commands[bound];
4027
      if (!bound) return false;
4028
    }
4029
    // Ensure previous input has been read, so that the handler sees a
4030
    // consistent view of the document
4031
    cm.display.input.ensurePolled();
4032
    var prevShift = cm.display.shift, done = false;
4033
    try {
4034
      if (isReadOnly(cm)) cm.state.suppressEdits = true;
4035
      if (dropShift) cm.display.shift = false;
4036
      done = bound(cm) != Pass;
4037
    } finally {
4038
      cm.display.shift = prevShift;
4039
      cm.state.suppressEdits = false;
4040
    }
4041
    return done;
4042
  }
4043
 
4044
  function lookupKeyForEditor(cm, name, handle) {
4045
    for (var i = 0; i < cm.state.keyMaps.length; i++) {
4046
      var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
4047
      if (result) return result;
4048
    }
4049
    return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
4050
      || lookupKey(name, cm.options.keyMap, handle, cm);
4051
  }
4052
 
4053
  var stopSeq = new Delayed;
4054
  function dispatchKey(cm, name, e, handle) {
4055
    var seq = cm.state.keySeq;
4056
    if (seq) {
4057
      if (isModifierKey(name)) return "handled";
4058
      stopSeq.set(50, function() {
4059
        if (cm.state.keySeq == seq) {
4060
          cm.state.keySeq = null;
4061
          cm.display.input.reset();
4062
        }
4063
      });
4064
      name = seq + " " + name;
4065
    }
4066
    var result = lookupKeyForEditor(cm, name, handle);
4067
 
4068
    if (result == "multi")
4069
      cm.state.keySeq = name;
4070
    if (result == "handled")
4071
      signalLater(cm, "keyHandled", cm, name, e);
4072
 
4073
    if (result == "handled" || result == "multi") {
4074
      e_preventDefault(e);
4075
      restartBlink(cm);
4076
    }
4077
 
4078
    if (seq && !result && /\'$/.test(name)) {
4079
      e_preventDefault(e);
4080
      return true;
4081
    }
4082
    return !!result;
4083
  }
4084
 
4085
  // Handle a key from the keydown event.
4086
  function handleKeyBinding(cm, e) {
4087
    var name = keyName(e, true);
4088
    if (!name) return false;
4089
 
4090
    if (e.shiftKey && !cm.state.keySeq) {
4091
      // First try to resolve full name (including 'Shift-'). Failing
4092
      // that, see if there is a cursor-motion command (starting with
4093
      // 'go') bound to the keyname without 'Shift-'.
4094
      return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
4095
          || dispatchKey(cm, name, e, function(b) {
4096
               if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
4097
                 return doHandleBinding(cm, b);
4098
             });
4099
    } else {
4100
      return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
4101
    }
4102
  }
4103
 
4104
  // Handle a key from the keypress event
4105
  function handleCharBinding(cm, e, ch) {
4106
    return dispatchKey(cm, "'" + ch + "'", e,
4107
                       function(b) { return doHandleBinding(cm, b, true); });
4108
  }
4109
 
4110
  var lastStoppedKey = null;
4111
  function onKeyDown(e) {
4112
    var cm = this;
4113
    cm.curOp.focus = activeElt();
4114
    if (signalDOMEvent(cm, e)) return;
4115
    // IE does strange things with escape.
4116
    if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
4117
    var code = e.keyCode;
4118
    cm.display.shift = code == 16 || e.shiftKey;
4119
    var handled = handleKeyBinding(cm, e);
4120
    if (presto) {
4121
      lastStoppedKey = handled ? code : null;
4122
      // Opera has no cut event... we try to at least catch the key combo
4123
      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
4124
        cm.replaceSelection("", null, "cut");
4125
    }
4126
 
4127
    // Turn mouse into crosshair when Alt is held on Mac.
4128
    if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
4129
      showCrossHair(cm);
4130
  }
4131
 
4132
  function showCrossHair(cm) {
4133
    var lineDiv = cm.display.lineDiv;
4134
    addClass(lineDiv, "CodeMirror-crosshair");
4135
 
4136
    function up(e) {
4137
      if (e.keyCode == 18 || !e.altKey) {
4138
        rmClass(lineDiv, "CodeMirror-crosshair");
4139
        off(document, "keyup", up);
4140
        off(document, "mouseover", up);
4141
      }
4142
    }
4143
    on(document, "keyup", up);
4144
    on(document, "mouseover", up);
4145
  }
4146
 
4147
  function onKeyUp(e) {
4148
    if (e.keyCode == 16) this.doc.sel.shift = false;
4149
    signalDOMEvent(this, e);
4150
  }
4151
 
4152
  function onKeyPress(e) {
4153
    var cm = this;
4154
    if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
4155
    var keyCode = e.keyCode, charCode = e.charCode;
4156
    if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
4157
    if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
4158
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
4159
    if (handleCharBinding(cm, e, ch)) return;
4160
    cm.display.input.onKeyPress(e);
4161
  }
4162
 
4163
  // FOCUS/BLUR EVENTS
4164
 
4165
  function delayBlurEvent(cm) {
4166
    cm.state.delayingBlurEvent = true;
4167
    setTimeout(function() {
4168
      if (cm.state.delayingBlurEvent) {
4169
        cm.state.delayingBlurEvent = false;
4170
        onBlur(cm);
4171
      }
4172
    }, 100);
4173
  }
4174
 
4175
  function onFocus(cm) {
4176
    if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
4177
 
4178
    if (cm.options.readOnly == "nocursor") return;
4179
    if (!cm.state.focused) {
4180
      signal(cm, "focus", cm);
4181
      cm.state.focused = true;
4182
      addClass(cm.display.wrapper, "CodeMirror-focused");
4183
      // This test prevents this from firing when a context
4184
      // menu is closed (since the input reset would kill the
4185
      // select-all detection hack)
4186
      if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
4187
        cm.display.input.reset();
4188
        if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
4189
      }
4190
      cm.display.input.receivedFocus();
4191
    }
4192
    restartBlink(cm);
4193
  }
4194
  function onBlur(cm) {
4195
    if (cm.state.delayingBlurEvent) return;
4196
 
4197
    if (cm.state.focused) {
4198
      signal(cm, "blur", cm);
4199
      cm.state.focused = false;
4200
      rmClass(cm.display.wrapper, "CodeMirror-focused");
4201
    }
4202
    clearInterval(cm.display.blinker);
4203
    setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
4204
  }
4205
 
4206
  // CONTEXT MENU HANDLING
4207
 
4208
  // To make the context menu work, we need to briefly unhide the
4209
  // textarea (making it as unobtrusive as possible) to let the
4210
  // right-click take effect on it.
4211
  function onContextMenu(cm, e) {
4212
    if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
4213
    cm.display.input.onContextMenu(e);
4214
  }
4215
 
4216
  function contextMenuInGutter(cm, e) {
4217
    if (!hasHandler(cm, "gutterContextMenu")) return false;
4218
    return gutterEvent(cm, e, "gutterContextMenu", false, signal);
4219
  }
4220
 
4221
  // UPDATING
4222
 
4223
  // Compute the position of the end of a change (its 'to' property
4224
  // refers to the pre-change end).
4225
  var changeEnd = CodeMirror.changeEnd = function(change) {
4226
    if (!change.text) return change.to;
4227
    return Pos(change.from.line + change.text.length - 1,
4228
               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
4229
  };
4230
 
4231
  // Adjust a position to refer to the post-change position of the
4232
  // same text, or the end of the change if the change covers it.
4233
  function adjustForChange(pos, change) {
4234
    if (cmp(pos, change.from) < 0) return pos;
4235
    if (cmp(pos, change.to) <= 0) return changeEnd(change);
4236
 
4237
    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4238
    if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
4239
    return Pos(line, ch);
4240
  }
4241
 
4242
  function computeSelAfterChange(doc, change) {
4243
    var out = [];
4244
    for (var i = 0; i < doc.sel.ranges.length; i++) {
4245
      var range = doc.sel.ranges[i];
4246
      out.push(new Range(adjustForChange(range.anchor, change),
4247
                         adjustForChange(range.head, change)));
4248
    }
4249
    return normalizeSelection(out, doc.sel.primIndex);
4250
  }
4251
 
4252
  function offsetPos(pos, old, nw) {
4253
    if (pos.line == old.line)
4254
      return Pos(nw.line, pos.ch - old.ch + nw.ch);
4255
    else
4256
      return Pos(nw.line + (pos.line - old.line), pos.ch);
4257
  }
4258
 
4259
  // Used by replaceSelections to allow moving the selection to the
4260
  // start or around the replaced test. Hint may be "start" or "around".
4261
  function computeReplacedSel(doc, changes, hint) {
4262
    var out = [];
4263
    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4264
    for (var i = 0; i < changes.length; i++) {
4265
      var change = changes[i];
4266
      var from = offsetPos(change.from, oldPrev, newPrev);
4267
      var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4268
      oldPrev = change.to;
4269
      newPrev = to;
4270
      if (hint == "around") {
4271
        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4272
        out[i] = new Range(inv ? to : from, inv ? from : to);
4273
      } else {
4274
        out[i] = new Range(from, from);
4275
      }
4276
    }
4277
    return new Selection(out, doc.sel.primIndex);
4278
  }
4279
 
4280
  // Allow "beforeChange" event handlers to influence a change
4281
  function filterChange(doc, change, update) {
4282
    var obj = {
4283
      canceled: false,
4284
      from: change.from,
4285
      to: change.to,
4286
      text: change.text,
4287
      origin: change.origin,
4288
      cancel: function() { this.canceled = true; }
4289
    };
4290
    if (update) obj.update = function(from, to, text, origin) {
4291
      if (from) this.from = clipPos(doc, from);
4292
      if (to) this.to = clipPos(doc, to);
4293
      if (text) this.text = text;
4294
      if (origin !== undefined) this.origin = origin;
4295
    };
4296
    signal(doc, "beforeChange", doc, obj);
4297
    if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
4298
 
4299
    if (obj.canceled) return null;
4300
    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
4301
  }
4302
 
4303
  // Apply a change to a document, and add it to the document's
4304
  // history, and propagating it to all linked documents.
4305
  function makeChange(doc, change, ignoreReadOnly) {
4306
    if (doc.cm) {
4307
      if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
4308
      if (doc.cm.state.suppressEdits) return;
4309
    }
4310
 
4311
    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
4312
      change = filterChange(doc, change, true);
4313
      if (!change) return;
4314
    }
4315
 
4316
    // Possibly split or suppress the update based on the presence
4317
    // of read-only spans in its range.
4318
    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
4319
    if (split) {
4320
      for (var i = split.length - 1; i >= 0; --i)
4321
        makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
4322
    } else {
4323
      makeChangeInner(doc, change);
4324
    }
4325
  }
4326
 
4327
  function makeChangeInner(doc, change) {
4328
    if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
4329
    var selAfter = computeSelAfterChange(doc, change);
4330
    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
4331
 
4332
    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
4333
    var rebased = [];
4334
 
4335
    linkedDocs(doc, function(doc, sharedHist) {
4336
      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4337
        rebaseHist(doc.history, change);
4338
        rebased.push(doc.history);
4339
      }
4340
      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
4341
    });
4342
  }
4343
 
4344
  // Revert a change stored in a document's history.
4345
  function makeChangeFromHistory(doc, type, allowSelectionOnly) {
4346
    if (doc.cm && doc.cm.state.suppressEdits) return;
4347
 
4348
    var hist = doc.history, event, selAfter = doc.sel;
4349
    var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
4350
 
4351
    // Verify that there is a useable event (so that ctrl-z won't
4352
    // needlessly clear selection events)
4353
    for (var i = 0; i < source.length; i++) {
4354
      event = source[i];
4355
      if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
4356
        break;
4357
    }
4358
    if (i == source.length) return;
4359
    hist.lastOrigin = hist.lastSelOrigin = null;
4360
 
4361
    for (;;) {
4362
      event = source.pop();
4363
      if (event.ranges) {
4364
        pushSelectionToHistory(event, dest);
4365
        if (allowSelectionOnly && !event.equals(doc.sel)) {
4366
          setSelection(doc, event, {clearRedo: false});
4367
          return;
4368
        }
4369
        selAfter = event;
4370
      }
4371
      else break;
4372
    }
4373
 
4374
    // Build up a reverse change object to add to the opposite history
4375
    // stack (redo when undoing, and vice versa).
4376
    var antiChanges = [];
4377
    pushSelectionToHistory(selAfter, dest);
4378
    dest.push({changes: antiChanges, generation: hist.generation});
4379
    hist.generation = event.generation || ++hist.maxGeneration;
4380
 
4381
    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
4382
 
4383
    for (var i = event.changes.length - 1; i >= 0; --i) {
4384
      var change = event.changes[i];
4385
      change.origin = type;
4386
      if (filter && !filterChange(doc, change, false)) {
4387
        source.length = 0;
4388
        return;
4389
      }
4390
 
4391
      antiChanges.push(historyChangeFromChange(doc, change));
4392
 
4393
      var after = i ? computeSelAfterChange(doc, change) : lst(source);
4394
      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
4395
      if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
4396
      var rebased = [];
4397
 
4398
      // Propagate to the linked documents
4399
      linkedDocs(doc, function(doc, sharedHist) {
4400
        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4401
          rebaseHist(doc.history, change);
4402
          rebased.push(doc.history);
4403
        }
4404
        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
4405
      });
4406
    }
4407
  }
4408
 
4409
  // Sub-views need their line numbers shifted when text is added
4410
  // above or below them in the parent document.
4411
  function shiftDoc(doc, distance) {
4412
    if (distance == 0) return;
4413
    doc.first += distance;
4414
    doc.sel = new Selection(map(doc.sel.ranges, function(range) {
4415
      return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
4416
                       Pos(range.head.line + distance, range.head.ch));
4417
    }), doc.sel.primIndex);
4418
    if (doc.cm) {
4419
      regChange(doc.cm, doc.first, doc.first - distance, distance);
4420
      for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
4421
        regLineChange(doc.cm, l, "gutter");
4422
    }
4423
  }
4424
 
4425
  // More lower-level change function, handling only a single document
4426
  // (not linked ones).
4427
  function makeChangeSingleDoc(doc, change, selAfter, spans) {
4428
    if (doc.cm && !doc.cm.curOp)
4429
      return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
4430
 
4431
    if (change.to.line < doc.first) {
4432
      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
4433
      return;
4434
    }
4435
    if (change.from.line > doc.lastLine()) return;
4436
 
4437
    // Clip the change to the size of this doc
4438
    if (change.from.line < doc.first) {
4439
      var shift = change.text.length - 1 - (doc.first - change.from.line);
4440
      shiftDoc(doc, shift);
4441
      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
4442
                text: [lst(change.text)], origin: change.origin};
4443
    }
4444
    var last = doc.lastLine();
4445
    if (change.to.line > last) {
4446
      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
4447
                text: [change.text[0]], origin: change.origin};
4448
    }
4449
 
4450
    change.removed = getBetween(doc, change.from, change.to);
4451
 
4452
    if (!selAfter) selAfter = computeSelAfterChange(doc, change);
4453
    if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
4454
    else updateDoc(doc, change, spans);
4455
    setSelectionNoUndo(doc, selAfter, sel_dontScroll);
4456
  }
4457
 
4458
  // Handle the interaction of a change to a document with the editor
4459
  // that this document is part of.
4460
  function makeChangeSingleDocInEditor(cm, change, spans) {
4461
    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
4462
 
4463
    var recomputeMaxLength = false, checkWidthStart = from.line;
4464
    if (!cm.options.lineWrapping) {
4465
      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
4466
      doc.iter(checkWidthStart, to.line + 1, function(line) {
4467
        if (line == display.maxLine) {
4468
          recomputeMaxLength = true;
4469
          return true;
4470
        }
4471
      });
4472
    }
4473
 
4474
    if (doc.sel.contains(change.from, change.to) > -1)
4475
      signalCursorActivity(cm);
4476
 
4477
    updateDoc(doc, change, spans, estimateHeight(cm));
4478
 
4479
    if (!cm.options.lineWrapping) {
4480
      doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
4481
        var len = lineLength(line);
4482
        if (len > display.maxLineLength) {
4483
          display.maxLine = line;
4484
          display.maxLineLength = len;
4485
          display.maxLineChanged = true;
4486
          recomputeMaxLength = false;
4487
        }
4488
      });
4489
      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
4490
    }
4491
 
4492
    // Adjust frontier, schedule worker
4493
    doc.frontier = Math.min(doc.frontier, from.line);
4494
    startWorker(cm, 400);
4495
 
4496
    var lendiff = change.text.length - (to.line - from.line) - 1;
4497
    // Remember that these lines changed, for updating the display
4498
    if (change.full)
4499
      regChange(cm);
4500
    else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
4501
      regLineChange(cm, from.line, "text");
4502
    else
4503
      regChange(cm, from.line, to.line + 1, lendiff);
4504
 
4505
    var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
4506
    if (changeHandler || changesHandler) {
4507
      var obj = {
4508
        from: from, to: to,
4509
        text: change.text,
4510
        removed: change.removed,
4511
        origin: change.origin
4512
      };
4513
      if (changeHandler) signalLater(cm, "change", cm, obj);
4514
      if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
4515
    }
4516
    cm.display.selForContextMenu = null;
4517
  }
4518
 
4519
  function replaceRange(doc, code, from, to, origin) {
4520
    if (!to) to = from;
4521
    if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
4522
    if (typeof code == "string") code = doc.splitLines(code);
4523
    makeChange(doc, {from: from, to: to, text: code, origin: origin});
4524
  }
4525
 
4526
  // SCROLLING THINGS INTO VIEW
4527
 
4528
  // If an editor sits on the top or bottom of the window, partially
4529
  // scrolled out of view, this ensures that the cursor is visible.
4530
  function maybeScrollWindow(cm, coords) {
4531
    if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
4532
 
4533
    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
4534
    if (coords.top + box.top < 0) doScroll = true;
4535
    else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
4536
    if (doScroll != null && !phantom) {
4537
      var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
4538
                           (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
4539
                           (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
4540
                           coords.left + "px; width: 2px;");
4541
      cm.display.lineSpace.appendChild(scrollNode);
4542
      scrollNode.scrollIntoView(doScroll);
4543
      cm.display.lineSpace.removeChild(scrollNode);
4544
    }
4545
  }
4546
 
4547
  // Scroll a given position into view (immediately), verifying that
4548
  // it actually became visible (as line heights are accurately
4549
  // measured, the position of something may 'drift' during drawing).
4550
  function scrollPosIntoView(cm, pos, end, margin) {
4551
    if (margin == null) margin = 0;
4552
    for (var limit = 0; limit < 5; limit++) {
4553
      var changed = false, coords = cursorCoords(cm, pos);
4554
      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
4555
      var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
4556
                                         Math.min(coords.top, endCoords.top) - margin,
4557
                                         Math.max(coords.left, endCoords.left),
4558
                                         Math.max(coords.bottom, endCoords.bottom) + margin);
4559
      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
4560
      if (scrollPos.scrollTop != null) {
4561
        setScrollTop(cm, scrollPos.scrollTop);
4562
        if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
4563
      }
4564
      if (scrollPos.scrollLeft != null) {
4565
        setScrollLeft(cm, scrollPos.scrollLeft);
4566
        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
4567
      }
4568
      if (!changed) break;
4569
    }
4570
    return coords;
4571
  }
4572
 
4573
  // Scroll a given set of coordinates into view (immediately).
4574
  function scrollIntoView(cm, x1, y1, x2, y2) {
4575
    var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
4576
    if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
4577
    if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
4578
  }
4579
 
4580
  // Calculate a new scroll position needed to scroll the given
4581
  // rectangle into view. Returns an object with scrollTop and
4582
  // scrollLeft properties. When these are undefined, the
4583
  // vertical/horizontal position does not need to be adjusted.
4584
  function calculateScrollPos(cm, x1, y1, x2, y2) {
4585
    var display = cm.display, snapMargin = textHeight(cm.display);
4586
    if (y1 < 0) y1 = 0;
4587
    var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
4588
    var screen = displayHeight(cm), result = {};
4589
    if (y2 - y1 > screen) y2 = y1 + screen;
4590
    var docBottom = cm.doc.height + paddingVert(display);
4591
    var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
4592
    if (y1 < screentop) {
4593
      result.scrollTop = atTop ? 0 : y1;
4594
    } else if (y2 > screentop + screen) {
4595
      var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
4596
      if (newTop != screentop) result.scrollTop = newTop;
4597
    }
4598
 
4599
    var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
4600
    var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
4601
    var tooWide = x2 - x1 > screenw;
4602
    if (tooWide) x2 = x1 + screenw;
4603
    if (x1 < 10)
4604
      result.scrollLeft = 0;
4605
    else if (x1 < screenleft)
4606
      result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
4607
    else if (x2 > screenw + screenleft - 3)
4608
      result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
4609
    return result;
4610
  }
4611
 
4612
  // Store a relative adjustment to the scroll position in the current
4613
  // operation (to be applied when the operation finishes).
4614
  function addToScrollPos(cm, left, top) {
4615
    if (left != null || top != null) resolveScrollToPos(cm);
4616
    if (left != null)
4617
      cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
4618
    if (top != null)
4619
      cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
4620
  }
4621
 
4622
  // Make sure that at the end of the operation the current cursor is
4623
  // shown.
4624
  function ensureCursorVisible(cm) {
4625
    resolveScrollToPos(cm);
4626
    var cur = cm.getCursor(), from = cur, to = cur;
4627
    if (!cm.options.lineWrapping) {
4628
      from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
4629
      to = Pos(cur.line, cur.ch + 1);
4630
    }
4631
    cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
4632
  }
4633
 
4634
  // When an operation has its scrollToPos property set, and another
4635
  // scroll action is applied before the end of the operation, this
4636
  // 'simulates' scrolling that position into view in a cheap way, so
4637
  // that the effect of intermediate scroll commands is not ignored.
4638
  function resolveScrollToPos(cm) {
4639
    var range = cm.curOp.scrollToPos;
4640
    if (range) {
4641
      cm.curOp.scrollToPos = null;
4642
      var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
4643
      var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
4644
                                    Math.min(from.top, to.top) - range.margin,
4645
                                    Math.max(from.right, to.right),
4646
                                    Math.max(from.bottom, to.bottom) + range.margin);
4647
      cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4648
    }
4649
  }
4650
 
4651
  // API UTILITIES
4652
 
4653
  // Indent the given line. The how parameter can be "smart",
4654
  // "add"/null, "subtract", or "prev". When aggressive is false
4655
  // (typically set to true for forced single-line indents), empty
4656
  // lines are not indented, and places where the mode returns Pass
4657
  // are left alone.
4658
  function indentLine(cm, n, how, aggressive) {
4659
    var doc = cm.doc, state;
4660
    if (how == null) how = "add";
4661
    if (how == "smart") {
4662
      // Fall back to "prev" when the mode doesn't have an indentation
4663
      // method.
4664
      if (!doc.mode.indent) how = "prev";
4665
      else state = getStateBefore(cm, n);
4666
    }
4667
 
4668
    var tabSize = cm.options.tabSize;
4669
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
4670
    if (line.stateAfter) line.stateAfter = null;
4671
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
4672
    if (!aggressive && !/\S/.test(line.text)) {
4673
      indentation = 0;
4674
      how = "not";
4675
    } else if (how == "smart") {
4676
      indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
4677
      if (indentation == Pass || indentation > 150) {
4678
        if (!aggressive) return;
4679
        how = "prev";
4680
      }
4681
    }
4682
    if (how == "prev") {
4683
      if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
4684
      else indentation = 0;
4685
    } else if (how == "add") {
4686
      indentation = curSpace + cm.options.indentUnit;
4687
    } else if (how == "subtract") {
4688
      indentation = curSpace - cm.options.indentUnit;
4689
    } else if (typeof how == "number") {
4690
      indentation = curSpace + how;
4691
    }
4692
    indentation = Math.max(0, indentation);
4693
 
4694
    var indentString = "", pos = 0;
4695
    if (cm.options.indentWithTabs)
4696
      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
4697
    if (pos < indentation) indentString += spaceStr(indentation - pos);
4698
 
4699
    if (indentString != curSpaceString) {
4700
      replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
4701
      line.stateAfter = null;
4702
      return true;
4703
    } else {
4704
      // Ensure that, if the cursor was in the whitespace at the start
4705
      // of the line, it is moved to the end of that space.
4706
      for (var i = 0; i < doc.sel.ranges.length; i++) {
4707
        var range = doc.sel.ranges[i];
4708
        if (range.head.line == n && range.head.ch < curSpaceString.length) {
4709
          var pos = Pos(n, curSpaceString.length);
4710
          replaceOneSelection(doc, i, new Range(pos, pos));
4711
          break;
4712
        }
4713
      }
4714
    }
4715
  }
4716
 
4717
  // Utility for applying a change to a line by handle or number,
4718
  // returning the number and optionally registering the line as
4719
  // changed.
4720
  function changeLine(doc, handle, changeType, op) {
4721
    var no = handle, line = handle;
4722
    if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
4723
    else no = lineNo(handle);
4724
    if (no == null) return null;
4725
    if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
4726
    return line;
4727
  }
4728
 
4729
  // Helper for deleting text near the selection(s), used to implement
4730
  // backspace, delete, and similar functionality.
4731
  function deleteNearSelection(cm, compute) {
4732
    var ranges = cm.doc.sel.ranges, kill = [];
4733
    // Build up a set of ranges to kill first, merging overlapping
4734
    // ranges.
4735
    for (var i = 0; i < ranges.length; i++) {
4736
      var toKill = compute(ranges[i]);
4737
      while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
4738
        var replaced = kill.pop();
4739
        if (cmp(replaced.from, toKill.from) < 0) {
4740
          toKill.from = replaced.from;
4741
          break;
4742
        }
4743
      }
4744
      kill.push(toKill);
4745
    }
4746
    // Next, remove those actual ranges.
4747
    runInOp(cm, function() {
4748
      for (var i = kill.length - 1; i >= 0; i--)
4749
        replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
4750
      ensureCursorVisible(cm);
4751
    });
4752
  }
4753
 
4754
  // Used for horizontal relative motion. Dir is -1 or 1 (left or
4755
  // right), unit can be "char", "column" (like char, but doesn't
4756
  // cross line boundaries), "word" (across next word), or "group" (to
4757
  // the start of next group of word or non-word-non-whitespace
4758
  // chars). The visually param controls whether, in right-to-left
4759
  // text, direction 1 means to move towards the next index in the
4760
  // string, or towards the character to the right of the current
4761
  // position. The resulting position will have a hitSide=true
4762
  // property if it reached the end of the document.
4763
  function findPosH(doc, pos, dir, unit, visually) {
4764
    var line = pos.line, ch = pos.ch, origDir = dir;
4765
    var lineObj = getLine(doc, line);
4766
    var possible = true;
4767
    function findNextLine() {
4768
      var l = line + dir;
4769
      if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
4770
      line = l;
4771
      return lineObj = getLine(doc, l);
4772
    }
4773
    function moveOnce(boundToLine) {
4774
      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
4775
      if (next == null) {
4776
        if (!boundToLine && findNextLine()) {
4777
          if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
4778
          else ch = dir < 0 ? lineObj.text.length : 0;
4779
        } else return (possible = false);
4780
      } else ch = next;
4781
      return true;
4782
    }
4783
 
4784
    if (unit == "char") moveOnce();
4785
    else if (unit == "column") moveOnce(true);
4786
    else if (unit == "word" || unit == "group") {
4787
      var sawType = null, group = unit == "group";
4788
      var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
4789
      for (var first = true;; first = false) {
4790
        if (dir < 0 && !moveOnce(!first)) break;
4791
        var cur = lineObj.text.charAt(ch) || "\n";
4792
        var type = isWordChar(cur, helper) ? "w"
4793
          : group && cur == "\n" ? "n"
4794
          : !group || /\s/.test(cur) ? null
4795
          : "p";
4796
        if (group && !first && !type) type = "s";
4797
        if (sawType && sawType != type) {
4798
          if (dir < 0) {dir = 1; moveOnce();}
4799
          break;
4800
        }
4801
 
4802
        if (type) sawType = type;
4803
        if (dir > 0 && !moveOnce(!first)) break;
4804
      }
4805
    }
4806
    var result = skipAtomic(doc, Pos(line, ch), origDir, true);
4807
    if (!possible) result.hitSide = true;
4808
    return result;
4809
  }
4810
 
4811
  // For relative vertical movement. Dir may be -1 or 1. Unit can be
4812
  // "page" or "line". The resulting position will have a hitSide=true
4813
  // property if it reached the end of the document.
4814
  function findPosV(cm, pos, dir, unit) {
4815
    var doc = cm.doc, x = pos.left, y;
4816
    if (unit == "page") {
4817
      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
4818
      y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
4819
    } else if (unit == "line") {
4820
      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
4821
    }
4822
    for (;;) {
4823
      var target = coordsChar(cm, x, y);
4824
      if (!target.outside) break;
4825
      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
4826
      y += dir * 5;
4827
    }
4828
    return target;
4829
  }
4830
 
4831
  // EDITOR METHODS
4832
 
4833
  // The publicly visible API. Note that methodOp(f) means
4834
  // 'wrap f in an operation, performed on its `this` parameter'.
4835
 
4836
  // This is not the complete set of editor methods. Most of the
4837
  // methods defined on the Doc type are also injected into
4838
  // CodeMirror.prototype, for backwards compatibility and
4839
  // convenience.
4840
 
4841
  CodeMirror.prototype = {
4842
    constructor: CodeMirror,
4843
    focus: function(){window.focus(); this.display.input.focus();},
4844
 
4845
    setOption: function(option, value) {
4846
      var options = this.options, old = options[option];
4847
      if (options[option] == value && option != "mode") return;
4848
      options[option] = value;
4849
      if (optionHandlers.hasOwnProperty(option))
4850
        operation(this, optionHandlers[option])(this, value, old);
4851
    },
4852
 
4853
    getOption: function(option) {return this.options[option];},
4854
    getDoc: function() {return this.doc;},
4855
 
4856
    addKeyMap: function(map, bottom) {
4857
      this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
4858
    },
4859
    removeKeyMap: function(map) {
4860
      var maps = this.state.keyMaps;
4861
      for (var i = 0; i < maps.length; ++i)
4862
        if (maps[i] == map || maps[i].name == map) {
4863
          maps.splice(i, 1);
4864
          return true;
4865
        }
4866
    },
4867
 
4868
    addOverlay: methodOp(function(spec, options) {
4869
      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
4870
      if (mode.startState) throw new Error("Overlays may not be stateful.");
4871
      this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
4872
      this.state.modeGen++;
4873
      regChange(this);
4874
    }),
4875
    removeOverlay: methodOp(function(spec) {
4876
      var overlays = this.state.overlays;
4877
      for (var i = 0; i < overlays.length; ++i) {
4878
        var cur = overlays[i].modeSpec;
4879
        if (cur == spec || typeof spec == "string" && cur.name == spec) {
4880
          overlays.splice(i, 1);
4881
          this.state.modeGen++;
4882
          regChange(this);
4883
          return;
4884
        }
4885
      }
4886
    }),
4887
 
4888
    indentLine: methodOp(function(n, dir, aggressive) {
4889
      if (typeof dir != "string" && typeof dir != "number") {
4890
        if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
4891
        else dir = dir ? "add" : "subtract";
4892
      }
4893
      if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
4894
    }),
4895
    indentSelection: methodOp(function(how) {
4896
      var ranges = this.doc.sel.ranges, end = -1;
4897
      for (var i = 0; i < ranges.length; i++) {
4898
        var range = ranges[i];
4899
        if (!range.empty()) {
4900
          var from = range.from(), to = range.to();
4901
          var start = Math.max(end, from.line);
4902
          end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
4903
          for (var j = start; j < end; ++j)
4904
            indentLine(this, j, how);
4905
          var newRanges = this.doc.sel.ranges;
4906
          if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
4907
            replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
4908
        } else if (range.head.line > end) {
4909
          indentLine(this, range.head.line, how, true);
4910
          end = range.head.line;
4911
          if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
4912
        }
4913
      }
4914
    }),
4915
 
4916
    // Fetch the parser token for a given character. Useful for hacks
4917
    // that want to inspect the mode state (say, for completion).
4918
    getTokenAt: function(pos, precise) {
4919
      return takeToken(this, pos, precise);
4920
    },
4921
 
4922
    getLineTokens: function(line, precise) {
4923
      return takeToken(this, Pos(line), precise, true);
4924
    },
4925
 
4926
    getTokenTypeAt: function(pos) {
4927
      pos = clipPos(this.doc, pos);
4928
      var styles = getLineStyles(this, getLine(this.doc, pos.line));
4929
      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
4930
      var type;
4931
      if (ch == 0) type = styles[2];
4932
      else for (;;) {
4933
        var mid = (before + after) >> 1;
4934
        if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
4935
        else if (styles[mid * 2 + 1] < ch) before = mid + 1;
4936
        else { type = styles[mid * 2 + 2]; break; }
4937
      }
4938
      var cut = type ? type.indexOf("cm-overlay ") : -1;
4939
      return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
4940
    },
4941
 
4942
    getModeAt: function(pos) {
4943
      var mode = this.doc.mode;
4944
      if (!mode.innerMode) return mode;
4945
      return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
4946
    },
4947
 
4948
    getHelper: function(pos, type) {
4949
      return this.getHelpers(pos, type)[0];
4950
    },
4951
 
4952
    getHelpers: function(pos, type) {
4953
      var found = [];
4954
      if (!helpers.hasOwnProperty(type)) return found;
4955
      var help = helpers[type], mode = this.getModeAt(pos);
4956
      if (typeof mode[type] == "string") {
4957
        if (help[mode[type]]) found.push(help[mode[type]]);
4958
      } else if (mode[type]) {
4959
        for (var i = 0; i < mode[type].length; i++) {
4960
          var val = help[mode[type][i]];
4961
          if (val) found.push(val);
4962
        }
4963
      } else if (mode.helperType && help[mode.helperType]) {
4964
        found.push(help[mode.helperType]);
4965
      } else if (help[mode.name]) {
4966
        found.push(help[mode.name]);
4967
      }
4968
      for (var i = 0; i < help._global.length; i++) {
4969
        var cur = help._global[i];
4970
        if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
4971
          found.push(cur.val);
4972
      }
4973
      return found;
4974
    },
4975
 
4976
    getStateAfter: function(line, precise) {
4977
      var doc = this.doc;
4978
      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
4979
      return getStateBefore(this, line + 1, precise);
4980
    },
4981
 
4982
    cursorCoords: function(start, mode) {
4983
      var pos, range = this.doc.sel.primary();
4984
      if (start == null) pos = range.head;
4985
      else if (typeof start == "object") pos = clipPos(this.doc, start);
4986
      else pos = start ? range.from() : range.to();
4987
      return cursorCoords(this, pos, mode || "page");
4988
    },
4989
 
4990
    charCoords: function(pos, mode) {
4991
      return charCoords(this, clipPos(this.doc, pos), mode || "page");
4992
    },
4993
 
4994
    coordsChar: function(coords, mode) {
4995
      coords = fromCoordSystem(this, coords, mode || "page");
4996
      return coordsChar(this, coords.left, coords.top);
4997
    },
4998
 
4999
    lineAtHeight: function(height, mode) {
5000
      height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
5001
      return lineAtHeight(this.doc, height + this.display.viewOffset);
5002
    },
5003
    heightAtLine: function(line, mode) {
5004
      var end = false, lineObj;
5005
      if (typeof line == "number") {
5006
        var last = this.doc.first + this.doc.size - 1;
5007
        if (line < this.doc.first) line = this.doc.first;
5008
        else if (line > last) { line = last; end = true; }
5009
        lineObj = getLine(this.doc, line);
5010
      } else {
5011
        lineObj = line;
5012
      }
5013
      return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
5014
        (end ? this.doc.height - heightAtLine(lineObj) : 0);
5015
    },
5016
 
5017
    defaultTextHeight: function() { return textHeight(this.display); },
5018
    defaultCharWidth: function() { return charWidth(this.display); },
5019
 
5020
    setGutterMarker: methodOp(function(line, gutterID, value) {
5021
      return changeLine(this.doc, line, "gutter", function(line) {
5022
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
5023
        markers[gutterID] = value;
5024
        if (!value && isEmpty(markers)) line.gutterMarkers = null;
5025
        return true;
5026
      });
5027
    }),
5028
 
5029
    clearGutter: methodOp(function(gutterID) {
5030
      var cm = this, doc = cm.doc, i = doc.first;
5031
      doc.iter(function(line) {
5032
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
5033
          line.gutterMarkers[gutterID] = null;
5034
          regLineChange(cm, i, "gutter");
5035
          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
5036
        }
5037
        ++i;
5038
      });
5039
    }),
5040
 
5041
    lineInfo: function(line) {
5042
      if (typeof line == "number") {
5043
        if (!isLine(this.doc, line)) return null;
5044
        var n = line;
5045
        line = getLine(this.doc, line);
5046
        if (!line) return null;
5047
      } else {
5048
        var n = lineNo(line);
5049
        if (n == null) return null;
5050
      }
5051
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
5052
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
5053
              widgets: line.widgets};
5054
    },
5055
 
5056
    getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
5057
 
5058
    addWidget: function(pos, node, scroll, vert, horiz) {
5059
      var display = this.display;
5060
      pos = cursorCoords(this, clipPos(this.doc, pos));
5061
      var top = pos.bottom, left = pos.left;
5062
      node.style.position = "absolute";
5063
      node.setAttribute("cm-ignore-events", "true");
5064
      this.display.input.setUneditable(node);
5065
      display.sizer.appendChild(node);
5066
      if (vert == "over") {
5067
        top = pos.top;
5068
      } else if (vert == "above" || vert == "near") {
5069
        var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
5070
        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
5071
        // Default to positioning above (if specified and possible); otherwise default to positioning below
5072
        if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
5073
          top = pos.top - node.offsetHeight;
5074
        else if (pos.bottom + node.offsetHeight <= vspace)
5075
          top = pos.bottom;
5076
        if (left + node.offsetWidth > hspace)
5077
          left = hspace - node.offsetWidth;
5078
      }
5079
      node.style.top = top + "px";
5080
      node.style.left = node.style.right = "";
5081
      if (horiz == "right") {
5082
        left = display.sizer.clientWidth - node.offsetWidth;
5083
        node.style.right = "0px";
5084
      } else {
5085
        if (horiz == "left") left = 0;
5086
        else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
5087
        node.style.left = left + "px";
5088
      }
5089
      if (scroll)
5090
        scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
5091
    },
5092
 
5093
    triggerOnKeyDown: methodOp(onKeyDown),
5094
    triggerOnKeyPress: methodOp(onKeyPress),
5095
    triggerOnKeyUp: onKeyUp,
5096
 
5097
    execCommand: function(cmd) {
5098
      if (commands.hasOwnProperty(cmd))
5099
        return commands[cmd].call(null, this);
5100
    },
5101
 
5102
    triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
5103
 
5104
    findPosH: function(from, amount, unit, visually) {
5105
      var dir = 1;
5106
      if (amount < 0) { dir = -1; amount = -amount; }
5107
      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5108
        cur = findPosH(this.doc, cur, dir, unit, visually);
5109
        if (cur.hitSide) break;
5110
      }
5111
      return cur;
5112
    },
5113
 
5114
    moveH: methodOp(function(dir, unit) {
5115
      var cm = this;
5116
      cm.extendSelectionsBy(function(range) {
5117
        if (cm.display.shift || cm.doc.extend || range.empty())
5118
          return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
5119
        else
5120
          return dir < 0 ? range.from() : range.to();
5121
      }, sel_move);
5122
    }),
5123
 
5124
    deleteH: methodOp(function(dir, unit) {
5125
      var sel = this.doc.sel, doc = this.doc;
5126
      if (sel.somethingSelected())
5127
        doc.replaceSelection("", null, "+delete");
5128
      else
5129
        deleteNearSelection(this, function(range) {
5130
          var other = findPosH(doc, range.head, dir, unit, false);
5131
          return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
5132
        });
5133
    }),
5134
 
5135
    findPosV: function(from, amount, unit, goalColumn) {
5136
      var dir = 1, x = goalColumn;
5137
      if (amount < 0) { dir = -1; amount = -amount; }
5138
      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5139
        var coords = cursorCoords(this, cur, "div");
5140
        if (x == null) x = coords.left;
5141
        else coords.left = x;
5142
        cur = findPosV(this, coords, dir, unit);
5143
        if (cur.hitSide) break;
5144
      }
5145
      return cur;
5146
    },
5147
 
5148
    moveV: methodOp(function(dir, unit) {
5149
      var cm = this, doc = this.doc, goals = [];
5150
      var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
5151
      doc.extendSelectionsBy(function(range) {
5152
        if (collapse)
5153
          return dir < 0 ? range.from() : range.to();
5154
        var headPos = cursorCoords(cm, range.head, "div");
5155
        if (range.goalColumn != null) headPos.left = range.goalColumn;
5156
        goals.push(headPos.left);
5157
        var pos = findPosV(cm, headPos, dir, unit);
5158
        if (unit == "page" && range == doc.sel.primary())
5159
          addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
5160
        return pos;
5161
      }, sel_move);
5162
      if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
5163
        doc.sel.ranges[i].goalColumn = goals[i];
5164
    }),
5165
 
5166
    // Find the word at the given position (as returned by coordsChar).
5167
    findWordAt: function(pos) {
5168
      var doc = this.doc, line = getLine(doc, pos.line).text;
5169
      var start = pos.ch, end = pos.ch;
5170
      if (line) {
5171
        var helper = this.getHelper(pos, "wordChars");
5172
        if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
5173
        var startChar = line.charAt(start);
5174
        var check = isWordChar(startChar, helper)
5175
          ? function(ch) { return isWordChar(ch, helper); }
5176
          : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
5177
          : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
5178
        while (start > 0 && check(line.charAt(start - 1))) --start;
5179
        while (end < line.length && check(line.charAt(end))) ++end;
5180
      }
5181
      return new Range(Pos(pos.line, start), Pos(pos.line, end));
5182
    },
5183
 
5184
    toggleOverwrite: function(value) {
5185
      if (value != null && value == this.state.overwrite) return;
5186
      if (this.state.overwrite = !this.state.overwrite)
5187
        addClass(this.display.cursorDiv, "CodeMirror-overwrite");
5188
      else
5189
        rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
5190
 
5191
      signal(this, "overwriteToggle", this, this.state.overwrite);
5192
    },
5193
    hasFocus: function() { return this.display.input.getField() == activeElt(); },
5194
 
5195
    scrollTo: methodOp(function(x, y) {
5196
      if (x != null || y != null) resolveScrollToPos(this);
5197
      if (x != null) this.curOp.scrollLeft = x;
5198
      if (y != null) this.curOp.scrollTop = y;
5199
    }),
5200
    getScrollInfo: function() {
5201
      var scroller = this.display.scroller;
5202
      return {left: scroller.scrollLeft, top: scroller.scrollTop,
5203
              height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
5204
              width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
5205
              clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
5206
    },
5207
 
5208
    scrollIntoView: methodOp(function(range, margin) {
5209
      if (range == null) {
5210
        range = {from: this.doc.sel.primary().head, to: null};
5211
        if (margin == null) margin = this.options.cursorScrollMargin;
5212
      } else if (typeof range == "number") {
5213
        range = {from: Pos(range, 0), to: null};
5214
      } else if (range.from == null) {
5215
        range = {from: range, to: null};
5216
      }
5217
      if (!range.to) range.to = range.from;
5218
      range.margin = margin || 0;
5219
 
5220
      if (range.from.line != null) {
5221
        resolveScrollToPos(this);
5222
        this.curOp.scrollToPos = range;
5223
      } else {
5224
        var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
5225
                                      Math.min(range.from.top, range.to.top) - range.margin,
5226
                                      Math.max(range.from.right, range.to.right),
5227
                                      Math.max(range.from.bottom, range.to.bottom) + range.margin);
5228
        this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
5229
      }
5230
    }),
5231
 
5232
    setSize: methodOp(function(width, height) {
5233
      var cm = this;
5234
      function interpret(val) {
5235
        return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
5236
      }
5237
      if (width != null) cm.display.wrapper.style.width = interpret(width);
5238
      if (height != null) cm.display.wrapper.style.height = interpret(height);
5239
      if (cm.options.lineWrapping) clearLineMeasurementCache(this);
5240
      var lineNo = cm.display.viewFrom;
5241
      cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
5242
        if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
5243
          if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
5244
        ++lineNo;
5245
      });
5246
      cm.curOp.forceUpdate = true;
5247
      signal(cm, "refresh", this);
5248
    }),
5249
 
5250
    operation: function(f){return runInOp(this, f);},
5251
 
5252
    refresh: methodOp(function() {
5253
      var oldHeight = this.display.cachedTextHeight;
5254
      regChange(this);
5255
      this.curOp.forceUpdate = true;
5256
      clearCaches(this);
5257
      this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
5258
      updateGutterSpace(this);
5259
      if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
5260
        estimateLineHeights(this);
5261
      signal(this, "refresh", this);
5262
    }),
5263
 
5264
    swapDoc: methodOp(function(doc) {
5265
      var old = this.doc;
5266
      old.cm = null;
5267
      attachDoc(this, doc);
5268
      clearCaches(this);
5269
      this.display.input.reset();
5270
      this.scrollTo(doc.scrollLeft, doc.scrollTop);
5271
      this.curOp.forceScroll = true;
5272
      signalLater(this, "swapDoc", this, old);
5273
      return old;
5274
    }),
5275
 
5276
    getInputField: function(){return this.display.input.getField();},
5277
    getWrapperElement: function(){return this.display.wrapper;},
5278
    getScrollerElement: function(){return this.display.scroller;},
5279
    getGutterElement: function(){return this.display.gutters;}
5280
  };
5281
  eventMixin(CodeMirror);
5282
 
5283
  // OPTION DEFAULTS
5284
 
5285
  // The default configuration options.
5286
  var defaults = CodeMirror.defaults = {};
5287
  // Functions to run when options are changed.
5288
  var optionHandlers = CodeMirror.optionHandlers = {};
5289
 
5290
  function option(name, deflt, handle, notOnInit) {
5291
    CodeMirror.defaults[name] = deflt;
5292
    if (handle) optionHandlers[name] =
5293
      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
5294
  }
5295
 
5296
  // Passed to option handlers when there is no old value.
5297
  var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
5298
 
5299
  // These two are, on init, called from the constructor because they
5300
  // have to be initialized before the editor can start at all.
5301
  option("value", "", function(cm, val) {
5302
    cm.setValue(val);
5303
  }, true);
5304
  option("mode", null, function(cm, val) {
5305
    cm.doc.modeOption = val;
5306
    loadMode(cm);
5307
  }, true);
5308
 
5309
  option("indentUnit", 2, loadMode, true);
5310
  option("indentWithTabs", false);
5311
  option("smartIndent", true);
5312
  option("tabSize", 4, function(cm) {
5313
    resetModeState(cm);
5314
    clearCaches(cm);
5315
    regChange(cm);
5316
  }, true);
5317
  option("lineSeparator", null, function(cm, val) {
5318
    cm.doc.lineSep = val;
5319
    if (!val) return;
5320
    var newBreaks = [], lineNo = cm.doc.first;
5321
    cm.doc.iter(function(line) {
5322
      for (var pos = 0;;) {
5323
        var found = line.text.indexOf(val, pos);
5324
        if (found == -1) break;
5325
        pos = found + val.length;
5326
        newBreaks.push(Pos(lineNo, found));
5327
      }
5328
      lineNo++;
5329
    });
5330
    for (var i = newBreaks.length - 1; i >= 0; i--)
5331
      replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
5332
  });
5333
  option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
5334
    cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
5335
    if (old != CodeMirror.Init) cm.refresh();
5336
  });
5337
  option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
5338
  option("electricChars", true);
5339
  option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
5340
    throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
5341
  }, true);
5342
  option("rtlMoveVisually", !windows);
5343
  option("wholeLineUpdateBefore", true);
5344
 
5345
  option("theme", "default", function(cm) {
5346
    themeChanged(cm);
5347
    guttersChanged(cm);
5348
  }, true);
5349
  option("keyMap", "default", function(cm, val, old) {
5350
    var next = getKeyMap(val);
5351
    var prev = old != CodeMirror.Init && getKeyMap(old);
5352
    if (prev && prev.detach) prev.detach(cm, next);
5353
    if (next.attach) next.attach(cm, prev || null);
5354
  });
5355
  option("extraKeys", null);
5356
 
5357
  option("lineWrapping", false, wrappingChanged, true);
5358
  option("gutters", [], function(cm) {
5359
    setGuttersForLineNumbers(cm.options);
5360
    guttersChanged(cm);
5361
  }, true);
5362
  option("fixedGutter", true, function(cm, val) {
5363
    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
5364
    cm.refresh();
5365
  }, true);
5366
  option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
5367
  option("scrollbarStyle", "native", function(cm) {
5368
    initScrollbars(cm);
5369
    updateScrollbars(cm);
5370
    cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
5371
    cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
5372
  }, true);
5373
  option("lineNumbers", false, function(cm) {
5374
    setGuttersForLineNumbers(cm.options);
5375
    guttersChanged(cm);
5376
  }, true);
5377
  option("firstLineNumber", 1, guttersChanged, true);
5378
  option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
5379
  option("showCursorWhenSelecting", false, updateSelection, true);
5380
 
5381
  option("resetSelectionOnContextMenu", true);
5382
  option("lineWiseCopyCut", true);
5383
 
5384
  option("readOnly", false, function(cm, val) {
5385
    if (val == "nocursor") {
5386
      onBlur(cm);
5387
      cm.display.input.blur();
5388
      cm.display.disabled = true;
5389
    } else {
5390
      cm.display.disabled = false;
5391
      if (!val) cm.display.input.reset();
5392
    }
5393
  });
5394
  option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
5395
  option("dragDrop", true, dragDropChanged);
5396
 
5397
  option("cursorBlinkRate", 530);
5398
  option("cursorScrollMargin", 0);
5399
  option("cursorHeight", 1, updateSelection, true);
5400
  option("singleCursorHeightPerLine", true, updateSelection, true);
5401
  option("workTime", 100);
5402
  option("workDelay", 100);
5403
  option("flattenSpans", true, resetModeState, true);
5404
  option("addModeClass", false, resetModeState, true);
5405
  option("pollInterval", 100);
5406
  option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
5407
  option("historyEventDelay", 1250);
5408
  option("viewportMargin", 10, function(cm){cm.refresh();}, true);
5409
  option("maxHighlightLength", 10000, resetModeState, true);
5410
  option("moveInputWithCursor", true, function(cm, val) {
5411
    if (!val) cm.display.input.resetPosition();
5412
  });
5413
 
5414
  option("tabindex", null, function(cm, val) {
5415
    cm.display.input.getField().tabIndex = val || "";
5416
  });
5417
  option("autofocus", null);
5418
 
5419
  // MODE DEFINITION AND QUERYING
5420
 
5421
  // Known modes, by name and by MIME
5422
  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
5423
 
5424
  // Extra arguments are stored as the mode's dependencies, which is
5425
  // used by (legacy) mechanisms like loadmode.js to automatically
5426
  // load a mode. (Preferred mechanism is the require/define calls.)
5427
  CodeMirror.defineMode = function(name, mode) {
5428
    if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
5429
    if (arguments.length > 2)
5430
      mode.dependencies = Array.prototype.slice.call(arguments, 2);
5431
    modes[name] = mode;
5432
  };
5433
 
5434
  CodeMirror.defineMIME = function(mime, spec) {
5435
    mimeModes[mime] = spec;
5436
  };
5437
 
5438
  // Given a MIME type, a {name, ...options} config object, or a name
5439
  // string, return a mode config object.
5440
  CodeMirror.resolveMode = function(spec) {
5441
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
5442
      spec = mimeModes[spec];
5443
    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
5444
      var found = mimeModes[spec.name];
5445
      if (typeof found == "string") found = {name: found};
5446
      spec = createObj(found, spec);
5447
      spec.name = found.name;
5448
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
5449
      return CodeMirror.resolveMode("application/xml");
5450
    }
5451
    if (typeof spec == "string") return {name: spec};
5452
    else return spec || {name: "null"};
5453
  };
5454
 
5455
  // Given a mode spec (anything that resolveMode accepts), find and
5456
  // initialize an actual mode object.
5457
  CodeMirror.getMode = function(options, spec) {
5458
    var spec = CodeMirror.resolveMode(spec);
5459
    var mfactory = modes[spec.name];
5460
    if (!mfactory) return CodeMirror.getMode(options, "text/plain");
5461
    var modeObj = mfactory(options, spec);
5462
    if (modeExtensions.hasOwnProperty(spec.name)) {
5463
      var exts = modeExtensions[spec.name];
5464
      for (var prop in exts) {
5465
        if (!exts.hasOwnProperty(prop)) continue;
5466
        if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
5467
        modeObj[prop] = exts[prop];
5468
      }
5469
    }
5470
    modeObj.name = spec.name;
5471
    if (spec.helperType) modeObj.helperType = spec.helperType;
5472
    if (spec.modeProps) for (var prop in spec.modeProps)
5473
      modeObj[prop] = spec.modeProps[prop];
5474
 
5475
    return modeObj;
5476
  };
5477
 
5478
  // Minimal default mode.
5479
  CodeMirror.defineMode("null", function() {
5480
    return {token: function(stream) {stream.skipToEnd();}};
5481
  });
5482
  CodeMirror.defineMIME("text/plain", "null");
5483
 
5484
  // This can be used to attach properties to mode objects from
5485
  // outside the actual mode definition.
5486
  var modeExtensions = CodeMirror.modeExtensions = {};
5487
  CodeMirror.extendMode = function(mode, properties) {
5488
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
5489
    copyObj(properties, exts);
5490
  };
5491
 
5492
  // EXTENSIONS
5493
 
5494
  CodeMirror.defineExtension = function(name, func) {
5495
    CodeMirror.prototype[name] = func;
5496
  };
5497
  CodeMirror.defineDocExtension = function(name, func) {
5498
    Doc.prototype[name] = func;
5499
  };
5500
  CodeMirror.defineOption = option;
5501
 
5502
  var initHooks = [];
5503
  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
5504
 
5505
  var helpers = CodeMirror.helpers = {};
5506
  CodeMirror.registerHelper = function(type, name, value) {
5507
    if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
5508
    helpers[type][name] = value;
5509
  };
5510
  CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
5511
    CodeMirror.registerHelper(type, name, value);
5512
    helpers[type]._global.push({pred: predicate, val: value});
5513
  };
5514
 
5515
  // MODE STATE HANDLING
5516
 
5517
  // Utility functions for working with state. Exported because nested
5518
  // modes need to do this for their inner modes.
5519
 
5520
  var copyState = CodeMirror.copyState = function(mode, state) {
5521
    if (state === true) return state;
5522
    if (mode.copyState) return mode.copyState(state);
5523
    var nstate = {};
5524
    for (var n in state) {
5525
      var val = state[n];
5526
      if (val instanceof Array) val = val.concat([]);
5527
      nstate[n] = val;
5528
    }
5529
    return nstate;
5530
  };
5531
 
5532
  var startState = CodeMirror.startState = function(mode, a1, a2) {
5533
    return mode.startState ? mode.startState(a1, a2) : true;
5534
  };
5535
 
5536
  // Given a mode and a state (for that mode), find the inner mode and
5537
  // state at the position that the state refers to.
5538
  CodeMirror.innerMode = function(mode, state) {
5539
    while (mode.innerMode) {
5540
      var info = mode.innerMode(state);
5541
      if (!info || info.mode == mode) break;
5542
      state = info.state;
5543
      mode = info.mode;
5544
    }
5545
    return info || {mode: mode, state: state};
5546
  };
5547
 
5548
  // STANDARD COMMANDS
5549
 
5550
  // Commands are parameter-less actions that can be performed on an
5551
  // editor, mostly used for keybindings.
5552
  var commands = CodeMirror.commands = {
5553
    selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
5554
    singleSelection: function(cm) {
5555
      cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
5556
    },
5557
    killLine: function(cm) {
5558
      deleteNearSelection(cm, function(range) {
5559
        if (range.empty()) {
5560
          var len = getLine(cm.doc, range.head.line).text.length;
5561
          if (range.head.ch == len && range.head.line < cm.lastLine())
5562
            return {from: range.head, to: Pos(range.head.line + 1, 0)};
5563
          else
5564
            return {from: range.head, to: Pos(range.head.line, len)};
5565
        } else {
5566
          return {from: range.from(), to: range.to()};
5567
        }
5568
      });
5569
    },
5570
    deleteLine: function(cm) {
5571
      deleteNearSelection(cm, function(range) {
5572
        return {from: Pos(range.from().line, 0),
5573
                to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
5574
      });
5575
    },
5576
    delLineLeft: function(cm) {
5577
      deleteNearSelection(cm, function(range) {
5578
        return {from: Pos(range.from().line, 0), to: range.from()};
5579
      });
5580
    },
5581
    delWrappedLineLeft: function(cm) {
5582
      deleteNearSelection(cm, function(range) {
5583
        var top = cm.charCoords(range.head, "div").top + 5;
5584
        var leftPos = cm.coordsChar({left: 0, top: top}, "div");
5585
        return {from: leftPos, to: range.from()};
5586
      });
5587
    },
5588
    delWrappedLineRight: function(cm) {
5589
      deleteNearSelection(cm, function(range) {
5590
        var top = cm.charCoords(range.head, "div").top + 5;
5591
        var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5592
        return {from: range.from(), to: rightPos };
5593
      });
5594
    },
5595
    undo: function(cm) {cm.undo();},
5596
    redo: function(cm) {cm.redo();},
5597
    undoSelection: function(cm) {cm.undoSelection();},
5598
    redoSelection: function(cm) {cm.redoSelection();},
5599
    goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
5600
    goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
5601
    goLineStart: function(cm) {
5602
      cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
5603
                            {origin: "+move", bias: 1});
5604
    },
5605
    goLineStartSmart: function(cm) {
5606
      cm.extendSelectionsBy(function(range) {
5607
        return lineStartSmart(cm, range.head);
5608
      }, {origin: "+move", bias: 1});
5609
    },
5610
    goLineEnd: function(cm) {
5611
      cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
5612
                            {origin: "+move", bias: -1});
5613
    },
5614
    goLineRight: function(cm) {
5615
      cm.extendSelectionsBy(function(range) {
5616
        var top = cm.charCoords(range.head, "div").top + 5;
5617
        return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5618
      }, sel_move);
5619
    },
5620
    goLineLeft: function(cm) {
5621
      cm.extendSelectionsBy(function(range) {
5622
        var top = cm.charCoords(range.head, "div").top + 5;
5623
        return cm.coordsChar({left: 0, top: top}, "div");
5624
      }, sel_move);
5625
    },
5626
    goLineLeftSmart: function(cm) {
5627
      cm.extendSelectionsBy(function(range) {
5628
        var top = cm.charCoords(range.head, "div").top + 5;
5629
        var pos = cm.coordsChar({left: 0, top: top}, "div");
5630
        if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
5631
        return pos;
5632
      }, sel_move);
5633
    },
5634
    goLineUp: function(cm) {cm.moveV(-1, "line");},
5635
    goLineDown: function(cm) {cm.moveV(1, "line");},
5636
    goPageUp: function(cm) {cm.moveV(-1, "page");},
5637
    goPageDown: function(cm) {cm.moveV(1, "page");},
5638
    goCharLeft: function(cm) {cm.moveH(-1, "char");},
5639
    goCharRight: function(cm) {cm.moveH(1, "char");},
5640
    goColumnLeft: function(cm) {cm.moveH(-1, "column");},
5641
    goColumnRight: function(cm) {cm.moveH(1, "column");},
5642
    goWordLeft: function(cm) {cm.moveH(-1, "word");},
5643
    goGroupRight: function(cm) {cm.moveH(1, "group");},
5644
    goGroupLeft: function(cm) {cm.moveH(-1, "group");},
5645
    goWordRight: function(cm) {cm.moveH(1, "word");},
5646
    delCharBefore: function(cm) {cm.deleteH(-1, "char");},
5647
    delCharAfter: function(cm) {cm.deleteH(1, "char");},
5648
    delWordBefore: function(cm) {cm.deleteH(-1, "word");},
5649
    delWordAfter: function(cm) {cm.deleteH(1, "word");},
5650
    delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
5651
    delGroupAfter: function(cm) {cm.deleteH(1, "group");},
5652
    indentAuto: function(cm) {cm.indentSelection("smart");},
5653
    indentMore: function(cm) {cm.indentSelection("add");},
5654
    indentLess: function(cm) {cm.indentSelection("subtract");},
5655
    insertTab: function(cm) {cm.replaceSelection("\t");},
5656
    insertSoftTab: function(cm) {
5657
      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
5658
      for (var i = 0; i < ranges.length; i++) {
5659
        var pos = ranges[i].from();
5660
        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5661
        spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
5662
      }
5663
      cm.replaceSelections(spaces);
5664
    },
5665
    defaultTab: function(cm) {
5666
      if (cm.somethingSelected()) cm.indentSelection("add");
5667
      else cm.execCommand("insertTab");
5668
    },
5669
    transposeChars: function(cm) {
5670
      runInOp(cm, function() {
5671
        var ranges = cm.listSelections(), newSel = [];
5672
        for (var i = 0; i < ranges.length; i++) {
5673
          var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
5674
          if (line) {
5675
            if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
5676
            if (cur.ch > 0) {
5677
              cur = new Pos(cur.line, cur.ch + 1);
5678
              cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
5679
                              Pos(cur.line, cur.ch - 2), cur, "+transpose");
5680
            } else if (cur.line > cm.doc.first) {
5681
              var prev = getLine(cm.doc, cur.line - 1).text;
5682
              if (prev)
5683
                cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
5684
                                prev.charAt(prev.length - 1),
5685
                                Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
5686
            }
5687
          }
5688
          newSel.push(new Range(cur, cur));
5689
        }
5690
        cm.setSelections(newSel);
5691
      });
5692
    },
5693
    newlineAndIndent: function(cm) {
5694
      runInOp(cm, function() {
5695
        var len = cm.listSelections().length;
5696
        for (var i = 0; i < len; i++) {
5697
          var range = cm.listSelections()[i];
5698
          cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
5699
          cm.indentLine(range.from().line + 1, null, true);
5700
          ensureCursorVisible(cm);
5701
        }
5702
      });
5703
    },
5704
    toggleOverwrite: function(cm) {cm.toggleOverwrite();}
5705
  };
5706
 
5707
 
5708
  // STANDARD KEYMAPS
5709
 
5710
  var keyMap = CodeMirror.keyMap = {};
5711
 
5712
  keyMap.basic = {
5713
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
5714
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
5715
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
5716
    "Tab": "defaultTab", "Shift-Tab": "indentAuto",
5717
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
5718
    "Esc": "singleSelection"
5719
  };
5720
  // Note that the save and find-related commands aren't defined by
5721
  // default. User code or addons can define them. Unknown commands
5722
  // are simply ignored.
5723
  keyMap.pcDefault = {
5724
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5725
    "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5726
    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5727
    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5728
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5729
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5730
    "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5731
    fallthrough: "basic"
5732
  };
5733
  // Very basic readline/emacs-style bindings, which are standard on Mac.
5734
  keyMap.emacsy = {
5735
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5736
    "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5737
    "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5738
    "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
5739
  };
5740
  keyMap.macDefault = {
5741
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5742
    "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5743
    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5744
    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5745
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5746
    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5747
    "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5748
    fallthrough: ["basic", "emacsy"]
5749
  };
5750
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
5751
 
5752
  // KEYMAP DISPATCH
5753
 
5754
  function normalizeKeyName(name) {
5755
    var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
5756
    var alt, ctrl, shift, cmd;
5757
    for (var i = 0; i < parts.length - 1; i++) {
5758
      var mod = parts[i];
5759
      if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
5760
      else if (/^a(lt)?$/i.test(mod)) alt = true;
5761
      else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
5762
      else if (/^s(hift)$/i.test(mod)) shift = true;
5763
      else throw new Error("Unrecognized modifier name: " + mod);
5764
    }
5765
    if (alt) name = "Alt-" + name;
5766
    if (ctrl) name = "Ctrl-" + name;
5767
    if (cmd) name = "Cmd-" + name;
5768
    if (shift) name = "Shift-" + name;
5769
    return name;
5770
  }
5771
 
5772
  // This is a kludge to keep keymaps mostly working as raw objects
5773
  // (backwards compatibility) while at the same time support features
5774
  // like normalization and multi-stroke key bindings. It compiles a
5775
  // new normalized keymap, and then updates the old object to reflect
5776
  // this.
5777
  CodeMirror.normalizeKeyMap = function(keymap) {
5778
    var copy = {};
5779
    for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
5780
      var value = keymap[keyname];
5781
      if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
5782
      if (value == "...") { delete keymap[keyname]; continue; }
5783
 
5784
      var keys = map(keyname.split(" "), normalizeKeyName);
5785
      for (var i = 0; i < keys.length; i++) {
5786
        var val, name;
5787
        if (i == keys.length - 1) {
5788
          name = keys.join(" ");
5789
          val = value;
5790
        } else {
5791
          name = keys.slice(0, i + 1).join(" ");
5792
          val = "...";
5793
        }
5794
        var prev = copy[name];
5795
        if (!prev) copy[name] = val;
5796
        else if (prev != val) throw new Error("Inconsistent bindings for " + name);
5797
      }
5798
      delete keymap[keyname];
5799
    }
5800
    for (var prop in copy) keymap[prop] = copy[prop];
5801
    return keymap;
5802
  };
5803
 
5804
  var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
5805
    map = getKeyMap(map);
5806
    var found = map.call ? map.call(key, context) : map[key];
5807
    if (found === false) return "nothing";
5808
    if (found === "...") return "multi";
5809
    if (found != null && handle(found)) return "handled";
5810
 
5811
    if (map.fallthrough) {
5812
      if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
5813
        return lookupKey(key, map.fallthrough, handle, context);
5814
      for (var i = 0; i < map.fallthrough.length; i++) {
5815
        var result = lookupKey(key, map.fallthrough[i], handle, context);
5816
        if (result) return result;
5817
      }
5818
    }
5819
  };
5820
 
5821
  // Modifier key presses don't count as 'real' key presses for the
5822
  // purpose of keymap fallthrough.
5823
  var isModifierKey = CodeMirror.isModifierKey = function(value) {
5824
    var name = typeof value == "string" ? value : keyNames[value.keyCode];
5825
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
5826
  };
5827
 
5828
  // Look up the name of a key as indicated by an event object.
5829
  var keyName = CodeMirror.keyName = function(event, noShift) {
5830
    if (presto && event.keyCode == 34 && event["char"]) return false;
5831
    var base = keyNames[event.keyCode], name = base;
5832
    if (name == null || event.altGraphKey) return false;
5833
    if (event.altKey && base != "Alt") name = "Alt-" + name;
5834
    if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
5835
    if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
5836
    if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
5837
    return name;
5838
  };
5839
 
5840
  function getKeyMap(val) {
5841
    return typeof val == "string" ? keyMap[val] : val;
5842
  }
5843
 
5844
  // FROMTEXTAREA
5845
 
5846
  CodeMirror.fromTextArea = function(textarea, options) {
5847
    options = options ? copyObj(options) : {};
5848
    options.value = textarea.value;
5849
    if (!options.tabindex && textarea.tabIndex)
5850
      options.tabindex = textarea.tabIndex;
5851
    if (!options.placeholder && textarea.placeholder)
5852
      options.placeholder = textarea.placeholder;
5853
    // Set autofocus to true if this textarea is focused, or if it has
5854
    // autofocus and no other element is focused.
5855
    if (options.autofocus == null) {
5856
      var hasFocus = activeElt();
5857
      options.autofocus = hasFocus == textarea ||
5858
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
5859
    }
5860
 
5861
    function save() {textarea.value = cm.getValue();}
5862
    if (textarea.form) {
5863
      on(textarea.form, "submit", save);
5864
      // Deplorable hack to make the submit method do the right thing.
5865
      if (!options.leaveSubmitMethodAlone) {
5866
        var form = textarea.form, realSubmit = form.submit;
5867
        try {
5868
          var wrappedSubmit = form.submit = function() {
5869
            save();
5870
            form.submit = realSubmit;
5871
            form.submit();
5872
            form.submit = wrappedSubmit;
5873
          };
5874
        } catch(e) {}
5875
      }
5876
    }
5877
 
5878
    options.finishInit = function(cm) {
5879
      cm.save = save;
5880
      cm.getTextArea = function() { return textarea; };
5881
      cm.toTextArea = function() {
5882
        cm.toTextArea = isNaN; // Prevent this from being ran twice
5883
        save();
5884
        textarea.parentNode.removeChild(cm.getWrapperElement());
5885
        textarea.style.display = "";
5886
        if (textarea.form) {
5887
          off(textarea.form, "submit", save);
5888
          if (typeof textarea.form.submit == "function")
5889
            textarea.form.submit = realSubmit;
5890
        }
5891
      };
5892
    };
5893
 
5894
    textarea.style.display = "none";
5895
    var cm = CodeMirror(function(node) {
5896
      textarea.parentNode.insertBefore(node, textarea.nextSibling);
5897
    }, options);
5898
    return cm;
5899
  };
5900
 
5901
  // STRING STREAM
5902
 
5903
  // Fed to the mode parsers, provides helper functions to make
5904
  // parsers more succinct.
5905
 
5906
  var StringStream = CodeMirror.StringStream = function(string, tabSize) {
5907
    this.pos = this.start = 0;
5908
    this.string = string;
5909
    this.tabSize = tabSize || 8;
5910
    this.lastColumnPos = this.lastColumnValue = 0;
5911
    this.lineStart = 0;
5912
  };
5913
 
5914
  StringStream.prototype = {
5915
    eol: function() {return this.pos >= this.string.length;},
5916
    sol: function() {return this.pos == this.lineStart;},
5917
    peek: function() {return this.string.charAt(this.pos) || undefined;},
5918
    next: function() {
5919
      if (this.pos < this.string.length)
5920
        return this.string.charAt(this.pos++);
5921
    },
5922
    eat: function(match) {
5923
      var ch = this.string.charAt(this.pos);
5924
      if (typeof match == "string") var ok = ch == match;
5925
      else var ok = ch && (match.test ? match.test(ch) : match(ch));
5926
      if (ok) {++this.pos; return ch;}
5927
    },
5928
    eatWhile: function(match) {
5929
      var start = this.pos;
5930
      while (this.eat(match)){}
5931
      return this.pos > start;
5932
    },
5933
    eatSpace: function() {
5934
      var start = this.pos;
5935
      while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
5936
      return this.pos > start;
5937
    },
5938
    skipToEnd: function() {this.pos = this.string.length;},
5939
    skipTo: function(ch) {
5940
      var found = this.string.indexOf(ch, this.pos);
5941
      if (found > -1) {this.pos = found; return true;}
5942
    },
5943
    backUp: function(n) {this.pos -= n;},
5944
    column: function() {
5945
      if (this.lastColumnPos < this.start) {
5946
        this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
5947
        this.lastColumnPos = this.start;
5948
      }
5949
      return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5950
    },
5951
    indentation: function() {
5952
      return countColumn(this.string, null, this.tabSize) -
5953
        (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5954
    },
5955
    match: function(pattern, consume, caseInsensitive) {
5956
      if (typeof pattern == "string") {
5957
        var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
5958
        var substr = this.string.substr(this.pos, pattern.length);
5959
        if (cased(substr) == cased(pattern)) {
5960
          if (consume !== false) this.pos += pattern.length;
5961
          return true;
5962
        }
5963
      } else {
5964
        var match = this.string.slice(this.pos).match(pattern);
5965
        if (match && match.index > 0) return null;
5966
        if (match && consume !== false) this.pos += match[0].length;
5967
        return match;
5968
      }
5969
    },
5970
    current: function(){return this.string.slice(this.start, this.pos);},
5971
    hideFirstChars: function(n, inner) {
5972
      this.lineStart += n;
5973
      try { return inner(); }
5974
      finally { this.lineStart -= n; }
5975
    }
5976
  };
5977
 
5978
  // TEXTMARKERS
5979
 
5980
  // Created with markText and setBookmark methods. A TextMarker is a
5981
  // handle that can be used to clear or find a marked position in the
5982
  // document. Line objects hold arrays (markedSpans) containing
5983
  // {from, to, marker} object pointing to such marker objects, and
5984
  // indicating that such a marker is present on that line. Multiple
5985
  // lines may point to the same marker when it spans across lines.
5986
  // The spans will have null for their from/to properties when the
5987
  // marker continues beyond the start/end of the line. Markers have
5988
  // links back to the lines they currently touch.
5989
 
5990
  var nextMarkerId = 0;
5991
 
5992
  var TextMarker = CodeMirror.TextMarker = function(doc, type) {
5993
    this.lines = [];
5994
    this.type = type;
5995
    this.doc = doc;
5996
    this.id = ++nextMarkerId;
5997
  };
5998
  eventMixin(TextMarker);
5999
 
6000
  // Clear the marker.
6001
  TextMarker.prototype.clear = function() {
6002
    if (this.explicitlyCleared) return;
6003
    var cm = this.doc.cm, withOp = cm && !cm.curOp;
6004
    if (withOp) startOperation(cm);
6005
    if (hasHandler(this, "clear")) {
6006
      var found = this.find();
6007
      if (found) signalLater(this, "clear", found.from, found.to);
6008
    }
6009
    var min = null, max = null;
6010
    for (var i = 0; i < this.lines.length; ++i) {
6011
      var line = this.lines[i];
6012
      var span = getMarkedSpanFor(line.markedSpans, this);
6013
      if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
6014
      else if (cm) {
6015
        if (span.to != null) max = lineNo(line);
6016
        if (span.from != null) min = lineNo(line);
6017
      }
6018
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
6019
      if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
6020
        updateLineHeight(line, textHeight(cm.display));
6021
    }
6022
    if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
6023
      var visual = visualLine(this.lines[i]), len = lineLength(visual);
6024
      if (len > cm.display.maxLineLength) {
6025
        cm.display.maxLine = visual;
6026
        cm.display.maxLineLength = len;
6027
        cm.display.maxLineChanged = true;
6028
      }
6029
    }
6030
 
6031
    if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
6032
    this.lines.length = 0;
6033
    this.explicitlyCleared = true;
6034
    if (this.atomic && this.doc.cantEdit) {
6035
      this.doc.cantEdit = false;
6036
      if (cm) reCheckSelection(cm.doc);
6037
    }
6038
    if (cm) signalLater(cm, "markerCleared", cm, this);
6039
    if (withOp) endOperation(cm);
6040
    if (this.parent) this.parent.clear();
6041
  };
6042
 
6043
  // Find the position of the marker in the document. Returns a {from,
6044
  // to} object by default. Side can be passed to get a specific side
6045
  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
6046
  // Pos objects returned contain a line object, rather than a line
6047
  // number (used to prevent looking up the same line twice).
6048
  TextMarker.prototype.find = function(side, lineObj) {
6049
    if (side == null && this.type == "bookmark") side = 1;
6050
    var from, to;
6051
    for (var i = 0; i < this.lines.length; ++i) {
6052
      var line = this.lines[i];
6053
      var span = getMarkedSpanFor(line.markedSpans, this);
6054
      if (span.from != null) {
6055
        from = Pos(lineObj ? line : lineNo(line), span.from);
6056
        if (side == -1) return from;
6057
      }
6058
      if (span.to != null) {
6059
        to = Pos(lineObj ? line : lineNo(line), span.to);
6060
        if (side == 1) return to;
6061
      }
6062
    }
6063
    return from && {from: from, to: to};
6064
  };
6065
 
6066
  // Signals that the marker's widget changed, and surrounding layout
6067
  // should be recomputed.
6068
  TextMarker.prototype.changed = function() {
6069
    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
6070
    if (!pos || !cm) return;
6071
    runInOp(cm, function() {
6072
      var line = pos.line, lineN = lineNo(pos.line);
6073
      var view = findViewForLine(cm, lineN);
6074
      if (view) {
6075
        clearLineMeasurementCacheFor(view);
6076
        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
6077
      }
6078
      cm.curOp.updateMaxLine = true;
6079
      if (!lineIsHidden(widget.doc, line) && widget.height != null) {
6080
        var oldHeight = widget.height;
6081
        widget.height = null;
6082
        var dHeight = widgetHeight(widget) - oldHeight;
6083
        if (dHeight)
6084
          updateLineHeight(line, line.height + dHeight);
6085
      }
6086
    });
6087
  };
6088
 
6089
  TextMarker.prototype.attachLine = function(line) {
6090
    if (!this.lines.length && this.doc.cm) {
6091
      var op = this.doc.cm.curOp;
6092
      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
6093
        (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
6094
    }
6095
    this.lines.push(line);
6096
  };
6097
  TextMarker.prototype.detachLine = function(line) {
6098
    this.lines.splice(indexOf(this.lines, line), 1);
6099
    if (!this.lines.length && this.doc.cm) {
6100
      var op = this.doc.cm.curOp;
6101
      (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
6102
    }
6103
  };
6104
 
6105
  // Collapsed markers have unique ids, in order to be able to order
6106
  // them, which is needed for uniquely determining an outer marker
6107
  // when they overlap (they may nest, but not partially overlap).
6108
  var nextMarkerId = 0;
6109
 
6110
  // Create a marker, wire it up to the right lines, and
6111
  function markText(doc, from, to, options, type) {
6112
    // Shared markers (across linked documents) are handled separately
6113
    // (markTextShared will call out to this again, once per
6114
    // document).
6115
    if (options && options.shared) return markTextShared(doc, from, to, options, type);
6116
    // Ensure we are in an operation.
6117
    if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
6118
 
6119
    var marker = new TextMarker(doc, type), diff = cmp(from, to);
6120
    if (options) copyObj(options, marker, false);
6121
    // Don't connect empty markers unless clearWhenEmpty is false
6122
    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6123
      return marker;
6124
    if (marker.replacedWith) {
6125
      // Showing up as a widget implies collapsed (widget replaces text)
6126
      marker.collapsed = true;
6127
      marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
6128
      if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
6129
      if (options.insertLeft) marker.widgetNode.insertLeft = true;
6130
    }
6131
    if (marker.collapsed) {
6132
      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6133
          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6134
        throw new Error("Inserting collapsed marker partially overlapping an existing one");
6135
      sawCollapsedSpans = true;
6136
    }
6137
 
6138
    if (marker.addToHistory)
6139
      addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
6140
 
6141
    var curLine = from.line, cm = doc.cm, updateMaxLine;
6142
    doc.iter(curLine, to.line + 1, function(line) {
6143
      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6144
        updateMaxLine = true;
6145
      if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
6146
      addMarkedSpan(line, new MarkedSpan(marker,
6147
                                         curLine == from.line ? from.ch : null,
6148
                                         curLine == to.line ? to.ch : null));
6149
      ++curLine;
6150
    });
6151
    // lineIsHidden depends on the presence of the spans, so needs a second pass
6152
    if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
6153
      if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
6154
    });
6155
 
6156
    if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
6157
 
6158
    if (marker.readOnly) {
6159
      sawReadOnlySpans = true;
6160
      if (doc.history.done.length || doc.history.undone.length)
6161
        doc.clearHistory();
6162
    }
6163
    if (marker.collapsed) {
6164
      marker.id = ++nextMarkerId;
6165
      marker.atomic = true;
6166
    }
6167
    if (cm) {
6168
      // Sync editor state
6169
      if (updateMaxLine) cm.curOp.updateMaxLine = true;
6170
      if (marker.collapsed)
6171
        regChange(cm, from.line, to.line + 1);
6172
      else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
6173
        for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
6174
      if (marker.atomic) reCheckSelection(cm.doc);
6175
      signalLater(cm, "markerAdded", cm, marker);
6176
    }
6177
    return marker;
6178
  }
6179
 
6180
  // SHARED TEXTMARKERS
6181
 
6182
  // A shared marker spans multiple linked documents. It is
6183
  // implemented as a meta-marker-object controlling multiple normal
6184
  // markers.
6185
  var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
6186
    this.markers = markers;
6187
    this.primary = primary;
6188
    for (var i = 0; i < markers.length; ++i)
6189
      markers[i].parent = this;
6190
  };
6191
  eventMixin(SharedTextMarker);
6192
 
6193
  SharedTextMarker.prototype.clear = function() {
6194
    if (this.explicitlyCleared) return;
6195
    this.explicitlyCleared = true;
6196
    for (var i = 0; i < this.markers.length; ++i)
6197
      this.markers[i].clear();
6198
    signalLater(this, "clear");
6199
  };
6200
  SharedTextMarker.prototype.find = function(side, lineObj) {
6201
    return this.primary.find(side, lineObj);
6202
  };
6203
 
6204
  function markTextShared(doc, from, to, options, type) {
6205
    options = copyObj(options);
6206
    options.shared = false;
6207
    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6208
    var widget = options.widgetNode;
6209
    linkedDocs(doc, function(doc) {
6210
      if (widget) options.widgetNode = widget.cloneNode(true);
6211
      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6212
      for (var i = 0; i < doc.linked.length; ++i)
6213
        if (doc.linked[i].isParent) return;
6214
      primary = lst(markers);
6215
    });
6216
    return new SharedTextMarker(markers, primary);
6217
  }
6218
 
6219
  function findSharedMarkers(doc) {
6220
    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
6221
                         function(m) { return m.parent; });
6222
  }
6223
 
6224
  function copySharedMarkers(doc, markers) {
6225
    for (var i = 0; i < markers.length; i++) {
6226
      var marker = markers[i], pos = marker.find();
6227
      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6228
      if (cmp(mFrom, mTo)) {
6229
        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6230
        marker.markers.push(subMark);
6231
        subMark.parent = marker;
6232
      }
6233
    }
6234
  }
6235
 
6236
  function detachSharedMarkers(markers) {
6237
    for (var i = 0; i < markers.length; i++) {
6238
      var marker = markers[i], linked = [marker.primary.doc];;
6239
      linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
6240
      for (var j = 0; j < marker.markers.length; j++) {
6241
        var subMarker = marker.markers[j];
6242
        if (indexOf(linked, subMarker.doc) == -1) {
6243
          subMarker.parent = null;
6244
          marker.markers.splice(j--, 1);
6245
        }
6246
      }
6247
    }
6248
  }
6249
 
6250
  // TEXTMARKER SPANS
6251
 
6252
  function MarkedSpan(marker, from, to) {
6253
    this.marker = marker;
6254
    this.from = from; this.to = to;
6255
  }
6256
 
6257
  // Search an array of spans for a span matching the given marker.
6258
  function getMarkedSpanFor(spans, marker) {
6259
    if (spans) for (var i = 0; i < spans.length; ++i) {
6260
      var span = spans[i];
6261
      if (span.marker == marker) return span;
6262
    }
6263
  }
6264
  // Remove a span from an array, returning undefined if no spans are
6265
  // left (we don't store arrays for lines without spans).
6266
  function removeMarkedSpan(spans, span) {
6267
    for (var r, i = 0; i < spans.length; ++i)
6268
      if (spans[i] != span) (r || (r = [])).push(spans[i]);
6269
    return r;
6270
  }
6271
  // Add a span to a line.
6272
  function addMarkedSpan(line, span) {
6273
    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
6274
    span.marker.attachLine(line);
6275
  }
6276
 
6277
  // Used for the algorithm that adjusts markers for a change in the
6278
  // document. These functions cut an array of spans at a given
6279
  // character position, returning an array of remaining chunks (or
6280
  // undefined if nothing remains).
6281
  function markedSpansBefore(old, startCh, isInsert) {
6282
    if (old) for (var i = 0, nw; i < old.length; ++i) {
6283
      var span = old[i], marker = span.marker;
6284
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
6285
      if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
6286
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
6287
        (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
6288
      }
6289
    }
6290
    return nw;
6291
  }
6292
  function markedSpansAfter(old, endCh, isInsert) {
6293
    if (old) for (var i = 0, nw; i < old.length; ++i) {
6294
      var span = old[i], marker = span.marker;
6295
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
6296
      if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
6297
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
6298
        (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
6299
                                              span.to == null ? null : span.to - endCh));
6300
      }
6301
    }
6302
    return nw;
6303
  }
6304
 
6305
  // Given a change object, compute the new set of marker spans that
6306
  // cover the line in which the change took place. Removes spans
6307
  // entirely within the change, reconnects spans belonging to the
6308
  // same marker that appear on both sides of the change, and cuts off
6309
  // spans partially within the change. Returns an array of span
6310
  // arrays with one element for each line in (after) the change.
6311
  function stretchSpansOverChange(doc, change) {
6312
    if (change.full) return null;
6313
    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
6314
    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
6315
    if (!oldFirst && !oldLast) return null;
6316
 
6317
    var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
6318
    // Get the spans that 'stick out' on both sides
6319
    var first = markedSpansBefore(oldFirst, startCh, isInsert);
6320
    var last = markedSpansAfter(oldLast, endCh, isInsert);
6321
 
6322
    // Next, merge those two ends
6323
    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
6324
    if (first) {
6325
      // Fix up .to properties of first
6326
      for (var i = 0; i < first.length; ++i) {
6327
        var span = first[i];
6328
        if (span.to == null) {
6329
          var found = getMarkedSpanFor(last, span.marker);
6330
          if (!found) span.to = startCh;
6331
          else if (sameLine) span.to = found.to == null ? null : found.to + offset;
6332
        }
6333
      }
6334
    }
6335
    if (last) {
6336
      // Fix up .from in last (or move them into first in case of sameLine)
6337
      for (var i = 0; i < last.length; ++i) {
6338
        var span = last[i];
6339
        if (span.to != null) span.to += offset;
6340
        if (span.from == null) {
6341
          var found = getMarkedSpanFor(first, span.marker);
6342
          if (!found) {
6343
            span.from = offset;
6344
            if (sameLine) (first || (first = [])).push(span);
6345
          }
6346
        } else {
6347
          span.from += offset;
6348
          if (sameLine) (first || (first = [])).push(span);
6349
        }
6350
      }
6351
    }
6352
    // Make sure we didn't create any zero-length spans
6353
    if (first) first = clearEmptySpans(first);
6354
    if (last && last != first) last = clearEmptySpans(last);
6355
 
6356
    var newMarkers = [first];
6357
    if (!sameLine) {
6358
      // Fill gap with whole-line-spans
6359
      var gap = change.text.length - 2, gapMarkers;
6360
      if (gap > 0 && first)
6361
        for (var i = 0; i < first.length; ++i)
6362
          if (first[i].to == null)
6363
            (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
6364
      for (var i = 0; i < gap; ++i)
6365
        newMarkers.push(gapMarkers);
6366
      newMarkers.push(last);
6367
    }
6368
    return newMarkers;
6369
  }
6370
 
6371
  // Remove spans that are empty and don't have a clearWhenEmpty
6372
  // option of false.
6373
  function clearEmptySpans(spans) {
6374
    for (var i = 0; i < spans.length; ++i) {
6375
      var span = spans[i];
6376
      if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
6377
        spans.splice(i--, 1);
6378
    }
6379
    if (!spans.length) return null;
6380
    return spans;
6381
  }
6382
 
6383
  // Used for un/re-doing changes from the history. Combines the
6384
  // result of computing the existing spans with the set of spans that
6385
  // existed in the history (so that deleting around a span and then
6386
  // undoing brings back the span).
6387
  function mergeOldSpans(doc, change) {
6388
    var old = getOldSpans(doc, change);
6389
    var stretched = stretchSpansOverChange(doc, change);
6390
    if (!old) return stretched;
6391
    if (!stretched) return old;
6392
 
6393
    for (var i = 0; i < old.length; ++i) {
6394
      var oldCur = old[i], stretchCur = stretched[i];
6395
      if (oldCur && stretchCur) {
6396
        spans: for (var j = 0; j < stretchCur.length; ++j) {
6397
          var span = stretchCur[j];
6398
          for (var k = 0; k < oldCur.length; ++k)
6399
            if (oldCur[k].marker == span.marker) continue spans;
6400
          oldCur.push(span);
6401
        }
6402
      } else if (stretchCur) {
6403
        old[i] = stretchCur;
6404
      }
6405
    }
6406
    return old;
6407
  }
6408
 
6409
  // Used to 'clip' out readOnly ranges when making a change.
6410
  function removeReadOnlyRanges(doc, from, to) {
6411
    var markers = null;
6412
    doc.iter(from.line, to.line + 1, function(line) {
6413
      if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
6414
        var mark = line.markedSpans[i].marker;
6415
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
6416
          (markers || (markers = [])).push(mark);
6417
      }
6418
    });
6419
    if (!markers) return null;
6420
    var parts = [{from: from, to: to}];
6421
    for (var i = 0; i < markers.length; ++i) {
6422
      var mk = markers[i], m = mk.find(0);
6423
      for (var j = 0; j < parts.length; ++j) {
6424
        var p = parts[j];
6425
        if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
6426
        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
6427
        if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
6428
          newParts.push({from: p.from, to: m.from});
6429
        if (dto > 0 || !mk.inclusiveRight && !dto)
6430
          newParts.push({from: m.to, to: p.to});
6431
        parts.splice.apply(parts, newParts);
6432
        j += newParts.length - 1;
6433
      }
6434
    }
6435
    return parts;
6436
  }
6437
 
6438
  // Connect or disconnect spans from a line.
6439
  function detachMarkedSpans(line) {
6440
    var spans = line.markedSpans;
6441
    if (!spans) return;
6442
    for (var i = 0; i < spans.length; ++i)
6443
      spans[i].marker.detachLine(line);
6444
    line.markedSpans = null;
6445
  }
6446
  function attachMarkedSpans(line, spans) {
6447
    if (!spans) return;
6448
    for (var i = 0; i < spans.length; ++i)
6449
      spans[i].marker.attachLine(line);
6450
    line.markedSpans = spans;
6451
  }
6452
 
6453
  // Helpers used when computing which overlapping collapsed span
6454
  // counts as the larger one.
6455
  function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
6456
  function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
6457
 
6458
  // Returns a number indicating which of two overlapping collapsed
6459
  // spans is larger (and thus includes the other). Falls back to
6460
  // comparing ids when the spans cover exactly the same range.
6461
  function compareCollapsedMarkers(a, b) {
6462
    var lenDiff = a.lines.length - b.lines.length;
6463
    if (lenDiff != 0) return lenDiff;
6464
    var aPos = a.find(), bPos = b.find();
6465
    var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
6466
    if (fromCmp) return -fromCmp;
6467
    var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
6468
    if (toCmp) return toCmp;
6469
    return b.id - a.id;
6470
  }
6471
 
6472
  // Find out whether a line ends or starts in a collapsed span. If
6473
  // so, return the marker for that span.
6474
  function collapsedSpanAtSide(line, start) {
6475
    var sps = sawCollapsedSpans && line.markedSpans, found;
6476
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6477
      sp = sps[i];
6478
      if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
6479
          (!found || compareCollapsedMarkers(found, sp.marker) < 0))
6480
        found = sp.marker;
6481
    }
6482
    return found;
6483
  }
6484
  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
6485
  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
6486
 
6487
  // Test whether there exists a collapsed span that partially
6488
  // overlaps (covers the start or end, but not both) of a new span.
6489
  // Such overlap is not allowed.
6490
  function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
6491
    var line = getLine(doc, lineNo);
6492
    var sps = sawCollapsedSpans && line.markedSpans;
6493
    if (sps) for (var i = 0; i < sps.length; ++i) {
6494
      var sp = sps[i];
6495
      if (!sp.marker.collapsed) continue;
6496
      var found = sp.marker.find(0);
6497
      var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
6498
      var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
6499
      if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
6500
      if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
6501
          fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
6502
        return true;
6503
    }
6504
  }
6505
 
6506
  // A visual line is a line as drawn on the screen. Folding, for
6507
  // example, can cause multiple logical lines to appear on the same
6508
  // visual line. This finds the start of the visual line that the
6509
  // given line is part of (usually that is the line itself).
6510
  function visualLine(line) {
6511
    var merged;
6512
    while (merged = collapsedSpanAtStart(line))
6513
      line = merged.find(-1, true).line;
6514
    return line;
6515
  }
6516
 
6517
  // Returns an array of logical lines that continue the visual line
6518
  // started by the argument, or undefined if there are no such lines.
6519
  function visualLineContinued(line) {
6520
    var merged, lines;
6521
    while (merged = collapsedSpanAtEnd(line)) {
6522
      line = merged.find(1, true).line;
6523
      (lines || (lines = [])).push(line);
6524
    }
6525
    return lines;
6526
  }
6527
 
6528
  // Get the line number of the start of the visual line that the
6529
  // given line number is part of.
6530
  function visualLineNo(doc, lineN) {
6531
    var line = getLine(doc, lineN), vis = visualLine(line);
6532
    if (line == vis) return lineN;
6533
    return lineNo(vis);
6534
  }
6535
  // Get the line number of the start of the next visual line after
6536
  // the given line.
6537
  function visualLineEndNo(doc, lineN) {
6538
    if (lineN > doc.lastLine()) return lineN;
6539
    var line = getLine(doc, lineN), merged;
6540
    if (!lineIsHidden(doc, line)) return lineN;
6541
    while (merged = collapsedSpanAtEnd(line))
6542
      line = merged.find(1, true).line;
6543
    return lineNo(line) + 1;
6544
  }
6545
 
6546
  // Compute whether a line is hidden. Lines count as hidden when they
6547
  // are part of a visual line that starts with another line, or when
6548
  // they are entirely covered by collapsed, non-widget span.
6549
  function lineIsHidden(doc, line) {
6550
    var sps = sawCollapsedSpans && line.markedSpans;
6551
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6552
      sp = sps[i];
6553
      if (!sp.marker.collapsed) continue;
6554
      if (sp.from == null) return true;
6555
      if (sp.marker.widgetNode) continue;
6556
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
6557
        return true;
6558
    }
6559
  }
6560
  function lineIsHiddenInner(doc, line, span) {
6561
    if (span.to == null) {
6562
      var end = span.marker.find(1, true);
6563
      return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
6564
    }
6565
    if (span.marker.inclusiveRight && span.to == line.text.length)
6566
      return true;
6567
    for (var sp, i = 0; i < line.markedSpans.length; ++i) {
6568
      sp = line.markedSpans[i];
6569
      if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
6570
          (sp.to == null || sp.to != span.from) &&
6571
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
6572
          lineIsHiddenInner(doc, line, sp)) return true;
6573
    }
6574
  }
6575
 
6576
  // LINE WIDGETS
6577
 
6578
  // Line widgets are block elements displayed above or below a line.
6579
 
6580
  var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
6581
    if (options) for (var opt in options) if (options.hasOwnProperty(opt))
6582
      this[opt] = options[opt];
6583
    this.doc = doc;
6584
    this.node = node;
6585
  };
6586
  eventMixin(LineWidget);
6587
 
6588
  function adjustScrollWhenAboveVisible(cm, line, diff) {
6589
    if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
6590
      addToScrollPos(cm, null, diff);
6591
  }
6592
 
6593
  LineWidget.prototype.clear = function() {
6594
    var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
6595
    if (no == null || !ws) return;
6596
    for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
6597
    if (!ws.length) line.widgets = null;
6598
    var height = widgetHeight(this);
6599
    updateLineHeight(line, Math.max(0, line.height - height));
6600
    if (cm) runInOp(cm, function() {
6601
      adjustScrollWhenAboveVisible(cm, line, -height);
6602
      regLineChange(cm, no, "widget");
6603
    });
6604
  };
6605
  LineWidget.prototype.changed = function() {
6606
    var oldH = this.height, cm = this.doc.cm, line = this.line;
6607
    this.height = null;
6608
    var diff = widgetHeight(this) - oldH;
6609
    if (!diff) return;
6610
    updateLineHeight(line, line.height + diff);
6611
    if (cm) runInOp(cm, function() {
6612
      cm.curOp.forceUpdate = true;
6613
      adjustScrollWhenAboveVisible(cm, line, diff);
6614
    });
6615
  };
6616
 
6617
  function widgetHeight(widget) {
6618
    if (widget.height != null) return widget.height;
6619
    var cm = widget.doc.cm;
6620
    if (!cm) return 0;
6621
    if (!contains(document.body, widget.node)) {
6622
      var parentStyle = "position: relative;";
6623
      if (widget.coverGutter)
6624
        parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
6625
      if (widget.noHScroll)
6626
        parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
6627
      removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
6628
    }
6629
    return widget.height = widget.node.offsetHeight;
6630
  }
6631
 
6632
  function addLineWidget(doc, handle, node, options) {
6633
    var widget = new LineWidget(doc, node, options);
6634
    var cm = doc.cm;
6635
    if (cm && widget.noHScroll) cm.display.alignWidgets = true;
6636
    changeLine(doc, handle, "widget", function(line) {
6637
      var widgets = line.widgets || (line.widgets = []);
6638
      if (widget.insertAt == null) widgets.push(widget);
6639
      else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
6640
      widget.line = line;
6641
      if (cm && !lineIsHidden(doc, line)) {
6642
        var aboveVisible = heightAtLine(line) < doc.scrollTop;
6643
        updateLineHeight(line, line.height + widgetHeight(widget));
6644
        if (aboveVisible) addToScrollPos(cm, null, widget.height);
6645
        cm.curOp.forceUpdate = true;
6646
      }
6647
      return true;
6648
    });
6649
    return widget;
6650
  }
6651
 
6652
  // LINE DATA STRUCTURE
6653
 
6654
  // Line objects. These hold state related to a line, including
6655
  // highlighting info (the styles array).
6656
  var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
6657
    this.text = text;
6658
    attachMarkedSpans(this, markedSpans);
6659
    this.height = estimateHeight ? estimateHeight(this) : 1;
6660
  };
6661
  eventMixin(Line);
6662
  Line.prototype.lineNo = function() { return lineNo(this); };
6663
 
6664
  // Change the content (text, markers) of a line. Automatically
6665
  // invalidates cached information and tries to re-estimate the
6666
  // line's height.
6667
  function updateLine(line, text, markedSpans, estimateHeight) {
6668
    line.text = text;
6669
    if (line.stateAfter) line.stateAfter = null;
6670
    if (line.styles) line.styles = null;
6671
    if (line.order != null) line.order = null;
6672
    detachMarkedSpans(line);
6673
    attachMarkedSpans(line, markedSpans);
6674
    var estHeight = estimateHeight ? estimateHeight(line) : 1;
6675
    if (estHeight != line.height) updateLineHeight(line, estHeight);
6676
  }
6677
 
6678
  // Detach a line from the document tree and its markers.
6679
  function cleanUpLine(line) {
6680
    line.parent = null;
6681
    detachMarkedSpans(line);
6682
  }
6683
 
6684
  function extractLineClasses(type, output) {
6685
    if (type) for (;;) {
6686
      var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
6687
      if (!lineClass) break;
6688
      type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
6689
      var prop = lineClass[1] ? "bgClass" : "textClass";
6690
      if (output[prop] == null)
6691
        output[prop] = lineClass[2];
6692
      else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
6693
        output[prop] += " " + lineClass[2];
6694
    }
6695
    return type;
6696
  }
6697
 
6698
  function callBlankLine(mode, state) {
6699
    if (mode.blankLine) return mode.blankLine(state);
6700
    if (!mode.innerMode) return;
6701
    var inner = CodeMirror.innerMode(mode, state);
6702
    if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
6703
  }
6704
 
6705
  function readToken(mode, stream, state, inner) {
6706
    for (var i = 0; i < 10; i++) {
6707
      if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
6708
      var style = mode.token(stream, state);
6709
      if (stream.pos > stream.start) return style;
6710
    }
6711
    throw new Error("Mode " + mode.name + " failed to advance stream.");
6712
  }
6713
 
6714
  // Utility for getTokenAt and getLineTokens
6715
  function takeToken(cm, pos, precise, asArray) {
6716
    function getObj(copy) {
6717
      return {start: stream.start, end: stream.pos,
6718
              string: stream.current(),
6719
              type: style || null,
6720
              state: copy ? copyState(doc.mode, state) : state};
6721
    }
6722
 
6723
    var doc = cm.doc, mode = doc.mode, style;
6724
    pos = clipPos(doc, pos);
6725
    var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
6726
    var stream = new StringStream(line.text, cm.options.tabSize), tokens;
6727
    if (asArray) tokens = [];
6728
    while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
6729
      stream.start = stream.pos;
6730
      style = readToken(mode, stream, state);
6731
      if (asArray) tokens.push(getObj(true));
6732
    }
6733
    return asArray ? tokens : getObj();
6734
  }
6735
 
6736
  // Run the given mode's parser over a line, calling f for each token.
6737
  function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
6738
    var flattenSpans = mode.flattenSpans;
6739
    if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
6740
    var curStart = 0, curStyle = null;
6741
    var stream = new StringStream(text, cm.options.tabSize), style;
6742
    var inner = cm.options.addModeClass && [null];
6743
    if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
6744
    while (!stream.eol()) {
6745
      if (stream.pos > cm.options.maxHighlightLength) {
6746
        flattenSpans = false;
6747
        if (forceToEnd) processLine(cm, text, state, stream.pos);
6748
        stream.pos = text.length;
6749
        style = null;
6750
      } else {
6751
        style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
6752
      }
6753
      if (inner) {
6754
        var mName = inner[0].name;
6755
        if (mName) style = "m-" + (style ? mName + " " + style : mName);
6756
      }
6757
      if (!flattenSpans || curStyle != style) {
6758
        while (curStart < stream.start) {
6759
          curStart = Math.min(stream.start, curStart + 50000);
6760
          f(curStart, curStyle);
6761
        }
6762
        curStyle = style;
6763
      }
6764
      stream.start = stream.pos;
6765
    }
6766
    while (curStart < stream.pos) {
6767
      // Webkit seems to refuse to render text nodes longer than 57444 characters
6768
      var pos = Math.min(stream.pos, curStart + 50000);
6769
      f(pos, curStyle);
6770
      curStart = pos;
6771
    }
6772
  }
6773
 
6774
  // Compute a style array (an array starting with a mode generation
6775
  // -- for invalidation -- followed by pairs of end positions and
6776
  // style strings), which is used to highlight the tokens on the
6777
  // line.
6778
  function highlightLine(cm, line, state, forceToEnd) {
6779
    // A styles array always starts with a number identifying the
6780
    // mode/overlays that it is based on (for easy invalidation).
6781
    var st = [cm.state.modeGen], lineClasses = {};
6782
    // Compute the base array of styles
6783
    runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
6784
      st.push(end, style);
6785
    }, lineClasses, forceToEnd);
6786
 
6787
    // Run overlays, adjust style array.
6788
    for (var o = 0; o < cm.state.overlays.length; ++o) {
6789
      var overlay = cm.state.overlays[o], i = 1, at = 0;
6790
      runMode(cm, line.text, overlay.mode, true, function(end, style) {
6791
        var start = i;
6792
        // Ensure there's a token end at the current position, and that i points at it
6793
        while (at < end) {
6794
          var i_end = st[i];
6795
          if (i_end > end)
6796
            st.splice(i, 1, end, st[i+1], i_end);
6797
          i += 2;
6798
          at = Math.min(end, i_end);
6799
        }
6800
        if (!style) return;
6801
        if (overlay.opaque) {
6802
          st.splice(start, i - start, end, "cm-overlay " + style);
6803
          i = start + 2;
6804
        } else {
6805
          for (; start < i; start += 2) {
6806
            var cur = st[start+1];
6807
            st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
6808
          }
6809
        }
6810
      }, lineClasses);
6811
    }
6812
 
6813
    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
6814
  }
6815
 
6816
  function getLineStyles(cm, line, updateFrontier) {
6817
    if (!line.styles || line.styles[0] != cm.state.modeGen) {
6818
      var state = getStateBefore(cm, lineNo(line));
6819
      var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
6820
      line.stateAfter = state;
6821
      line.styles = result.styles;
6822
      if (result.classes) line.styleClasses = result.classes;
6823
      else if (line.styleClasses) line.styleClasses = null;
6824
      if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
6825
    }
6826
    return line.styles;
6827
  }
6828
 
6829
  // Lightweight form of highlight -- proceed over this line and
6830
  // update state, but don't save a style array. Used for lines that
6831
  // aren't currently visible.
6832
  function processLine(cm, text, state, startAt) {
6833
    var mode = cm.doc.mode;
6834
    var stream = new StringStream(text, cm.options.tabSize);
6835
    stream.start = stream.pos = startAt || 0;
6836
    if (text == "") callBlankLine(mode, state);
6837
    while (!stream.eol()) {
6838
      readToken(mode, stream, state);
6839
      stream.start = stream.pos;
6840
    }
6841
  }
6842
 
6843
  // Convert a style as returned by a mode (either null, or a string
6844
  // containing one or more styles) to a CSS style. This is cached,
6845
  // and also looks for line-wide styles.
6846
  var styleToClassCache = {}, styleToClassCacheWithMode = {};
6847
  function interpretTokenStyle(style, options) {
6848
    if (!style || /^\s*$/.test(style)) return null;
6849
    var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
6850
    return cache[style] ||
6851
      (cache[style] = style.replace(/\S+/g, "cm-$&"));
6852
  }
6853
 
6854
  // Render the DOM representation of the text of a line. Also builds
6855
  // up a 'line map', which points at the DOM nodes that represent
6856
  // specific stretches of text, and is used by the measuring code.
6857
  // The returned object contains the DOM node, this map, and
6858
  // information about line-wide styles that were set by the mode.
6859
  function buildLineContent(cm, lineView) {
6860
    // The padding-right forces the element to have a 'border', which
6861
    // is needed on Webkit to be able to get line-level bounding
6862
    // rectangles for it (in measureChar).
6863
    var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
6864
    var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
6865
                   col: 0, pos: 0, cm: cm,
6866
                   splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
6867
    lineView.measure = {};
6868
 
6869
    // Iterate over the logical lines that make up this visual line.
6870
    for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
6871
      var line = i ? lineView.rest[i - 1] : lineView.line, order;
6872
      builder.pos = 0;
6873
      builder.addToken = buildToken;
6874
      // Optionally wire in some hacks into the token-rendering
6875
      // algorithm, to deal with browser quirks.
6876
      if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
6877
        builder.addToken = buildTokenBadBidi(builder.addToken, order);
6878
      builder.map = [];
6879
      var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
6880
      insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
6881
      if (line.styleClasses) {
6882
        if (line.styleClasses.bgClass)
6883
          builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
6884
        if (line.styleClasses.textClass)
6885
          builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
6886
      }
6887
 
6888
      // Ensure at least a single node is present, for measuring.
6889
      if (builder.map.length == 0)
6890
        builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
6891
 
6892
      // Store the map and a cache object for the current logical line
6893
      if (i == 0) {
6894
        lineView.measure.map = builder.map;
6895
        lineView.measure.cache = {};
6896
      } else {
6897
        (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
6898
        (lineView.measure.caches || (lineView.measure.caches = [])).push({});
6899
      }
6900
    }
6901
 
6902
    // See issue #2901
6903
    if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
6904
      builder.content.className = "cm-tab-wrap-hack";
6905
 
6906
    signal(cm, "renderLine", cm, lineView.line, builder.pre);
6907
    if (builder.pre.className)
6908
      builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
6909
 
6910
    return builder;
6911
  }
6912
 
6913
  function defaultSpecialCharPlaceholder(ch) {
6914
    var token = elt("span", "\u2022", "cm-invalidchar");
6915
    token.title = "\\u" + ch.charCodeAt(0).toString(16);
6916
    token.setAttribute("aria-label", token.title);
6917
    return token;
6918
  }
6919
 
6920
  // Build up the DOM representation for a single token, and add it to
6921
  // the line map. Takes care to render special characters separately.
6922
  function buildToken(builder, text, style, startStyle, endStyle, title, css) {
6923
    if (!text) return;
6924
    var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
6925
    var special = builder.cm.state.specialChars, mustWrap = false;
6926
    if (!special.test(text)) {
6927
      builder.col += text.length;
6928
      var content = document.createTextNode(displayText);
6929
      builder.map.push(builder.pos, builder.pos + text.length, content);
6930
      if (ie && ie_version < 9) mustWrap = true;
6931
      builder.pos += text.length;
6932
    } else {
6933
      var content = document.createDocumentFragment(), pos = 0;
6934
      while (true) {
6935
        special.lastIndex = pos;
6936
        var m = special.exec(text);
6937
        var skipped = m ? m.index - pos : text.length - pos;
6938
        if (skipped) {
6939
          var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
6940
          if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6941
          else content.appendChild(txt);
6942
          builder.map.push(builder.pos, builder.pos + skipped, txt);
6943
          builder.col += skipped;
6944
          builder.pos += skipped;
6945
        }
6946
        if (!m) break;
6947
        pos += skipped + 1;
6948
        if (m[0] == "\t") {
6949
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
6950
          var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
6951
          txt.setAttribute("role", "presentation");
6952
          txt.setAttribute("cm-text", "\t");
6953
          builder.col += tabWidth;
6954
        } else if (m[0] == "\r" || m[0] == "\n") {
6955
          var txt = content.appendChild(elt("span", m[0] == "\r" ? "␍" : "␤", "cm-invalidchar"));
6956
          txt.setAttribute("cm-text", m[0]);
6957
          builder.col += 1;
6958
        } else {
6959
          var txt = builder.cm.options.specialCharPlaceholder(m[0]);
6960
          txt.setAttribute("cm-text", m[0]);
6961
          if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6962
          else content.appendChild(txt);
6963
          builder.col += 1;
6964
        }
6965
        builder.map.push(builder.pos, builder.pos + 1, txt);
6966
        builder.pos++;
6967
      }
6968
    }
6969
    if (style || startStyle || endStyle || mustWrap || css) {
6970
      var fullStyle = style || "";
6971
      if (startStyle) fullStyle += startStyle;
6972
      if (endStyle) fullStyle += endStyle;
6973
      var token = elt("span", [content], fullStyle, css);
6974
      if (title) token.title = title;
6975
      return builder.content.appendChild(token);
6976
    }
6977
    builder.content.appendChild(content);
6978
  }
6979
 
6980
  function splitSpaces(old) {
6981
    var out = " ";
6982
    for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
6983
    out += " ";
6984
    return out;
6985
  }
6986
 
6987
  // Work around nonsense dimensions being reported for stretches of
6988
  // right-to-left text.
6989
  function buildTokenBadBidi(inner, order) {
6990
    return function(builder, text, style, startStyle, endStyle, title, css) {
6991
      style = style ? style + " cm-force-border" : "cm-force-border";
6992
      var start = builder.pos, end = start + text.length;
6993
      for (;;) {
6994
        // Find the part that overlaps with the start of this text
6995
        for (var i = 0; i < order.length; i++) {
6996
          var part = order[i];
6997
          if (part.to > start && part.from <= start) break;
6998
        }
6999
        if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
7000
        inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
7001
        startStyle = null;
7002
        text = text.slice(part.to - start);
7003
        start = part.to;
7004
      }
7005
    };
7006
  }
7007
 
7008
  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
7009
    var widget = !ignoreWidget && marker.widgetNode;
7010
    if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
7011
    if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
7012
      if (!widget)
7013
        widget = builder.content.appendChild(document.createElement("span"));
7014
      widget.setAttribute("cm-marker", marker.id);
7015
    }
7016
    if (widget) {
7017
      builder.cm.display.input.setUneditable(widget);
7018
      builder.content.appendChild(widget);
7019
    }
7020
    builder.pos += size;
7021
  }
7022
 
7023
  // Outputs a number of spans to make up a line, taking highlighting
7024
  // and marked text into account.
7025
  function insertLineContent(line, builder, styles) {
7026
    var spans = line.markedSpans, allText = line.text, at = 0;
7027
    if (!spans) {
7028
      for (var i = 1; i < styles.length; i+=2)
7029
        builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
7030
      return;
7031
    }
7032
 
7033
    var len = allText.length, pos = 0, i = 1, text = "", style, css;
7034
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
7035
    for (;;) {
7036
      if (nextChange == pos) { // Update current marker set
7037
        spanStyle = spanEndStyle = spanStartStyle = title = css = "";
7038
        collapsed = null; nextChange = Infinity;
7039
        var foundBookmarks = [];
7040
        for (var j = 0; j < spans.length; ++j) {
7041
          var sp = spans[j], m = sp.marker;
7042
          if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
7043
            foundBookmarks.push(m);
7044
          } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
7045
            if (sp.to != null && sp.to != pos && nextChange > sp.to) {
7046
              nextChange = sp.to;
7047
              spanEndStyle = "";
7048
            }
7049
            if (m.className) spanStyle += " " + m.className;
7050
            if (m.css) css = m.css;
7051
            if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
7052
            if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
7053
            if (m.title && !title) title = m.title;
7054
            if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
7055
              collapsed = sp;
7056
          } else if (sp.from > pos && nextChange > sp.from) {
7057
            nextChange = sp.from;
7058
          }
7059
        }
7060
        if (collapsed && (collapsed.from || 0) == pos) {
7061
          buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
7062
                             collapsed.marker, collapsed.from == null);
7063
          if (collapsed.to == null) return;
7064
          if (collapsed.to == pos) collapsed = false;
7065
        }
7066
        if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
7067
          buildCollapsedSpan(builder, 0, foundBookmarks[j]);
7068
      }
7069
      if (pos >= len) break;
7070
 
7071
      var upto = Math.min(len, nextChange);
7072
      while (true) {
7073
        if (text) {
7074
          var end = pos + text.length;
7075
          if (!collapsed) {
7076
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
7077
            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
7078
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
7079
          }
7080
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
7081
          pos = end;
7082
          spanStartStyle = "";
7083
        }
7084
        text = allText.slice(at, at = styles[i++]);
7085
        style = interpretTokenStyle(styles[i++], builder.cm.options);
7086
      }
7087
    }
7088
  }
7089
 
7090
  // DOCUMENT DATA STRUCTURE
7091
 
7092
  // By default, updates that start and end at the beginning of a line
7093
  // are treated specially, in order to make the association of line
7094
  // widgets and marker elements with the text behave more intuitive.
7095
  function isWholeLineUpdate(doc, change) {
7096
    return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
7097
      (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
7098
  }
7099
 
7100
  // Perform a change on the document data structure.
7101
  function updateDoc(doc, change, markedSpans, estimateHeight) {
7102
    function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
7103
    function update(line, text, spans) {
7104
      updateLine(line, text, spans, estimateHeight);
7105
      signalLater(line, "change", line, change);
7106
    }
7107
    function linesFor(start, end) {
7108
      for (var i = start, result = []; i < end; ++i)
7109
        result.push(new Line(text[i], spansFor(i), estimateHeight));
7110
      return result;
7111
    }
7112
 
7113
    var from = change.from, to = change.to, text = change.text;
7114
    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
7115
    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
7116
 
7117
    // Adjust the line structure
7118
    if (change.full) {
7119
      doc.insert(0, linesFor(0, text.length));
7120
      doc.remove(text.length, doc.size - text.length);
7121
    } else if (isWholeLineUpdate(doc, change)) {
7122
      // This is a whole-line replace. Treated specially to make
7123
      // sure line objects move the way they are supposed to.
7124
      var added = linesFor(0, text.length - 1);
7125
      update(lastLine, lastLine.text, lastSpans);
7126
      if (nlines) doc.remove(from.line, nlines);
7127
      if (added.length) doc.insert(from.line, added);
7128
    } else if (firstLine == lastLine) {
7129
      if (text.length == 1) {
7130
        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
7131
      } else {
7132
        var added = linesFor(1, text.length - 1);
7133
        added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
7134
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7135
        doc.insert(from.line + 1, added);
7136
      }
7137
    } else if (text.length == 1) {
7138
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
7139
      doc.remove(from.line + 1, nlines);
7140
    } else {
7141
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7142
      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
7143
      var added = linesFor(1, text.length - 1);
7144
      if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
7145
      doc.insert(from.line + 1, added);
7146
    }
7147
 
7148
    signalLater(doc, "change", doc, change);
7149
  }
7150
 
7151
  // The document is represented as a BTree consisting of leaves, with
7152
  // chunk of lines in them, and branches, with up to ten leaves or
7153
  // other branch nodes below them. The top node is always a branch
7154
  // node, and is the document object itself (meaning it has
7155
  // additional methods and properties).
7156
  //
7157
  // All nodes have parent links. The tree is used both to go from
7158
  // line numbers to line objects, and to go from objects to numbers.
7159
  // It also indexes by height, and is used to convert between height
7160
  // and line object, and to find the total height of the document.
7161
  //
7162
  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
7163
 
7164
  function LeafChunk(lines) {
7165
    this.lines = lines;
7166
    this.parent = null;
7167
    for (var i = 0, height = 0; i < lines.length; ++i) {
7168
      lines[i].parent = this;
7169
      height += lines[i].height;
7170
    }
7171
    this.height = height;
7172
  }
7173
 
7174
  LeafChunk.prototype = {
7175
    chunkSize: function() { return this.lines.length; },
7176
    // Remove the n lines at offset 'at'.
7177
    removeInner: function(at, n) {
7178
      for (var i = at, e = at + n; i < e; ++i) {
7179
        var line = this.lines[i];
7180
        this.height -= line.height;
7181
        cleanUpLine(line);
7182
        signalLater(line, "delete");
7183
      }
7184
      this.lines.splice(at, n);
7185
    },
7186
    // Helper used to collapse a small branch into a single leaf.
7187
    collapse: function(lines) {
7188
      lines.push.apply(lines, this.lines);
7189
    },
7190
    // Insert the given array of lines at offset 'at', count them as
7191
    // having the given height.
7192
    insertInner: function(at, lines, height) {
7193
      this.height += height;
7194
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
7195
      for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
7196
    },
7197
    // Used to iterate over a part of the tree.
7198
    iterN: function(at, n, op) {
7199
      for (var e = at + n; at < e; ++at)
7200
        if (op(this.lines[at])) return true;
7201
    }
7202
  };
7203
 
7204
  function BranchChunk(children) {
7205
    this.children = children;
7206
    var size = 0, height = 0;
7207
    for (var i = 0; i < children.length; ++i) {
7208
      var ch = children[i];
7209
      size += ch.chunkSize(); height += ch.height;
7210
      ch.parent = this;
7211
    }
7212
    this.size = size;
7213
    this.height = height;
7214
    this.parent = null;
7215
  }
7216
 
7217
  BranchChunk.prototype = {
7218
    chunkSize: function() { return this.size; },
7219
    removeInner: function(at, n) {
7220
      this.size -= n;
7221
      for (var i = 0; i < this.children.length; ++i) {
7222
        var child = this.children[i], sz = child.chunkSize();
7223
        if (at < sz) {
7224
          var rm = Math.min(n, sz - at), oldHeight = child.height;
7225
          child.removeInner(at, rm);
7226
          this.height -= oldHeight - child.height;
7227
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
7228
          if ((n -= rm) == 0) break;
7229
          at = 0;
7230
        } else at -= sz;
7231
      }
7232
      // If the result is smaller than 25 lines, ensure that it is a
7233
      // single leaf node.
7234
      if (this.size - n < 25 &&
7235
          (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
7236
        var lines = [];
7237
        this.collapse(lines);
7238
        this.children = [new LeafChunk(lines)];
7239
        this.children[0].parent = this;
7240
      }
7241
    },
7242
    collapse: function(lines) {
7243
      for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
7244
    },
7245
    insertInner: function(at, lines, height) {
7246
      this.size += lines.length;
7247
      this.height += height;
7248
      for (var i = 0; i < this.children.length; ++i) {
7249
        var child = this.children[i], sz = child.chunkSize();
7250
        if (at <= sz) {
7251
          child.insertInner(at, lines, height);
7252
          if (child.lines && child.lines.length > 50) {
7253
            while (child.lines.length > 50) {
7254
              var spilled = child.lines.splice(child.lines.length - 25, 25);
7255
              var newleaf = new LeafChunk(spilled);
7256
              child.height -= newleaf.height;
7257
              this.children.splice(i + 1, 0, newleaf);
7258
              newleaf.parent = this;
7259
            }
7260
            this.maybeSpill();
7261
          }
7262
          break;
7263
        }
7264
        at -= sz;
7265
      }
7266
    },
7267
    // When a node has grown, check whether it should be split.
7268
    maybeSpill: function() {
7269
      if (this.children.length <= 10) return;
7270
      var me = this;
7271
      do {
7272
        var spilled = me.children.splice(me.children.length - 5, 5);
7273
        var sibling = new BranchChunk(spilled);
7274
        if (!me.parent) { // Become the parent node
7275
          var copy = new BranchChunk(me.children);
7276
          copy.parent = me;
7277
          me.children = [copy, sibling];
7278
          me = copy;
7279
        } else {
7280
          me.size -= sibling.size;
7281
          me.height -= sibling.height;
7282
          var myIndex = indexOf(me.parent.children, me);
7283
          me.parent.children.splice(myIndex + 1, 0, sibling);
7284
        }
7285
        sibling.parent = me.parent;
7286
      } while (me.children.length > 10);
7287
      me.parent.maybeSpill();
7288
    },
7289
    iterN: function(at, n, op) {
7290
      for (var i = 0; i < this.children.length; ++i) {
7291
        var child = this.children[i], sz = child.chunkSize();
7292
        if (at < sz) {
7293
          var used = Math.min(n, sz - at);
7294
          if (child.iterN(at, used, op)) return true;
7295
          if ((n -= used) == 0) break;
7296
          at = 0;
7297
        } else at -= sz;
7298
      }
7299
    }
7300
  };
7301
 
7302
  var nextDocId = 0;
7303
  var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
7304
    if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
7305
    if (firstLine == null) firstLine = 0;
7306
 
7307
    BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
7308
    this.first = firstLine;
7309
    this.scrollTop = this.scrollLeft = 0;
7310
    this.cantEdit = false;
7311
    this.cleanGeneration = 1;
7312
    this.frontier = firstLine;
7313
    var start = Pos(firstLine, 0);
7314
    this.sel = simpleSelection(start);
7315
    this.history = new History(null);
7316
    this.id = ++nextDocId;
7317
    this.modeOption = mode;
7318
    this.lineSep = lineSep;
7319
 
7320
    if (typeof text == "string") text = this.splitLines(text);
7321
    updateDoc(this, {from: start, to: start, text: text});
7322
    setSelection(this, simpleSelection(start), sel_dontScroll);
7323
  };
7324
 
7325
  Doc.prototype = createObj(BranchChunk.prototype, {
7326
    constructor: Doc,
7327
    // Iterate over the document. Supports two forms -- with only one
7328
    // argument, it calls that for each line in the document. With
7329
    // three, it iterates over the range given by the first two (with
7330
    // the second being non-inclusive).
7331
    iter: function(from, to, op) {
7332
      if (op) this.iterN(from - this.first, to - from, op);
7333
      else this.iterN(this.first, this.first + this.size, from);
7334
    },
7335
 
7336
    // Non-public interface for adding and removing lines.
7337
    insert: function(at, lines) {
7338
      var height = 0;
7339
      for (var i = 0; i < lines.length; ++i) height += lines[i].height;
7340
      this.insertInner(at - this.first, lines, height);
7341
    },
7342
    remove: function(at, n) { this.removeInner(at - this.first, n); },
7343
 
7344
    // From here, the methods are part of the public interface. Most
7345
    // are also available from CodeMirror (editor) instances.
7346
 
7347
    getValue: function(lineSep) {
7348
      var lines = getLines(this, this.first, this.first + this.size);
7349
      if (lineSep === false) return lines;
7350
      return lines.join(lineSep || this.lineSeparator());
7351
    },
7352
    setValue: docMethodOp(function(code) {
7353
      var top = Pos(this.first, 0), last = this.first + this.size - 1;
7354
      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
7355
                        text: this.splitLines(code), origin: "setValue", full: true}, true);
7356
      setSelection(this, simpleSelection(top));
7357
    }),
7358
    replaceRange: function(code, from, to, origin) {
7359
      from = clipPos(this, from);
7360
      to = to ? clipPos(this, to) : from;
7361
      replaceRange(this, code, from, to, origin);
7362
    },
7363
    getRange: function(from, to, lineSep) {
7364
      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
7365
      if (lineSep === false) return lines;
7366
      return lines.join(lineSep || this.lineSeparator());
7367
    },
7368
 
7369
    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
7370
 
7371
    getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
7372
    getLineNumber: function(line) {return lineNo(line);},
7373
 
7374
    getLineHandleVisualStart: function(line) {
7375
      if (typeof line == "number") line = getLine(this, line);
7376
      return visualLine(line);
7377
    },
7378
 
7379
    lineCount: function() {return this.size;},
7380
    firstLine: function() {return this.first;},
7381
    lastLine: function() {return this.first + this.size - 1;},
7382
 
7383
    clipPos: function(pos) {return clipPos(this, pos);},
7384
 
7385
    getCursor: function(start) {
7386
      var range = this.sel.primary(), pos;
7387
      if (start == null || start == "head") pos = range.head;
7388
      else if (start == "anchor") pos = range.anchor;
7389
      else if (start == "end" || start == "to" || start === false) pos = range.to();
7390
      else pos = range.from();
7391
      return pos;
7392
    },
7393
    listSelections: function() { return this.sel.ranges; },
7394
    somethingSelected: function() {return this.sel.somethingSelected();},
7395
 
7396
    setCursor: docMethodOp(function(line, ch, options) {
7397
      setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
7398
    }),
7399
    setSelection: docMethodOp(function(anchor, head, options) {
7400
      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
7401
    }),
7402
    extendSelection: docMethodOp(function(head, other, options) {
7403
      extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
7404
    }),
7405
    extendSelections: docMethodOp(function(heads, options) {
7406
      extendSelections(this, clipPosArray(this, heads, options));
7407
    }),
7408
    extendSelectionsBy: docMethodOp(function(f, options) {
7409
      extendSelections(this, map(this.sel.ranges, f), options);
7410
    }),
7411
    setSelections: docMethodOp(function(ranges, primary, options) {
7412
      if (!ranges.length) return;
7413
      for (var i = 0, out = []; i < ranges.length; i++)
7414
        out[i] = new Range(clipPos(this, ranges[i].anchor),
7415
                           clipPos(this, ranges[i].head));
7416
      if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
7417
      setSelection(this, normalizeSelection(out, primary), options);
7418
    }),
7419
    addSelection: docMethodOp(function(anchor, head, options) {
7420
      var ranges = this.sel.ranges.slice(0);
7421
      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
7422
      setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
7423
    }),
7424
 
7425
    getSelection: function(lineSep) {
7426
      var ranges = this.sel.ranges, lines;
7427
      for (var i = 0; i < ranges.length; i++) {
7428
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7429
        lines = lines ? lines.concat(sel) : sel;
7430
      }
7431
      if (lineSep === false) return lines;
7432
      else return lines.join(lineSep || this.lineSeparator());
7433
    },
7434
    getSelections: function(lineSep) {
7435
      var parts = [], ranges = this.sel.ranges;
7436
      for (var i = 0; i < ranges.length; i++) {
7437
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7438
        if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
7439
        parts[i] = sel;
7440
      }
7441
      return parts;
7442
    },
7443
    replaceSelection: function(code, collapse, origin) {
7444
      var dup = [];
7445
      for (var i = 0; i < this.sel.ranges.length; i++)
7446
        dup[i] = code;
7447
      this.replaceSelections(dup, collapse, origin || "+input");
7448
    },
7449
    replaceSelections: docMethodOp(function(code, collapse, origin) {
7450
      var changes = [], sel = this.sel;
7451
      for (var i = 0; i < sel.ranges.length; i++) {
7452
        var range = sel.ranges[i];
7453
        changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
7454
      }
7455
      var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
7456
      for (var i = changes.length - 1; i >= 0; i--)
7457
        makeChange(this, changes[i]);
7458
      if (newSel) setSelectionReplaceHistory(this, newSel);
7459
      else if (this.cm) ensureCursorVisible(this.cm);
7460
    }),
7461
    undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
7462
    redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
7463
    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
7464
    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
7465
 
7466
    setExtending: function(val) {this.extend = val;},
7467
    getExtending: function() {return this.extend;},
7468
 
7469
    historySize: function() {
7470
      var hist = this.history, done = 0, undone = 0;
7471
      for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
7472
      for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
7473
      return {undo: done, redo: undone};
7474
    },
7475
    clearHistory: function() {this.history = new History(this.history.maxGeneration);},
7476
 
7477
    markClean: function() {
7478
      this.cleanGeneration = this.changeGeneration(true);
7479
    },
7480
    changeGeneration: function(forceSplit) {
7481
      if (forceSplit)
7482
        this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
7483
      return this.history.generation;
7484
    },
7485
    isClean: function (gen) {
7486
      return this.history.generation == (gen || this.cleanGeneration);
7487
    },
7488
 
7489
    getHistory: function() {
7490
      return {done: copyHistoryArray(this.history.done),
7491
              undone: copyHistoryArray(this.history.undone)};
7492
    },
7493
    setHistory: function(histData) {
7494
      var hist = this.history = new History(this.history.maxGeneration);
7495
      hist.done = copyHistoryArray(histData.done.slice(0), null, true);
7496
      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
7497
    },
7498
 
7499
    addLineClass: docMethodOp(function(handle, where, cls) {
7500
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7501
        var prop = where == "text" ? "textClass"
7502
                 : where == "background" ? "bgClass"
7503
                 : where == "gutter" ? "gutterClass" : "wrapClass";
7504
        if (!line[prop]) line[prop] = cls;
7505
        else if (classTest(cls).test(line[prop])) return false;
7506
        else line[prop] += " " + cls;
7507
        return true;
7508
      });
7509
    }),
7510
    removeLineClass: docMethodOp(function(handle, where, cls) {
7511
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7512
        var prop = where == "text" ? "textClass"
7513
                 : where == "background" ? "bgClass"
7514
                 : where == "gutter" ? "gutterClass" : "wrapClass";
7515
        var cur = line[prop];
7516
        if (!cur) return false;
7517
        else if (cls == null) line[prop] = null;
7518
        else {
7519
          var found = cur.match(classTest(cls));
7520
          if (!found) return false;
7521
          var end = found.index + found[0].length;
7522
          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
7523
        }
7524
        return true;
7525
      });
7526
    }),
7527
 
7528
    addLineWidget: docMethodOp(function(handle, node, options) {
7529
      return addLineWidget(this, handle, node, options);
7530
    }),
7531
    removeLineWidget: function(widget) { widget.clear(); },
7532
 
7533
    markText: function(from, to, options) {
7534
      return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
7535
    },
7536
    setBookmark: function(pos, options) {
7537
      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
7538
                      insertLeft: options && options.insertLeft,
7539
                      clearWhenEmpty: false, shared: options && options.shared,
7540
                      handleMouseEvents: options && options.handleMouseEvents};
7541
      pos = clipPos(this, pos);
7542
      return markText(this, pos, pos, realOpts, "bookmark");
7543
    },
7544
    findMarksAt: function(pos) {
7545
      pos = clipPos(this, pos);
7546
      var markers = [], spans = getLine(this, pos.line).markedSpans;
7547
      if (spans) for (var i = 0; i < spans.length; ++i) {
7548
        var span = spans[i];
7549
        if ((span.from == null || span.from <= pos.ch) &&
7550
            (span.to == null || span.to >= pos.ch))
7551
          markers.push(span.marker.parent || span.marker);
7552
      }
7553
      return markers;
7554
    },
7555
    findMarks: function(from, to, filter) {
7556
      from = clipPos(this, from); to = clipPos(this, to);
7557
      var found = [], lineNo = from.line;
7558
      this.iter(from.line, to.line + 1, function(line) {
7559
        var spans = line.markedSpans;
7560
        if (spans) for (var i = 0; i < spans.length; i++) {
7561
          var span = spans[i];
7562
          if (!(lineNo == from.line && from.ch > span.to ||
7563
                span.from == null && lineNo != from.line||
7564
                lineNo == to.line && span.from > to.ch) &&
7565
              (!filter || filter(span.marker)))
7566
            found.push(span.marker.parent || span.marker);
7567
        }
7568
        ++lineNo;
7569
      });
7570
      return found;
7571
    },
7572
    getAllMarks: function() {
7573
      var markers = [];
7574
      this.iter(function(line) {
7575
        var sps = line.markedSpans;
7576
        if (sps) for (var i = 0; i < sps.length; ++i)
7577
          if (sps[i].from != null) markers.push(sps[i].marker);
7578
      });
7579
      return markers;
7580
    },
7581
 
7582
    posFromIndex: function(off) {
7583
      var ch, lineNo = this.first;
7584
      this.iter(function(line) {
7585
        var sz = line.text.length + 1;
7586
        if (sz > off) { ch = off; return true; }
7587
        off -= sz;
7588
        ++lineNo;
7589
      });
7590
      return clipPos(this, Pos(lineNo, ch));
7591
    },
7592
    indexFromPos: function (coords) {
7593
      coords = clipPos(this, coords);
7594
      var index = coords.ch;
7595
      if (coords.line < this.first || coords.ch < 0) return 0;
7596
      this.iter(this.first, coords.line, function (line) {
7597
        index += line.text.length + 1;
7598
      });
7599
      return index;
7600
    },
7601
 
7602
    copy: function(copyHistory) {
7603
      var doc = new Doc(getLines(this, this.first, this.first + this.size),
7604
                        this.modeOption, this.first, this.lineSep);
7605
      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
7606
      doc.sel = this.sel;
7607
      doc.extend = false;
7608
      if (copyHistory) {
7609
        doc.history.undoDepth = this.history.undoDepth;
7610
        doc.setHistory(this.getHistory());
7611
      }
7612
      return doc;
7613
    },
7614
 
7615
    linkedDoc: function(options) {
7616
      if (!options) options = {};
7617
      var from = this.first, to = this.first + this.size;
7618
      if (options.from != null && options.from > from) from = options.from;
7619
      if (options.to != null && options.to < to) to = options.to;
7620
      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
7621
      if (options.sharedHist) copy.history = this.history;
7622
      (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
7623
      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
7624
      copySharedMarkers(copy, findSharedMarkers(this));
7625
      return copy;
7626
    },
7627
    unlinkDoc: function(other) {
7628
      if (other instanceof CodeMirror) other = other.doc;
7629
      if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
7630
        var link = this.linked[i];
7631
        if (link.doc != other) continue;
7632
        this.linked.splice(i, 1);
7633
        other.unlinkDoc(this);
7634
        detachSharedMarkers(findSharedMarkers(this));
7635
        break;
7636
      }
7637
      // If the histories were shared, split them again
7638
      if (other.history == this.history) {
7639
        var splitIds = [other.id];
7640
        linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
7641
        other.history = new History(null);
7642
        other.history.done = copyHistoryArray(this.history.done, splitIds);
7643
        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
7644
      }
7645
    },
7646
    iterLinkedDocs: function(f) {linkedDocs(this, f);},
7647
 
7648
    getMode: function() {return this.mode;},
7649
    getEditor: function() {return this.cm;},
7650
 
7651
    splitLines: function(str) {
7652
      if (this.lineSep) return str.split(this.lineSep);
7653
      return splitLinesAuto(str);
7654
    },
7655
    lineSeparator: function() { return this.lineSep || "\n"; }
7656
  });
7657
 
7658
  // Public alias.
7659
  Doc.prototype.eachLine = Doc.prototype.iter;
7660
 
7661
  // Set up methods on CodeMirror's prototype to redirect to the editor's document.
7662
  var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
7663
  for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
7664
    CodeMirror.prototype[prop] = (function(method) {
7665
      return function() {return method.apply(this.doc, arguments);};
7666
    })(Doc.prototype[prop]);
7667
 
7668
  eventMixin(Doc);
7669
 
7670
  // Call f for all linked documents.
7671
  function linkedDocs(doc, f, sharedHistOnly) {
7672
    function propagate(doc, skip, sharedHist) {
7673
      if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
7674
        var rel = doc.linked[i];
7675
        if (rel.doc == skip) continue;
7676
        var shared = sharedHist && rel.sharedHist;
7677
        if (sharedHistOnly && !shared) continue;
7678
        f(rel.doc, shared);
7679
        propagate(rel.doc, doc, shared);
7680
      }
7681
    }
7682
    propagate(doc, null, true);
7683
  }
7684
 
7685
  // Attach a document to an editor.
7686
  function attachDoc(cm, doc) {
7687
    if (doc.cm) throw new Error("This document is already in use.");
7688
    cm.doc = doc;
7689
    doc.cm = cm;
7690
    estimateLineHeights(cm);
7691
    loadMode(cm);
7692
    if (!cm.options.lineWrapping) findMaxLine(cm);
7693
    cm.options.mode = doc.modeOption;
7694
    regChange(cm);
7695
  }
7696
 
7697
  // LINE UTILITIES
7698
 
7699
  // Find the line object corresponding to the given line number.
7700
  function getLine(doc, n) {
7701
    n -= doc.first;
7702
    if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
7703
    for (var chunk = doc; !chunk.lines;) {
7704
      for (var i = 0;; ++i) {
7705
        var child = chunk.children[i], sz = child.chunkSize();
7706
        if (n < sz) { chunk = child; break; }
7707
        n -= sz;
7708
      }
7709
    }
7710
    return chunk.lines[n];
7711
  }
7712
 
7713
  // Get the part of a document between two positions, as an array of
7714
  // strings.
7715
  function getBetween(doc, start, end) {
7716
    var out = [], n = start.line;
7717
    doc.iter(start.line, end.line + 1, function(line) {
7718
      var text = line.text;
7719
      if (n == end.line) text = text.slice(0, end.ch);
7720
      if (n == start.line) text = text.slice(start.ch);
7721
      out.push(text);
7722
      ++n;
7723
    });
7724
    return out;
7725
  }
7726
  // Get the lines between from and to, as array of strings.
7727
  function getLines(doc, from, to) {
7728
    var out = [];
7729
    doc.iter(from, to, function(line) { out.push(line.text); });
7730
    return out;
7731
  }
7732
 
7733
  // Update the height of a line, propagating the height change
7734
  // upwards to parent nodes.
7735
  function updateLineHeight(line, height) {
7736
    var diff = height - line.height;
7737
    if (diff) for (var n = line; n; n = n.parent) n.height += diff;
7738
  }
7739
 
7740
  // Given a line object, find its line number by walking up through
7741
  // its parent links.
7742
  function lineNo(line) {
7743
    if (line.parent == null) return null;
7744
    var cur = line.parent, no = indexOf(cur.lines, line);
7745
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
7746
      for (var i = 0;; ++i) {
7747
        if (chunk.children[i] == cur) break;
7748
        no += chunk.children[i].chunkSize();
7749
      }
7750
    }
7751
    return no + cur.first;
7752
  }
7753
 
7754
  // Find the line at the given vertical position, using the height
7755
  // information in the document tree.
7756
  function lineAtHeight(chunk, h) {
7757
    var n = chunk.first;
7758
    outer: do {
7759
      for (var i = 0; i < chunk.children.length; ++i) {
7760
        var child = chunk.children[i], ch = child.height;
7761
        if (h < ch) { chunk = child; continue outer; }
7762
        h -= ch;
7763
        n += child.chunkSize();
7764
      }
7765
      return n;
7766
    } while (!chunk.lines);
7767
    for (var i = 0; i < chunk.lines.length; ++i) {
7768
      var line = chunk.lines[i], lh = line.height;
7769
      if (h < lh) break;
7770
      h -= lh;
7771
    }
7772
    return n + i;
7773
  }
7774
 
7775
 
7776
  // Find the height above the given line.
7777
  function heightAtLine(lineObj) {
7778
    lineObj = visualLine(lineObj);
7779
 
7780
    var h = 0, chunk = lineObj.parent;
7781
    for (var i = 0; i < chunk.lines.length; ++i) {
7782
      var line = chunk.lines[i];
7783
      if (line == lineObj) break;
7784
      else h += line.height;
7785
    }
7786
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
7787
      for (var i = 0; i < p.children.length; ++i) {
7788
        var cur = p.children[i];
7789
        if (cur == chunk) break;
7790
        else h += cur.height;
7791
      }
7792
    }
7793
    return h;
7794
  }
7795
 
7796
  // Get the bidi ordering for the given line (and cache it). Returns
7797
  // false for lines that are fully left-to-right, and an array of
7798
  // BidiSpan objects otherwise.
7799
  function getOrder(line) {
7800
    var order = line.order;
7801
    if (order == null) order = line.order = bidiOrdering(line.text);
7802
    return order;
7803
  }
7804
 
7805
  // HISTORY
7806
 
7807
  function History(startGen) {
7808
    // Arrays of change events and selections. Doing something adds an
7809
    // event to done and clears undo. Undoing moves events from done
7810
    // to undone, redoing moves them in the other direction.
7811
    this.done = []; this.undone = [];
7812
    this.undoDepth = Infinity;
7813
    // Used to track when changes can be merged into a single undo
7814
    // event
7815
    this.lastModTime = this.lastSelTime = 0;
7816
    this.lastOp = this.lastSelOp = null;
7817
    this.lastOrigin = this.lastSelOrigin = null;
7818
    // Used by the isClean() method
7819
    this.generation = this.maxGeneration = startGen || 1;
7820
  }
7821
 
7822
  // Create a history change event from an updateDoc-style change
7823
  // object.
7824
  function historyChangeFromChange(doc, change) {
7825
    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
7826
    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
7827
    linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
7828
    return histChange;
7829
  }
7830
 
7831
  // Pop all selection events off the end of a history array. Stop at
7832
  // a change event.
7833
  function clearSelectionEvents(array) {
7834
    while (array.length) {
7835
      var last = lst(array);
7836
      if (last.ranges) array.pop();
7837
      else break;
7838
    }
7839
  }
7840
 
7841
  // Find the top change event in the history. Pop off selection
7842
  // events that are in the way.
7843
  function lastChangeEvent(hist, force) {
7844
    if (force) {
7845
      clearSelectionEvents(hist.done);
7846
      return lst(hist.done);
7847
    } else if (hist.done.length && !lst(hist.done).ranges) {
7848
      return lst(hist.done);
7849
    } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
7850
      hist.done.pop();
7851
      return lst(hist.done);
7852
    }
7853
  }
7854
 
7855
  // Register a change in the history. Merges changes that are within
7856
  // a single operation, ore are close together with an origin that
7857
  // allows merging (starting with "+") into a single event.
7858
  function addChangeToHistory(doc, change, selAfter, opId) {
7859
    var hist = doc.history;
7860
    hist.undone.length = 0;
7861
    var time = +new Date, cur;
7862
 
7863
    if ((hist.lastOp == opId ||
7864
         hist.lastOrigin == change.origin && change.origin &&
7865
         ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
7866
          change.origin.charAt(0) == "*")) &&
7867
        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
7868
      // Merge this change into the last event
7869
      var last = lst(cur.changes);
7870
      if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
7871
        // Optimized case for simple insertion -- don't want to add
7872
        // new changesets for every character typed
7873
        last.to = changeEnd(change);
7874
      } else {
7875
        // Add new sub-event
7876
        cur.changes.push(historyChangeFromChange(doc, change));
7877
      }
7878
    } else {
7879
      // Can not be merged, start a new event.
7880
      var before = lst(hist.done);
7881
      if (!before || !before.ranges)
7882
        pushSelectionToHistory(doc.sel, hist.done);
7883
      cur = {changes: [historyChangeFromChange(doc, change)],
7884
             generation: hist.generation};
7885
      hist.done.push(cur);
7886
      while (hist.done.length > hist.undoDepth) {
7887
        hist.done.shift();
7888
        if (!hist.done[0].ranges) hist.done.shift();
7889
      }
7890
    }
7891
    hist.done.push(selAfter);
7892
    hist.generation = ++hist.maxGeneration;
7893
    hist.lastModTime = hist.lastSelTime = time;
7894
    hist.lastOp = hist.lastSelOp = opId;
7895
    hist.lastOrigin = hist.lastSelOrigin = change.origin;
7896
 
7897
    if (!last) signal(doc, "historyAdded");
7898
  }
7899
 
7900
  function selectionEventCanBeMerged(doc, origin, prev, sel) {
7901
    var ch = origin.charAt(0);
7902
    return ch == "*" ||
7903
      ch == "+" &&
7904
      prev.ranges.length == sel.ranges.length &&
7905
      prev.somethingSelected() == sel.somethingSelected() &&
7906
      new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
7907
  }
7908
 
7909
  // Called whenever the selection changes, sets the new selection as
7910
  // the pending selection in the history, and pushes the old pending
7911
  // selection into the 'done' array when it was significantly
7912
  // different (in number of selected ranges, emptiness, or time).
7913
  function addSelectionToHistory(doc, sel, opId, options) {
7914
    var hist = doc.history, origin = options && options.origin;
7915
 
7916
    // A new event is started when the previous origin does not match
7917
    // the current, or the origins don't allow matching. Origins
7918
    // starting with * are always merged, those starting with + are
7919
    // merged when similar and close together in time.
7920
    if (opId == hist.lastSelOp ||
7921
        (origin && hist.lastSelOrigin == origin &&
7922
         (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
7923
          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
7924
      hist.done[hist.done.length - 1] = sel;
7925
    else
7926
      pushSelectionToHistory(sel, hist.done);
7927
 
7928
    hist.lastSelTime = +new Date;
7929
    hist.lastSelOrigin = origin;
7930
    hist.lastSelOp = opId;
7931
    if (options && options.clearRedo !== false)
7932
      clearSelectionEvents(hist.undone);
7933
  }
7934
 
7935
  function pushSelectionToHistory(sel, dest) {
7936
    var top = lst(dest);
7937
    if (!(top && top.ranges && top.equals(sel)))
7938
      dest.push(sel);
7939
  }
7940
 
7941
  // Used to store marked span information in the history.
7942
  function attachLocalSpans(doc, change, from, to) {
7943
    var existing = change["spans_" + doc.id], n = 0;
7944
    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
7945
      if (line.markedSpans)
7946
        (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
7947
      ++n;
7948
    });
7949
  }
7950
 
7951
  // When un/re-doing restores text containing marked spans, those
7952
  // that have been explicitly cleared should not be restored.
7953
  function removeClearedSpans(spans) {
7954
    if (!spans) return null;
7955
    for (var i = 0, out; i < spans.length; ++i) {
7956
      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
7957
      else if (out) out.push(spans[i]);
7958
    }
7959
    return !out ? spans : out.length ? out : null;
7960
  }
7961
 
7962
  // Retrieve and filter the old marked spans stored in a change event.
7963
  function getOldSpans(doc, change) {
7964
    var found = change["spans_" + doc.id];
7965
    if (!found) return null;
7966
    for (var i = 0, nw = []; i < change.text.length; ++i)
7967
      nw.push(removeClearedSpans(found[i]));
7968
    return nw;
7969
  }
7970
 
7971
  // Used both to provide a JSON-safe object in .getHistory, and, when
7972
  // detaching a document, to split the history in two
7973
  function copyHistoryArray(events, newGroup, instantiateSel) {
7974
    for (var i = 0, copy = []; i < events.length; ++i) {
7975
      var event = events[i];
7976
      if (event.ranges) {
7977
        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
7978
        continue;
7979
      }
7980
      var changes = event.changes, newChanges = [];
7981
      copy.push({changes: newChanges});
7982
      for (var j = 0; j < changes.length; ++j) {
7983
        var change = changes[j], m;
7984
        newChanges.push({from: change.from, to: change.to, text: change.text});
7985
        if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
7986
          if (indexOf(newGroup, Number(m[1])) > -1) {
7987
            lst(newChanges)[prop] = change[prop];
7988
            delete change[prop];
7989
          }
7990
        }
7991
      }
7992
    }
7993
    return copy;
7994
  }
7995
 
7996
  // Rebasing/resetting history to deal with externally-sourced changes
7997
 
7998
  function rebaseHistSelSingle(pos, from, to, diff) {
7999
    if (to < pos.line) {
8000
      pos.line += diff;
8001
    } else if (from < pos.line) {
8002
      pos.line = from;
8003
      pos.ch = 0;
8004
    }
8005
  }
8006
 
8007
  // Tries to rebase an array of history events given a change in the
8008
  // document. If the change touches the same lines as the event, the
8009
  // event, and everything 'behind' it, is discarded. If the change is
8010
  // before the event, the event's positions are updated. Uses a
8011
  // copy-on-write scheme for the positions, to avoid having to
8012
  // reallocate them all on every rebase, but also avoid problems with
8013
  // shared position objects being unsafely updated.
8014
  function rebaseHistArray(array, from, to, diff) {
8015
    for (var i = 0; i < array.length; ++i) {
8016
      var sub = array[i], ok = true;
8017
      if (sub.ranges) {
8018
        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
8019
        for (var j = 0; j < sub.ranges.length; j++) {
8020
          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
8021
          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
8022
        }
8023
        continue;
8024
      }
8025
      for (var j = 0; j < sub.changes.length; ++j) {
8026
        var cur = sub.changes[j];
8027
        if (to < cur.from.line) {
8028
          cur.from = Pos(cur.from.line + diff, cur.from.ch);
8029
          cur.to = Pos(cur.to.line + diff, cur.to.ch);
8030
        } else if (from <= cur.to.line) {
8031
          ok = false;
8032
          break;
8033
        }
8034
      }
8035
      if (!ok) {
8036
        array.splice(0, i + 1);
8037
        i = 0;
8038
      }
8039
    }
8040
  }
8041
 
8042
  function rebaseHist(hist, change) {
8043
    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
8044
    rebaseHistArray(hist.done, from, to, diff);
8045
    rebaseHistArray(hist.undone, from, to, diff);
8046
  }
8047
 
8048
  // EVENT UTILITIES
8049
 
8050
  // Due to the fact that we still support jurassic IE versions, some
8051
  // compatibility wrappers are needed.
8052
 
8053
  var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
8054
    if (e.preventDefault) e.preventDefault();
8055
    else e.returnValue = false;
8056
  };
8057
  var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
8058
    if (e.stopPropagation) e.stopPropagation();
8059
    else e.cancelBubble = true;
8060
  };
8061
  function e_defaultPrevented(e) {
8062
    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
8063
  }
8064
  var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
8065
 
8066
  function e_target(e) {return e.target || e.srcElement;}
8067
  function e_button(e) {
8068
    var b = e.which;
8069
    if (b == null) {
8070
      if (e.button & 1) b = 1;
8071
      else if (e.button & 2) b = 3;
8072
      else if (e.button & 4) b = 2;
8073
    }
8074
    if (mac && e.ctrlKey && b == 1) b = 3;
8075
    return b;
8076
  }
8077
 
8078
  // EVENT HANDLING
8079
 
8080
  // Lightweight event framework. on/off also work on DOM nodes,
8081
  // registering native DOM handlers.
8082
 
8083
  var on = CodeMirror.on = function(emitter, type, f) {
8084
    if (emitter.addEventListener)
8085
      emitter.addEventListener(type, f, false);
8086
    else if (emitter.attachEvent)
8087
      emitter.attachEvent("on" + type, f);
8088
    else {
8089
      var map = emitter._handlers || (emitter._handlers = {});
8090
      var arr = map[type] || (map[type] = []);
8091
      arr.push(f);
8092
    }
8093
  };
8094
 
8095
  var off = CodeMirror.off = function(emitter, type, f) {
8096
    if (emitter.removeEventListener)
8097
      emitter.removeEventListener(type, f, false);
8098
    else if (emitter.detachEvent)
8099
      emitter.detachEvent("on" + type, f);
8100
    else {
8101
      var arr = emitter._handlers && emitter._handlers[type];
8102
      if (!arr) return;
8103
      for (var i = 0; i < arr.length; ++i)
8104
        if (arr[i] == f) { arr.splice(i, 1); break; }
8105
    }
8106
  };
8107
 
8108
  var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
8109
    var arr = emitter._handlers && emitter._handlers[type];
8110
    if (!arr) return;
8111
    var args = Array.prototype.slice.call(arguments, 2);
8112
    for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
8113
  };
8114
 
8115
  var orphanDelayedCallbacks = null;
8116
 
8117
  // Often, we want to signal events at a point where we are in the
8118
  // middle of some work, but don't want the handler to start calling
8119
  // other methods on the editor, which might be in an inconsistent
8120
  // state or simply not expect any other events to happen.
8121
  // signalLater looks whether there are any handlers, and schedules
8122
  // them to be executed when the last operation ends, or, if no
8123
  // operation is active, when a timeout fires.
8124
  function signalLater(emitter, type /*, values...*/) {
8125
    var arr = emitter._handlers && emitter._handlers[type];
8126
    if (!arr) return;
8127
    var args = Array.prototype.slice.call(arguments, 2), list;
8128
    if (operationGroup) {
8129
      list = operationGroup.delayedCallbacks;
8130
    } else if (orphanDelayedCallbacks) {
8131
      list = orphanDelayedCallbacks;
8132
    } else {
8133
      list = orphanDelayedCallbacks = [];
8134
      setTimeout(fireOrphanDelayed, 0);
8135
    }
8136
    function bnd(f) {return function(){f.apply(null, args);};};
8137
    for (var i = 0; i < arr.length; ++i)
8138
      list.push(bnd(arr[i]));
8139
  }
8140
 
8141
  function fireOrphanDelayed() {
8142
    var delayed = orphanDelayedCallbacks;
8143
    orphanDelayedCallbacks = null;
8144
    for (var i = 0; i < delayed.length; ++i) delayed[i]();
8145
  }
8146
 
8147
  // The DOM events that CodeMirror handles can be overridden by
8148
  // registering a (non-DOM) handler on the editor for the event name,
8149
  // and preventDefault-ing the event in that handler.
8150
  function signalDOMEvent(cm, e, override) {
8151
    if (typeof e == "string")
8152
      e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
8153
    signal(cm, override || e.type, cm, e);
8154
    return e_defaultPrevented(e) || e.codemirrorIgnore;
8155
  }
8156
 
8157
  function signalCursorActivity(cm) {
8158
    var arr = cm._handlers && cm._handlers.cursorActivity;
8159
    if (!arr) return;
8160
    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
8161
    for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
8162
      set.push(arr[i]);
8163
  }
8164
 
8165
  function hasHandler(emitter, type) {
8166
    var arr = emitter._handlers && emitter._handlers[type];
8167
    return arr && arr.length > 0;
8168
  }
8169
 
8170
  // Add on and off methods to a constructor's prototype, to make
8171
  // registering events on such objects more convenient.
8172
  function eventMixin(ctor) {
8173
    ctor.prototype.on = function(type, f) {on(this, type, f);};
8174
    ctor.prototype.off = function(type, f) {off(this, type, f);};
8175
  }
8176
 
8177
  // MISC UTILITIES
8178
 
8179
  // Number of pixels added to scroller and sizer to hide scrollbar
8180
  var scrollerGap = 30;
8181
 
8182
  // Returned or thrown by various protocols to signal 'I'm not
8183
  // handling this'.
8184
  var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
8185
 
8186
  // Reused option objects for setSelection & friends
8187
  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
8188
 
8189
  function Delayed() {this.id = null;}
8190
  Delayed.prototype.set = function(ms, f) {
8191
    clearTimeout(this.id);
8192
    this.id = setTimeout(f, ms);
8193
  };
8194
 
8195
  // Counts the column offset in a string, taking tabs into account.
8196
  // Used mostly to find indentation.
8197
  var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
8198
    if (end == null) {
8199
      end = string.search(/[^\s\u00a0]/);
8200
      if (end == -1) end = string.length;
8201
    }
8202
    for (var i = startIndex || 0, n = startValue || 0;;) {
8203
      var nextTab = string.indexOf("\t", i);
8204
      if (nextTab < 0 || nextTab >= end)
8205
        return n + (end - i);
8206
      n += nextTab - i;
8207
      n += tabSize - (n % tabSize);
8208
      i = nextTab + 1;
8209
    }
8210
  };
8211
 
8212
  // The inverse of countColumn -- find the offset that corresponds to
8213
  // a particular column.
8214
  function findColumn(string, goal, tabSize) {
8215
    for (var pos = 0, col = 0;;) {
8216
      var nextTab = string.indexOf("\t", pos);
8217
      if (nextTab == -1) nextTab = string.length;
8218
      var skipped = nextTab - pos;
8219
      if (nextTab == string.length || col + skipped >= goal)
8220
        return pos + Math.min(skipped, goal - col);
8221
      col += nextTab - pos;
8222
      col += tabSize - (col % tabSize);
8223
      pos = nextTab + 1;
8224
      if (col >= goal) return pos;
8225
    }
8226
  }
8227
 
8228
  var spaceStrs = [""];
8229
  function spaceStr(n) {
8230
    while (spaceStrs.length <= n)
8231
      spaceStrs.push(lst(spaceStrs) + " ");
8232
    return spaceStrs[n];
8233
  }
8234
 
8235
  function lst(arr) { return arr[arr.length-1]; }
8236
 
8237
  var selectInput = function(node) { node.select(); };
8238
  if (ios) // Mobile Safari apparently has a bug where select() is broken.
8239
    selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
8240
  else if (ie) // Suppress mysterious IE10 errors
8241
    selectInput = function(node) { try { node.select(); } catch(_e) {} };
8242
 
8243
  function indexOf(array, elt) {
8244
    for (var i = 0; i < array.length; ++i)
8245
      if (array[i] == elt) return i;
8246
    return -1;
8247
  }
8248
  function map(array, f) {
8249
    var out = [];
8250
    for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
8251
    return out;
8252
  }
8253
 
8254
  function nothing() {}
8255
 
8256
  function createObj(base, props) {
8257
    var inst;
8258
    if (Object.create) {
8259
      inst = Object.create(base);
8260
    } else {
8261
      nothing.prototype = base;
8262
      inst = new nothing();
8263
    }
8264
    if (props) copyObj(props, inst);
8265
    return inst;
8266
  };
8267
 
8268
  function copyObj(obj, target, overwrite) {
8269
    if (!target) target = {};
8270
    for (var prop in obj)
8271
      if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
8272
        target[prop] = obj[prop];
8273
    return target;
8274
  }
8275
 
8276
  function bind(f) {
8277
    var args = Array.prototype.slice.call(arguments, 1);
8278
    return function(){return f.apply(null, args);};
8279
  }
8280
 
8281
  var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
8282
  var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
8283
    return /\w/.test(ch) || ch > "\x80" &&
8284
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
8285
  };
8286
  function isWordChar(ch, helper) {
8287
    if (!helper) return isWordCharBasic(ch);
8288
    if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
8289
    return helper.test(ch);
8290
  }
8291
 
8292
  function isEmpty(obj) {
8293
    for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
8294
    return true;
8295
  }
8296
 
8297
  // Extending unicode characters. A series of a non-extending char +
8298
  // any number of extending chars is treated as a single unit as far
8299
  // as editing and measuring is concerned. This is not fully correct,
8300
  // since some scripts/fonts/browsers also treat other configurations
8301
  // of code points as a group.
8302
  var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
8303
  function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
8304
 
8305
  // DOM UTILITIES
8306
 
8307
  function elt(tag, content, className, style) {
8308
    var e = document.createElement(tag);
8309
    if (className) e.className = className;
8310
    if (style) e.style.cssText = style;
8311
    if (typeof content == "string") e.appendChild(document.createTextNode(content));
8312
    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
8313
    return e;
8314
  }
8315
 
8316
  var range;
8317
  if (document.createRange) range = function(node, start, end, endNode) {
8318
    var r = document.createRange();
8319
    r.setEnd(endNode || node, end);
8320
    r.setStart(node, start);
8321
    return r;
8322
  };
8323
  else range = function(node, start, end) {
8324
    var r = document.body.createTextRange();
8325
    try { r.moveToElementText(node.parentNode); }
8326
    catch(e) { return r; }
8327
    r.collapse(true);
8328
    r.moveEnd("character", end);
8329
    r.moveStart("character", start);
8330
    return r;
8331
  };
8332
 
8333
  function removeChildren(e) {
8334
    for (var count = e.childNodes.length; count > 0; --count)
8335
      e.removeChild(e.firstChild);
8336
    return e;
8337
  }
8338
 
8339
  function removeChildrenAndAdd(parent, e) {
8340
    return removeChildren(parent).appendChild(e);
8341
  }
8342
 
8343
  var contains = CodeMirror.contains = function(parent, child) {
8344
    if (child.nodeType == 3) // Android browser always returns false when child is a textnode
8345
      child = child.parentNode;
8346
    if (parent.contains)
8347
      return parent.contains(child);
8348
    do {
8349
      if (child.nodeType == 11) child = child.host;
8350
      if (child == parent) return true;
8351
    } while (child = child.parentNode);
8352
  };
8353
 
8354
  function activeElt() {
8355
    var activeElement = document.activeElement;
8356
    while (activeElement && activeElement.root && activeElement.root.activeElement)
8357
      activeElement = activeElement.root.activeElement;
8358
    return activeElement;
8359
  }
8360
  // Older versions of IE throws unspecified error when touching
8361
  // document.activeElement in some cases (during loading, in iframe)
8362
  if (ie && ie_version < 11) activeElt = function() {
8363
    try { return document.activeElement; }
8364
    catch(e) { return document.body; }
8365
  };
8366
 
8367
  function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
8368
  var rmClass = CodeMirror.rmClass = function(node, cls) {
8369
    var current = node.className;
8370
    var match = classTest(cls).exec(current);
8371
    if (match) {
8372
      var after = current.slice(match.index + match[0].length);
8373
      node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
8374
    }
8375
  };
8376
  var addClass = CodeMirror.addClass = function(node, cls) {
8377
    var current = node.className;
8378
    if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
8379
  };
8380
  function joinClasses(a, b) {
8381
    var as = a.split(" ");
8382
    for (var i = 0; i < as.length; i++)
8383
      if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
8384
    return b;
8385
  }
8386
 
8387
  // WINDOW-WIDE EVENTS
8388
 
8389
  // These must be handled carefully, because naively registering a
8390
  // handler for each editor will cause the editors to never be
8391
  // garbage collected.
8392
 
8393
  function forEachCodeMirror(f) {
8394
    if (!document.body.getElementsByClassName) return;
8395
    var byClass = document.body.getElementsByClassName("CodeMirror");
8396
    for (var i = 0; i < byClass.length; i++) {
8397
      var cm = byClass[i].CodeMirror;
8398
      if (cm) f(cm);
8399
    }
8400
  }
8401
 
8402
  var globalsRegistered = false;
8403
  function ensureGlobalHandlers() {
8404
    if (globalsRegistered) return;
8405
    registerGlobalHandlers();
8406
    globalsRegistered = true;
8407
  }
8408
  function registerGlobalHandlers() {
8409
    // When the window resizes, we need to refresh active editors.
8410
    var resizeTimer;
8411
    on(window, "resize", function() {
8412
      if (resizeTimer == null) resizeTimer = setTimeout(function() {
8413
        resizeTimer = null;
8414
        forEachCodeMirror(onResize);
8415
      }, 100);
8416
    });
8417
    // When the window loses focus, we want to show the editor as blurred
8418
    on(window, "blur", function() {
8419
      forEachCodeMirror(onBlur);
8420
    });
8421
  }
8422
 
8423
  // FEATURE DETECTION
8424
 
8425
  // Detect drag-and-drop
8426
  var dragAndDrop = function() {
8427
    // There is *some* kind of drag-and-drop support in IE6-8, but I
8428
    // couldn't get it to work yet.
8429
    if (ie && ie_version < 9) return false;
8430
    var div = elt('div');
8431
    return "draggable" in div || "dragDrop" in div;
8432
  }();
8433
 
8434
  var zwspSupported;
8435
  function zeroWidthElement(measure) {
8436
    if (zwspSupported == null) {
8437
      var test = elt("span", "\u200b");
8438
      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
8439
      if (measure.firstChild.offsetHeight != 0)
8440
        zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
8441
    }
8442
    var node = zwspSupported ? elt("span", "\u200b") :
8443
      elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
8444
    node.setAttribute("cm-text", "");
8445
    return node;
8446
  }
8447
 
8448
  // Feature-detect IE's crummy client rect reporting for bidi text
8449
  var badBidiRects;
8450
  function hasBadBidiRects(measure) {
8451
    if (badBidiRects != null) return badBidiRects;
8452
    var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
8453
    var r0 = range(txt, 0, 1).getBoundingClientRect();
8454
    if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
8455
    var r1 = range(txt, 1, 2).getBoundingClientRect();
8456
    return badBidiRects = (r1.right - r0.right < 3);
8457
  }
8458
 
8459
  // See if "".split is the broken IE version, if so, provide an
8460
  // alternative way to split lines.
8461
  var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
8462
    var pos = 0, result = [], l = string.length;
8463
    while (pos <= l) {
8464
      var nl = string.indexOf("\n", pos);
8465
      if (nl == -1) nl = string.length;
8466
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
8467
      var rt = line.indexOf("\r");
8468
      if (rt != -1) {
8469
        result.push(line.slice(0, rt));
8470
        pos += rt + 1;
8471
      } else {
8472
        result.push(line);
8473
        pos = nl + 1;
8474
      }
8475
    }
8476
    return result;
8477
  } : function(string){return string.split(/\r\n?|\n/);};
8478
 
8479
  var hasSelection = window.getSelection ? function(te) {
8480
    try { return te.selectionStart != te.selectionEnd; }
8481
    catch(e) { return false; }
8482
  } : function(te) {
8483
    try {var range = te.ownerDocument.selection.createRange();}
8484
    catch(e) {}
8485
    if (!range || range.parentElement() != te) return false;
8486
    return range.compareEndPoints("StartToEnd", range) != 0;
8487
  };
8488
 
8489
  var hasCopyEvent = (function() {
8490
    var e = elt("div");
8491
    if ("oncopy" in e) return true;
8492
    e.setAttribute("oncopy", "return;");
8493
    return typeof e.oncopy == "function";
8494
  })();
8495
 
8496
  var badZoomedRects = null;
8497
  function hasBadZoomedRects(measure) {
8498
    if (badZoomedRects != null) return badZoomedRects;
8499
    var node = removeChildrenAndAdd(measure, elt("span", "x"));
8500
    var normal = node.getBoundingClientRect();
8501
    var fromRange = range(node, 0, 1).getBoundingClientRect();
8502
    return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
8503
  }
8504
 
8505
  // KEY NAMES
8506
 
8507
  var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
8508
                  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
8509
                  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
8510
                  46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
8511
                  173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
8512
                  221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
8513
                  63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
8514
  CodeMirror.keyNames = keyNames;
8515
  (function() {
8516
    // Number keys
8517
    for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
8518
    // Alphabetic keys
8519
    for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
8520
    // Function keys
8521
    for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
8522
  })();
8523
 
8524
  // BIDI HELPERS
8525
 
8526
  function iterateBidiSections(order, from, to, f) {
8527
    if (!order) return f(from, to, "ltr");
8528
    var found = false;
8529
    for (var i = 0; i < order.length; ++i) {
8530
      var part = order[i];
8531
      if (part.from < to && part.to > from || from == to && part.to == from) {
8532
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
8533
        found = true;
8534
      }
8535
    }
8536
    if (!found) f(from, to, "ltr");
8537
  }
8538
 
8539
  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
8540
  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
8541
 
8542
  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
8543
  function lineRight(line) {
8544
    var order = getOrder(line);
8545
    if (!order) return line.text.length;
8546
    return bidiRight(lst(order));
8547
  }
8548
 
8549
  function lineStart(cm, lineN) {
8550
    var line = getLine(cm.doc, lineN);
8551
    var visual = visualLine(line);
8552
    if (visual != line) lineN = lineNo(visual);
8553
    var order = getOrder(visual);
8554
    var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
8555
    return Pos(lineN, ch);
8556
  }
8557
  function lineEnd(cm, lineN) {
8558
    var merged, line = getLine(cm.doc, lineN);
8559
    while (merged = collapsedSpanAtEnd(line)) {
8560
      line = merged.find(1, true).line;
8561
      lineN = null;
8562
    }
8563
    var order = getOrder(line);
8564
    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
8565
    return Pos(lineN == null ? lineNo(line) : lineN, ch);
8566
  }
8567
  function lineStartSmart(cm, pos) {
8568
    var start = lineStart(cm, pos.line);
8569
    var line = getLine(cm.doc, start.line);
8570
    var order = getOrder(line);
8571
    if (!order || order[0].level == 0) {
8572
      var firstNonWS = Math.max(0, line.text.search(/\S/));
8573
      var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
8574
      return Pos(start.line, inWS ? 0 : firstNonWS);
8575
    }
8576
    return start;
8577
  }
8578
 
8579
  function compareBidiLevel(order, a, b) {
8580
    var linedir = order[0].level;
8581
    if (a == linedir) return true;
8582
    if (b == linedir) return false;
8583
    return a < b;
8584
  }
8585
  var bidiOther;
8586
  function getBidiPartAt(order, pos) {
8587
    bidiOther = null;
8588
    for (var i = 0, found; i < order.length; ++i) {
8589
      var cur = order[i];
8590
      if (cur.from < pos && cur.to > pos) return i;
8591
      if ((cur.from == pos || cur.to == pos)) {
8592
        if (found == null) {
8593
          found = i;
8594
        } else if (compareBidiLevel(order, cur.level, order[found].level)) {
8595
          if (cur.from != cur.to) bidiOther = found;
8596
          return i;
8597
        } else {
8598
          if (cur.from != cur.to) bidiOther = i;
8599
          return found;
8600
        }
8601
      }
8602
    }
8603
    return found;
8604
  }
8605
 
8606
  function moveInLine(line, pos, dir, byUnit) {
8607
    if (!byUnit) return pos + dir;
8608
    do pos += dir;
8609
    while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
8610
    return pos;
8611
  }
8612
 
8613
  // This is needed in order to move 'visually' through bi-directional
8614
  // text -- i.e., pressing left should make the cursor go left, even
8615
  // when in RTL text. The tricky part is the 'jumps', where RTL and
8616
  // LTR text touch each other. This often requires the cursor offset
8617
  // to move more than one unit, in order to visually move one unit.
8618
  function moveVisually(line, start, dir, byUnit) {
8619
    var bidi = getOrder(line);
8620
    if (!bidi) return moveLogically(line, start, dir, byUnit);
8621
    var pos = getBidiPartAt(bidi, start), part = bidi[pos];
8622
    var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
8623
 
8624
    for (;;) {
8625
      if (target > part.from && target < part.to) return target;
8626
      if (target == part.from || target == part.to) {
8627
        if (getBidiPartAt(bidi, target) == pos) return target;
8628
        part = bidi[pos += dir];
8629
        return (dir > 0) == part.level % 2 ? part.to : part.from;
8630
      } else {
8631
        part = bidi[pos += dir];
8632
        if (!part) return null;
8633
        if ((dir > 0) == part.level % 2)
8634
          target = moveInLine(line, part.to, -1, byUnit);
8635
        else
8636
          target = moveInLine(line, part.from, 1, byUnit);
8637
      }
8638
    }
8639
  }
8640
 
8641
  function moveLogically(line, start, dir, byUnit) {
8642
    var target = start + dir;
8643
    if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
8644
    return target < 0 || target > line.text.length ? null : target;
8645
  }
8646
 
8647
  // Bidirectional ordering algorithm
8648
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
8649
  // that this (partially) implements.
8650
 
8651
  // One-char codes used for character types:
8652
  // L (L):   Left-to-Right
8653
  // R (R):   Right-to-Left
8654
  // r (AL):  Right-to-Left Arabic
8655
  // 1 (EN):  European Number
8656
  // + (ES):  European Number Separator
8657
  // % (ET):  European Number Terminator
8658
  // n (AN):  Arabic Number
8659
  // , (CS):  Common Number Separator
8660
  // m (NSM): Non-Spacing Mark
8661
  // b (BN):  Boundary Neutral
8662
  // s (B):   Paragraph Separator
8663
  // t (S):   Segment Separator
8664
  // w (WS):  Whitespace
8665
  // N (ON):  Other Neutrals
8666
 
8667
  // Returns null if characters are ordered as they appear
8668
  // (left-to-right), or an array of sections ({from, to, level}
8669
  // objects) in the order in which they occur visually.
8670
  var bidiOrdering = (function() {
8671
    // Character types for codepoints 0 to 0xff
8672
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
8673
    // Character types for codepoints 0x600 to 0x6ff
8674
    var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
8675
    function charType(code) {
8676
      if (code <= 0xf7) return lowTypes.charAt(code);
8677
      else if (0x590 <= code && code <= 0x5f4) return "R";
8678
      else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
8679
      else if (0x6ee <= code && code <= 0x8ac) return "r";
8680
      else if (0x2000 <= code && code <= 0x200b) return "w";
8681
      else if (code == 0x200c) return "b";
8682
      else return "L";
8683
    }
8684
 
8685
    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
8686
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
8687
    // Browsers seem to always treat the boundaries of block elements as being L.
8688
    var outerType = "L";
8689
 
8690
    function BidiSpan(level, from, to) {
8691
      this.level = level;
8692
      this.from = from; this.to = to;
8693
    }
8694
 
8695
    return function(str) {
8696
      if (!bidiRE.test(str)) return false;
8697
      var len = str.length, types = [];
8698
      for (var i = 0, type; i < len; ++i)
8699
        types.push(type = charType(str.charCodeAt(i)));
8700
 
8701
      // W1. Examine each non-spacing mark (NSM) in the level run, and
8702
      // change the type of the NSM to the type of the previous
8703
      // character. If the NSM is at the start of the level run, it will
8704
      // get the type of sor.
8705
      for (var i = 0, prev = outerType; i < len; ++i) {
8706
        var type = types[i];
8707
        if (type == "m") types[i] = prev;
8708
        else prev = type;
8709
      }
8710
 
8711
      // W2. Search backwards from each instance of a European number
8712
      // until the first strong type (R, L, AL, or sor) is found. If an
8713
      // AL is found, change the type of the European number to Arabic
8714
      // number.
8715
      // W3. Change all ALs to R.
8716
      for (var i = 0, cur = outerType; i < len; ++i) {
8717
        var type = types[i];
8718
        if (type == "1" && cur == "r") types[i] = "n";
8719
        else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
8720
      }
8721
 
8722
      // W4. A single European separator between two European numbers
8723
      // changes to a European number. A single common separator between
8724
      // two numbers of the same type changes to that type.
8725
      for (var i = 1, prev = types[0]; i < len - 1; ++i) {
8726
        var type = types[i];
8727
        if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
8728
        else if (type == "," && prev == types[i+1] &&
8729
                 (prev == "1" || prev == "n")) types[i] = prev;
8730
        prev = type;
8731
      }
8732
 
8733
      // W5. A sequence of European terminators adjacent to European
8734
      // numbers changes to all European numbers.
8735
      // W6. Otherwise, separators and terminators change to Other
8736
      // Neutral.
8737
      for (var i = 0; i < len; ++i) {
8738
        var type = types[i];
8739
        if (type == ",") types[i] = "N";
8740
        else if (type == "%") {
8741
          for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
8742
          var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
8743
          for (var j = i; j < end; ++j) types[j] = replace;
8744
          i = end - 1;
8745
        }
8746
      }
8747
 
8748
      // W7. Search backwards from each instance of a European number
8749
      // until the first strong type (R, L, or sor) is found. If an L is
8750
      // found, then change the type of the European number to L.
8751
      for (var i = 0, cur = outerType; i < len; ++i) {
8752
        var type = types[i];
8753
        if (cur == "L" && type == "1") types[i] = "L";
8754
        else if (isStrong.test(type)) cur = type;
8755
      }
8756
 
8757
      // N1. A sequence of neutrals takes the direction of the
8758
      // surrounding strong text if the text on both sides has the same
8759
      // direction. European and Arabic numbers act as if they were R in
8760
      // terms of their influence on neutrals. Start-of-level-run (sor)
8761
      // and end-of-level-run (eor) are used at level run boundaries.
8762
      // N2. Any remaining neutrals take the embedding direction.
8763
      for (var i = 0; i < len; ++i) {
8764
        if (isNeutral.test(types[i])) {
8765
          for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
8766
          var before = (i ? types[i-1] : outerType) == "L";
8767
          var after = (end < len ? types[end] : outerType) == "L";
8768
          var replace = before || after ? "L" : "R";
8769
          for (var j = i; j < end; ++j) types[j] = replace;
8770
          i = end - 1;
8771
        }
8772
      }
8773
 
8774
      // Here we depart from the documented algorithm, in order to avoid
8775
      // building up an actual levels array. Since there are only three
8776
      // levels (0, 1, 2) in an implementation that doesn't take
8777
      // explicit embedding into account, we can build up the order on
8778
      // the fly, without following the level-based algorithm.
8779
      var order = [], m;
8780
      for (var i = 0; i < len;) {
8781
        if (countsAsLeft.test(types[i])) {
8782
          var start = i;
8783
          for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
8784
          order.push(new BidiSpan(0, start, i));
8785
        } else {
8786
          var pos = i, at = order.length;
8787
          for (++i; i < len && types[i] != "L"; ++i) {}
8788
          for (var j = pos; j < i;) {
8789
            if (countsAsNum.test(types[j])) {
8790
              if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
8791
              var nstart = j;
8792
              for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
8793
              order.splice(at, 0, new BidiSpan(2, nstart, j));
8794
              pos = j;
8795
            } else ++j;
8796
          }
8797
          if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
8798
        }
8799
      }
8800
      if (order[0].level == 1 && (m = str.match(/^\s+/))) {
8801
        order[0].from = m[0].length;
8802
        order.unshift(new BidiSpan(0, 0, m[0].length));
8803
      }
8804
      if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
8805
        lst(order).to -= m[0].length;
8806
        order.push(new BidiSpan(0, len - m[0].length, len));
8807
      }
8808
      if (order[0].level == 2)
8809
        order.unshift(new BidiSpan(1, order[0].to, order[0].to));
8810
      if (order[0].level != lst(order).level)
8811
        order.push(new BidiSpan(order[0].level, len, len));
8812
 
8813
      return order;
8814
    };
8815
  })();
8816
 
8817
  // THE END
8818
 
8819
  CodeMirror.version = "5.6.0";
8820
 
8821
  return CodeMirror;
8822
});