Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
/*eslint-disable*/
2
// CodeMirror, copyright (c) by Marijn Haverbeke and others
3
// Distributed under an MIT license: https://codemirror.net/LICENSE
4
 
5
// This is CodeMirror (https://codemirror.net), a code editor
6
// implemented in JavaScript on top of the browser's DOM.
7
//
8
// You can find some technical background for some of the code below
9
// at http://marijnhaverbeke.nl/blog/#cm-internals .
10
 
11
(function (global, factory) {
12
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
13
  typeof define === 'function' && define.amd ? define(factory) :
14
  (global.CodeMirror = factory());
15
}(this, (function () { 'use strict';
16
 
17
  // Kludges for bugs and behavior differences that can't be feature
18
  // detected are enabled based on userAgent etc sniffing.
19
  var userAgent = navigator.userAgent;
20
  var platform = navigator.platform;
21
 
22
  var gecko = /gecko\/\d/i.test(userAgent);
23
  var ie_upto10 = /MSIE \d/.test(userAgent);
24
  var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
25
  var edge = /Edge\/(\d+)/.exec(userAgent);
26
  var ie = ie_upto10 || ie_11up || edge;
27
  var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
28
  var webkit = !edge && /WebKit\//.test(userAgent);
29
  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
30
  var chrome = !edge && /Chrome\//.test(userAgent);
31
  var presto = /Opera\//.test(userAgent);
32
  var safari = /Apple Computer/.test(navigator.vendor);
33
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
34
  var phantom = /PhantomJS/.test(userAgent);
35
 
36
  var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
37
  var android = /Android/.test(userAgent);
38
  // This is woefully incomplete. Suggestions for alternative methods welcome.
39
  var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
40
  var mac = ios || /Mac/.test(platform);
41
  var chromeOS = /\bCrOS\b/.test(userAgent);
42
  var windows = /win/i.test(platform);
43
 
44
  var presto_version = presto && 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
  function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
52
 
53
  var rmClass = function(node, cls) {
54
    var current = node.className;
55
    var match = classTest(cls).exec(current);
56
    if (match) {
57
      var after = current.slice(match.index + match[0].length);
58
      node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
59
    }
60
  };
61
 
62
  function removeChildren(e) {
63
    for (var count = e.childNodes.length; count > 0; --count)
64
      { e.removeChild(e.firstChild); }
65
    return e
66
  }
67
 
68
  function removeChildrenAndAdd(parent, e) {
69
    return removeChildren(parent).appendChild(e)
70
  }
71
 
72
  function elt(tag, content, className, style) {
73
    var e = document.createElement(tag);
74
    if (className) { e.className = className; }
75
    if (style) { e.style.cssText = style; }
76
    if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
77
    else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
78
    return e
79
  }
80
  // wrapper for elt, which removes the elt from the accessibility tree
81
  function eltP(tag, content, className, style) {
82
    var e = elt(tag, content, className, style);
83
    e.setAttribute("role", "presentation");
84
    return e
85
  }
86
 
87
  var range;
88
  if (document.createRange) { range = function(node, start, end, endNode) {
89
    var r = document.createRange();
90
    r.setEnd(endNode || node, end);
91
    r.setStart(node, start);
92
    return r
93
  }; }
94
  else { range = function(node, start, end) {
95
    var r = document.body.createTextRange();
96
    try { r.moveToElementText(node.parentNode); }
97
    catch(e) { return r }
98
    r.collapse(true);
99
    r.moveEnd("character", end);
100
    r.moveStart("character", start);
101
    return r
102
  }; }
103
 
104
  function contains(parent, child) {
105
    if (child.nodeType == 3) // Android browser always returns false when child is a textnode
106
      { child = child.parentNode; }
107
    if (parent.contains)
108
      { return parent.contains(child) }
109
    do {
110
      if (child.nodeType == 11) { child = child.host; }
111
      if (child == parent) { return true }
112
    } while (child = child.parentNode)
113
  }
114
 
115
  function activeElt() {
116
    // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
117
    // IE < 10 will throw when accessed while the page is loading or in an iframe.
118
    // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
119
    var activeElement;
120
    try {
121
      activeElement = document.activeElement;
122
    } catch(e) {
123
      activeElement = document.body || null;
124
    }
125
    while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
126
      { activeElement = activeElement.shadowRoot.activeElement; }
127
    return activeElement
128
  }
129
 
130
  function addClass(node, cls) {
131
    var current = node.className;
132
    if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
133
  }
134
  function joinClasses(a, b) {
135
    var as = a.split(" ");
136
    for (var i = 0; i < as.length; i++)
137
      { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
138
    return b
139
  }
140
 
141
  var selectInput = function(node) { node.select(); };
142
  if (ios) // Mobile Safari apparently has a bug where select() is broken.
143
    { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
144
  else if (ie) // Suppress mysterious IE10 errors
145
    { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
146
 
147
  function bind(f) {
148
    var args = Array.prototype.slice.call(arguments, 1);
149
    return function(){return f.apply(null, args)}
150
  }
151
 
152
  function copyObj(obj, target, overwrite) {
153
    if (!target) { target = {}; }
154
    for (var prop in obj)
155
      { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
156
        { target[prop] = obj[prop]; } }
157
    return target
158
  }
159
 
160
  // Counts the column offset in a string, taking tabs into account.
161
  // Used mostly to find indentation.
162
  function countColumn(string, end, tabSize, startIndex, startValue) {
163
    if (end == null) {
164
      end = string.search(/[^\s\u00a0]/);
165
      if (end == -1) { end = string.length; }
166
    }
167
    for (var i = startIndex || 0, n = startValue || 0;;) {
168
      var nextTab = string.indexOf("\t", i);
169
      if (nextTab < 0 || nextTab >= end)
170
        { return n + (end - i) }
171
      n += nextTab - i;
172
      n += tabSize - (n % tabSize);
173
      i = nextTab + 1;
174
    }
175
  }
176
 
177
  var Delayed = function() {this.id = null;};
178
  Delayed.prototype.set = function (ms, f) {
179
    clearTimeout(this.id);
180
    this.id = setTimeout(f, ms);
181
  };
182
 
183
  function indexOf(array, elt) {
184
    for (var i = 0; i < array.length; ++i)
185
      { if (array[i] == elt) { return i } }
186
    return -1
187
  }
188
 
189
  // Number of pixels added to scroller and sizer to hide scrollbar
190
  var scrollerGap = 30;
191
 
192
  // Returned or thrown by various protocols to signal 'I'm not
193
  // handling this'.
194
  var Pass = {toString: function(){return "CodeMirror.Pass"}};
195
 
196
  // Reused option objects for setSelection & friends
197
  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
198
 
199
  // The inverse of countColumn -- find the offset that corresponds to
200
  // a particular column.
201
  function findColumn(string, goal, tabSize) {
202
    for (var pos = 0, col = 0;;) {
203
      var nextTab = string.indexOf("\t", pos);
204
      if (nextTab == -1) { nextTab = string.length; }
205
      var skipped = nextTab - pos;
206
      if (nextTab == string.length || col + skipped >= goal)
207
        { return pos + Math.min(skipped, goal - col) }
208
      col += nextTab - pos;
209
      col += tabSize - (col % tabSize);
210
      pos = nextTab + 1;
211
      if (col >= goal) { return pos }
212
    }
213
  }
214
 
215
  var spaceStrs = [""];
216
  function spaceStr(n) {
217
    while (spaceStrs.length <= n)
218
      { spaceStrs.push(lst(spaceStrs) + " "); }
219
    return spaceStrs[n]
220
  }
221
 
222
  function lst(arr) { return arr[arr.length-1] }
223
 
224
  function map(array, f) {
225
    var out = [];
226
    for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
227
    return out
228
  }
229
 
230
  function insertSorted(array, value, score) {
231
    var pos = 0, priority = score(value);
232
    while (pos < array.length && score(array[pos]) <= priority) { pos++; }
233
    array.splice(pos, 0, value);
234
  }
235
 
236
  function nothing() {}
237
 
238
  function createObj(base, props) {
239
    var inst;
240
    if (Object.create) {
241
      inst = Object.create(base);
242
    } else {
243
      nothing.prototype = base;
244
      inst = new nothing();
245
    }
246
    if (props) { copyObj(props, inst); }
247
    return inst
248
  }
249
 
250
  var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
251
  function isWordCharBasic(ch) {
252
    return /\w/.test(ch) || ch > "\x80" &&
253
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
254
  }
255
  function isWordChar(ch, helper) {
256
    if (!helper) { return isWordCharBasic(ch) }
257
    if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
258
    return helper.test(ch)
259
  }
260
 
261
  function isEmpty(obj) {
262
    for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
263
    return true
264
  }
265
 
266
  // Extending unicode characters. A series of a non-extending char +
267
  // any number of extending chars is treated as a single unit as far
268
  // as editing and measuring is concerned. This is not fully correct,
269
  // since some scripts/fonts/browsers also treat other configurations
270
  // of code points as a group.
271
  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]/;
272
  function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
273
 
274
  // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
275
  function skipExtendingChars(str, pos, dir) {
276
    while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
277
    return pos
278
  }
279
 
280
  // Returns the value from the range [`from`; `to`] that satisfies
281
  // `pred` and is closest to `from`. Assumes that at least `to`
282
  // satisfies `pred`. Supports `from` being greater than `to`.
283
  function findFirst(pred, from, to) {
284
    // At any point we are certain `to` satisfies `pred`, don't know
285
    // whether `from` does.
286
    var dir = from > to ? -1 : 1;
287
    for (;;) {
288
      if (from == to) { return from }
289
      var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
290
      if (mid == from) { return pred(mid) ? from : to }
291
      if (pred(mid)) { to = mid; }
292
      else { from = mid + dir; }
293
    }
294
  }
295
 
296
  // The display handles the DOM integration, both for input reading
297
  // and content drawing. It holds references to DOM nodes and
298
  // display-related state.
299
 
300
  function Display(place, doc, input) {
301
    var d = this;
302
    this.input = input;
303
 
304
    // Covers bottom-right square when both scrollbars are present.
305
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
306
    d.scrollbarFiller.setAttribute("cm-not-content", "true");
307
    // Covers bottom of gutter when coverGutterNextToScrollbar is on
308
    // and h scrollbar is present.
309
    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
310
    d.gutterFiller.setAttribute("cm-not-content", "true");
311
    // Will contain the actual code, positioned to cover the viewport.
312
    d.lineDiv = eltP("div", null, "CodeMirror-code");
313
    // Elements are added to these to represent selection and cursors.
314
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
315
    d.cursorDiv = elt("div", null, "CodeMirror-cursors");
316
    // A visibility: hidden element used to find the size of things.
317
    d.measure = elt("div", null, "CodeMirror-measure");
318
    // When lines outside of the viewport are measured, they are drawn in this.
319
    d.lineMeasure = elt("div", null, "CodeMirror-measure");
320
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
321
    d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
322
                      null, "position: relative; outline: none");
323
    var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
324
    // Moved around its parent to cover visible view.
325
    d.mover = elt("div", [lines], null, "position: relative");
326
    // Set to the height of the document, allowing scrolling.
327
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
328
    d.sizerWidth = null;
329
    // Behavior of elts with overflow: auto and padding is
330
    // inconsistent across browsers. This is used to ensure the
331
    // scrollable area is big enough.
332
    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
333
    // Will contain the gutters, if any.
334
    d.gutters = elt("div", null, "CodeMirror-gutters");
335
    d.lineGutter = null;
336
    // Actual scrollable element.
337
    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
338
    d.scroller.setAttribute("tabIndex", "-1");
339
    // The element in which the editor lives.
340
    d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
341
 
342
    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
343
    if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
344
    if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
345
 
346
    if (place) {
347
      if (place.appendChild) { place.appendChild(d.wrapper); }
348
      else { place(d.wrapper); }
349
    }
350
 
351
    // Current rendered range (may be bigger than the view window).
352
    d.viewFrom = d.viewTo = doc.first;
353
    d.reportedViewFrom = d.reportedViewTo = doc.first;
354
    // Information about the rendered lines.
355
    d.view = [];
356
    d.renderedView = null;
357
    // Holds info about a single rendered line when it was rendered
358
    // for measurement, while not in view.
359
    d.externalMeasured = null;
360
    // Empty space (in pixels) above the view
361
    d.viewOffset = 0;
362
    d.lastWrapHeight = d.lastWrapWidth = 0;
363
    d.updateLineNumbers = null;
364
 
365
    d.nativeBarWidth = d.barHeight = d.barWidth = 0;
366
    d.scrollbarsClipped = false;
367
 
368
    // Used to only resize the line number gutter when necessary (when
369
    // the amount of lines crosses a boundary that makes its width change)
370
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
371
    // Set to true when a non-horizontal-scrolling line widget is
372
    // added. As an optimization, line widget aligning is skipped when
373
    // this is false.
374
    d.alignWidgets = false;
375
 
376
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
377
 
378
    // Tracks the maximum line length so that the horizontal scrollbar
379
    // can be kept static when scrolling.
380
    d.maxLine = null;
381
    d.maxLineLength = 0;
382
    d.maxLineChanged = false;
383
 
384
    // Used for measuring wheel scrolling granularity
385
    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
386
 
387
    // True when shift is held down.
388
    d.shift = false;
389
 
390
    // Used to track whether anything happened since the context menu
391
    // was opened.
392
    d.selForContextMenu = null;
393
 
394
    d.activeTouch = null;
395
 
396
    input.init(d);
397
  }
398
 
399
  // Find the line object corresponding to the given line number.
400
  function getLine(doc, n) {
401
    n -= doc.first;
402
    if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
403
    var chunk = doc;
404
    while (!chunk.lines) {
405
      for (var i = 0;; ++i) {
406
        var child = chunk.children[i], sz = child.chunkSize();
407
        if (n < sz) { chunk = child; break }
408
        n -= sz;
409
      }
410
    }
411
    return chunk.lines[n]
412
  }
413
 
414
  // Get the part of a document between two positions, as an array of
415
  // strings.
416
  function getBetween(doc, start, end) {
417
    var out = [], n = start.line;
418
    doc.iter(start.line, end.line + 1, function (line) {
419
      var text = line.text;
420
      if (n == end.line) { text = text.slice(0, end.ch); }
421
      if (n == start.line) { text = text.slice(start.ch); }
422
      out.push(text);
423
      ++n;
424
    });
425
    return out
426
  }
427
  // Get the lines between from and to, as array of strings.
428
  function getLines(doc, from, to) {
429
    var out = [];
430
    doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
431
    return out
432
  }
433
 
434
  // Update the height of a line, propagating the height change
435
  // upwards to parent nodes.
436
  function updateLineHeight(line, height) {
437
    var diff = height - line.height;
438
    if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
439
  }
440
 
441
  // Given a line object, find its line number by walking up through
442
  // its parent links.
443
  function lineNo(line) {
444
    if (line.parent == null) { return null }
445
    var cur = line.parent, no = indexOf(cur.lines, line);
446
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
447
      for (var i = 0;; ++i) {
448
        if (chunk.children[i] == cur) { break }
449
        no += chunk.children[i].chunkSize();
450
      }
451
    }
452
    return no + cur.first
453
  }
454
 
455
  // Find the line at the given vertical position, using the height
456
  // information in the document tree.
457
  function lineAtHeight(chunk, h) {
458
    var n = chunk.first;
459
    outer: do {
460
      for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
461
        var child = chunk.children[i$1], ch = child.height;
462
        if (h < ch) { chunk = child; continue outer }
463
        h -= ch;
464
        n += child.chunkSize();
465
      }
466
      return n
467
    } while (!chunk.lines)
468
    var i = 0;
469
    for (; i < chunk.lines.length; ++i) {
470
      var line = chunk.lines[i], lh = line.height;
471
      if (h < lh) { break }
472
      h -= lh;
473
    }
474
    return n + i
475
  }
476
 
477
  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
478
 
479
  function lineNumberFor(options, i) {
480
    return String(options.lineNumberFormatter(i + options.firstLineNumber))
481
  }
482
 
483
  // A Pos instance represents a position within the text.
484
  function Pos(line, ch, sticky) {
485
    if ( sticky === void 0 ) sticky = null;
486
 
487
    if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
488
    this.line = line;
489
    this.ch = ch;
490
    this.sticky = sticky;
491
  }
492
 
493
  // Compare two positions, return 0 if they are the same, a negative
494
  // number when a is less, and a positive number otherwise.
495
  function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
496
 
497
  function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
498
 
499
  function copyPos(x) {return Pos(x.line, x.ch)}
500
  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
501
  function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
502
 
503
  // Most of the external API clips given positions to make sure they
504
  // actually exist within the document.
505
  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
506
  function clipPos(doc, pos) {
507
    if (pos.line < doc.first) { return Pos(doc.first, 0) }
508
    var last = doc.first + doc.size - 1;
509
    if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
510
    return clipToLen(pos, getLine(doc, pos.line).text.length)
511
  }
512
  function clipToLen(pos, linelen) {
513
    var ch = pos.ch;
514
    if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
515
    else if (ch < 0) { return Pos(pos.line, 0) }
516
    else { return pos }
517
  }
518
  function clipPosArray(doc, array) {
519
    var out = [];
520
    for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
521
    return out
522
  }
523
 
524
  // Optimize some code when these features are not used.
525
  var sawReadOnlySpans = false, sawCollapsedSpans = false;
526
 
527
  function seeReadOnlySpans() {
528
    sawReadOnlySpans = true;
529
  }
530
 
531
  function seeCollapsedSpans() {
532
    sawCollapsedSpans = true;
533
  }
534
 
535
  // TEXTMARKER SPANS
536
 
537
  function MarkedSpan(marker, from, to) {
538
    this.marker = marker;
539
    this.from = from; this.to = to;
540
  }
541
 
542
  // Search an array of spans for a span matching the given marker.
543
  function getMarkedSpanFor(spans, marker) {
544
    if (spans) { for (var i = 0; i < spans.length; ++i) {
545
      var span = spans[i];
546
      if (span.marker == marker) { return span }
547
    } }
548
  }
549
  // Remove a span from an array, returning undefined if no spans are
550
  // left (we don't store arrays for lines without spans).
551
  function removeMarkedSpan(spans, span) {
552
    var r;
553
    for (var i = 0; i < spans.length; ++i)
554
      { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
555
    return r
556
  }
557
  // Add a span to a line.
558
  function addMarkedSpan(line, span) {
559
    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
560
    span.marker.attachLine(line);
561
  }
562
 
563
  // Used for the algorithm that adjusts markers for a change in the
564
  // document. These functions cut an array of spans at a given
565
  // character position, returning an array of remaining chunks (or
566
  // undefined if nothing remains).
567
  function markedSpansBefore(old, startCh, isInsert) {
568
    var nw;
569
    if (old) { for (var i = 0; i < old.length; ++i) {
570
      var span = old[i], marker = span.marker;
571
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
572
      if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
573
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
574
        ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
575
      }
576
    } }
577
    return nw
578
  }
579
  function markedSpansAfter(old, endCh, isInsert) {
580
    var nw;
581
    if (old) { for (var i = 0; i < old.length; ++i) {
582
      var span = old[i], marker = span.marker;
583
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
584
      if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
585
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
586
        ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
587
                                              span.to == null ? null : span.to - endCh));
588
      }
589
    } }
590
    return nw
591
  }
592
 
593
  // Given a change object, compute the new set of marker spans that
594
  // cover the line in which the change took place. Removes spans
595
  // entirely within the change, reconnects spans belonging to the
596
  // same marker that appear on both sides of the change, and cuts off
597
  // spans partially within the change. Returns an array of span
598
  // arrays with one element for each line in (after) the change.
599
  function stretchSpansOverChange(doc, change) {
600
    if (change.full) { return null }
601
    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
602
    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
603
    if (!oldFirst && !oldLast) { return null }
604
 
605
    var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
606
    // Get the spans that 'stick out' on both sides
607
    var first = markedSpansBefore(oldFirst, startCh, isInsert);
608
    var last = markedSpansAfter(oldLast, endCh, isInsert);
609
 
610
    // Next, merge those two ends
611
    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
612
    if (first) {
613
      // Fix up .to properties of first
614
      for (var i = 0; i < first.length; ++i) {
615
        var span = first[i];
616
        if (span.to == null) {
617
          var found = getMarkedSpanFor(last, span.marker);
618
          if (!found) { span.to = startCh; }
619
          else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
620
        }
621
      }
622
    }
623
    if (last) {
624
      // Fix up .from in last (or move them into first in case of sameLine)
625
      for (var i$1 = 0; i$1 < last.length; ++i$1) {
626
        var span$1 = last[i$1];
627
        if (span$1.to != null) { span$1.to += offset; }
628
        if (span$1.from == null) {
629
          var found$1 = getMarkedSpanFor(first, span$1.marker);
630
          if (!found$1) {
631
            span$1.from = offset;
632
            if (sameLine) { (first || (first = [])).push(span$1); }
633
          }
634
        } else {
635
          span$1.from += offset;
636
          if (sameLine) { (first || (first = [])).push(span$1); }
637
        }
638
      }
639
    }
640
    // Make sure we didn't create any zero-length spans
641
    if (first) { first = clearEmptySpans(first); }
642
    if (last && last != first) { last = clearEmptySpans(last); }
643
 
644
    var newMarkers = [first];
645
    if (!sameLine) {
646
      // Fill gap with whole-line-spans
647
      var gap = change.text.length - 2, gapMarkers;
648
      if (gap > 0 && first)
649
        { for (var i$2 = 0; i$2 < first.length; ++i$2)
650
          { if (first[i$2].to == null)
651
            { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
652
      for (var i$3 = 0; i$3 < gap; ++i$3)
653
        { newMarkers.push(gapMarkers); }
654
      newMarkers.push(last);
655
    }
656
    return newMarkers
657
  }
658
 
659
  // Remove spans that are empty and don't have a clearWhenEmpty
660
  // option of false.
661
  function clearEmptySpans(spans) {
662
    for (var i = 0; i < spans.length; ++i) {
663
      var span = spans[i];
664
      if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
665
        { spans.splice(i--, 1); }
666
    }
667
    if (!spans.length) { return null }
668
    return spans
669
  }
670
 
671
  // Used to 'clip' out readOnly ranges when making a change.
672
  function removeReadOnlyRanges(doc, from, to) {
673
    var markers = null;
674
    doc.iter(from.line, to.line + 1, function (line) {
675
      if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
676
        var mark = line.markedSpans[i].marker;
677
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
678
          { (markers || (markers = [])).push(mark); }
679
      } }
680
    });
681
    if (!markers) { return null }
682
    var parts = [{from: from, to: to}];
683
    for (var i = 0; i < markers.length; ++i) {
684
      var mk = markers[i], m = mk.find(0);
685
      for (var j = 0; j < parts.length; ++j) {
686
        var p = parts[j];
687
        if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
688
        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
689
        if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
690
          { newParts.push({from: p.from, to: m.from}); }
691
        if (dto > 0 || !mk.inclusiveRight && !dto)
692
          { newParts.push({from: m.to, to: p.to}); }
693
        parts.splice.apply(parts, newParts);
694
        j += newParts.length - 3;
695
      }
696
    }
697
    return parts
698
  }
699
 
700
  // Connect or disconnect spans from a line.
701
  function detachMarkedSpans(line) {
702
    var spans = line.markedSpans;
703
    if (!spans) { return }
704
    for (var i = 0; i < spans.length; ++i)
705
      { spans[i].marker.detachLine(line); }
706
    line.markedSpans = null;
707
  }
708
  function attachMarkedSpans(line, spans) {
709
    if (!spans) { return }
710
    for (var i = 0; i < spans.length; ++i)
711
      { spans[i].marker.attachLine(line); }
712
    line.markedSpans = spans;
713
  }
714
 
715
  // Helpers used when computing which overlapping collapsed span
716
  // counts as the larger one.
717
  function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
718
  function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
719
 
720
  // Returns a number indicating which of two overlapping collapsed
721
  // spans is larger (and thus includes the other). Falls back to
722
  // comparing ids when the spans cover exactly the same range.
723
  function compareCollapsedMarkers(a, b) {
724
    var lenDiff = a.lines.length - b.lines.length;
725
    if (lenDiff != 0) { return lenDiff }
726
    var aPos = a.find(), bPos = b.find();
727
    var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
728
    if (fromCmp) { return -fromCmp }
729
    var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
730
    if (toCmp) { return toCmp }
731
    return b.id - a.id
732
  }
733
 
734
  // Find out whether a line ends or starts in a collapsed span. If
735
  // so, return the marker for that span.
736
  function collapsedSpanAtSide(line, start) {
737
    var sps = sawCollapsedSpans && line.markedSpans, found;
738
    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
739
      sp = sps[i];
740
      if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
741
          (!found || compareCollapsedMarkers(found, sp.marker) < 0))
742
        { found = sp.marker; }
743
    } }
744
    return found
745
  }
746
  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
747
  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
748
 
749
  function collapsedSpanAround(line, ch) {
750
    var sps = sawCollapsedSpans && line.markedSpans, found;
751
    if (sps) { for (var i = 0; i < sps.length; ++i) {
752
      var sp = sps[i];
753
      if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
754
          (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
755
    } }
756
    return found
757
  }
758
 
759
  // Test whether there exists a collapsed span that partially
760
  // overlaps (covers the start or end, but not both) of a new span.
761
  // Such overlap is not allowed.
762
  function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
763
    var line = getLine(doc, lineNo$$1);
764
    var sps = sawCollapsedSpans && line.markedSpans;
765
    if (sps) { for (var i = 0; i < sps.length; ++i) {
766
      var sp = sps[i];
767
      if (!sp.marker.collapsed) { continue }
768
      var found = sp.marker.find(0);
769
      var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
770
      var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
771
      if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
772
      if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
773
          fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
774
        { return true }
775
    } }
776
  }
777
 
778
  // A visual line is a line as drawn on the screen. Folding, for
779
  // example, can cause multiple logical lines to appear on the same
780
  // visual line. This finds the start of the visual line that the
781
  // given line is part of (usually that is the line itself).
782
  function visualLine(line) {
783
    var merged;
784
    while (merged = collapsedSpanAtStart(line))
785
      { line = merged.find(-1, true).line; }
786
    return line
787
  }
788
 
789
  function visualLineEnd(line) {
790
    var merged;
791
    while (merged = collapsedSpanAtEnd(line))
792
      { line = merged.find(1, true).line; }
793
    return line
794
  }
795
 
796
  // Returns an array of logical lines that continue the visual line
797
  // started by the argument, or undefined if there are no such lines.
798
  function visualLineContinued(line) {
799
    var merged, lines;
800
    while (merged = collapsedSpanAtEnd(line)) {
801
      line = merged.find(1, true).line
802
      ;(lines || (lines = [])).push(line);
803
    }
804
    return lines
805
  }
806
 
807
  // Get the line number of the start of the visual line that the
808
  // given line number is part of.
809
  function visualLineNo(doc, lineN) {
810
    var line = getLine(doc, lineN), vis = visualLine(line);
811
    if (line == vis) { return lineN }
812
    return lineNo(vis)
813
  }
814
 
815
  // Get the line number of the start of the next visual line after
816
  // the given line.
817
  function visualLineEndNo(doc, lineN) {
818
    if (lineN > doc.lastLine()) { return lineN }
819
    var line = getLine(doc, lineN), merged;
820
    if (!lineIsHidden(doc, line)) { return lineN }
821
    while (merged = collapsedSpanAtEnd(line))
822
      { line = merged.find(1, true).line; }
823
    return lineNo(line) + 1
824
  }
825
 
826
  // Compute whether a line is hidden. Lines count as hidden when they
827
  // are part of a visual line that starts with another line, or when
828
  // they are entirely covered by collapsed, non-widget span.
829
  function lineIsHidden(doc, line) {
830
    var sps = sawCollapsedSpans && line.markedSpans;
831
    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
832
      sp = sps[i];
833
      if (!sp.marker.collapsed) { continue }
834
      if (sp.from == null) { return true }
835
      if (sp.marker.widgetNode) { continue }
836
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
837
        { return true }
838
    } }
839
  }
840
  function lineIsHiddenInner(doc, line, span) {
841
    if (span.to == null) {
842
      var end = span.marker.find(1, true);
843
      return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
844
    }
845
    if (span.marker.inclusiveRight && span.to == line.text.length)
846
      { return true }
847
    for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
848
      sp = line.markedSpans[i];
849
      if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
850
          (sp.to == null || sp.to != span.from) &&
851
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
852
          lineIsHiddenInner(doc, line, sp)) { return true }
853
    }
854
  }
855
 
856
  // Find the height above the given line.
857
  function heightAtLine(lineObj) {
858
    lineObj = visualLine(lineObj);
859
 
860
    var h = 0, chunk = lineObj.parent;
861
    for (var i = 0; i < chunk.lines.length; ++i) {
862
      var line = chunk.lines[i];
863
      if (line == lineObj) { break }
864
      else { h += line.height; }
865
    }
866
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
867
      for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
868
        var cur = p.children[i$1];
869
        if (cur == chunk) { break }
870
        else { h += cur.height; }
871
      }
872
    }
873
    return h
874
  }
875
 
876
  // Compute the character length of a line, taking into account
877
  // collapsed ranges (see markText) that might hide parts, and join
878
  // other lines onto it.
879
  function lineLength(line) {
880
    if (line.height == 0) { return 0 }
881
    var len = line.text.length, merged, cur = line;
882
    while (merged = collapsedSpanAtStart(cur)) {
883
      var found = merged.find(0, true);
884
      cur = found.from.line;
885
      len += found.from.ch - found.to.ch;
886
    }
887
    cur = line;
888
    while (merged = collapsedSpanAtEnd(cur)) {
889
      var found$1 = merged.find(0, true);
890
      len -= cur.text.length - found$1.from.ch;
891
      cur = found$1.to.line;
892
      len += cur.text.length - found$1.to.ch;
893
    }
894
    return len
895
  }
896
 
897
  // Find the longest line in the document.
898
  function findMaxLine(cm) {
899
    var d = cm.display, doc = cm.doc;
900
    d.maxLine = getLine(doc, doc.first);
901
    d.maxLineLength = lineLength(d.maxLine);
902
    d.maxLineChanged = true;
903
    doc.iter(function (line) {
904
      var len = lineLength(line);
905
      if (len > d.maxLineLength) {
906
        d.maxLineLength = len;
907
        d.maxLine = line;
908
      }
909
    });
910
  }
911
 
912
  // BIDI HELPERS
913
 
914
  function iterateBidiSections(order, from, to, f) {
915
    if (!order) { return f(from, to, "ltr", 0) }
916
    var found = false;
917
    for (var i = 0; i < order.length; ++i) {
918
      var part = order[i];
919
      if (part.from < to && part.to > from || from == to && part.to == from) {
920
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
921
        found = true;
922
      }
923
    }
924
    if (!found) { f(from, to, "ltr"); }
925
  }
926
 
927
  var bidiOther = null;
928
  function getBidiPartAt(order, ch, sticky) {
929
    var found;
930
    bidiOther = null;
931
    for (var i = 0; i < order.length; ++i) {
932
      var cur = order[i];
933
      if (cur.from < ch && cur.to > ch) { return i }
934
      if (cur.to == ch) {
935
        if (cur.from != cur.to && sticky == "before") { found = i; }
936
        else { bidiOther = i; }
937
      }
938
      if (cur.from == ch) {
939
        if (cur.from != cur.to && sticky != "before") { found = i; }
940
        else { bidiOther = i; }
941
      }
942
    }
943
    return found != null ? found : bidiOther
944
  }
945
 
946
  // Bidirectional ordering algorithm
947
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
948
  // that this (partially) implements.
949
 
950
  // One-char codes used for character types:
951
  // L (L):   Left-to-Right
952
  // R (R):   Right-to-Left
953
  // r (AL):  Right-to-Left Arabic
954
  // 1 (EN):  European Number
955
  // + (ES):  European Number Separator
956
  // % (ET):  European Number Terminator
957
  // n (AN):  Arabic Number
958
  // , (CS):  Common Number Separator
959
  // m (NSM): Non-Spacing Mark
960
  // b (BN):  Boundary Neutral
961
  // s (B):   Paragraph Separator
962
  // t (S):   Segment Separator
963
  // w (WS):  Whitespace
964
  // N (ON):  Other Neutrals
965
 
966
  // Returns null if characters are ordered as they appear
967
  // (left-to-right), or an array of sections ({from, to, level}
968
  // objects) in the order in which they occur visually.
969
  var bidiOrdering = (function() {
970
    // Character types for codepoints 0 to 0xff
971
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
972
    // Character types for codepoints 0x600 to 0x6f9
973
    var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
974
    function charType(code) {
975
      if (code <= 0xf7) { return lowTypes.charAt(code) }
976
      else if (0x590 <= code && code <= 0x5f4) { return "R" }
977
      else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
978
      else if (0x6ee <= code && code <= 0x8ac) { return "r" }
979
      else if (0x2000 <= code && code <= 0x200b) { return "w" }
980
      else if (code == 0x200c) { return "b" }
981
      else { return "L" }
982
    }
983
 
984
    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
985
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
986
 
987
    function BidiSpan(level, from, to) {
988
      this.level = level;
989
      this.from = from; this.to = to;
990
    }
991
 
992
    return function(str, direction) {
993
      var outerType = direction == "ltr" ? "L" : "R";
994
 
995
      if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
996
      var len = str.length, types = [];
997
      for (var i = 0; i < len; ++i)
998
        { types.push(charType(str.charCodeAt(i))); }
999
 
1000
      // W1. Examine each non-spacing mark (NSM) in the level run, and
1001
      // change the type of the NSM to the type of the previous
1002
      // character. If the NSM is at the start of the level run, it will
1003
      // get the type of sor.
1004
      for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
1005
        var type = types[i$1];
1006
        if (type == "m") { types[i$1] = prev; }
1007
        else { prev = type; }
1008
      }
1009
 
1010
      // W2. Search backwards from each instance of a European number
1011
      // until the first strong type (R, L, AL, or sor) is found. If an
1012
      // AL is found, change the type of the European number to Arabic
1013
      // number.
1014
      // W3. Change all ALs to R.
1015
      for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
1016
        var type$1 = types[i$2];
1017
        if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
1018
        else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
1019
      }
1020
 
1021
      // W4. A single European separator between two European numbers
1022
      // changes to a European number. A single common separator between
1023
      // two numbers of the same type changes to that type.
1024
      for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
1025
        var type$2 = types[i$3];
1026
        if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
1027
        else if (type$2 == "," && prev$1 == types[i$3+1] &&
1028
                 (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
1029
        prev$1 = type$2;
1030
      }
1031
 
1032
      // W5. A sequence of European terminators adjacent to European
1033
      // numbers changes to all European numbers.
1034
      // W6. Otherwise, separators and terminators change to Other
1035
      // Neutral.
1036
      for (var i$4 = 0; i$4 < len; ++i$4) {
1037
        var type$3 = types[i$4];
1038
        if (type$3 == ",") { types[i$4] = "N"; }
1039
        else if (type$3 == "%") {
1040
          var end = (void 0);
1041
          for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
1042
          var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
1043
          for (var j = i$4; j < end; ++j) { types[j] = replace; }
1044
          i$4 = end - 1;
1045
        }
1046
      }
1047
 
1048
      // W7. Search backwards from each instance of a European number
1049
      // until the first strong type (R, L, or sor) is found. If an L is
1050
      // found, then change the type of the European number to L.
1051
      for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
1052
        var type$4 = types[i$5];
1053
        if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
1054
        else if (isStrong.test(type$4)) { cur$1 = type$4; }
1055
      }
1056
 
1057
      // N1. A sequence of neutrals takes the direction of the
1058
      // surrounding strong text if the text on both sides has the same
1059
      // direction. European and Arabic numbers act as if they were R in
1060
      // terms of their influence on neutrals. Start-of-level-run (sor)
1061
      // and end-of-level-run (eor) are used at level run boundaries.
1062
      // N2. Any remaining neutrals take the embedding direction.
1063
      for (var i$6 = 0; i$6 < len; ++i$6) {
1064
        if (isNeutral.test(types[i$6])) {
1065
          var end$1 = (void 0);
1066
          for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
1067
          var before = (i$6 ? types[i$6-1] : outerType) == "L";
1068
          var after = (end$1 < len ? types[end$1] : outerType) == "L";
1069
          var replace$1 = before == after ? (before ? "L" : "R") : outerType;
1070
          for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
1071
          i$6 = end$1 - 1;
1072
        }
1073
      }
1074
 
1075
      // Here we depart from the documented algorithm, in order to avoid
1076
      // building up an actual levels array. Since there are only three
1077
      // levels (0, 1, 2) in an implementation that doesn't take
1078
      // explicit embedding into account, we can build up the order on
1079
      // the fly, without following the level-based algorithm.
1080
      var order = [], m;
1081
      for (var i$7 = 0; i$7 < len;) {
1082
        if (countsAsLeft.test(types[i$7])) {
1083
          var start = i$7;
1084
          for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
1085
          order.push(new BidiSpan(0, start, i$7));
1086
        } else {
1087
          var pos = i$7, at = order.length;
1088
          for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
1089
          for (var j$2 = pos; j$2 < i$7;) {
1090
            if (countsAsNum.test(types[j$2])) {
1091
              if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
1092
              var nstart = j$2;
1093
              for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
1094
              order.splice(at, 0, new BidiSpan(2, nstart, j$2));
1095
              pos = j$2;
1096
            } else { ++j$2; }
1097
          }
1098
          if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
1099
        }
1100
      }
1101
      if (direction == "ltr") {
1102
        if (order[0].level == 1 && (m = str.match(/^\s+/))) {
1103
          order[0].from = m[0].length;
1104
          order.unshift(new BidiSpan(0, 0, m[0].length));
1105
        }
1106
        if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
1107
          lst(order).to -= m[0].length;
1108
          order.push(new BidiSpan(0, len - m[0].length, len));
1109
        }
1110
      }
1111
 
1112
      return direction == "rtl" ? order.reverse() : order
1113
    }
1114
  })();
1115
 
1116
  // Get the bidi ordering for the given line (and cache it). Returns
1117
  // false for lines that are fully left-to-right, and an array of
1118
  // BidiSpan objects otherwise.
1119
  function getOrder(line, direction) {
1120
    var order = line.order;
1121
    if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
1122
    return order
1123
  }
1124
 
1125
  // EVENT HANDLING
1126
 
1127
  // Lightweight event framework. on/off also work on DOM nodes,
1128
  // registering native DOM handlers.
1129
 
1130
  var noHandlers = [];
1131
 
1132
  var on = function(emitter, type, f) {
1133
    if (emitter.addEventListener) {
1134
      emitter.addEventListener(type, f, false);
1135
    } else if (emitter.attachEvent) {
1136
      emitter.attachEvent("on" + type, f);
1137
    } else {
1138
      var map$$1 = emitter._handlers || (emitter._handlers = {});
1139
      map$$1[type] = (map$$1[type] || noHandlers).concat(f);
1140
    }
1141
  };
1142
 
1143
  function getHandlers(emitter, type) {
1144
    return emitter._handlers && emitter._handlers[type] || noHandlers
1145
  }
1146
 
1147
  function off(emitter, type, f) {
1148
    if (emitter.removeEventListener) {
1149
      emitter.removeEventListener(type, f, false);
1150
    } else if (emitter.detachEvent) {
1151
      emitter.detachEvent("on" + type, f);
1152
    } else {
1153
      var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
1154
      if (arr) {
1155
        var index = indexOf(arr, f);
1156
        if (index > -1)
1157
          { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
1158
      }
1159
    }
1160
  }
1161
 
1162
  function signal(emitter, type /*, values...*/) {
1163
    var handlers = getHandlers(emitter, type);
1164
    if (!handlers.length) { return }
1165
    var args = Array.prototype.slice.call(arguments, 2);
1166
    for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
1167
  }
1168
 
1169
  // The DOM events that CodeMirror handles can be overridden by
1170
  // registering a (non-DOM) handler on the editor for the event name,
1171
  // and preventDefault-ing the event in that handler.
1172
  function signalDOMEvent(cm, e, override) {
1173
    if (typeof e == "string")
1174
      { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
1175
    signal(cm, override || e.type, cm, e);
1176
    return e_defaultPrevented(e) || e.codemirrorIgnore
1177
  }
1178
 
1179
  function signalCursorActivity(cm) {
1180
    var arr = cm._handlers && cm._handlers.cursorActivity;
1181
    if (!arr) { return }
1182
    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
1183
    for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
1184
      { set.push(arr[i]); } }
1185
  }
1186
 
1187
  function hasHandler(emitter, type) {
1188
    return getHandlers(emitter, type).length > 0
1189
  }
1190
 
1191
  // Add on and off methods to a constructor's prototype, to make
1192
  // registering events on such objects more convenient.
1193
  function eventMixin(ctor) {
1194
    ctor.prototype.on = function(type, f) {on(this, type, f);};
1195
    ctor.prototype.off = function(type, f) {off(this, type, f);};
1196
  }
1197
 
1198
  // Due to the fact that we still support jurassic IE versions, some
1199
  // compatibility wrappers are needed.
1200
 
1201
  function e_preventDefault(e) {
1202
    if (e.preventDefault) { e.preventDefault(); }
1203
    else { e.returnValue = false; }
1204
  }
1205
  function e_stopPropagation(e) {
1206
    if (e.stopPropagation) { e.stopPropagation(); }
1207
    else { e.cancelBubble = true; }
1208
  }
1209
  function e_defaultPrevented(e) {
1210
    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
1211
  }
1212
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
1213
 
1214
  function e_target(e) {return e.target || e.srcElement}
1215
  function e_button(e) {
1216
    var b = e.which;
1217
    if (b == null) {
1218
      if (e.button & 1) { b = 1; }
1219
      else if (e.button & 2) { b = 3; }
1220
      else if (e.button & 4) { b = 2; }
1221
    }
1222
    if (mac && e.ctrlKey && b == 1) { b = 3; }
1223
    return b
1224
  }
1225
 
1226
  // Detect drag-and-drop
1227
  var dragAndDrop = function() {
1228
    // There is *some* kind of drag-and-drop support in IE6-8, but I
1229
    // couldn't get it to work yet.
1230
    if (ie && ie_version < 9) { return false }
1231
    var div = elt('div');
1232
    return "draggable" in div || "dragDrop" in div
1233
  }();
1234
 
1235
  var zwspSupported;
1236
  function zeroWidthElement(measure) {
1237
    if (zwspSupported == null) {
1238
      var test = elt("span", "\u200b");
1239
      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
1240
      if (measure.firstChild.offsetHeight != 0)
1241
        { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
1242
    }
1243
    var node = zwspSupported ? elt("span", "\u200b") :
1244
      elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
1245
    node.setAttribute("cm-text", "");
1246
    return node
1247
  }
1248
 
1249
  // Feature-detect IE's crummy client rect reporting for bidi text
1250
  var badBidiRects;
1251
  function hasBadBidiRects(measure) {
1252
    if (badBidiRects != null) { return badBidiRects }
1253
    var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
1254
    var r0 = range(txt, 0, 1).getBoundingClientRect();
1255
    var r1 = range(txt, 1, 2).getBoundingClientRect();
1256
    removeChildren(measure);
1257
    if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
1258
    return badBidiRects = (r1.right - r0.right < 3)
1259
  }
1260
 
1261
  // See if "".split is the broken IE version, if so, provide an
1262
  // alternative way to split lines.
1263
  var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
1264
    var pos = 0, result = [], l = string.length;
1265
    while (pos <= l) {
1266
      var nl = string.indexOf("\n", pos);
1267
      if (nl == -1) { nl = string.length; }
1268
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
1269
      var rt = line.indexOf("\r");
1270
      if (rt != -1) {
1271
        result.push(line.slice(0, rt));
1272
        pos += rt + 1;
1273
      } else {
1274
        result.push(line);
1275
        pos = nl + 1;
1276
      }
1277
    }
1278
    return result
1279
  } : function (string) { return string.split(/\r\n?|\n/); };
1280
 
1281
  var hasSelection = window.getSelection ? function (te) {
1282
    try { return te.selectionStart != te.selectionEnd }
1283
    catch(e) { return false }
1284
  } : function (te) {
1285
    var range$$1;
1286
    try {range$$1 = te.ownerDocument.selection.createRange();}
1287
    catch(e) {}
1288
    if (!range$$1 || range$$1.parentElement() != te) { return false }
1289
    return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
1290
  };
1291
 
1292
  var hasCopyEvent = (function () {
1293
    var e = elt("div");
1294
    if ("oncopy" in e) { return true }
1295
    e.setAttribute("oncopy", "return;");
1296
    return typeof e.oncopy == "function"
1297
  })();
1298
 
1299
  var badZoomedRects = null;
1300
  function hasBadZoomedRects(measure) {
1301
    if (badZoomedRects != null) { return badZoomedRects }
1302
    var node = removeChildrenAndAdd(measure, elt("span", "x"));
1303
    var normal = node.getBoundingClientRect();
1304
    var fromRange = range(node, 0, 1).getBoundingClientRect();
1305
    return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
1306
  }
1307
 
1308
  // Known modes, by name and by MIME
1309
  var modes = {}, mimeModes = {};
1310
 
1311
  // Extra arguments are stored as the mode's dependencies, which is
1312
  // used by (legacy) mechanisms like loadmode.js to automatically
1313
  // load a mode. (Preferred mechanism is the require/define calls.)
1314
  function defineMode(name, mode) {
1315
    if (arguments.length > 2)
1316
      { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
1317
    modes[name] = mode;
1318
  }
1319
 
1320
  function defineMIME(mime, spec) {
1321
    mimeModes[mime] = spec;
1322
  }
1323
 
1324
  // Given a MIME type, a {name, ...options} config object, or a name
1325
  // string, return a mode config object.
1326
  function resolveMode(spec) {
1327
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
1328
      spec = mimeModes[spec];
1329
    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
1330
      var found = mimeModes[spec.name];
1331
      if (typeof found == "string") { found = {name: found}; }
1332
      spec = createObj(found, spec);
1333
      spec.name = found.name;
1334
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
1335
      return resolveMode("application/xml")
1336
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
1337
      return resolveMode("application/json")
1338
    }
1339
    if (typeof spec == "string") { return {name: spec} }
1340
    else { return spec || {name: "null"} }
1341
  }
1342
 
1343
  // Given a mode spec (anything that resolveMode accepts), find and
1344
  // initialize an actual mode object.
1345
  function getMode(options, spec) {
1346
    spec = resolveMode(spec);
1347
    var mfactory = modes[spec.name];
1348
    if (!mfactory) { return getMode(options, "text/plain") }
1349
    var modeObj = mfactory(options, spec);
1350
    if (modeExtensions.hasOwnProperty(spec.name)) {
1351
      var exts = modeExtensions[spec.name];
1352
      for (var prop in exts) {
1353
        if (!exts.hasOwnProperty(prop)) { continue }
1354
        if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
1355
        modeObj[prop] = exts[prop];
1356
      }
1357
    }
1358
    modeObj.name = spec.name;
1359
    if (spec.helperType) { modeObj.helperType = spec.helperType; }
1360
    if (spec.modeProps) { for (var prop$1 in spec.modeProps)
1361
      { modeObj[prop$1] = spec.modeProps[prop$1]; } }
1362
 
1363
    return modeObj
1364
  }
1365
 
1366
  // This can be used to attach properties to mode objects from
1367
  // outside the actual mode definition.
1368
  var modeExtensions = {};
1369
  function extendMode(mode, properties) {
1370
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
1371
    copyObj(properties, exts);
1372
  }
1373
 
1374
  function copyState(mode, state) {
1375
    if (state === true) { return state }
1376
    if (mode.copyState) { return mode.copyState(state) }
1377
    var nstate = {};
1378
    for (var n in state) {
1379
      var val = state[n];
1380
      if (val instanceof Array) { val = val.concat([]); }
1381
      nstate[n] = val;
1382
    }
1383
    return nstate
1384
  }
1385
 
1386
  // Given a mode and a state (for that mode), find the inner mode and
1387
  // state at the position that the state refers to.
1388
  function innerMode(mode, state) {
1389
    var info;
1390
    while (mode.innerMode) {
1391
      info = mode.innerMode(state);
1392
      if (!info || info.mode == mode) { break }
1393
      state = info.state;
1394
      mode = info.mode;
1395
    }
1396
    return info || {mode: mode, state: state}
1397
  }
1398
 
1399
  function startState(mode, a1, a2) {
1400
    return mode.startState ? mode.startState(a1, a2) : true
1401
  }
1402
 
1403
  // STRING STREAM
1404
 
1405
  // Fed to the mode parsers, provides helper functions to make
1406
  // parsers more succinct.
1407
 
1408
  var StringStream = function(string, tabSize, lineOracle) {
1409
    this.pos = this.start = 0;
1410
    this.string = string;
1411
    this.tabSize = tabSize || 8;
1412
    this.lastColumnPos = this.lastColumnValue = 0;
1413
    this.lineStart = 0;
1414
    this.lineOracle = lineOracle;
1415
  };
1416
 
1417
  StringStream.prototype.eol = function () {return this.pos >= this.string.length};
1418
  StringStream.prototype.sol = function () {return this.pos == this.lineStart};
1419
  StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
1420
  StringStream.prototype.next = function () {
1421
    if (this.pos < this.string.length)
1422
      { return this.string.charAt(this.pos++) }
1423
  };
1424
  StringStream.prototype.eat = function (match) {
1425
    var ch = this.string.charAt(this.pos);
1426
    var ok;
1427
    if (typeof match == "string") { ok = ch == match; }
1428
    else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
1429
    if (ok) {++this.pos; return ch}
1430
  };
1431
  StringStream.prototype.eatWhile = function (match) {
1432
    var start = this.pos;
1433
    while (this.eat(match)){}
1434
    return this.pos > start
1435
  };
1436
  StringStream.prototype.eatSpace = function () {
1437
    var start = this.pos;
1438
    while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
1439
    return this.pos > start
1440
  };
1441
  StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
1442
  StringStream.prototype.skipTo = function (ch) {
1443
    var found = this.string.indexOf(ch, this.pos);
1444
    if (found > -1) {this.pos = found; return true}
1445
  };
1446
  StringStream.prototype.backUp = function (n) {this.pos -= n;};
1447
  StringStream.prototype.column = function () {
1448
    if (this.lastColumnPos < this.start) {
1449
      this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
1450
      this.lastColumnPos = this.start;
1451
    }
1452
    return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
1453
  };
1454
  StringStream.prototype.indentation = function () {
1455
    return countColumn(this.string, null, this.tabSize) -
1456
      (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
1457
  };
1458
  StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
1459
    if (typeof pattern == "string") {
1460
      var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
1461
      var substr = this.string.substr(this.pos, pattern.length);
1462
      if (cased(substr) == cased(pattern)) {
1463
        if (consume !== false) { this.pos += pattern.length; }
1464
        return true
1465
      }
1466
    } else {
1467
      var match = this.string.slice(this.pos).match(pattern);
1468
      if (match && match.index > 0) { return null }
1469
      if (match && consume !== false) { this.pos += match[0].length; }
1470
      return match
1471
    }
1472
  };
1473
  StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
1474
  StringStream.prototype.hideFirstChars = function (n, inner) {
1475
    this.lineStart += n;
1476
    try { return inner() }
1477
    finally { this.lineStart -= n; }
1478
  };
1479
  StringStream.prototype.lookAhead = function (n) {
1480
    var oracle = this.lineOracle;
1481
    return oracle && oracle.lookAhead(n)
1482
  };
1483
  StringStream.prototype.baseToken = function () {
1484
    var oracle = this.lineOracle;
1485
    return oracle && oracle.baseToken(this.pos)
1486
  };
1487
 
1488
  var SavedContext = function(state, lookAhead) {
1489
    this.state = state;
1490
    this.lookAhead = lookAhead;
1491
  };
1492
 
1493
  var Context = function(doc, state, line, lookAhead) {
1494
    this.state = state;
1495
    this.doc = doc;
1496
    this.line = line;
1497
    this.maxLookAhead = lookAhead || 0;
1498
    this.baseTokens = null;
1499
    this.baseTokenPos = 1;
1500
  };
1501
 
1502
  Context.prototype.lookAhead = function (n) {
1503
    var line = this.doc.getLine(this.line + n);
1504
    if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
1505
    return line
1506
  };
1507
 
1508
  Context.prototype.baseToken = function (n) {
1509
    if (!this.baseTokens) { return null }
1510
    while (this.baseTokens[this.baseTokenPos] <= n)
1511
      { this.baseTokenPos += 2; }
1512
    var type = this.baseTokens[this.baseTokenPos + 1];
1513
    return {type: type && type.replace(/( |^)overlay .*/, ""),
1514
            size: this.baseTokens[this.baseTokenPos] - n}
1515
  };
1516
 
1517
  Context.prototype.nextLine = function () {
1518
    this.line++;
1519
    if (this.maxLookAhead > 0) { this.maxLookAhead--; }
1520
  };
1521
 
1522
  Context.fromSaved = function (doc, saved, line) {
1523
    if (saved instanceof SavedContext)
1524
      { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
1525
    else
1526
      { return new Context(doc, copyState(doc.mode, saved), line) }
1527
  };
1528
 
1529
  Context.prototype.save = function (copy) {
1530
    var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
1531
    return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
1532
  };
1533
 
1534
 
1535
  // Compute a style array (an array starting with a mode generation
1536
  // -- for invalidation -- followed by pairs of end positions and
1537
  // style strings), which is used to highlight the tokens on the
1538
  // line.
1539
  function highlightLine(cm, line, context, forceToEnd) {
1540
    // A styles array always starts with a number identifying the
1541
    // mode/overlays that it is based on (for easy invalidation).
1542
    var st = [cm.state.modeGen], lineClasses = {};
1543
    // Compute the base array of styles
1544
    runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
1545
            lineClasses, forceToEnd);
1546
    var state = context.state;
1547
 
1548
    // Run overlays, adjust style array.
1549
    var loop = function ( o ) {
1550
      context.baseTokens = st;
1551
      var overlay = cm.state.overlays[o], i = 1, at = 0;
1552
      context.state = true;
1553
      runMode(cm, line.text, overlay.mode, context, function (end, style) {
1554
        var start = i;
1555
        // Ensure there's a token end at the current position, and that i points at it
1556
        while (at < end) {
1557
          var i_end = st[i];
1558
          if (i_end > end)
1559
            { st.splice(i, 1, end, st[i+1], i_end); }
1560
          i += 2;
1561
          at = Math.min(end, i_end);
1562
        }
1563
        if (!style) { return }
1564
        if (overlay.opaque) {
1565
          st.splice(start, i - start, end, "overlay " + style);
1566
          i = start + 2;
1567
        } else {
1568
          for (; start < i; start += 2) {
1569
            var cur = st[start+1];
1570
            st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
1571
          }
1572
        }
1573
      }, lineClasses);
1574
      context.state = state;
1575
      context.baseTokens = null;
1576
      context.baseTokenPos = 1;
1577
    };
1578
 
1579
    for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
1580
 
1581
    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
1582
  }
1583
 
1584
  function getLineStyles(cm, line, updateFrontier) {
1585
    if (!line.styles || line.styles[0] != cm.state.modeGen) {
1586
      var context = getContextBefore(cm, lineNo(line));
1587
      var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
1588
      var result = highlightLine(cm, line, context);
1589
      if (resetState) { context.state = resetState; }
1590
      line.stateAfter = context.save(!resetState);
1591
      line.styles = result.styles;
1592
      if (result.classes) { line.styleClasses = result.classes; }
1593
      else if (line.styleClasses) { line.styleClasses = null; }
1594
      if (updateFrontier === cm.doc.highlightFrontier)
1595
        { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
1596
    }
1597
    return line.styles
1598
  }
1599
 
1600
  function getContextBefore(cm, n, precise) {
1601
    var doc = cm.doc, display = cm.display;
1602
    if (!doc.mode.startState) { return new Context(doc, true, n) }
1603
    var start = findStartLine(cm, n, precise);
1604
    var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
1605
    var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
1606
 
1607
    doc.iter(start, n, function (line) {
1608
      processLine(cm, line.text, context);
1609
      var pos = context.line;
1610
      line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
1611
      context.nextLine();
1612
    });
1613
    if (precise) { doc.modeFrontier = context.line; }
1614
    return context
1615
  }
1616
 
1617
  // Lightweight form of highlight -- proceed over this line and
1618
  // update state, but don't save a style array. Used for lines that
1619
  // aren't currently visible.
1620
  function processLine(cm, text, context, startAt) {
1621
    var mode = cm.doc.mode;
1622
    var stream = new StringStream(text, cm.options.tabSize, context);
1623
    stream.start = stream.pos = startAt || 0;
1624
    if (text == "") { callBlankLine(mode, context.state); }
1625
    while (!stream.eol()) {
1626
      readToken(mode, stream, context.state);
1627
      stream.start = stream.pos;
1628
    }
1629
  }
1630
 
1631
  function callBlankLine(mode, state) {
1632
    if (mode.blankLine) { return mode.blankLine(state) }
1633
    if (!mode.innerMode) { return }
1634
    var inner = innerMode(mode, state);
1635
    if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
1636
  }
1637
 
1638
  function readToken(mode, stream, state, inner) {
1639
    for (var i = 0; i < 10; i++) {
1640
      if (inner) { inner[0] = innerMode(mode, state).mode; }
1641
      var style = mode.token(stream, state);
1642
      if (stream.pos > stream.start) { return style }
1643
    }
1644
    throw new Error("Mode " + mode.name + " failed to advance stream.")
1645
  }
1646
 
1647
  var Token = function(stream, type, state) {
1648
    this.start = stream.start; this.end = stream.pos;
1649
    this.string = stream.current();
1650
    this.type = type || null;
1651
    this.state = state;
1652
  };
1653
 
1654
  // Utility for getTokenAt and getLineTokens
1655
  function takeToken(cm, pos, precise, asArray) {
1656
    var doc = cm.doc, mode = doc.mode, style;
1657
    pos = clipPos(doc, pos);
1658
    var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
1659
    var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
1660
    if (asArray) { tokens = []; }
1661
    while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
1662
      stream.start = stream.pos;
1663
      style = readToken(mode, stream, context.state);
1664
      if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
1665
    }
1666
    return asArray ? tokens : new Token(stream, style, context.state)
1667
  }
1668
 
1669
  function extractLineClasses(type, output) {
1670
    if (type) { for (;;) {
1671
      var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
1672
      if (!lineClass) { break }
1673
      type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
1674
      var prop = lineClass[1] ? "bgClass" : "textClass";
1675
      if (output[prop] == null)
1676
        { output[prop] = lineClass[2]; }
1677
      else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
1678
        { output[prop] += " " + lineClass[2]; }
1679
    } }
1680
    return type
1681
  }
1682
 
1683
  // Run the given mode's parser over a line, calling f for each token.
1684
  function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
1685
    var flattenSpans = mode.flattenSpans;
1686
    if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
1687
    var curStart = 0, curStyle = null;
1688
    var stream = new StringStream(text, cm.options.tabSize, context), style;
1689
    var inner = cm.options.addModeClass && [null];
1690
    if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
1691
    while (!stream.eol()) {
1692
      if (stream.pos > cm.options.maxHighlightLength) {
1693
        flattenSpans = false;
1694
        if (forceToEnd) { processLine(cm, text, context, stream.pos); }
1695
        stream.pos = text.length;
1696
        style = null;
1697
      } else {
1698
        style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
1699
      }
1700
      if (inner) {
1701
        var mName = inner[0].name;
1702
        if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
1703
      }
1704
      if (!flattenSpans || curStyle != style) {
1705
        while (curStart < stream.start) {
1706
          curStart = Math.min(stream.start, curStart + 5000);
1707
          f(curStart, curStyle);
1708
        }
1709
        curStyle = style;
1710
      }
1711
      stream.start = stream.pos;
1712
    }
1713
    while (curStart < stream.pos) {
1714
      // Webkit seems to refuse to render text nodes longer than 57444
1715
      // characters, and returns inaccurate measurements in nodes
1716
      // starting around 5000 chars.
1717
      var pos = Math.min(stream.pos, curStart + 5000);
1718
      f(pos, curStyle);
1719
      curStart = pos;
1720
    }
1721
  }
1722
 
1723
  // Finds the line to start with when starting a parse. Tries to
1724
  // find a line with a stateAfter, so that it can start with a
1725
  // valid state. If that fails, it returns the line with the
1726
  // smallest indentation, which tends to need the least context to
1727
  // parse correctly.
1728
  function findStartLine(cm, n, precise) {
1729
    var minindent, minline, doc = cm.doc;
1730
    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
1731
    for (var search = n; search > lim; --search) {
1732
      if (search <= doc.first) { return doc.first }
1733
      var line = getLine(doc, search - 1), after = line.stateAfter;
1734
      if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
1735
        { return search }
1736
      var indented = countColumn(line.text, null, cm.options.tabSize);
1737
      if (minline == null || minindent > indented) {
1738
        minline = search - 1;
1739
        minindent = indented;
1740
      }
1741
    }
1742
    return minline
1743
  }
1744
 
1745
  function retreatFrontier(doc, n) {
1746
    doc.modeFrontier = Math.min(doc.modeFrontier, n);
1747
    if (doc.highlightFrontier < n - 10) { return }
1748
    var start = doc.first;
1749
    for (var line = n - 1; line > start; line--) {
1750
      var saved = getLine(doc, line).stateAfter;
1751
      // change is on 3
1752
      // state on line 1 looked ahead 2 -- so saw 3
1753
      // test 1 + 2 < 3 should cover this
1754
      if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
1755
        start = line + 1;
1756
        break
1757
      }
1758
    }
1759
    doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
1760
  }
1761
 
1762
  // LINE DATA STRUCTURE
1763
 
1764
  // Line objects. These hold state related to a line, including
1765
  // highlighting info (the styles array).
1766
  var Line = function(text, markedSpans, estimateHeight) {
1767
    this.text = text;
1768
    attachMarkedSpans(this, markedSpans);
1769
    this.height = estimateHeight ? estimateHeight(this) : 1;
1770
  };
1771
 
1772
  Line.prototype.lineNo = function () { return lineNo(this) };
1773
  eventMixin(Line);
1774
 
1775
  // Change the content (text, markers) of a line. Automatically
1776
  // invalidates cached information and tries to re-estimate the
1777
  // line's height.
1778
  function updateLine(line, text, markedSpans, estimateHeight) {
1779
    line.text = text;
1780
    if (line.stateAfter) { line.stateAfter = null; }
1781
    if (line.styles) { line.styles = null; }
1782
    if (line.order != null) { line.order = null; }
1783
    detachMarkedSpans(line);
1784
    attachMarkedSpans(line, markedSpans);
1785
    var estHeight = estimateHeight ? estimateHeight(line) : 1;
1786
    if (estHeight != line.height) { updateLineHeight(line, estHeight); }
1787
  }
1788
 
1789
  // Detach a line from the document tree and its markers.
1790
  function cleanUpLine(line) {
1791
    line.parent = null;
1792
    detachMarkedSpans(line);
1793
  }
1794
 
1795
  // Convert a style as returned by a mode (either null, or a string
1796
  // containing one or more styles) to a CSS style. This is cached,
1797
  // and also looks for line-wide styles.
1798
  var styleToClassCache = {}, styleToClassCacheWithMode = {};
1799
  function interpretTokenStyle(style, options) {
1800
    if (!style || /^\s*$/.test(style)) { return null }
1801
    var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
1802
    return cache[style] ||
1803
      (cache[style] = style.replace(/\S+/g, "cm-$&"))
1804
  }
1805
 
1806
  // Render the DOM representation of the text of a line. Also builds
1807
  // up a 'line map', which points at the DOM nodes that represent
1808
  // specific stretches of text, and is used by the measuring code.
1809
  // The returned object contains the DOM node, this map, and
1810
  // information about line-wide styles that were set by the mode.
1811
  function buildLineContent(cm, lineView) {
1812
    // The padding-right forces the element to have a 'border', which
1813
    // is needed on Webkit to be able to get line-level bounding
1814
    // rectangles for it (in measureChar).
1815
    var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
1816
    var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
1817
                   col: 0, pos: 0, cm: cm,
1818
                   trailingSpace: false,
1819
                   splitSpaces: cm.getOption("lineWrapping")};
1820
    lineView.measure = {};
1821
 
1822
    // Iterate over the logical lines that make up this visual line.
1823
    for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
1824
      var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
1825
      builder.pos = 0;
1826
      builder.addToken = buildToken;
1827
      // Optionally wire in some hacks into the token-rendering
1828
      // algorithm, to deal with browser quirks.
1829
      if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
1830
        { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
1831
      builder.map = [];
1832
      var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
1833
      insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
1834
      if (line.styleClasses) {
1835
        if (line.styleClasses.bgClass)
1836
          { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
1837
        if (line.styleClasses.textClass)
1838
          { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
1839
      }
1840
 
1841
      // Ensure at least a single node is present, for measuring.
1842
      if (builder.map.length == 0)
1843
        { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
1844
 
1845
      // Store the map and a cache object for the current logical line
1846
      if (i == 0) {
1847
        lineView.measure.map = builder.map;
1848
        lineView.measure.cache = {};
1849
      } else {
1850
  (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
1851
        ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
1852
      }
1853
    }
1854
 
1855
    // See issue #2901
1856
    if (webkit) {
1857
      var last = builder.content.lastChild;
1858
      if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
1859
        { builder.content.className = "cm-tab-wrap-hack"; }
1860
    }
1861
 
1862
    signal(cm, "renderLine", cm, lineView.line, builder.pre);
1863
    if (builder.pre.className)
1864
      { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
1865
 
1866
    return builder
1867
  }
1868
 
1869
  function defaultSpecialCharPlaceholder(ch) {
1870
    var token = elt("span", "\u2022", "cm-invalidchar");
1871
    token.title = "\\u" + ch.charCodeAt(0).toString(16);
1872
    token.setAttribute("aria-label", token.title);
1873
    return token
1874
  }
1875
 
1876
  // Build up the DOM representation for a single token, and add it to
1877
  // the line map. Takes care to render special characters separately.
1878
  function buildToken(builder, text, style, startStyle, endStyle, title, css) {
1879
    if (!text) { return }
1880
    var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
1881
    var special = builder.cm.state.specialChars, mustWrap = false;
1882
    var content;
1883
    if (!special.test(text)) {
1884
      builder.col += text.length;
1885
      content = document.createTextNode(displayText);
1886
      builder.map.push(builder.pos, builder.pos + text.length, content);
1887
      if (ie && ie_version < 9) { mustWrap = true; }
1888
      builder.pos += text.length;
1889
    } else {
1890
      content = document.createDocumentFragment();
1891
      var pos = 0;
1892
      while (true) {
1893
        special.lastIndex = pos;
1894
        var m = special.exec(text);
1895
        var skipped = m ? m.index - pos : text.length - pos;
1896
        if (skipped) {
1897
          var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
1898
          if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
1899
          else { content.appendChild(txt); }
1900
          builder.map.push(builder.pos, builder.pos + skipped, txt);
1901
          builder.col += skipped;
1902
          builder.pos += skipped;
1903
        }
1904
        if (!m) { break }
1905
        pos += skipped + 1;
1906
        var txt$1 = (void 0);
1907
        if (m[0] == "\t") {
1908
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
1909
          txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
1910
          txt$1.setAttribute("role", "presentation");
1911
          txt$1.setAttribute("cm-text", "\t");
1912
          builder.col += tabWidth;
1913
        } else if (m[0] == "\r" || m[0] == "\n") {
1914
          txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
1915
          txt$1.setAttribute("cm-text", m[0]);
1916
          builder.col += 1;
1917
        } else {
1918
          txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
1919
          txt$1.setAttribute("cm-text", m[0]);
1920
          if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
1921
          else { content.appendChild(txt$1); }
1922
          builder.col += 1;
1923
        }
1924
        builder.map.push(builder.pos, builder.pos + 1, txt$1);
1925
        builder.pos++;
1926
      }
1927
    }
1928
    builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
1929
    if (style || startStyle || endStyle || mustWrap || css) {
1930
      var fullStyle = style || "";
1931
      if (startStyle) { fullStyle += startStyle; }
1932
      if (endStyle) { fullStyle += endStyle; }
1933
      var token = elt("span", [content], fullStyle, css);
1934
      if (title) { token.title = title; }
1935
      return builder.content.appendChild(token)
1936
    }
1937
    builder.content.appendChild(content);
1938
  }
1939
 
1940
  // Change some spaces to NBSP to prevent the browser from collapsing
1941
  // trailing spaces at the end of a line when rendering text (issue #1362).
1942
  function splitSpaces(text, trailingBefore) {
1943
    if (text.length > 1 && !/  /.test(text)) { return text }
1944
    var spaceBefore = trailingBefore, result = "";
1945
    for (var i = 0; i < text.length; i++) {
1946
      var ch = text.charAt(i);
1947
      if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
1948
        { ch = "\u00a0"; }
1949
      result += ch;
1950
      spaceBefore = ch == " ";
1951
    }
1952
    return result
1953
  }
1954
 
1955
  // Work around nonsense dimensions being reported for stretches of
1956
  // right-to-left text.
1957
  function buildTokenBadBidi(inner, order) {
1958
    return function (builder, text, style, startStyle, endStyle, title, css) {
1959
      style = style ? style + " cm-force-border" : "cm-force-border";
1960
      var start = builder.pos, end = start + text.length;
1961
      for (;;) {
1962
        // Find the part that overlaps with the start of this text
1963
        var part = (void 0);
1964
        for (var i = 0; i < order.length; i++) {
1965
          part = order[i];
1966
          if (part.to > start && part.from <= start) { break }
1967
        }
1968
        if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
1969
        inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
1970
        startStyle = null;
1971
        text = text.slice(part.to - start);
1972
        start = part.to;
1973
      }
1974
    }
1975
  }
1976
 
1977
  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
1978
    var widget = !ignoreWidget && marker.widgetNode;
1979
    if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
1980
    if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
1981
      if (!widget)
1982
        { widget = builder.content.appendChild(document.createElement("span")); }
1983
      widget.setAttribute("cm-marker", marker.id);
1984
    }
1985
    if (widget) {
1986
      builder.cm.display.input.setUneditable(widget);
1987
      builder.content.appendChild(widget);
1988
    }
1989
    builder.pos += size;
1990
    builder.trailingSpace = false;
1991
  }
1992
 
1993
  // Outputs a number of spans to make up a line, taking highlighting
1994
  // and marked text into account.
1995
  function insertLineContent(line, builder, styles) {
1996
    var spans = line.markedSpans, allText = line.text, at = 0;
1997
    if (!spans) {
1998
      for (var i$1 = 1; i$1 < styles.length; i$1+=2)
1999
        { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
2000
      return
2001
    }
2002
 
2003
    var len = allText.length, pos = 0, i = 1, text = "", style, css;
2004
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
2005
    for (;;) {
2006
      if (nextChange == pos) { // Update current marker set
2007
        spanStyle = spanEndStyle = spanStartStyle = title = css = "";
2008
        collapsed = null; nextChange = Infinity;
2009
        var foundBookmarks = [], endStyles = (void 0);
2010
        for (var j = 0; j < spans.length; ++j) {
2011
          var sp = spans[j], m = sp.marker;
2012
          if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
2013
            foundBookmarks.push(m);
2014
          } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
2015
            if (sp.to != null && sp.to != pos && nextChange > sp.to) {
2016
              nextChange = sp.to;
2017
              spanEndStyle = "";
2018
            }
2019
            if (m.className) { spanStyle += " " + m.className; }
2020
            if (m.css) { css = (css ? css + ";" : "") + m.css; }
2021
            if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
2022
            if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
2023
            if (m.title && !title) { title = m.title; }
2024
            if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
2025
              { collapsed = sp; }
2026
          } else if (sp.from > pos && nextChange > sp.from) {
2027
            nextChange = sp.from;
2028
          }
2029
        }
2030
        if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
2031
          { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
2032
 
2033
        if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
2034
          { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
2035
        if (collapsed && (collapsed.from || 0) == pos) {
2036
          buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
2037
                             collapsed.marker, collapsed.from == null);
2038
          if (collapsed.to == null) { return }
2039
          if (collapsed.to == pos) { collapsed = false; }
2040
        }
2041
      }
2042
      if (pos >= len) { break }
2043
 
2044
      var upto = Math.min(len, nextChange);
2045
      while (true) {
2046
        if (text) {
2047
          var end = pos + text.length;
2048
          if (!collapsed) {
2049
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
2050
            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
2051
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
2052
          }
2053
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
2054
          pos = end;
2055
          spanStartStyle = "";
2056
        }
2057
        text = allText.slice(at, at = styles[i++]);
2058
        style = interpretTokenStyle(styles[i++], builder.cm.options);
2059
      }
2060
    }
2061
  }
2062
 
2063
 
2064
  // These objects are used to represent the visible (currently drawn)
2065
  // part of the document. A LineView may correspond to multiple
2066
  // logical lines, if those are connected by collapsed ranges.
2067
  function LineView(doc, line, lineN) {
2068
    // The starting line
2069
    this.line = line;
2070
    // Continuing lines, if any
2071
    this.rest = visualLineContinued(line);
2072
    // Number of logical lines in this visual line
2073
    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
2074
    this.node = this.text = null;
2075
    this.hidden = lineIsHidden(doc, line);
2076
  }
2077
 
2078
  // Create a range of LineView objects for the given lines.
2079
  function buildViewArray(cm, from, to) {
2080
    var array = [], nextPos;
2081
    for (var pos = from; pos < to; pos = nextPos) {
2082
      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
2083
      nextPos = pos + view.size;
2084
      array.push(view);
2085
    }
2086
    return array
2087
  }
2088
 
2089
  var operationGroup = null;
2090
 
2091
  function pushOperation(op) {
2092
    if (operationGroup) {
2093
      operationGroup.ops.push(op);
2094
    } else {
2095
      op.ownsGroup = operationGroup = {
2096
        ops: [op],
2097
        delayedCallbacks: []
2098
      };
2099
    }
2100
  }
2101
 
2102
  function fireCallbacksForOps(group) {
2103
    // Calls delayed callbacks and cursorActivity handlers until no
2104
    // new ones appear
2105
    var callbacks = group.delayedCallbacks, i = 0;
2106
    do {
2107
      for (; i < callbacks.length; i++)
2108
        { callbacks[i].call(null); }
2109
      for (var j = 0; j < group.ops.length; j++) {
2110
        var op = group.ops[j];
2111
        if (op.cursorActivityHandlers)
2112
          { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
2113
            { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
2114
      }
2115
    } while (i < callbacks.length)
2116
  }
2117
 
2118
  function finishOperation(op, endCb) {
2119
    var group = op.ownsGroup;
2120
    if (!group) { return }
2121
 
2122
    try { fireCallbacksForOps(group); }
2123
    finally {
2124
      operationGroup = null;
2125
      endCb(group);
2126
    }
2127
  }
2128
 
2129
  var orphanDelayedCallbacks = null;
2130
 
2131
  // Often, we want to signal events at a point where we are in the
2132
  // middle of some work, but don't want the handler to start calling
2133
  // other methods on the editor, which might be in an inconsistent
2134
  // state or simply not expect any other events to happen.
2135
  // signalLater looks whether there are any handlers, and schedules
2136
  // them to be executed when the last operation ends, or, if no
2137
  // operation is active, when a timeout fires.
2138
  function signalLater(emitter, type /*, values...*/) {
2139
    var arr = getHandlers(emitter, type);
2140
    if (!arr.length) { return }
2141
    var args = Array.prototype.slice.call(arguments, 2), list;
2142
    if (operationGroup) {
2143
      list = operationGroup.delayedCallbacks;
2144
    } else if (orphanDelayedCallbacks) {
2145
      list = orphanDelayedCallbacks;
2146
    } else {
2147
      list = orphanDelayedCallbacks = [];
2148
      setTimeout(fireOrphanDelayed, 0);
2149
    }
2150
    var loop = function ( i ) {
2151
      list.push(function () { return arr[i].apply(null, args); });
2152
    };
2153
 
2154
    for (var i = 0; i < arr.length; ++i)
2155
      loop( i );
2156
  }
2157
 
2158
  function fireOrphanDelayed() {
2159
    var delayed = orphanDelayedCallbacks;
2160
    orphanDelayedCallbacks = null;
2161
    for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
2162
  }
2163
 
2164
  // When an aspect of a line changes, a string is added to
2165
  // lineView.changes. This updates the relevant part of the line's
2166
  // DOM structure.
2167
  function updateLineForChanges(cm, lineView, lineN, dims) {
2168
    for (var j = 0; j < lineView.changes.length; j++) {
2169
      var type = lineView.changes[j];
2170
      if (type == "text") { updateLineText(cm, lineView); }
2171
      else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
2172
      else if (type == "class") { updateLineClasses(cm, lineView); }
2173
      else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
2174
    }
2175
    lineView.changes = null;
2176
  }
2177
 
2178
  // Lines with gutter elements, widgets or a background class need to
2179
  // be wrapped, and have the extra elements added to the wrapper div
2180
  function ensureLineWrapped(lineView) {
2181
    if (lineView.node == lineView.text) {
2182
      lineView.node = elt("div", null, null, "position: relative");
2183
      if (lineView.text.parentNode)
2184
        { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
2185
      lineView.node.appendChild(lineView.text);
2186
      if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
2187
    }
2188
    return lineView.node
2189
  }
2190
 
2191
  function updateLineBackground(cm, lineView) {
2192
    var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
2193
    if (cls) { cls += " CodeMirror-linebackground"; }
2194
    if (lineView.background) {
2195
      if (cls) { lineView.background.className = cls; }
2196
      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
2197
    } else if (cls) {
2198
      var wrap = ensureLineWrapped(lineView);
2199
      lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
2200
      cm.display.input.setUneditable(lineView.background);
2201
    }
2202
  }
2203
 
2204
  // Wrapper around buildLineContent which will reuse the structure
2205
  // in display.externalMeasured when possible.
2206
  function getLineContent(cm, lineView) {
2207
    var ext = cm.display.externalMeasured;
2208
    if (ext && ext.line == lineView.line) {
2209
      cm.display.externalMeasured = null;
2210
      lineView.measure = ext.measure;
2211
      return ext.built
2212
    }
2213
    return buildLineContent(cm, lineView)
2214
  }
2215
 
2216
  // Redraw the line's text. Interacts with the background and text
2217
  // classes because the mode may output tokens that influence these
2218
  // classes.
2219
  function updateLineText(cm, lineView) {
2220
    var cls = lineView.text.className;
2221
    var built = getLineContent(cm, lineView);
2222
    if (lineView.text == lineView.node) { lineView.node = built.pre; }
2223
    lineView.text.parentNode.replaceChild(built.pre, lineView.text);
2224
    lineView.text = built.pre;
2225
    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
2226
      lineView.bgClass = built.bgClass;
2227
      lineView.textClass = built.textClass;
2228
      updateLineClasses(cm, lineView);
2229
    } else if (cls) {
2230
      lineView.text.className = cls;
2231
    }
2232
  }
2233
 
2234
  function updateLineClasses(cm, lineView) {
2235
    updateLineBackground(cm, lineView);
2236
    if (lineView.line.wrapClass)
2237
      { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
2238
    else if (lineView.node != lineView.text)
2239
      { lineView.node.className = ""; }
2240
    var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
2241
    lineView.text.className = textClass || "";
2242
  }
2243
 
2244
  function updateLineGutter(cm, lineView, lineN, dims) {
2245
    if (lineView.gutter) {
2246
      lineView.node.removeChild(lineView.gutter);
2247
      lineView.gutter = null;
2248
    }
2249
    if (lineView.gutterBackground) {
2250
      lineView.node.removeChild(lineView.gutterBackground);
2251
      lineView.gutterBackground = null;
2252
    }
2253
    if (lineView.line.gutterClass) {
2254
      var wrap = ensureLineWrapped(lineView);
2255
      lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
2256
                                      ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
2257
      cm.display.input.setUneditable(lineView.gutterBackground);
2258
      wrap.insertBefore(lineView.gutterBackground, lineView.text);
2259
    }
2260
    var markers = lineView.line.gutterMarkers;
2261
    if (cm.options.lineNumbers || markers) {
2262
      var wrap$1 = ensureLineWrapped(lineView);
2263
      var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
2264
      cm.display.input.setUneditable(gutterWrap);
2265
      wrap$1.insertBefore(gutterWrap, lineView.text);
2266
      if (lineView.line.gutterClass)
2267
        { gutterWrap.className += " " + lineView.line.gutterClass; }
2268
      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
2269
        { lineView.lineNumber = gutterWrap.appendChild(
2270
          elt("div", lineNumberFor(cm.options, lineN),
2271
              "CodeMirror-linenumber CodeMirror-gutter-elt",
2272
              ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
2273
      if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
2274
        var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
2275
        if (found)
2276
          { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
2277
                                     ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
2278
      } }
2279
    }
2280
  }
2281
 
2282
  function updateLineWidgets(cm, lineView, dims) {
2283
    if (lineView.alignable) { lineView.alignable = null; }
2284
    for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
2285
      next = node.nextSibling;
2286
      if (node.className == "CodeMirror-linewidget")
2287
        { lineView.node.removeChild(node); }
2288
    }
2289
    insertLineWidgets(cm, lineView, dims);
2290
  }
2291
 
2292
  // Build a line's DOM representation from scratch
2293
  function buildLineElement(cm, lineView, lineN, dims) {
2294
    var built = getLineContent(cm, lineView);
2295
    lineView.text = lineView.node = built.pre;
2296
    if (built.bgClass) { lineView.bgClass = built.bgClass; }
2297
    if (built.textClass) { lineView.textClass = built.textClass; }
2298
 
2299
    updateLineClasses(cm, lineView);
2300
    updateLineGutter(cm, lineView, lineN, dims);
2301
    insertLineWidgets(cm, lineView, dims);
2302
    return lineView.node
2303
  }
2304
 
2305
  // A lineView may contain multiple logical lines (when merged by
2306
  // collapsed spans). The widgets for all of them need to be drawn.
2307
  function insertLineWidgets(cm, lineView, dims) {
2308
    insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
2309
    if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2310
      { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
2311
  }
2312
 
2313
  function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
2314
    if (!line.widgets) { return }
2315
    var wrap = ensureLineWrapped(lineView);
2316
    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
2317
      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
2318
      if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
2319
      positionLineWidget(widget, node, lineView, dims);
2320
      cm.display.input.setUneditable(node);
2321
      if (allowAbove && widget.above)
2322
        { wrap.insertBefore(node, lineView.gutter || lineView.text); }
2323
      else
2324
        { wrap.appendChild(node); }
2325
      signalLater(widget, "redraw");
2326
    }
2327
  }
2328
 
2329
  function positionLineWidget(widget, node, lineView, dims) {
2330
    if (widget.noHScroll) {
2331
  (lineView.alignable || (lineView.alignable = [])).push(node);
2332
      var width = dims.wrapperWidth;
2333
      node.style.left = dims.fixedPos + "px";
2334
      if (!widget.coverGutter) {
2335
        width -= dims.gutterTotalWidth;
2336
        node.style.paddingLeft = dims.gutterTotalWidth + "px";
2337
      }
2338
      node.style.width = width + "px";
2339
    }
2340
    if (widget.coverGutter) {
2341
      node.style.zIndex = 5;
2342
      node.style.position = "relative";
2343
      if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
2344
    }
2345
  }
2346
 
2347
  function widgetHeight(widget) {
2348
    if (widget.height != null) { return widget.height }
2349
    var cm = widget.doc.cm;
2350
    if (!cm) { return 0 }
2351
    if (!contains(document.body, widget.node)) {
2352
      var parentStyle = "position: relative;";
2353
      if (widget.coverGutter)
2354
        { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
2355
      if (widget.noHScroll)
2356
        { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
2357
      removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
2358
    }
2359
    return widget.height = widget.node.parentNode.offsetHeight
2360
  }
2361
 
2362
  // Return true when the given mouse event happened in a widget
2363
  function eventInWidget(display, e) {
2364
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
2365
      if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
2366
          (n.parentNode == display.sizer && n != display.mover))
2367
        { return true }
2368
    }
2369
  }
2370
 
2371
  // POSITION MEASUREMENT
2372
 
2373
  function paddingTop(display) {return display.lineSpace.offsetTop}
2374
  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
2375
  function paddingH(display) {
2376
    if (display.cachedPaddingH) { return display.cachedPaddingH }
2377
    var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2378
    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2379
    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2380
    if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
2381
    return data
2382
  }
2383
 
2384
  function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
2385
  function displayWidth(cm) {
2386
    return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
2387
  }
2388
  function displayHeight(cm) {
2389
    return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
2390
  }
2391
 
2392
  // Ensure the lineView.wrapping.heights array is populated. This is
2393
  // an array of bottom offsets for the lines that make up a drawn
2394
  // line. When lineWrapping is on, there might be more than one
2395
  // height.
2396
  function ensureLineHeights(cm, lineView, rect) {
2397
    var wrapping = cm.options.lineWrapping;
2398
    var curWidth = wrapping && displayWidth(cm);
2399
    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2400
      var heights = lineView.measure.heights = [];
2401
      if (wrapping) {
2402
        lineView.measure.width = curWidth;
2403
        var rects = lineView.text.firstChild.getClientRects();
2404
        for (var i = 0; i < rects.length - 1; i++) {
2405
          var cur = rects[i], next = rects[i + 1];
2406
          if (Math.abs(cur.bottom - next.bottom) > 2)
2407
            { heights.push((cur.bottom + next.top) / 2 - rect.top); }
2408
        }
2409
      }
2410
      heights.push(rect.bottom - rect.top);
2411
    }
2412
  }
2413
 
2414
  // Find a line map (mapping character offsets to text nodes) and a
2415
  // measurement cache for the given line number. (A line view might
2416
  // contain multiple lines when collapsed ranges are present.)
2417
  function mapFromLineView(lineView, line, lineN) {
2418
    if (lineView.line == line)
2419
      { return {map: lineView.measure.map, cache: lineView.measure.cache} }
2420
    for (var i = 0; i < lineView.rest.length; i++)
2421
      { if (lineView.rest[i] == line)
2422
        { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
2423
    for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
2424
      { if (lineNo(lineView.rest[i$1]) > lineN)
2425
        { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
2426
  }
2427
 
2428
  // Render a line into the hidden node display.externalMeasured. Used
2429
  // when measurement is needed for a line that's not in the viewport.
2430
  function updateExternalMeasurement(cm, line) {
2431
    line = visualLine(line);
2432
    var lineN = lineNo(line);
2433
    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2434
    view.lineN = lineN;
2435
    var built = view.built = buildLineContent(cm, view);
2436
    view.text = built.pre;
2437
    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2438
    return view
2439
  }
2440
 
2441
  // Get a {top, bottom, left, right} box (in line-local coordinates)
2442
  // for a given character.
2443
  function measureChar(cm, line, ch, bias) {
2444
    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
2445
  }
2446
 
2447
  // Find a line view that corresponds to the given line number.
2448
  function findViewForLine(cm, lineN) {
2449
    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2450
      { return cm.display.view[findViewIndex(cm, lineN)] }
2451
    var ext = cm.display.externalMeasured;
2452
    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2453
      { return ext }
2454
  }
2455
 
2456
  // Measurement can be split in two steps, the set-up work that
2457
  // applies to the whole line, and the measurement of the actual
2458
  // character. Functions like coordsChar, that need to do a lot of
2459
  // measurements in a row, can thus ensure that the set-up work is
2460
  // only done once.
2461
  function prepareMeasureForLine(cm, line) {
2462
    var lineN = lineNo(line);
2463
    var view = findViewForLine(cm, lineN);
2464
    if (view && !view.text) {
2465
      view = null;
2466
    } else if (view && view.changes) {
2467
      updateLineForChanges(cm, view, lineN, getDimensions(cm));
2468
      cm.curOp.forceUpdate = true;
2469
    }
2470
    if (!view)
2471
      { view = updateExternalMeasurement(cm, line); }
2472
 
2473
    var info = mapFromLineView(view, line, lineN);
2474
    return {
2475
      line: line, view: view, rect: null,
2476
      map: info.map, cache: info.cache, before: info.before,
2477
      hasHeights: false
2478
    }
2479
  }
2480
 
2481
  // Given a prepared measurement object, measures the position of an
2482
  // actual character (or fetches it from the cache).
2483
  function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2484
    if (prepared.before) { ch = -1; }
2485
    var key = ch + (bias || ""), found;
2486
    if (prepared.cache.hasOwnProperty(key)) {
2487
      found = prepared.cache[key];
2488
    } else {
2489
      if (!prepared.rect)
2490
        { prepared.rect = prepared.view.text.getBoundingClientRect(); }
2491
      if (!prepared.hasHeights) {
2492
        ensureLineHeights(cm, prepared.view, prepared.rect);
2493
        prepared.hasHeights = true;
2494
      }
2495
      found = measureCharInner(cm, prepared, ch, bias);
2496
      if (!found.bogus) { prepared.cache[key] = found; }
2497
    }
2498
    return {left: found.left, right: found.right,
2499
            top: varHeight ? found.rtop : found.top,
2500
            bottom: varHeight ? found.rbottom : found.bottom}
2501
  }
2502
 
2503
  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2504
 
2505
  function nodeAndOffsetInLineMap(map$$1, ch, bias) {
2506
    var node, start, end, collapse, mStart, mEnd;
2507
    // First, search the line map for the text node corresponding to,
2508
    // or closest to, the target character.
2509
    for (var i = 0; i < map$$1.length; i += 3) {
2510
      mStart = map$$1[i];
2511
      mEnd = map$$1[i + 1];
2512
      if (ch < mStart) {
2513
        start = 0; end = 1;
2514
        collapse = "left";
2515
      } else if (ch < mEnd) {
2516
        start = ch - mStart;
2517
        end = start + 1;
2518
      } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
2519
        end = mEnd - mStart;
2520
        start = end - 1;
2521
        if (ch >= mEnd) { collapse = "right"; }
2522
      }
2523
      if (start != null) {
2524
        node = map$$1[i + 2];
2525
        if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2526
          { collapse = bias; }
2527
        if (bias == "left" && start == 0)
2528
          { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
2529
            node = map$$1[(i -= 3) + 2];
2530
            collapse = "left";
2531
          } }
2532
        if (bias == "right" && start == mEnd - mStart)
2533
          { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
2534
            node = map$$1[(i += 3) + 2];
2535
            collapse = "right";
2536
          } }
2537
        break
2538
      }
2539
    }
2540
    return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
2541
  }
2542
 
2543
  function getUsefulRect(rects, bias) {
2544
    var rect = nullRect;
2545
    if (bias == "left") { for (var i = 0; i < rects.length; i++) {
2546
      if ((rect = rects[i]).left != rect.right) { break }
2547
    } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
2548
      if ((rect = rects[i$1]).left != rect.right) { break }
2549
    } }
2550
    return rect
2551
  }
2552
 
2553
  function measureCharInner(cm, prepared, ch, bias) {
2554
    var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2555
    var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2556
 
2557
    var rect;
2558
    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2559
      for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2560
        while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
2561
        while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
2562
        if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
2563
          { rect = node.parentNode.getBoundingClientRect(); }
2564
        else
2565
          { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
2566
        if (rect.left || rect.right || start == 0) { break }
2567
        end = start;
2568
        start = start - 1;
2569
        collapse = "right";
2570
      }
2571
      if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
2572
    } else { // If it is a widget, simply get the box for the whole widget.
2573
      if (start > 0) { collapse = bias = "right"; }
2574
      var rects;
2575
      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2576
        { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
2577
      else
2578
        { rect = node.getBoundingClientRect(); }
2579
    }
2580
    if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2581
      var rSpan = node.parentNode.getClientRects()[0];
2582
      if (rSpan)
2583
        { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
2584
      else
2585
        { rect = nullRect; }
2586
    }
2587
 
2588
    var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2589
    var mid = (rtop + rbot) / 2;
2590
    var heights = prepared.view.measure.heights;
2591
    var i = 0;
2592
    for (; i < heights.length - 1; i++)
2593
      { if (mid < heights[i]) { break } }
2594
    var top = i ? heights[i - 1] : 0, bot = heights[i];
2595
    var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2596
                  right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2597
                  top: top, bottom: bot};
2598
    if (!rect.left && !rect.right) { result.bogus = true; }
2599
    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2600
 
2601
    return result
2602
  }
2603
 
2604
  // Work around problem with bounding client rects on ranges being
2605
  // returned incorrectly when zoomed on IE10 and below.
2606
  function maybeUpdateRectForZooming(measure, rect) {
2607
    if (!window.screen || screen.logicalXDPI == null ||
2608
        screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2609
      { return rect }
2610
    var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2611
    var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2612
    return {left: rect.left * scaleX, right: rect.right * scaleX,
2613
            top: rect.top * scaleY, bottom: rect.bottom * scaleY}
2614
  }
2615
 
2616
  function clearLineMeasurementCacheFor(lineView) {
2617
    if (lineView.measure) {
2618
      lineView.measure.cache = {};
2619
      lineView.measure.heights = null;
2620
      if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2621
        { lineView.measure.caches[i] = {}; } }
2622
    }
2623
  }
2624
 
2625
  function clearLineMeasurementCache(cm) {
2626
    cm.display.externalMeasure = null;
2627
    removeChildren(cm.display.lineMeasure);
2628
    for (var i = 0; i < cm.display.view.length; i++)
2629
      { clearLineMeasurementCacheFor(cm.display.view[i]); }
2630
  }
2631
 
2632
  function clearCaches(cm) {
2633
    clearLineMeasurementCache(cm);
2634
    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2635
    if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
2636
    cm.display.lineNumChars = null;
2637
  }
2638
 
2639
  function pageScrollX() {
2640
    // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
2641
    // which causes page_Offset and bounding client rects to use
2642
    // different reference viewports and invalidate our calculations.
2643
    if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
2644
    return window.pageXOffset || (document.documentElement || document.body).scrollLeft
2645
  }
2646
  function pageScrollY() {
2647
    if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
2648
    return window.pageYOffset || (document.documentElement || document.body).scrollTop
2649
  }
2650
 
2651
  function widgetTopHeight(lineObj) {
2652
    var height = 0;
2653
    if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
2654
      { height += widgetHeight(lineObj.widgets[i]); } } }
2655
    return height
2656
  }
2657
 
2658
  // Converts a {top, bottom, left, right} box from line-local
2659
  // coordinates into another coordinate system. Context may be one of
2660
  // "line", "div" (display.lineDiv), "local"./null (editor), "window",
2661
  // or "page".
2662
  function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
2663
    if (!includeWidgets) {
2664
      var height = widgetTopHeight(lineObj);
2665
      rect.top += height; rect.bottom += height;
2666
    }
2667
    if (context == "line") { return rect }
2668
    if (!context) { context = "local"; }
2669
    var yOff = heightAtLine(lineObj);
2670
    if (context == "local") { yOff += paddingTop(cm.display); }
2671
    else { yOff -= cm.display.viewOffset; }
2672
    if (context == "page" || context == "window") {
2673
      var lOff = cm.display.lineSpace.getBoundingClientRect();
2674
      yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2675
      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2676
      rect.left += xOff; rect.right += xOff;
2677
    }
2678
    rect.top += yOff; rect.bottom += yOff;
2679
    return rect
2680
  }
2681
 
2682
  // Coverts a box from "div" coords to another coordinate system.
2683
  // Context may be "window", "page", "div", or "local"./null.
2684
  function fromCoordSystem(cm, coords, context) {
2685
    if (context == "div") { return coords }
2686
    var left = coords.left, top = coords.top;
2687
    // First move into "page" coordinate system
2688
    if (context == "page") {
2689
      left -= pageScrollX();
2690
      top -= pageScrollY();
2691
    } else if (context == "local" || !context) {
2692
      var localBox = cm.display.sizer.getBoundingClientRect();
2693
      left += localBox.left;
2694
      top += localBox.top;
2695
    }
2696
 
2697
    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2698
    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
2699
  }
2700
 
2701
  function charCoords(cm, pos, context, lineObj, bias) {
2702
    if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
2703
    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
2704
  }
2705
 
2706
  // Returns a box for a given cursor position, which may have an
2707
  // 'other' property containing the position of the secondary cursor
2708
  // on a bidi boundary.
2709
  // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
2710
  // and after `char - 1` in writing order of `char - 1`
2711
  // A cursor Pos(line, char, "after") is on the same visual line as `char`
2712
  // and before `char` in writing order of `char`
2713
  // Examples (upper-case letters are RTL, lower-case are LTR):
2714
  //     Pos(0, 1, ...)
2715
  //     before   after
2716
  // ab     a|b     a|b
2717
  // aB     a|B     aB|
2718
  // Ab     |Ab     A|b
2719
  // AB     B|A     B|A
2720
  // Every position after the last character on a line is considered to stick
2721
  // to the last character on the line.
2722
  function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2723
    lineObj = lineObj || getLine(cm.doc, pos.line);
2724
    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2725
    function get(ch, right) {
2726
      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2727
      if (right) { m.left = m.right; } else { m.right = m.left; }
2728
      return intoCoordSystem(cm, lineObj, m, context)
2729
    }
2730
    var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
2731
    if (ch >= lineObj.text.length) {
2732
      ch = lineObj.text.length;
2733
      sticky = "before";
2734
    } else if (ch <= 0) {
2735
      ch = 0;
2736
      sticky = "after";
2737
    }
2738
    if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
2739
 
2740
    function getBidi(ch, partPos, invert) {
2741
      var part = order[partPos], right = part.level == 1;
2742
      return get(invert ? ch - 1 : ch, right != invert)
2743
    }
2744
    var partPos = getBidiPartAt(order, ch, sticky);
2745
    var other = bidiOther;
2746
    var val = getBidi(ch, partPos, sticky == "before");
2747
    if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
2748
    return val
2749
  }
2750
 
2751
  // Used to cheaply estimate the coordinates for a position. Used for
2752
  // intermediate scroll updates.
2753
  function estimateCoords(cm, pos) {
2754
    var left = 0;
2755
    pos = clipPos(cm.doc, pos);
2756
    if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
2757
    var lineObj = getLine(cm.doc, pos.line);
2758
    var top = heightAtLine(lineObj) + paddingTop(cm.display);
2759
    return {left: left, right: left, top: top, bottom: top + lineObj.height}
2760
  }
2761
 
2762
  // Positions returned by coordsChar contain some extra information.
2763
  // xRel is the relative x position of the input coordinates compared
2764
  // to the found position (so xRel > 0 means the coordinates are to
2765
  // the right of the character position, for example). When outside
2766
  // is true, that means the coordinates lie outside the line's
2767
  // vertical range.
2768
  function PosWithInfo(line, ch, sticky, outside, xRel) {
2769
    var pos = Pos(line, ch, sticky);
2770
    pos.xRel = xRel;
2771
    if (outside) { pos.outside = true; }
2772
    return pos
2773
  }
2774
 
2775
  // Compute the character position closest to the given coordinates.
2776
  // Input must be lineSpace-local ("div" coordinate system).
2777
  function coordsChar(cm, x, y) {
2778
    var doc = cm.doc;
2779
    y += cm.display.viewOffset;
2780
    if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
2781
    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2782
    if (lineN > last)
2783
      { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
2784
    if (x < 0) { x = 0; }
2785
 
2786
    var lineObj = getLine(doc, lineN);
2787
    for (;;) {
2788
      var found = coordsCharInner(cm, lineObj, lineN, x, y);
2789
      var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));
2790
      if (!collapsed) { return found }
2791
      var rangeEnd = collapsed.find(1);
2792
      if (rangeEnd.line == lineN) { return rangeEnd }
2793
      lineObj = getLine(doc, lineN = rangeEnd.line);
2794
    }
2795
  }
2796
 
2797
  function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
2798
    y -= widgetTopHeight(lineObj);
2799
    var end = lineObj.text.length;
2800
    var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
2801
    end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
2802
    return {begin: begin, end: end}
2803
  }
2804
 
2805
  function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
2806
    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2807
    var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
2808
    return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
2809
  }
2810
 
2811
  // Returns true if the given side of a box is after the given
2812
  // coordinates, in top-to-bottom, left-to-right order.
2813
  function boxIsAfter(box, x, y, left) {
2814
    return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
2815
  }
2816
 
2817
  function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
2818
    // Move y into line-local coordinate space
2819
    y -= heightAtLine(lineObj);
2820
    var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2821
    // When directly calling `measureCharPrepared`, we have to adjust
2822
    // for the widgets at this line.
2823
    var widgetHeight$$1 = widgetTopHeight(lineObj);
2824
    var begin = 0, end = lineObj.text.length, ltr = true;
2825
 
2826
    var order = getOrder(lineObj, cm.doc.direction);
2827
    // If the line isn't plain left-to-right text, first figure out
2828
    // which bidi section the coordinates fall into.
2829
    if (order) {
2830
      var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
2831
                   (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
2832
      ltr = part.level != 1;
2833
      // The awkward -1 offsets are needed because findFirst (called
2834
      // on these below) will treat its first bound as inclusive,
2835
      // second as exclusive, but we want to actually address the
2836
      // characters in the part's range
2837
      begin = ltr ? part.from : part.to - 1;
2838
      end = ltr ? part.to : part.from - 1;
2839
    }
2840
 
2841
    // A binary search to find the first character whose bounding box
2842
    // starts after the coordinates. If we run across any whose box wrap
2843
    // the coordinates, store that.
2844
    var chAround = null, boxAround = null;
2845
    var ch = findFirst(function (ch) {
2846
      var box = measureCharPrepared(cm, preparedMeasure, ch);
2847
      box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
2848
      if (!boxIsAfter(box, x, y, false)) { return false }
2849
      if (box.top <= y && box.left <= x) {
2850
        chAround = ch;
2851
        boxAround = box;
2852
      }
2853
      return true
2854
    }, begin, end);
2855
 
2856
    var baseX, sticky, outside = false;
2857
    // If a box around the coordinates was found, use that
2858
    if (boxAround) {
2859
      // Distinguish coordinates nearer to the left or right side of the box
2860
      var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
2861
      ch = chAround + (atStart ? 0 : 1);
2862
      sticky = atStart ? "after" : "before";
2863
      baseX = atLeft ? boxAround.left : boxAround.right;
2864
    } else {
2865
      // (Adjust for extended bound, if necessary.)
2866
      if (!ltr && (ch == end || ch == begin)) { ch++; }
2867
      // To determine which side to associate with, get the box to the
2868
      // left of the character and compare it's vertical position to the
2869
      // coordinates
2870
      sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
2871
        (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
2872
        "after" : "before";
2873
      // Now get accurate coordinates for this place, in order to get a
2874
      // base X position
2875
      var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
2876
      baseX = coords.left;
2877
      outside = y < coords.top || y >= coords.bottom;
2878
    }
2879
 
2880
    ch = skipExtendingChars(lineObj.text, ch, 1);
2881
    return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
2882
  }
2883
 
2884
  function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
2885
    // Bidi parts are sorted left-to-right, and in a non-line-wrapping
2886
    // situation, we can take this ordering to correspond to the visual
2887
    // ordering. This finds the first part whose end is after the given
2888
    // coordinates.
2889
    var index = findFirst(function (i) {
2890
      var part = order[i], ltr = part.level != 1;
2891
      return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
2892
                                     "line", lineObj, preparedMeasure), x, y, true)
2893
    }, 0, order.length - 1);
2894
    var part = order[index];
2895
    // If this isn't the first part, the part's start is also after
2896
    // the coordinates, and the coordinates aren't on the same line as
2897
    // that start, move one part back.
2898
    if (index > 0) {
2899
      var ltr = part.level != 1;
2900
      var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
2901
                               "line", lineObj, preparedMeasure);
2902
      if (boxIsAfter(start, x, y, true) && start.top > y)
2903
        { part = order[index - 1]; }
2904
    }
2905
    return part
2906
  }
2907
 
2908
  function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
2909
    // In a wrapped line, rtl text on wrapping boundaries can do things
2910
    // that don't correspond to the ordering in our `order` array at
2911
    // all, so a binary search doesn't work, and we want to return a
2912
    // part that only spans one line so that the binary search in
2913
    // coordsCharInner is safe. As such, we first find the extent of the
2914
    // wrapped line, and then do a flat search in which we discard any
2915
    // spans that aren't on the line.
2916
    var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
2917
    var begin = ref.begin;
2918
    var end = ref.end;
2919
    if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
2920
    var part = null, closestDist = null;
2921
    for (var i = 0; i < order.length; i++) {
2922
      var p = order[i];
2923
      if (p.from >= end || p.to <= begin) { continue }
2924
      var ltr = p.level != 1;
2925
      var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
2926
      // Weigh against spans ending before this, so that they are only
2927
      // picked if nothing ends after
2928
      var dist = endX < x ? x - endX + 1e9 : endX - x;
2929
      if (!part || closestDist > dist) {
2930
        part = p;
2931
        closestDist = dist;
2932
      }
2933
    }
2934
    if (!part) { part = order[order.length - 1]; }
2935
    // Clip the part to the wrapped line.
2936
    if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
2937
    if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
2938
    return part
2939
  }
2940
 
2941
  var measureText;
2942
  // Compute the default text height.
2943
  function textHeight(display) {
2944
    if (display.cachedTextHeight != null) { return display.cachedTextHeight }
2945
    if (measureText == null) {
2946
      measureText = elt("pre");
2947
      // Measure a bunch of lines, for browsers that compute
2948
      // fractional heights.
2949
      for (var i = 0; i < 49; ++i) {
2950
        measureText.appendChild(document.createTextNode("x"));
2951
        measureText.appendChild(elt("br"));
2952
      }
2953
      measureText.appendChild(document.createTextNode("x"));
2954
    }
2955
    removeChildrenAndAdd(display.measure, measureText);
2956
    var height = measureText.offsetHeight / 50;
2957
    if (height > 3) { display.cachedTextHeight = height; }
2958
    removeChildren(display.measure);
2959
    return height || 1
2960
  }
2961
 
2962
  // Compute the default character width.
2963
  function charWidth(display) {
2964
    if (display.cachedCharWidth != null) { return display.cachedCharWidth }
2965
    var anchor = elt("span", "xxxxxxxxxx");
2966
    var pre = elt("pre", [anchor]);
2967
    removeChildrenAndAdd(display.measure, pre);
2968
    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2969
    if (width > 2) { display.cachedCharWidth = width; }
2970
    return width || 10
2971
  }
2972
 
2973
  // Do a bulk-read of the DOM positions and sizes needed to draw the
2974
  // view, so that we don't interleave reading and writing to the DOM.
2975
  function getDimensions(cm) {
2976
    var d = cm.display, left = {}, width = {};
2977
    var gutterLeft = d.gutters.clientLeft;
2978
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
2979
      left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
2980
      width[cm.options.gutters[i]] = n.clientWidth;
2981
    }
2982
    return {fixedPos: compensateForHScroll(d),
2983
            gutterTotalWidth: d.gutters.offsetWidth,
2984
            gutterLeft: left,
2985
            gutterWidth: width,
2986
            wrapperWidth: d.wrapper.clientWidth}
2987
  }
2988
 
2989
  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
2990
  // but using getBoundingClientRect to get a sub-pixel-accurate
2991
  // result.
2992
  function compensateForHScroll(display) {
2993
    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
2994
  }
2995
 
2996
  // Returns a function that estimates the height of a line, to use as
2997
  // first approximation until the line becomes visible (and is thus
2998
  // properly measurable).
2999
  function estimateHeight(cm) {
3000
    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
3001
    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
3002
    return function (line) {
3003
      if (lineIsHidden(cm.doc, line)) { return 0 }
3004
 
3005
      var widgetsHeight = 0;
3006
      if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
3007
        if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
3008
      } }
3009
 
3010
      if (wrapping)
3011
        { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
3012
      else
3013
        { return widgetsHeight + th }
3014
    }
3015
  }
3016
 
3017
  function estimateLineHeights(cm) {
3018
    var doc = cm.doc, est = estimateHeight(cm);
3019
    doc.iter(function (line) {
3020
      var estHeight = est(line);
3021
      if (estHeight != line.height) { updateLineHeight(line, estHeight); }
3022
    });
3023
  }
3024
 
3025
  // Given a mouse event, find the corresponding position. If liberal
3026
  // is false, it checks whether a gutter or scrollbar was clicked,
3027
  // and returns null if it was. forRect is used by rectangular
3028
  // selections, and tries to estimate a character position even for
3029
  // coordinates beyond the right of the text.
3030
  function posFromMouse(cm, e, liberal, forRect) {
3031
    var display = cm.display;
3032
    if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
3033
 
3034
    var x, y, space = display.lineSpace.getBoundingClientRect();
3035
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3036
    try { x = e.clientX - space.left; y = e.clientY - space.top; }
3037
    catch (e) { return null }
3038
    var coords = coordsChar(cm, x, y), line;
3039
    if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3040
      var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3041
      coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3042
    }
3043
    return coords
3044
  }
3045
 
3046
  // Find the view element corresponding to a given line. Return null
3047
  // when the line isn't visible.
3048
  function findViewIndex(cm, n) {
3049
    if (n >= cm.display.viewTo) { return null }
3050
    n -= cm.display.viewFrom;
3051
    if (n < 0) { return null }
3052
    var view = cm.display.view;
3053
    for (var i = 0; i < view.length; i++) {
3054
      n -= view[i].size;
3055
      if (n < 0) { return i }
3056
    }
3057
  }
3058
 
3059
  function updateSelection(cm) {
3060
    cm.display.input.showSelection(cm.display.input.prepareSelection());
3061
  }
3062
 
3063
  function prepareSelection(cm, primary) {
3064
    if ( primary === void 0 ) primary = true;
3065
 
3066
    var doc = cm.doc, result = {};
3067
    var curFragment = result.cursors = document.createDocumentFragment();
3068
    var selFragment = result.selection = document.createDocumentFragment();
3069
 
3070
    for (var i = 0; i < doc.sel.ranges.length; i++) {
3071
      if (!primary && i == doc.sel.primIndex) { continue }
3072
      var range$$1 = doc.sel.ranges[i];
3073
      if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
3074
      var collapsed = range$$1.empty();
3075
      if (collapsed || cm.options.showCursorWhenSelecting)
3076
        { drawSelectionCursor(cm, range$$1.head, curFragment); }
3077
      if (!collapsed)
3078
        { drawSelectionRange(cm, range$$1, selFragment); }
3079
    }
3080
    return result
3081
  }
3082
 
3083
  // Draws a cursor for the given range
3084
  function drawSelectionCursor(cm, head, output) {
3085
    var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
3086
 
3087
    var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
3088
    cursor.style.left = pos.left + "px";
3089
    cursor.style.top = pos.top + "px";
3090
    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
3091
 
3092
    if (pos.other) {
3093
      // Secondary cursor, shown when on a 'jump' in bi-directional text
3094
      var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
3095
      otherCursor.style.display = "";
3096
      otherCursor.style.left = pos.other.left + "px";
3097
      otherCursor.style.top = pos.other.top + "px";
3098
      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
3099
    }
3100
  }
3101
 
3102
  function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
3103
 
3104
  // Draws the given range as a highlighted selection
3105
  function drawSelectionRange(cm, range$$1, output) {
3106
    var display = cm.display, doc = cm.doc;
3107
    var fragment = document.createDocumentFragment();
3108
    var padding = paddingH(cm.display), leftSide = padding.left;
3109
    var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
3110
    var docLTR = doc.direction == "ltr";
3111
 
3112
    function add(left, top, width, bottom) {
3113
      if (top < 0) { top = 0; }
3114
      top = Math.round(top);
3115
      bottom = Math.round(bottom);
3116
      fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n                             top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n                             height: " + (bottom - top) + "px")));
3117
    }
3118
 
3119
    function drawForLine(line, fromArg, toArg) {
3120
      var lineObj = getLine(doc, line);
3121
      var lineLen = lineObj.text.length;
3122
      var start, end;
3123
      function coords(ch, bias) {
3124
        return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
3125
      }
3126
 
3127
      function wrapX(pos, dir, side) {
3128
        var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
3129
        var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
3130
        var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
3131
        return coords(ch, prop)[prop]
3132
      }
3133
 
3134
      var order = getOrder(lineObj, doc.direction);
3135
      iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
3136
        var ltr = dir == "ltr";
3137
        var fromPos = coords(from, ltr ? "left" : "right");
3138
        var toPos = coords(to - 1, ltr ? "right" : "left");
3139
 
3140
        var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
3141
        var first = i == 0, last = !order || i == order.length - 1;
3142
        if (toPos.top - fromPos.top <= 3) { // Single line
3143
          var openLeft = (docLTR ? openStart : openEnd) && first;
3144
          var openRight = (docLTR ? openEnd : openStart) && last;
3145
          var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
3146
          var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
3147
          add(left, fromPos.top, right - left, fromPos.bottom);
3148
        } else { // Multiple lines
3149
          var topLeft, topRight, botLeft, botRight;
3150
          if (ltr) {
3151
            topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
3152
            topRight = docLTR ? rightSide : wrapX(from, dir, "before");
3153
            botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
3154
            botRight = docLTR && openEnd && last ? rightSide : toPos.right;
3155
          } else {
3156
            topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
3157
            topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
3158
            botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
3159
            botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
3160
          }
3161
          add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
3162
          if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
3163
          add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
3164
        }
3165
 
3166
        if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
3167
        if (cmpCoords(toPos, start) < 0) { start = toPos; }
3168
        if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
3169
        if (cmpCoords(toPos, end) < 0) { end = toPos; }
3170
      });
3171
      return {start: start, end: end}
3172
    }
3173
 
3174
    var sFrom = range$$1.from(), sTo = range$$1.to();
3175
    if (sFrom.line == sTo.line) {
3176
      drawForLine(sFrom.line, sFrom.ch, sTo.ch);
3177
    } else {
3178
      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
3179
      var singleVLine = visualLine(fromLine) == visualLine(toLine);
3180
      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
3181
      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
3182
      if (singleVLine) {
3183
        if (leftEnd.top < rightStart.top - 2) {
3184
          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
3185
          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
3186
        } else {
3187
          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
3188
        }
3189
      }
3190
      if (leftEnd.bottom < rightStart.top)
3191
        { add(leftSide, leftEnd.bottom, null, rightStart.top); }
3192
    }
3193
 
3194
    output.appendChild(fragment);
3195
  }
3196
 
3197
  // Cursor-blinking
3198
  function restartBlink(cm) {
3199
    if (!cm.state.focused) { return }
3200
    var display = cm.display;
3201
    clearInterval(display.blinker);
3202
    var on = true;
3203
    display.cursorDiv.style.visibility = "";
3204
    if (cm.options.cursorBlinkRate > 0)
3205
      { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
3206
        cm.options.cursorBlinkRate); }
3207
    else if (cm.options.cursorBlinkRate < 0)
3208
      { display.cursorDiv.style.visibility = "hidden"; }
3209
  }
3210
 
3211
  function ensureFocus(cm) {
3212
    if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
3213
  }
3214
 
3215
  function delayBlurEvent(cm) {
3216
    cm.state.delayingBlurEvent = true;
3217
    setTimeout(function () { if (cm.state.delayingBlurEvent) {
3218
      cm.state.delayingBlurEvent = false;
3219
      onBlur(cm);
3220
    } }, 100);
3221
  }
3222
 
3223
  function onFocus(cm, e) {
3224
    if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
3225
 
3226
    if (cm.options.readOnly == "nocursor") { return }
3227
    if (!cm.state.focused) {
3228
      signal(cm, "focus", cm, e);
3229
      cm.state.focused = true;
3230
      addClass(cm.display.wrapper, "CodeMirror-focused");
3231
      // This test prevents this from firing when a context
3232
      // menu is closed (since the input reset would kill the
3233
      // select-all detection hack)
3234
      if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
3235
        cm.display.input.reset();
3236
        if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
3237
      }
3238
      cm.display.input.receivedFocus();
3239
    }
3240
    restartBlink(cm);
3241
  }
3242
  function onBlur(cm, e) {
3243
    if (cm.state.delayingBlurEvent) { return }
3244
 
3245
    if (cm.state.focused) {
3246
      signal(cm, "blur", cm, e);
3247
      cm.state.focused = false;
3248
      rmClass(cm.display.wrapper, "CodeMirror-focused");
3249
    }
3250
    clearInterval(cm.display.blinker);
3251
    setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
3252
  }
3253
 
3254
  // Read the actual heights of the rendered lines, and update their
3255
  // stored heights to match.
3256
  function updateHeightsInViewport(cm) {
3257
    var display = cm.display;
3258
    var prevBottom = display.lineDiv.offsetTop;
3259
    for (var i = 0; i < display.view.length; i++) {
3260
      var cur = display.view[i], height = (void 0);
3261
      if (cur.hidden) { continue }
3262
      if (ie && ie_version < 8) {
3263
        var bot = cur.node.offsetTop + cur.node.offsetHeight;
3264
        height = bot - prevBottom;
3265
        prevBottom = bot;
3266
      } else {
3267
        var box = cur.node.getBoundingClientRect();
3268
        height = box.bottom - box.top;
3269
      }
3270
      var diff = cur.line.height - height;
3271
      if (height < 2) { height = textHeight(display); }
3272
      if (diff > .005 || diff < -.005) {
3273
        updateLineHeight(cur.line, height);
3274
        updateWidgetHeight(cur.line);
3275
        if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
3276
          { updateWidgetHeight(cur.rest[j]); } }
3277
      }
3278
    }
3279
  }
3280
 
3281
  // Read and store the height of line widgets associated with the
3282
  // given line.
3283
  function updateWidgetHeight(line) {
3284
    if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
3285
      var w = line.widgets[i], parent = w.node.parentNode;
3286
      if (parent) { w.height = parent.offsetHeight; }
3287
    } }
3288
  }
3289
 
3290
  // Compute the lines that are visible in a given viewport (defaults
3291
  // the the current scroll position). viewport may contain top,
3292
  // height, and ensure (see op.scrollToPos) properties.
3293
  function visibleLines(display, doc, viewport) {
3294
    var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
3295
    top = Math.floor(top - paddingTop(display));
3296
    var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
3297
 
3298
    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
3299
    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
3300
    // forces those lines into the viewport (if possible).
3301
    if (viewport && viewport.ensure) {
3302
      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
3303
      if (ensureFrom < from) {
3304
        from = ensureFrom;
3305
        to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
3306
      } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
3307
        from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
3308
        to = ensureTo;
3309
      }
3310
    }
3311
    return {from: from, to: Math.max(to, from + 1)}
3312
  }
3313
 
3314
  // Re-align line numbers and gutter marks to compensate for
3315
  // horizontal scrolling.
3316
  function alignHorizontally(cm) {
3317
    var display = cm.display, view = display.view;
3318
    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
3319
    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
3320
    var gutterW = display.gutters.offsetWidth, left = comp + "px";
3321
    for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
3322
      if (cm.options.fixedGutter) {
3323
        if (view[i].gutter)
3324
          { view[i].gutter.style.left = left; }
3325
        if (view[i].gutterBackground)
3326
          { view[i].gutterBackground.style.left = left; }
3327
      }
3328
      var align = view[i].alignable;
3329
      if (align) { for (var j = 0; j < align.length; j++)
3330
        { align[j].style.left = left; } }
3331
    } }
3332
    if (cm.options.fixedGutter)
3333
      { display.gutters.style.left = (comp + gutterW) + "px"; }
3334
  }
3335
 
3336
  // Used to ensure that the line number gutter is still the right
3337
  // size for the current document size. Returns true when an update
3338
  // is needed.
3339
  function maybeUpdateLineNumberWidth(cm) {
3340
    if (!cm.options.lineNumbers) { return false }
3341
    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
3342
    if (last.length != display.lineNumChars) {
3343
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
3344
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
3345
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
3346
      display.lineGutter.style.width = "";
3347
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
3348
      display.lineNumWidth = display.lineNumInnerWidth + padding;
3349
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
3350
      display.lineGutter.style.width = display.lineNumWidth + "px";
3351
      updateGutterSpace(cm);
3352
      return true
3353
    }
3354
    return false
3355
  }
3356
 
3357
  // SCROLLING THINGS INTO VIEW
3358
 
3359
  // If an editor sits on the top or bottom of the window, partially
3360
  // scrolled out of view, this ensures that the cursor is visible.
3361
  function maybeScrollWindow(cm, rect) {
3362
    if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
3363
 
3364
    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
3365
    if (rect.top + box.top < 0) { doScroll = true; }
3366
    else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
3367
    if (doScroll != null && !phantom) {
3368
      var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n                         top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n                         height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n                         left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
3369
      cm.display.lineSpace.appendChild(scrollNode);
3370
      scrollNode.scrollIntoView(doScroll);
3371
      cm.display.lineSpace.removeChild(scrollNode);
3372
    }
3373
  }
3374
 
3375
  // Scroll a given position into view (immediately), verifying that
3376
  // it actually became visible (as line heights are accurately
3377
  // measured, the position of something may 'drift' during drawing).
3378
  function scrollPosIntoView(cm, pos, end, margin) {
3379
    if (margin == null) { margin = 0; }
3380
    var rect;
3381
    if (!cm.options.lineWrapping && pos == end) {
3382
      // Set pos and end to the cursor positions around the character pos sticks to
3383
      // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
3384
      // If pos == Pos(_, 0, "before"), pos and end are unchanged
3385
      pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
3386
      end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
3387
    }
3388
    for (var limit = 0; limit < 5; limit++) {
3389
      var changed = false;
3390
      var coords = cursorCoords(cm, pos);
3391
      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
3392
      rect = {left: Math.min(coords.left, endCoords.left),
3393
              top: Math.min(coords.top, endCoords.top) - margin,
3394
              right: Math.max(coords.left, endCoords.left),
3395
              bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
3396
      var scrollPos = calculateScrollPos(cm, rect);
3397
      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
3398
      if (scrollPos.scrollTop != null) {
3399
        updateScrollTop(cm, scrollPos.scrollTop);
3400
        if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
3401
      }
3402
      if (scrollPos.scrollLeft != null) {
3403
        setScrollLeft(cm, scrollPos.scrollLeft);
3404
        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
3405
      }
3406
      if (!changed) { break }
3407
    }
3408
    return rect
3409
  }
3410
 
3411
  // Scroll a given set of coordinates into view (immediately).
3412
  function scrollIntoView(cm, rect) {
3413
    var scrollPos = calculateScrollPos(cm, rect);
3414
    if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
3415
    if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
3416
  }
3417
 
3418
  // Calculate a new scroll position needed to scroll the given
3419
  // rectangle into view. Returns an object with scrollTop and
3420
  // scrollLeft properties. When these are undefined, the
3421
  // vertical/horizontal position does not need to be adjusted.
3422
  function calculateScrollPos(cm, rect) {
3423
    var display = cm.display, snapMargin = textHeight(cm.display);
3424
    if (rect.top < 0) { rect.top = 0; }
3425
    var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
3426
    var screen = displayHeight(cm), result = {};
3427
    if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
3428
    var docBottom = cm.doc.height + paddingVert(display);
3429
    var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
3430
    if (rect.top < screentop) {
3431
      result.scrollTop = atTop ? 0 : rect.top;
3432
    } else if (rect.bottom > screentop + screen) {
3433
      var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
3434
      if (newTop != screentop) { result.scrollTop = newTop; }
3435
    }
3436
 
3437
    var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
3438
    var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
3439
    var tooWide = rect.right - rect.left > screenw;
3440
    if (tooWide) { rect.right = rect.left + screenw; }
3441
    if (rect.left < 10)
3442
      { result.scrollLeft = 0; }
3443
    else if (rect.left < screenleft)
3444
      { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
3445
    else if (rect.right > screenw + screenleft - 3)
3446
      { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
3447
    return result
3448
  }
3449
 
3450
  // Store a relative adjustment to the scroll position in the current
3451
  // operation (to be applied when the operation finishes).
3452
  function addToScrollTop(cm, top) {
3453
    if (top == null) { return }
3454
    resolveScrollToPos(cm);
3455
    cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
3456
  }
3457
 
3458
  // Make sure that at the end of the operation the current cursor is
3459
  // shown.
3460
  function ensureCursorVisible(cm) {
3461
    resolveScrollToPos(cm);
3462
    var cur = cm.getCursor();
3463
    cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
3464
  }
3465
 
3466
  function scrollToCoords(cm, x, y) {
3467
    if (x != null || y != null) { resolveScrollToPos(cm); }
3468
    if (x != null) { cm.curOp.scrollLeft = x; }
3469
    if (y != null) { cm.curOp.scrollTop = y; }
3470
  }
3471
 
3472
  function scrollToRange(cm, range$$1) {
3473
    resolveScrollToPos(cm);
3474
    cm.curOp.scrollToPos = range$$1;
3475
  }
3476
 
3477
  // When an operation has its scrollToPos property set, and another
3478
  // scroll action is applied before the end of the operation, this
3479
  // 'simulates' scrolling that position into view in a cheap way, so
3480
  // that the effect of intermediate scroll commands is not ignored.
3481
  function resolveScrollToPos(cm) {
3482
    var range$$1 = cm.curOp.scrollToPos;
3483
    if (range$$1) {
3484
      cm.curOp.scrollToPos = null;
3485
      var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
3486
      scrollToCoordsRange(cm, from, to, range$$1.margin);
3487
    }
3488
  }
3489
 
3490
  function scrollToCoordsRange(cm, from, to, margin) {
3491
    var sPos = calculateScrollPos(cm, {
3492
      left: Math.min(from.left, to.left),
3493
      top: Math.min(from.top, to.top) - margin,
3494
      right: Math.max(from.right, to.right),
3495
      bottom: Math.max(from.bottom, to.bottom) + margin
3496
    });
3497
    scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
3498
  }
3499
 
3500
  // Sync the scrollable area and scrollbars, ensure the viewport
3501
  // covers the visible area.
3502
  function updateScrollTop(cm, val) {
3503
    if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
3504
    if (!gecko) { updateDisplaySimple(cm, {top: val}); }
3505
    setScrollTop(cm, val, true);
3506
    if (gecko) { updateDisplaySimple(cm); }
3507
    startWorker(cm, 100);
3508
  }
3509
 
3510
  function setScrollTop(cm, val, forceScroll) {
3511
    val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
3512
    if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
3513
    cm.doc.scrollTop = val;
3514
    cm.display.scrollbars.setScrollTop(val);
3515
    if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
3516
  }
3517
 
3518
  // Sync scroller and scrollbar, ensure the gutter elements are
3519
  // aligned.
3520
  function setScrollLeft(cm, val, isScroller, forceScroll) {
3521
    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3522
    if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
3523
    cm.doc.scrollLeft = val;
3524
    alignHorizontally(cm);
3525
    if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
3526
    cm.display.scrollbars.setScrollLeft(val);
3527
  }
3528
 
3529
  // SCROLLBARS
3530
 
3531
  // Prepare DOM reads needed to update the scrollbars. Done in one
3532
  // shot to minimize update/measure roundtrips.
3533
  function measureForScrollbars(cm) {
3534
    var d = cm.display, gutterW = d.gutters.offsetWidth;
3535
    var docH = Math.round(cm.doc.height + paddingVert(cm.display));
3536
    return {
3537
      clientHeight: d.scroller.clientHeight,
3538
      viewHeight: d.wrapper.clientHeight,
3539
      scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
3540
      viewWidth: d.wrapper.clientWidth,
3541
      barLeft: cm.options.fixedGutter ? gutterW : 0,
3542
      docHeight: docH,
3543
      scrollHeight: docH + scrollGap(cm) + d.barHeight,
3544
      nativeBarWidth: d.nativeBarWidth,
3545
      gutterWidth: gutterW
3546
    }
3547
  }
3548
 
3549
  var NativeScrollbars = function(place, scroll, cm) {
3550
    this.cm = cm;
3551
    var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
3552
    var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
3553
    vert.tabIndex = horiz.tabIndex = -1;
3554
    place(vert); place(horiz);
3555
 
3556
    on(vert, "scroll", function () {
3557
      if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
3558
    });
3559
    on(horiz, "scroll", function () {
3560
      if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
3561
    });
3562
 
3563
    this.checkedZeroWidth = false;
3564
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
3565
    if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
3566
  };
3567
 
3568
  NativeScrollbars.prototype.update = function (measure) {
3569
    var needsH = measure.scrollWidth > measure.clientWidth + 1;
3570
    var needsV = measure.scrollHeight > measure.clientHeight + 1;
3571
    var sWidth = measure.nativeBarWidth;
3572
 
3573
    if (needsV) {
3574
      this.vert.style.display = "block";
3575
      this.vert.style.bottom = needsH ? sWidth + "px" : "0";
3576
      var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
3577
      // A bug in IE8 can cause this value to be negative, so guard it.
3578
      this.vert.firstChild.style.height =
3579
        Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
3580
    } else {
3581
      this.vert.style.display = "";
3582
      this.vert.firstChild.style.height = "0";
3583
    }
3584
 
3585
    if (needsH) {
3586
      this.horiz.style.display = "block";
3587
      this.horiz.style.right = needsV ? sWidth + "px" : "0";
3588
      this.horiz.style.left = measure.barLeft + "px";
3589
      var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
3590
      this.horiz.firstChild.style.width =
3591
        Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
3592
    } else {
3593
      this.horiz.style.display = "";
3594
      this.horiz.firstChild.style.width = "0";
3595
    }
3596
 
3597
    if (!this.checkedZeroWidth && measure.clientHeight > 0) {
3598
      if (sWidth == 0) { this.zeroWidthHack(); }
3599
      this.checkedZeroWidth = true;
3600
    }
3601
 
3602
    return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
3603
  };
3604
 
3605
  NativeScrollbars.prototype.setScrollLeft = function (pos) {
3606
    if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
3607
    if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
3608
  };
3609
 
3610
  NativeScrollbars.prototype.setScrollTop = function (pos) {
3611
    if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
3612
    if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
3613
  };
3614
 
3615
  NativeScrollbars.prototype.zeroWidthHack = function () {
3616
    var w = mac && !mac_geMountainLion ? "12px" : "18px";
3617
    this.horiz.style.height = this.vert.style.width = w;
3618
    this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
3619
    this.disableHoriz = new Delayed;
3620
    this.disableVert = new Delayed;
3621
  };
3622
 
3623
  NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
3624
    bar.style.pointerEvents = "auto";
3625
    function maybeDisable() {
3626
      // To find out whether the scrollbar is still visible, we
3627
      // check whether the element under the pixel in the bottom
3628
      // right corner of the scrollbar box is the scrollbar box
3629
      // itself (when the bar is still visible) or its filler child
3630
      // (when the bar is hidden). If it is still visible, we keep
3631
      // it enabled, if it's hidden, we disable pointer events.
3632
      var box = bar.getBoundingClientRect();
3633
      var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
3634
          : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
3635
      if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
3636
      else { delay.set(1000, maybeDisable); }
3637
    }
3638
    delay.set(1000, maybeDisable);
3639
  };
3640
 
3641
  NativeScrollbars.prototype.clear = function () {
3642
    var parent = this.horiz.parentNode;
3643
    parent.removeChild(this.horiz);
3644
    parent.removeChild(this.vert);
3645
  };
3646
 
3647
  var NullScrollbars = function () {};
3648
 
3649
  NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
3650
  NullScrollbars.prototype.setScrollLeft = function () {};
3651
  NullScrollbars.prototype.setScrollTop = function () {};
3652
  NullScrollbars.prototype.clear = function () {};
3653
 
3654
  function updateScrollbars(cm, measure) {
3655
    if (!measure) { measure = measureForScrollbars(cm); }
3656
    var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
3657
    updateScrollbarsInner(cm, measure);
3658
    for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
3659
      if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
3660
        { updateHeightsInViewport(cm); }
3661
      updateScrollbarsInner(cm, measureForScrollbars(cm));
3662
      startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
3663
    }
3664
  }
3665
 
3666
  // Re-synchronize the fake scrollbars with the actual size of the
3667
  // content.
3668
  function updateScrollbarsInner(cm, measure) {
3669
    var d = cm.display;
3670
    var sizes = d.scrollbars.update(measure);
3671
 
3672
    d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
3673
    d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
3674
    d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
3675
 
3676
    if (sizes.right && sizes.bottom) {
3677
      d.scrollbarFiller.style.display = "block";
3678
      d.scrollbarFiller.style.height = sizes.bottom + "px";
3679
      d.scrollbarFiller.style.width = sizes.right + "px";
3680
    } else { d.scrollbarFiller.style.display = ""; }
3681
    if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
3682
      d.gutterFiller.style.display = "block";
3683
      d.gutterFiller.style.height = sizes.bottom + "px";
3684
      d.gutterFiller.style.width = measure.gutterWidth + "px";
3685
    } else { d.gutterFiller.style.display = ""; }
3686
  }
3687
 
3688
  var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
3689
 
3690
  function initScrollbars(cm) {
3691
    if (cm.display.scrollbars) {
3692
      cm.display.scrollbars.clear();
3693
      if (cm.display.scrollbars.addClass)
3694
        { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3695
    }
3696
 
3697
    cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
3698
      cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
3699
      // Prevent clicks in the scrollbars from killing focus
3700
      on(node, "mousedown", function () {
3701
        if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
3702
      });
3703
      node.setAttribute("cm-not-content", "true");
3704
    }, function (pos, axis) {
3705
      if (axis == "horizontal") { setScrollLeft(cm, pos); }
3706
      else { updateScrollTop(cm, pos); }
3707
    }, cm);
3708
    if (cm.display.scrollbars.addClass)
3709
      { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3710
  }
3711
 
3712
  // Operations are used to wrap a series of changes to the editor
3713
  // state in such a way that each change won't have to update the
3714
  // cursor and display (which would be awkward, slow, and
3715
  // error-prone). Instead, display updates are batched and then all
3716
  // combined and executed at once.
3717
 
3718
  var nextOpId = 0;
3719
  // Start a new operation.
3720
  function startOperation(cm) {
3721
    cm.curOp = {
3722
      cm: cm,
3723
      viewChanged: false,      // Flag that indicates that lines might need to be redrawn
3724
      startHeight: cm.doc.height, // Used to detect need to update scrollbar
3725
      forceUpdate: false,      // Used to force a redraw
3726
      updateInput: null,       // Whether to reset the input textarea
3727
      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
3728
      changeObjs: null,        // Accumulated changes, for firing change events
3729
      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
3730
      cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
3731
      selectionChanged: false, // Whether the selection needs to be redrawn
3732
      updateMaxLine: false,    // Set when the widest line needs to be determined anew
3733
      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
3734
      scrollToPos: null,       // Used to scroll to a specific position
3735
      focus: false,
3736
      id: ++nextOpId           // Unique ID
3737
    };
3738
    pushOperation(cm.curOp);
3739
  }
3740
 
3741
  // Finish an operation, updating the display and signalling delayed events
3742
  function endOperation(cm) {
3743
    var op = cm.curOp;
3744
    if (op) { finishOperation(op, function (group) {
3745
      for (var i = 0; i < group.ops.length; i++)
3746
        { group.ops[i].cm.curOp = null; }
3747
      endOperations(group);
3748
    }); }
3749
  }
3750
 
3751
  // The DOM updates done when an operation finishes are batched so
3752
  // that the minimum number of relayouts are required.
3753
  function endOperations(group) {
3754
    var ops = group.ops;
3755
    for (var i = 0; i < ops.length; i++) // Read DOM
3756
      { endOperation_R1(ops[i]); }
3757
    for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
3758
      { endOperation_W1(ops[i$1]); }
3759
    for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
3760
      { endOperation_R2(ops[i$2]); }
3761
    for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
3762
      { endOperation_W2(ops[i$3]); }
3763
    for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
3764
      { endOperation_finish(ops[i$4]); }
3765
  }
3766
 
3767
  function endOperation_R1(op) {
3768
    var cm = op.cm, display = cm.display;
3769
    maybeClipScrollbars(cm);
3770
    if (op.updateMaxLine) { findMaxLine(cm); }
3771
 
3772
    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3773
      op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3774
                         op.scrollToPos.to.line >= display.viewTo) ||
3775
      display.maxLineChanged && cm.options.lineWrapping;
3776
    op.update = op.mustUpdate &&
3777
      new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3778
  }
3779
 
3780
  function endOperation_W1(op) {
3781
    op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3782
  }
3783
 
3784
  function endOperation_R2(op) {
3785
    var cm = op.cm, display = cm.display;
3786
    if (op.updatedDisplay) { updateHeightsInViewport(cm); }
3787
 
3788
    op.barMeasure = measureForScrollbars(cm);
3789
 
3790
    // If the max line changed since it was last measured, measure it,
3791
    // and ensure the document's width matches it.
3792
    // updateDisplay_W2 will use these properties to do the actual resizing
3793
    if (display.maxLineChanged && !cm.options.lineWrapping) {
3794
      op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3795
      cm.display.sizerWidth = op.adjustWidthTo;
3796
      op.barMeasure.scrollWidth =
3797
        Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3798
      op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3799
    }
3800
 
3801
    if (op.updatedDisplay || op.selectionChanged)
3802
      { op.preparedSelection = display.input.prepareSelection(); }
3803
  }
3804
 
3805
  function endOperation_W2(op) {
3806
    var cm = op.cm;
3807
 
3808
    if (op.adjustWidthTo != null) {
3809
      cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3810
      if (op.maxScrollLeft < cm.doc.scrollLeft)
3811
        { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
3812
      cm.display.maxLineChanged = false;
3813
    }
3814
 
3815
    var takeFocus = op.focus && op.focus == activeElt();
3816
    if (op.preparedSelection)
3817
      { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
3818
    if (op.updatedDisplay || op.startHeight != cm.doc.height)
3819
      { updateScrollbars(cm, op.barMeasure); }
3820
    if (op.updatedDisplay)
3821
      { setDocumentHeight(cm, op.barMeasure); }
3822
 
3823
    if (op.selectionChanged) { restartBlink(cm); }
3824
 
3825
    if (cm.state.focused && op.updateInput)
3826
      { cm.display.input.reset(op.typing); }
3827
    if (takeFocus) { ensureFocus(op.cm); }
3828
  }
3829
 
3830
  function endOperation_finish(op) {
3831
    var cm = op.cm, display = cm.display, doc = cm.doc;
3832
 
3833
    if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
3834
 
3835
    // Abort mouse wheel delta measurement, when scrolling explicitly
3836
    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3837
      { display.wheelStartX = display.wheelStartY = null; }
3838
 
3839
    // Propagate the scroll position to the actual DOM scroller
3840
    if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
3841
 
3842
    if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
3843
    // If we need to scroll a specific position into view, do so.
3844
    if (op.scrollToPos) {
3845
      var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3846
                                   clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3847
      maybeScrollWindow(cm, rect);
3848
    }
3849
 
3850
    // Fire events for markers that are hidden/unidden by editing or
3851
    // undoing
3852
    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3853
    if (hidden) { for (var i = 0; i < hidden.length; ++i)
3854
      { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
3855
    if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
3856
      { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
3857
 
3858
    if (display.wrapper.offsetHeight)
3859
      { doc.scrollTop = cm.display.scroller.scrollTop; }
3860
 
3861
    // Fire change events, and delayed event handlers
3862
    if (op.changeObjs)
3863
      { signal(cm, "changes", cm, op.changeObjs); }
3864
    if (op.update)
3865
      { op.update.finish(); }
3866
  }
3867
 
3868
  // Run the given function in an operation
3869
  function runInOp(cm, f) {
3870
    if (cm.curOp) { return f() }
3871
    startOperation(cm);
3872
    try { return f() }
3873
    finally { endOperation(cm); }
3874
  }
3875
  // Wraps a function in an operation. Returns the wrapped function.
3876
  function operation(cm, f) {
3877
    return function() {
3878
      if (cm.curOp) { return f.apply(cm, arguments) }
3879
      startOperation(cm);
3880
      try { return f.apply(cm, arguments) }
3881
      finally { endOperation(cm); }
3882
    }
3883
  }
3884
  // Used to add methods to editor and doc instances, wrapping them in
3885
  // operations.
3886
  function methodOp(f) {
3887
    return function() {
3888
      if (this.curOp) { return f.apply(this, arguments) }
3889
      startOperation(this);
3890
      try { return f.apply(this, arguments) }
3891
      finally { endOperation(this); }
3892
    }
3893
  }
3894
  function docMethodOp(f) {
3895
    return function() {
3896
      var cm = this.cm;
3897
      if (!cm || cm.curOp) { return f.apply(this, arguments) }
3898
      startOperation(cm);
3899
      try { return f.apply(this, arguments) }
3900
      finally { endOperation(cm); }
3901
    }
3902
  }
3903
 
3904
  // Updates the display.view data structure for a given change to the
3905
  // document. From and to are in pre-change coordinates. Lendiff is
3906
  // the amount of lines added or subtracted by the change. This is
3907
  // used for changes that span multiple lines, or change the way
3908
  // lines are divided into visual lines. regLineChange (below)
3909
  // registers single-line changes.
3910
  function regChange(cm, from, to, lendiff) {
3911
    if (from == null) { from = cm.doc.first; }
3912
    if (to == null) { to = cm.doc.first + cm.doc.size; }
3913
    if (!lendiff) { lendiff = 0; }
3914
 
3915
    var display = cm.display;
3916
    if (lendiff && to < display.viewTo &&
3917
        (display.updateLineNumbers == null || display.updateLineNumbers > from))
3918
      { display.updateLineNumbers = from; }
3919
 
3920
    cm.curOp.viewChanged = true;
3921
 
3922
    if (from >= display.viewTo) { // Change after
3923
      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3924
        { resetView(cm); }
3925
    } else if (to <= display.viewFrom) { // Change before
3926
      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3927
        resetView(cm);
3928
      } else {
3929
        display.viewFrom += lendiff;
3930
        display.viewTo += lendiff;
3931
      }
3932
    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3933
      resetView(cm);
3934
    } else if (from <= display.viewFrom) { // Top overlap
3935
      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3936
      if (cut) {
3937
        display.view = display.view.slice(cut.index);
3938
        display.viewFrom = cut.lineN;
3939
        display.viewTo += lendiff;
3940
      } else {
3941
        resetView(cm);
3942
      }
3943
    } else if (to >= display.viewTo) { // Bottom overlap
3944
      var cut$1 = viewCuttingPoint(cm, from, from, -1);
3945
      if (cut$1) {
3946
        display.view = display.view.slice(0, cut$1.index);
3947
        display.viewTo = cut$1.lineN;
3948
      } else {
3949
        resetView(cm);
3950
      }
3951
    } else { // Gap in the middle
3952
      var cutTop = viewCuttingPoint(cm, from, from, -1);
3953
      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3954
      if (cutTop && cutBot) {
3955
        display.view = display.view.slice(0, cutTop.index)
3956
          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3957
          .concat(display.view.slice(cutBot.index));
3958
        display.viewTo += lendiff;
3959
      } else {
3960
        resetView(cm);
3961
      }
3962
    }
3963
 
3964
    var ext = display.externalMeasured;
3965
    if (ext) {
3966
      if (to < ext.lineN)
3967
        { ext.lineN += lendiff; }
3968
      else if (from < ext.lineN + ext.size)
3969
        { display.externalMeasured = null; }
3970
    }
3971
  }
3972
 
3973
  // Register a change to a single line. Type must be one of "text",
3974
  // "gutter", "class", "widget"
3975
  function regLineChange(cm, line, type) {
3976
    cm.curOp.viewChanged = true;
3977
    var display = cm.display, ext = cm.display.externalMeasured;
3978
    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3979
      { display.externalMeasured = null; }
3980
 
3981
    if (line < display.viewFrom || line >= display.viewTo) { return }
3982
    var lineView = display.view[findViewIndex(cm, line)];
3983
    if (lineView.node == null) { return }
3984
    var arr = lineView.changes || (lineView.changes = []);
3985
    if (indexOf(arr, type) == -1) { arr.push(type); }
3986
  }
3987
 
3988
  // Clear the view.
3989
  function resetView(cm) {
3990
    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3991
    cm.display.view = [];
3992
    cm.display.viewOffset = 0;
3993
  }
3994
 
3995
  function viewCuttingPoint(cm, oldN, newN, dir) {
3996
    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3997
    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3998
      { return {index: index, lineN: newN} }
3999
    var n = cm.display.viewFrom;
4000
    for (var i = 0; i < index; i++)
4001
      { n += view[i].size; }
4002
    if (n != oldN) {
4003
      if (dir > 0) {
4004
        if (index == view.length - 1) { return null }
4005
        diff = (n + view[index].size) - oldN;
4006
        index++;
4007
      } else {
4008
        diff = n - oldN;
4009
      }
4010
      oldN += diff; newN += diff;
4011
    }
4012
    while (visualLineNo(cm.doc, newN) != newN) {
4013
      if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
4014
      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
4015
      index += dir;
4016
    }
4017
    return {index: index, lineN: newN}
4018
  }
4019
 
4020
  // Force the view to cover a given range, adding empty view element
4021
  // or clipping off existing ones as needed.
4022
  function adjustView(cm, from, to) {
4023
    var display = cm.display, view = display.view;
4024
    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
4025
      display.view = buildViewArray(cm, from, to);
4026
      display.viewFrom = from;
4027
    } else {
4028
      if (display.viewFrom > from)
4029
        { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
4030
      else if (display.viewFrom < from)
4031
        { display.view = display.view.slice(findViewIndex(cm, from)); }
4032
      display.viewFrom = from;
4033
      if (display.viewTo < to)
4034
        { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
4035
      else if (display.viewTo > to)
4036
        { display.view = display.view.slice(0, findViewIndex(cm, to)); }
4037
    }
4038
    display.viewTo = to;
4039
  }
4040
 
4041
  // Count the number of lines in the view whose DOM representation is
4042
  // out of date (or nonexistent).
4043
  function countDirtyView(cm) {
4044
    var view = cm.display.view, dirty = 0;
4045
    for (var i = 0; i < view.length; i++) {
4046
      var lineView = view[i];
4047
      if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
4048
    }
4049
    return dirty
4050
  }
4051
 
4052
  // HIGHLIGHT WORKER
4053
 
4054
  function startWorker(cm, time) {
4055
    if (cm.doc.highlightFrontier < cm.display.viewTo)
4056
      { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
4057
  }
4058
 
4059
  function highlightWorker(cm) {
4060
    var doc = cm.doc;
4061
    if (doc.highlightFrontier >= cm.display.viewTo) { return }
4062
    var end = +new Date + cm.options.workTime;
4063
    var context = getContextBefore(cm, doc.highlightFrontier);
4064
    var changedLines = [];
4065
 
4066
    doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
4067
      if (context.line >= cm.display.viewFrom) { // Visible
4068
        var oldStyles = line.styles;
4069
        var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
4070
        var highlighted = highlightLine(cm, line, context, true);
4071
        if (resetState) { context.state = resetState; }
4072
        line.styles = highlighted.styles;
4073
        var oldCls = line.styleClasses, newCls = highlighted.classes;
4074
        if (newCls) { line.styleClasses = newCls; }
4075
        else if (oldCls) { line.styleClasses = null; }
4076
        var ischange = !oldStyles || oldStyles.length != line.styles.length ||
4077
          oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
4078
        for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
4079
        if (ischange) { changedLines.push(context.line); }
4080
        line.stateAfter = context.save();
4081
        context.nextLine();
4082
      } else {
4083
        if (line.text.length <= cm.options.maxHighlightLength)
4084
          { processLine(cm, line.text, context); }
4085
        line.stateAfter = context.line % 5 == 0 ? context.save() : null;
4086
        context.nextLine();
4087
      }
4088
      if (+new Date > end) {
4089
        startWorker(cm, cm.options.workDelay);
4090
        return true
4091
      }
4092
    });
4093
    doc.highlightFrontier = context.line;
4094
    doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
4095
    if (changedLines.length) { runInOp(cm, function () {
4096
      for (var i = 0; i < changedLines.length; i++)
4097
        { regLineChange(cm, changedLines[i], "text"); }
4098
    }); }
4099
  }
4100
 
4101
  // DISPLAY DRAWING
4102
 
4103
  var DisplayUpdate = function(cm, viewport, force) {
4104
    var display = cm.display;
4105
 
4106
    this.viewport = viewport;
4107
    // Store some values that we'll need later (but don't want to force a relayout for)
4108
    this.visible = visibleLines(display, cm.doc, viewport);
4109
    this.editorIsHidden = !display.wrapper.offsetWidth;
4110
    this.wrapperHeight = display.wrapper.clientHeight;
4111
    this.wrapperWidth = display.wrapper.clientWidth;
4112
    this.oldDisplayWidth = displayWidth(cm);
4113
    this.force = force;
4114
    this.dims = getDimensions(cm);
4115
    this.events = [];
4116
  };
4117
 
4118
  DisplayUpdate.prototype.signal = function (emitter, type) {
4119
    if (hasHandler(emitter, type))
4120
      { this.events.push(arguments); }
4121
  };
4122
  DisplayUpdate.prototype.finish = function () {
4123
    for (var i = 0; i < this.events.length; i++)
4124
      { signal.apply(null, this.events[i]); }
4125
  };
4126
 
4127
  function maybeClipScrollbars(cm) {
4128
    var display = cm.display;
4129
    if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
4130
      display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
4131
      display.heightForcer.style.height = scrollGap(cm) + "px";
4132
      display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
4133
      display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
4134
      display.scrollbarsClipped = true;
4135
    }
4136
  }
4137
 
4138
  function selectionSnapshot(cm) {
4139
    if (cm.hasFocus()) { return null }
4140
    var active = activeElt();
4141
    if (!active || !contains(cm.display.lineDiv, active)) { return null }
4142
    var result = {activeElt: active};
4143
    if (window.getSelection) {
4144
      var sel = window.getSelection();
4145
      if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
4146
        result.anchorNode = sel.anchorNode;
4147
        result.anchorOffset = sel.anchorOffset;
4148
        result.focusNode = sel.focusNode;
4149
        result.focusOffset = sel.focusOffset;
4150
      }
4151
    }
4152
    return result
4153
  }
4154
 
4155
  function restoreSelection(snapshot) {
4156
    if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
4157
    snapshot.activeElt.focus();
4158
    if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
4159
      var sel = window.getSelection(), range$$1 = document.createRange();
4160
      range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
4161
      range$$1.collapse(false);
4162
      sel.removeAllRanges();
4163
      sel.addRange(range$$1);
4164
      sel.extend(snapshot.focusNode, snapshot.focusOffset);
4165
    }
4166
  }
4167
 
4168
  // Does the actual updating of the line display. Bails out
4169
  // (returning false) when there is nothing to be done and forced is
4170
  // false.
4171
  function updateDisplayIfNeeded(cm, update) {
4172
    var display = cm.display, doc = cm.doc;
4173
 
4174
    if (update.editorIsHidden) {
4175
      resetView(cm);
4176
      return false
4177
    }
4178
 
4179
    // Bail out if the visible area is already rendered and nothing changed.
4180
    if (!update.force &&
4181
        update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
4182
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
4183
        display.renderedView == display.view && countDirtyView(cm) == 0)
4184
      { return false }
4185
 
4186
    if (maybeUpdateLineNumberWidth(cm)) {
4187
      resetView(cm);
4188
      update.dims = getDimensions(cm);
4189
    }
4190
 
4191
    // Compute a suitable new viewport (from & to)
4192
    var end = doc.first + doc.size;
4193
    var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
4194
    var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
4195
    if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
4196
    if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
4197
    if (sawCollapsedSpans) {
4198
      from = visualLineNo(cm.doc, from);
4199
      to = visualLineEndNo(cm.doc, to);
4200
    }
4201
 
4202
    var different = from != display.viewFrom || to != display.viewTo ||
4203
      display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
4204
    adjustView(cm, from, to);
4205
 
4206
    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
4207
    // Position the mover div to align with the current scroll position
4208
    cm.display.mover.style.top = display.viewOffset + "px";
4209
 
4210
    var toUpdate = countDirtyView(cm);
4211
    if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
4212
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
4213
      { return false }
4214
 
4215
    // For big changes, we hide the enclosing element during the
4216
    // update, since that speeds up the operations on most browsers.
4217
    var selSnapshot = selectionSnapshot(cm);
4218
    if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
4219
    patchDisplay(cm, display.updateLineNumbers, update.dims);
4220
    if (toUpdate > 4) { display.lineDiv.style.display = ""; }
4221
    display.renderedView = display.view;
4222
    // There might have been a widget with a focused element that got
4223
    // hidden or updated, if so re-focus it.
4224
    restoreSelection(selSnapshot);
4225
 
4226
    // Prevent selection and cursors from interfering with the scroll
4227
    // width and height.
4228
    removeChildren(display.cursorDiv);
4229
    removeChildren(display.selectionDiv);
4230
    display.gutters.style.height = display.sizer.style.minHeight = 0;
4231
 
4232
    if (different) {
4233
      display.lastWrapHeight = update.wrapperHeight;
4234
      display.lastWrapWidth = update.wrapperWidth;
4235
      startWorker(cm, 400);
4236
    }
4237
 
4238
    display.updateLineNumbers = null;
4239
 
4240
    return true
4241
  }
4242
 
4243
  function postUpdateDisplay(cm, update) {
4244
    var viewport = update.viewport;
4245
 
4246
    for (var first = true;; first = false) {
4247
      if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
4248
        // Clip forced viewport to actual scrollable area.
4249
        if (viewport && viewport.top != null)
4250
          { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
4251
        // Updated line heights might result in the drawn area not
4252
        // actually covering the viewport. Keep looping until it does.
4253
        update.visible = visibleLines(cm.display, cm.doc, viewport);
4254
        if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
4255
          { break }
4256
      }
4257
      if (!updateDisplayIfNeeded(cm, update)) { break }
4258
      updateHeightsInViewport(cm);
4259
      var barMeasure = measureForScrollbars(cm);
4260
      updateSelection(cm);
4261
      updateScrollbars(cm, barMeasure);
4262
      setDocumentHeight(cm, barMeasure);
4263
      update.force = false;
4264
    }
4265
 
4266
    update.signal(cm, "update", cm);
4267
    if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
4268
      update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
4269
      cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
4270
    }
4271
  }
4272
 
4273
  function updateDisplaySimple(cm, viewport) {
4274
    var update = new DisplayUpdate(cm, viewport);
4275
    if (updateDisplayIfNeeded(cm, update)) {
4276
      updateHeightsInViewport(cm);
4277
      postUpdateDisplay(cm, update);
4278
      var barMeasure = measureForScrollbars(cm);
4279
      updateSelection(cm);
4280
      updateScrollbars(cm, barMeasure);
4281
      setDocumentHeight(cm, barMeasure);
4282
      update.finish();
4283
    }
4284
  }
4285
 
4286
  // Sync the actual display DOM structure with display.view, removing
4287
  // nodes for lines that are no longer in view, and creating the ones
4288
  // that are not there yet, and updating the ones that are out of
4289
  // date.
4290
  function patchDisplay(cm, updateNumbersFrom, dims) {
4291
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
4292
    var container = display.lineDiv, cur = container.firstChild;
4293
 
4294
    function rm(node) {
4295
      var next = node.nextSibling;
4296
      // Works around a throw-scroll bug in OS X Webkit
4297
      if (webkit && mac && cm.display.currentWheelTarget == node)
4298
        { node.style.display = "none"; }
4299
      else
4300
        { node.parentNode.removeChild(node); }
4301
      return next
4302
    }
4303
 
4304
    var view = display.view, lineN = display.viewFrom;
4305
    // Loop over the elements in the view, syncing cur (the DOM nodes
4306
    // in display.lineDiv) with the view as we go.
4307
    for (var i = 0; i < view.length; i++) {
4308
      var lineView = view[i];
4309
      if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
4310
        var node = buildLineElement(cm, lineView, lineN, dims);
4311
        container.insertBefore(node, cur);
4312
      } else { // Already drawn
4313
        while (cur != lineView.node) { cur = rm(cur); }
4314
        var updateNumber = lineNumbers && updateNumbersFrom != null &&
4315
          updateNumbersFrom <= lineN && lineView.lineNumber;
4316
        if (lineView.changes) {
4317
          if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
4318
          updateLineForChanges(cm, lineView, lineN, dims);
4319
        }
4320
        if (updateNumber) {
4321
          removeChildren(lineView.lineNumber);
4322
          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
4323
        }
4324
        cur = lineView.node.nextSibling;
4325
      }
4326
      lineN += lineView.size;
4327
    }
4328
    while (cur) { cur = rm(cur); }
4329
  }
4330
 
4331
  function updateGutterSpace(cm) {
4332
    var width = cm.display.gutters.offsetWidth;
4333
    cm.display.sizer.style.marginLeft = width + "px";
4334
  }
4335
 
4336
  function setDocumentHeight(cm, measure) {
4337
    cm.display.sizer.style.minHeight = measure.docHeight + "px";
4338
    cm.display.heightForcer.style.top = measure.docHeight + "px";
4339
    cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
4340
  }
4341
 
4342
  // Rebuild the gutter elements, ensure the margin to the left of the
4343
  // code matches their width.
4344
  function updateGutters(cm) {
4345
    var gutters = cm.display.gutters, specs = cm.options.gutters;
4346
    removeChildren(gutters);
4347
    var i = 0;
4348
    for (; i < specs.length; ++i) {
4349
      var gutterClass = specs[i];
4350
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
4351
      if (gutterClass == "CodeMirror-linenumbers") {
4352
        cm.display.lineGutter = gElt;
4353
        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
4354
      }
4355
    }
4356
    gutters.style.display = i ? "" : "none";
4357
    updateGutterSpace(cm);
4358
  }
4359
 
4360
  // Make sure the gutters options contains the element
4361
  // "CodeMirror-linenumbers" when the lineNumbers option is true.
4362
  function setGuttersForLineNumbers(options) {
4363
    var found = indexOf(options.gutters, "CodeMirror-linenumbers");
4364
    if (found == -1 && options.lineNumbers) {
4365
      options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
4366
    } else if (found > -1 && !options.lineNumbers) {
4367
      options.gutters = options.gutters.slice(0);
4368
      options.gutters.splice(found, 1);
4369
    }
4370
  }
4371
 
4372
  // Since the delta values reported on mouse wheel events are
4373
  // unstandardized between browsers and even browser versions, and
4374
  // generally horribly unpredictable, this code starts by measuring
4375
  // the scroll effect that the first few mouse wheel events have,
4376
  // and, from that, detects the way it can convert deltas to pixel
4377
  // offsets afterwards.
4378
  //
4379
  // The reason we want to know the amount a wheel event will scroll
4380
  // is that it gives us a chance to update the display before the
4381
  // actual scrolling happens, reducing flickering.
4382
 
4383
  var wheelSamples = 0, wheelPixelsPerUnit = null;
4384
  // Fill in a browser-detected starting value on browsers where we
4385
  // know one. These don't have to be accurate -- the result of them
4386
  // being wrong would just be a slight flicker on the first wheel
4387
  // scroll (if it is large enough).
4388
  if (ie) { wheelPixelsPerUnit = -.53; }
4389
  else if (gecko) { wheelPixelsPerUnit = 15; }
4390
  else if (chrome) { wheelPixelsPerUnit = -.7; }
4391
  else if (safari) { wheelPixelsPerUnit = -1/3; }
4392
 
4393
  function wheelEventDelta(e) {
4394
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
4395
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
4396
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
4397
    else if (dy == null) { dy = e.wheelDelta; }
4398
    return {x: dx, y: dy}
4399
  }
4400
  function wheelEventPixels(e) {
4401
    var delta = wheelEventDelta(e);
4402
    delta.x *= wheelPixelsPerUnit;
4403
    delta.y *= wheelPixelsPerUnit;
4404
    return delta
4405
  }
4406
 
4407
  function onScrollWheel(cm, e) {
4408
    var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
4409
 
4410
    var display = cm.display, scroll = display.scroller;
4411
    // Quit if there's nothing to scroll here
4412
    var canScrollX = scroll.scrollWidth > scroll.clientWidth;
4413
    var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4414
    if (!(dx && canScrollX || dy && canScrollY)) { return }
4415
 
4416
    // Webkit browsers on OS X abort momentum scrolls when the target
4417
    // of the scroll event is removed from the scrollable element.
4418
    // This hack (see related code in patchDisplay) makes sure the
4419
    // element is kept around.
4420
    if (dy && mac && webkit) {
4421
      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4422
        for (var i = 0; i < view.length; i++) {
4423
          if (view[i].node == cur) {
4424
            cm.display.currentWheelTarget = cur;
4425
            break outer
4426
          }
4427
        }
4428
      }
4429
    }
4430
 
4431
    // On some browsers, horizontal scrolling will cause redraws to
4432
    // happen before the gutter has been realigned, causing it to
4433
    // wriggle around in a most unseemly way. When we have an
4434
    // estimated pixels/delta value, we just handle horizontal
4435
    // scrolling entirely here. It'll be slightly off from native, but
4436
    // better than glitching out.
4437
    if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
4438
      if (dy && canScrollY)
4439
        { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
4440
      setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
4441
      // Only prevent default scrolling if vertical scrolling is
4442
      // actually possible. Otherwise, it causes vertical scroll
4443
      // jitter on OSX trackpads when deltaX is small and deltaY
4444
      // is large (issue #3579)
4445
      if (!dy || (dy && canScrollY))
4446
        { e_preventDefault(e); }
4447
      display.wheelStartX = null; // Abort measurement, if in progress
4448
      return
4449
    }
4450
 
4451
    // 'Project' the visible viewport to cover the area that is being
4452
    // scrolled into view (if we know enough to estimate it).
4453
    if (dy && wheelPixelsPerUnit != null) {
4454
      var pixels = dy * wheelPixelsPerUnit;
4455
      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4456
      if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
4457
      else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
4458
      updateDisplaySimple(cm, {top: top, bottom: bot});
4459
    }
4460
 
4461
    if (wheelSamples < 20) {
4462
      if (display.wheelStartX == null) {
4463
        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4464
        display.wheelDX = dx; display.wheelDY = dy;
4465
        setTimeout(function () {
4466
          if (display.wheelStartX == null) { return }
4467
          var movedX = scroll.scrollLeft - display.wheelStartX;
4468
          var movedY = scroll.scrollTop - display.wheelStartY;
4469
          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4470
            (movedX && display.wheelDX && movedX / display.wheelDX);
4471
          display.wheelStartX = display.wheelStartY = null;
4472
          if (!sample) { return }
4473
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4474
          ++wheelSamples;
4475
        }, 200);
4476
      } else {
4477
        display.wheelDX += dx; display.wheelDY += dy;
4478
      }
4479
    }
4480
  }
4481
 
4482
  // Selection objects are immutable. A new one is created every time
4483
  // the selection changes. A selection is one or more non-overlapping
4484
  // (and non-touching) ranges, sorted, and an integer that indicates
4485
  // which one is the primary selection (the one that's scrolled into
4486
  // view, that getCursor returns, etc).
4487
  var Selection = function(ranges, primIndex) {
4488
    this.ranges = ranges;
4489
    this.primIndex = primIndex;
4490
  };
4491
 
4492
  Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
4493
 
4494
  Selection.prototype.equals = function (other) {
4495
    if (other == this) { return true }
4496
    if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
4497
    for (var i = 0; i < this.ranges.length; i++) {
4498
      var here = this.ranges[i], there = other.ranges[i];
4499
      if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
4500
    }
4501
    return true
4502
  };
4503
 
4504
  Selection.prototype.deepCopy = function () {
4505
    var out = [];
4506
    for (var i = 0; i < this.ranges.length; i++)
4507
      { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
4508
    return new Selection(out, this.primIndex)
4509
  };
4510
 
4511
  Selection.prototype.somethingSelected = function () {
4512
    for (var i = 0; i < this.ranges.length; i++)
4513
      { if (!this.ranges[i].empty()) { return true } }
4514
    return false
4515
  };
4516
 
4517
  Selection.prototype.contains = function (pos, end) {
4518
    if (!end) { end = pos; }
4519
    for (var i = 0; i < this.ranges.length; i++) {
4520
      var range = this.ranges[i];
4521
      if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
4522
        { return i }
4523
    }
4524
    return -1
4525
  };
4526
 
4527
  var Range = function(anchor, head) {
4528
    this.anchor = anchor; this.head = head;
4529
  };
4530
 
4531
  Range.prototype.from = function () { return minPos(this.anchor, this.head) };
4532
  Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
4533
  Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
4534
 
4535
  // Take an unsorted, potentially overlapping set of ranges, and
4536
  // build a selection out of it. 'Consumes' ranges array (modifying
4537
  // it).
4538
  function normalizeSelection(cm, ranges, primIndex) {
4539
    var mayTouch = cm && cm.options.selectionsMayTouch;
4540
    var prim = ranges[primIndex];
4541
    ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
4542
    primIndex = indexOf(ranges, prim);
4543
    for (var i = 1; i < ranges.length; i++) {
4544
      var cur = ranges[i], prev = ranges[i - 1];
4545
      var diff = cmp(prev.to(), cur.from());
4546
      if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
4547
        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
4548
        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
4549
        if (i <= primIndex) { --primIndex; }
4550
        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
4551
      }
4552
    }
4553
    return new Selection(ranges, primIndex)
4554
  }
4555
 
4556
  function simpleSelection(anchor, head) {
4557
    return new Selection([new Range(anchor, head || anchor)], 0)
4558
  }
4559
 
4560
  // Compute the position of the end of a change (its 'to' property
4561
  // refers to the pre-change end).
4562
  function changeEnd(change) {
4563
    if (!change.text) { return change.to }
4564
    return Pos(change.from.line + change.text.length - 1,
4565
               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
4566
  }
4567
 
4568
  // Adjust a position to refer to the post-change position of the
4569
  // same text, or the end of the change if the change covers it.
4570
  function adjustForChange(pos, change) {
4571
    if (cmp(pos, change.from) < 0) { return pos }
4572
    if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
4573
 
4574
    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4575
    if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
4576
    return Pos(line, ch)
4577
  }
4578
 
4579
  function computeSelAfterChange(doc, change) {
4580
    var out = [];
4581
    for (var i = 0; i < doc.sel.ranges.length; i++) {
4582
      var range = doc.sel.ranges[i];
4583
      out.push(new Range(adjustForChange(range.anchor, change),
4584
                         adjustForChange(range.head, change)));
4585
    }
4586
    return normalizeSelection(doc.cm, out, doc.sel.primIndex)
4587
  }
4588
 
4589
  function offsetPos(pos, old, nw) {
4590
    if (pos.line == old.line)
4591
      { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
4592
    else
4593
      { return Pos(nw.line + (pos.line - old.line), pos.ch) }
4594
  }
4595
 
4596
  // Used by replaceSelections to allow moving the selection to the
4597
  // start or around the replaced test. Hint may be "start" or "around".
4598
  function computeReplacedSel(doc, changes, hint) {
4599
    var out = [];
4600
    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4601
    for (var i = 0; i < changes.length; i++) {
4602
      var change = changes[i];
4603
      var from = offsetPos(change.from, oldPrev, newPrev);
4604
      var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4605
      oldPrev = change.to;
4606
      newPrev = to;
4607
      if (hint == "around") {
4608
        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4609
        out[i] = new Range(inv ? to : from, inv ? from : to);
4610
      } else {
4611
        out[i] = new Range(from, from);
4612
      }
4613
    }
4614
    return new Selection(out, doc.sel.primIndex)
4615
  }
4616
 
4617
  // Used to get the editor into a consistent state again when options change.
4618
 
4619
  function loadMode(cm) {
4620
    cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
4621
    resetModeState(cm);
4622
  }
4623
 
4624
  function resetModeState(cm) {
4625
    cm.doc.iter(function (line) {
4626
      if (line.stateAfter) { line.stateAfter = null; }
4627
      if (line.styles) { line.styles = null; }
4628
    });
4629
    cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
4630
    startWorker(cm, 100);
4631
    cm.state.modeGen++;
4632
    if (cm.curOp) { regChange(cm); }
4633
  }
4634
 
4635
  // DOCUMENT DATA STRUCTURE
4636
 
4637
  // By default, updates that start and end at the beginning of a line
4638
  // are treated specially, in order to make the association of line
4639
  // widgets and marker elements with the text behave more intuitive.
4640
  function isWholeLineUpdate(doc, change) {
4641
    return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
4642
      (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
4643
  }
4644
 
4645
  // Perform a change on the document data structure.
4646
  function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
4647
    function spansFor(n) {return markedSpans ? markedSpans[n] : null}
4648
    function update(line, text, spans) {
4649
      updateLine(line, text, spans, estimateHeight$$1);
4650
      signalLater(line, "change", line, change);
4651
    }
4652
    function linesFor(start, end) {
4653
      var result = [];
4654
      for (var i = start; i < end; ++i)
4655
        { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
4656
      return result
4657
    }
4658
 
4659
    var from = change.from, to = change.to, text = change.text;
4660
    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4661
    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4662
 
4663
    // Adjust the line structure
4664
    if (change.full) {
4665
      doc.insert(0, linesFor(0, text.length));
4666
      doc.remove(text.length, doc.size - text.length);
4667
    } else if (isWholeLineUpdate(doc, change)) {
4668
      // This is a whole-line replace. Treated specially to make
4669
      // sure line objects move the way they are supposed to.
4670
      var added = linesFor(0, text.length - 1);
4671
      update(lastLine, lastLine.text, lastSpans);
4672
      if (nlines) { doc.remove(from.line, nlines); }
4673
      if (added.length) { doc.insert(from.line, added); }
4674
    } else if (firstLine == lastLine) {
4675
      if (text.length == 1) {
4676
        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4677
      } else {
4678
        var added$1 = linesFor(1, text.length - 1);
4679
        added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
4680
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4681
        doc.insert(from.line + 1, added$1);
4682
      }
4683
    } else if (text.length == 1) {
4684
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4685
      doc.remove(from.line + 1, nlines);
4686
    } else {
4687
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4688
      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4689
      var added$2 = linesFor(1, text.length - 1);
4690
      if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
4691
      doc.insert(from.line + 1, added$2);
4692
    }
4693
 
4694
    signalLater(doc, "change", doc, change);
4695
  }
4696
 
4697
  // Call f for all linked documents.
4698
  function linkedDocs(doc, f, sharedHistOnly) {
4699
    function propagate(doc, skip, sharedHist) {
4700
      if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
4701
        var rel = doc.linked[i];
4702
        if (rel.doc == skip) { continue }
4703
        var shared = sharedHist && rel.sharedHist;
4704
        if (sharedHistOnly && !shared) { continue }
4705
        f(rel.doc, shared);
4706
        propagate(rel.doc, doc, shared);
4707
      } }
4708
    }
4709
    propagate(doc, null, true);
4710
  }
4711
 
4712
  // Attach a document to an editor.
4713
  function attachDoc(cm, doc) {
4714
    if (doc.cm) { throw new Error("This document is already in use.") }
4715
    cm.doc = doc;
4716
    doc.cm = cm;
4717
    estimateLineHeights(cm);
4718
    loadMode(cm);
4719
    setDirectionClass(cm);
4720
    if (!cm.options.lineWrapping) { findMaxLine(cm); }
4721
    cm.options.mode = doc.modeOption;
4722
    regChange(cm);
4723
  }
4724
 
4725
  function setDirectionClass(cm) {
4726
  (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
4727
  }
4728
 
4729
  function directionChanged(cm) {
4730
    runInOp(cm, function () {
4731
      setDirectionClass(cm);
4732
      regChange(cm);
4733
    });
4734
  }
4735
 
4736
  function History(startGen) {
4737
    // Arrays of change events and selections. Doing something adds an
4738
    // event to done and clears undo. Undoing moves events from done
4739
    // to undone, redoing moves them in the other direction.
4740
    this.done = []; this.undone = [];
4741
    this.undoDepth = Infinity;
4742
    // Used to track when changes can be merged into a single undo
4743
    // event
4744
    this.lastModTime = this.lastSelTime = 0;
4745
    this.lastOp = this.lastSelOp = null;
4746
    this.lastOrigin = this.lastSelOrigin = null;
4747
    // Used by the isClean() method
4748
    this.generation = this.maxGeneration = startGen || 1;
4749
  }
4750
 
4751
  // Create a history change event from an updateDoc-style change
4752
  // object.
4753
  function historyChangeFromChange(doc, change) {
4754
    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
4755
    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
4756
    linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
4757
    return histChange
4758
  }
4759
 
4760
  // Pop all selection events off the end of a history array. Stop at
4761
  // a change event.
4762
  function clearSelectionEvents(array) {
4763
    while (array.length) {
4764
      var last = lst(array);
4765
      if (last.ranges) { array.pop(); }
4766
      else { break }
4767
    }
4768
  }
4769
 
4770
  // Find the top change event in the history. Pop off selection
4771
  // events that are in the way.
4772
  function lastChangeEvent(hist, force) {
4773
    if (force) {
4774
      clearSelectionEvents(hist.done);
4775
      return lst(hist.done)
4776
    } else if (hist.done.length && !lst(hist.done).ranges) {
4777
      return lst(hist.done)
4778
    } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
4779
      hist.done.pop();
4780
      return lst(hist.done)
4781
    }
4782
  }
4783
 
4784
  // Register a change in the history. Merges changes that are within
4785
  // a single operation, or are close together with an origin that
4786
  // allows merging (starting with "+") into a single event.
4787
  function addChangeToHistory(doc, change, selAfter, opId) {
4788
    var hist = doc.history;
4789
    hist.undone.length = 0;
4790
    var time = +new Date, cur;
4791
    var last;
4792
 
4793
    if ((hist.lastOp == opId ||
4794
         hist.lastOrigin == change.origin && change.origin &&
4795
         ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
4796
          change.origin.charAt(0) == "*")) &&
4797
        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
4798
      // Merge this change into the last event
4799
      last = lst(cur.changes);
4800
      if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
4801
        // Optimized case for simple insertion -- don't want to add
4802
        // new changesets for every character typed
4803
        last.to = changeEnd(change);
4804
      } else {
4805
        // Add new sub-event
4806
        cur.changes.push(historyChangeFromChange(doc, change));
4807
      }
4808
    } else {
4809
      // Can not be merged, start a new event.
4810
      var before = lst(hist.done);
4811
      if (!before || !before.ranges)
4812
        { pushSelectionToHistory(doc.sel, hist.done); }
4813
      cur = {changes: [historyChangeFromChange(doc, change)],
4814
             generation: hist.generation};
4815
      hist.done.push(cur);
4816
      while (hist.done.length > hist.undoDepth) {
4817
        hist.done.shift();
4818
        if (!hist.done[0].ranges) { hist.done.shift(); }
4819
      }
4820
    }
4821
    hist.done.push(selAfter);
4822
    hist.generation = ++hist.maxGeneration;
4823
    hist.lastModTime = hist.lastSelTime = time;
4824
    hist.lastOp = hist.lastSelOp = opId;
4825
    hist.lastOrigin = hist.lastSelOrigin = change.origin;
4826
 
4827
    if (!last) { signal(doc, "historyAdded"); }
4828
  }
4829
 
4830
  function selectionEventCanBeMerged(doc, origin, prev, sel) {
4831
    var ch = origin.charAt(0);
4832
    return ch == "*" ||
4833
      ch == "+" &&
4834
      prev.ranges.length == sel.ranges.length &&
4835
      prev.somethingSelected() == sel.somethingSelected() &&
4836
      new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
4837
  }
4838
 
4839
  // Called whenever the selection changes, sets the new selection as
4840
  // the pending selection in the history, and pushes the old pending
4841
  // selection into the 'done' array when it was significantly
4842
  // different (in number of selected ranges, emptiness, or time).
4843
  function addSelectionToHistory(doc, sel, opId, options) {
4844
    var hist = doc.history, origin = options && options.origin;
4845
 
4846
    // A new event is started when the previous origin does not match
4847
    // the current, or the origins don't allow matching. Origins
4848
    // starting with * are always merged, those starting with + are
4849
    // merged when similar and close together in time.
4850
    if (opId == hist.lastSelOp ||
4851
        (origin && hist.lastSelOrigin == origin &&
4852
         (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
4853
          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
4854
      { hist.done[hist.done.length - 1] = sel; }
4855
    else
4856
      { pushSelectionToHistory(sel, hist.done); }
4857
 
4858
    hist.lastSelTime = +new Date;
4859
    hist.lastSelOrigin = origin;
4860
    hist.lastSelOp = opId;
4861
    if (options && options.clearRedo !== false)
4862
      { clearSelectionEvents(hist.undone); }
4863
  }
4864
 
4865
  function pushSelectionToHistory(sel, dest) {
4866
    var top = lst(dest);
4867
    if (!(top && top.ranges && top.equals(sel)))
4868
      { dest.push(sel); }
4869
  }
4870
 
4871
  // Used to store marked span information in the history.
4872
  function attachLocalSpans(doc, change, from, to) {
4873
    var existing = change["spans_" + doc.id], n = 0;
4874
    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
4875
      if (line.markedSpans)
4876
        { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
4877
      ++n;
4878
    });
4879
  }
4880
 
4881
  // When un/re-doing restores text containing marked spans, those
4882
  // that have been explicitly cleared should not be restored.
4883
  function removeClearedSpans(spans) {
4884
    if (!spans) { return null }
4885
    var out;
4886
    for (var i = 0; i < spans.length; ++i) {
4887
      if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
4888
      else if (out) { out.push(spans[i]); }
4889
    }
4890
    return !out ? spans : out.length ? out : null
4891
  }
4892
 
4893
  // Retrieve and filter the old marked spans stored in a change event.
4894
  function getOldSpans(doc, change) {
4895
    var found = change["spans_" + doc.id];
4896
    if (!found) { return null }
4897
    var nw = [];
4898
    for (var i = 0; i < change.text.length; ++i)
4899
      { nw.push(removeClearedSpans(found[i])); }
4900
    return nw
4901
  }
4902
 
4903
  // Used for un/re-doing changes from the history. Combines the
4904
  // result of computing the existing spans with the set of spans that
4905
  // existed in the history (so that deleting around a span and then
4906
  // undoing brings back the span).
4907
  function mergeOldSpans(doc, change) {
4908
    var old = getOldSpans(doc, change);
4909
    var stretched = stretchSpansOverChange(doc, change);
4910
    if (!old) { return stretched }
4911
    if (!stretched) { return old }
4912
 
4913
    for (var i = 0; i < old.length; ++i) {
4914
      var oldCur = old[i], stretchCur = stretched[i];
4915
      if (oldCur && stretchCur) {
4916
        spans: for (var j = 0; j < stretchCur.length; ++j) {
4917
          var span = stretchCur[j];
4918
          for (var k = 0; k < oldCur.length; ++k)
4919
            { if (oldCur[k].marker == span.marker) { continue spans } }
4920
          oldCur.push(span);
4921
        }
4922
      } else if (stretchCur) {
4923
        old[i] = stretchCur;
4924
      }
4925
    }
4926
    return old
4927
  }
4928
 
4929
  // Used both to provide a JSON-safe object in .getHistory, and, when
4930
  // detaching a document, to split the history in two
4931
  function copyHistoryArray(events, newGroup, instantiateSel) {
4932
    var copy = [];
4933
    for (var i = 0; i < events.length; ++i) {
4934
      var event = events[i];
4935
      if (event.ranges) {
4936
        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
4937
        continue
4938
      }
4939
      var changes = event.changes, newChanges = [];
4940
      copy.push({changes: newChanges});
4941
      for (var j = 0; j < changes.length; ++j) {
4942
        var change = changes[j], m = (void 0);
4943
        newChanges.push({from: change.from, to: change.to, text: change.text});
4944
        if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
4945
          if (indexOf(newGroup, Number(m[1])) > -1) {
4946
            lst(newChanges)[prop] = change[prop];
4947
            delete change[prop];
4948
          }
4949
        } } }
4950
      }
4951
    }
4952
    return copy
4953
  }
4954
 
4955
  // The 'scroll' parameter given to many of these indicated whether
4956
  // the new cursor position should be scrolled into view after
4957
  // modifying the selection.
4958
 
4959
  // If shift is held or the extend flag is set, extends a range to
4960
  // include a given position (and optionally a second position).
4961
  // Otherwise, simply returns the range between the given positions.
4962
  // Used for cursor motion and such.
4963
  function extendRange(range, head, other, extend) {
4964
    if (extend) {
4965
      var anchor = range.anchor;
4966
      if (other) {
4967
        var posBefore = cmp(head, anchor) < 0;
4968
        if (posBefore != (cmp(other, anchor) < 0)) {
4969
          anchor = head;
4970
          head = other;
4971
        } else if (posBefore != (cmp(head, other) < 0)) {
4972
          head = other;
4973
        }
4974
      }
4975
      return new Range(anchor, head)
4976
    } else {
4977
      return new Range(other || head, head)
4978
    }
4979
  }
4980
 
4981
  // Extend the primary selection range, discard the rest.
4982
  function extendSelection(doc, head, other, options, extend) {
4983
    if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
4984
    setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
4985
  }
4986
 
4987
  // Extend all selections (pos is an array of selections with length
4988
  // equal the number of selections)
4989
  function extendSelections(doc, heads, options) {
4990
    var out = [];
4991
    var extend = doc.cm && (doc.cm.display.shift || doc.extend);
4992
    for (var i = 0; i < doc.sel.ranges.length; i++)
4993
      { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
4994
    var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
4995
    setSelection(doc, newSel, options);
4996
  }
4997
 
4998
  // Updates a single range in the selection.
4999
  function replaceOneSelection(doc, i, range, options) {
5000
    var ranges = doc.sel.ranges.slice(0);
5001
    ranges[i] = range;
5002
    setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
5003
  }
5004
 
5005
  // Reset the selection to a single range.
5006
  function setSimpleSelection(doc, anchor, head, options) {
5007
    setSelection(doc, simpleSelection(anchor, head), options);
5008
  }
5009
 
5010
  // Give beforeSelectionChange handlers a change to influence a
5011
  // selection update.
5012
  function filterSelectionChange(doc, sel, options) {
5013
    var obj = {
5014
      ranges: sel.ranges,
5015
      update: function(ranges) {
5016
        this.ranges = [];
5017
        for (var i = 0; i < ranges.length; i++)
5018
          { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
5019
                                     clipPos(doc, ranges[i].head)); }
5020
      },
5021
      origin: options && options.origin
5022
    };
5023
    signal(doc, "beforeSelectionChange", doc, obj);
5024
    if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
5025
    if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
5026
    else { return sel }
5027
  }
5028
 
5029
  function setSelectionReplaceHistory(doc, sel, options) {
5030
    var done = doc.history.done, last = lst(done);
5031
    if (last && last.ranges) {
5032
      done[done.length - 1] = sel;
5033
      setSelectionNoUndo(doc, sel, options);
5034
    } else {
5035
      setSelection(doc, sel, options);
5036
    }
5037
  }
5038
 
5039
  // Set a new selection.
5040
  function setSelection(doc, sel, options) {
5041
    setSelectionNoUndo(doc, sel, options);
5042
    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
5043
  }
5044
 
5045
  function setSelectionNoUndo(doc, sel, options) {
5046
    if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
5047
      { sel = filterSelectionChange(doc, sel, options); }
5048
 
5049
    var bias = options && options.bias ||
5050
      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
5051
    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
5052
 
5053
    if (!(options && options.scroll === false) && doc.cm)
5054
      { ensureCursorVisible(doc.cm); }
5055
  }
5056
 
5057
  function setSelectionInner(doc, sel) {
5058
    if (sel.equals(doc.sel)) { return }
5059
 
5060
    doc.sel = sel;
5061
 
5062
    if (doc.cm) {
5063
      doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
5064
      signalCursorActivity(doc.cm);
5065
    }
5066
    signalLater(doc, "cursorActivity", doc);
5067
  }
5068
 
5069
  // Verify that the selection does not partially select any atomic
5070
  // marked ranges.
5071
  function reCheckSelection(doc) {
5072
    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
5073
  }
5074
 
5075
  // Return a selection that does not partially select any atomic
5076
  // ranges.
5077
  function skipAtomicInSelection(doc, sel, bias, mayClear) {
5078
    var out;
5079
    for (var i = 0; i < sel.ranges.length; i++) {
5080
      var range = sel.ranges[i];
5081
      var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
5082
      var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
5083
      var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
5084
      if (out || newAnchor != range.anchor || newHead != range.head) {
5085
        if (!out) { out = sel.ranges.slice(0, i); }
5086
        out[i] = new Range(newAnchor, newHead);
5087
      }
5088
    }
5089
    return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
5090
  }
5091
 
5092
  function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
5093
    var line = getLine(doc, pos.line);
5094
    if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
5095
      var sp = line.markedSpans[i], m = sp.marker;
5096
      if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
5097
          (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
5098
        if (mayClear) {
5099
          signal(m, "beforeCursorEnter");
5100
          if (m.explicitlyCleared) {
5101
            if (!line.markedSpans) { break }
5102
            else {--i; continue}
5103
          }
5104
        }
5105
        if (!m.atomic) { continue }
5106
 
5107
        if (oldPos) {
5108
          var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
5109
          if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
5110
            { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
5111
          if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
5112
            { return skipAtomicInner(doc, near, pos, dir, mayClear) }
5113
        }
5114
 
5115
        var far = m.find(dir < 0 ? -1 : 1);
5116
        if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
5117
          { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
5118
        return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
5119
      }
5120
    } }
5121
    return pos
5122
  }
5123
 
5124
  // Ensure a given position is not inside an atomic range.
5125
  function skipAtomic(doc, pos, oldPos, bias, mayClear) {
5126
    var dir = bias || 1;
5127
    var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
5128
        (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
5129
        skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
5130
        (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
5131
    if (!found) {
5132
      doc.cantEdit = true;
5133
      return Pos(doc.first, 0)
5134
    }
5135
    return found
5136
  }
5137
 
5138
  function movePos(doc, pos, dir, line) {
5139
    if (dir < 0 && pos.ch == 0) {
5140
      if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
5141
      else { return null }
5142
    } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
5143
      if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
5144
      else { return null }
5145
    } else {
5146
      return new Pos(pos.line, pos.ch + dir)
5147
    }
5148
  }
5149
 
5150
  function selectAll(cm) {
5151
    cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
5152
  }
5153
 
5154
  // UPDATING
5155
 
5156
  // Allow "beforeChange" event handlers to influence a change
5157
  function filterChange(doc, change, update) {
5158
    var obj = {
5159
      canceled: false,
5160
      from: change.from,
5161
      to: change.to,
5162
      text: change.text,
5163
      origin: change.origin,
5164
      cancel: function () { return obj.canceled = true; }
5165
    };
5166
    if (update) { obj.update = function (from, to, text, origin) {
5167
      if (from) { obj.from = clipPos(doc, from); }
5168
      if (to) { obj.to = clipPos(doc, to); }
5169
      if (text) { obj.text = text; }
5170
      if (origin !== undefined) { obj.origin = origin; }
5171
    }; }
5172
    signal(doc, "beforeChange", doc, obj);
5173
    if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
5174
 
5175
    if (obj.canceled) { return null }
5176
    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
5177
  }
5178
 
5179
  // Apply a change to a document, and add it to the document's
5180
  // history, and propagating it to all linked documents.
5181
  function makeChange(doc, change, ignoreReadOnly) {
5182
    if (doc.cm) {
5183
      if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
5184
      if (doc.cm.state.suppressEdits) { return }
5185
    }
5186
 
5187
    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
5188
      change = filterChange(doc, change, true);
5189
      if (!change) { return }
5190
    }
5191
 
5192
    // Possibly split or suppress the update based on the presence
5193
    // of read-only spans in its range.
5194
    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
5195
    if (split) {
5196
      for (var i = split.length - 1; i >= 0; --i)
5197
        { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
5198
    } else {
5199
      makeChangeInner(doc, change);
5200
    }
5201
  }
5202
 
5203
  function makeChangeInner(doc, change) {
5204
    if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
5205
    var selAfter = computeSelAfterChange(doc, change);
5206
    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
5207
 
5208
    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
5209
    var rebased = [];
5210
 
5211
    linkedDocs(doc, function (doc, sharedHist) {
5212
      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5213
        rebaseHist(doc.history, change);
5214
        rebased.push(doc.history);
5215
      }
5216
      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
5217
    });
5218
  }
5219
 
5220
  // Revert a change stored in a document's history.
5221
  function makeChangeFromHistory(doc, type, allowSelectionOnly) {
5222
    var suppress = doc.cm && doc.cm.state.suppressEdits;
5223
    if (suppress && !allowSelectionOnly) { return }
5224
 
5225
    var hist = doc.history, event, selAfter = doc.sel;
5226
    var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
5227
 
5228
    // Verify that there is a useable event (so that ctrl-z won't
5229
    // needlessly clear selection events)
5230
    var i = 0;
5231
    for (; i < source.length; i++) {
5232
      event = source[i];
5233
      if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
5234
        { break }
5235
    }
5236
    if (i == source.length) { return }
5237
    hist.lastOrigin = hist.lastSelOrigin = null;
5238
 
5239
    for (;;) {
5240
      event = source.pop();
5241
      if (event.ranges) {
5242
        pushSelectionToHistory(event, dest);
5243
        if (allowSelectionOnly && !event.equals(doc.sel)) {
5244
          setSelection(doc, event, {clearRedo: false});
5245
          return
5246
        }
5247
        selAfter = event;
5248
      } else if (suppress) {
5249
        source.push(event);
5250
        return
5251
      } else { break }
5252
    }
5253
 
5254
    // Build up a reverse change object to add to the opposite history
5255
    // stack (redo when undoing, and vice versa).
5256
    var antiChanges = [];
5257
    pushSelectionToHistory(selAfter, dest);
5258
    dest.push({changes: antiChanges, generation: hist.generation});
5259
    hist.generation = event.generation || ++hist.maxGeneration;
5260
 
5261
    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
5262
 
5263
    var loop = function ( i ) {
5264
      var change = event.changes[i];
5265
      change.origin = type;
5266
      if (filter && !filterChange(doc, change, false)) {
5267
        source.length = 0;
5268
        return {}
5269
      }
5270
 
5271
      antiChanges.push(historyChangeFromChange(doc, change));
5272
 
5273
      var after = i ? computeSelAfterChange(doc, change) : lst(source);
5274
      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
5275
      if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
5276
      var rebased = [];
5277
 
5278
      // Propagate to the linked documents
5279
      linkedDocs(doc, function (doc, sharedHist) {
5280
        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5281
          rebaseHist(doc.history, change);
5282
          rebased.push(doc.history);
5283
        }
5284
        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
5285
      });
5286
    };
5287
 
5288
    for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
5289
      var returned = loop( i$1 );
5290
 
5291
      if ( returned ) return returned.v;
5292
    }
5293
  }
5294
 
5295
  // Sub-views need their line numbers shifted when text is added
5296
  // above or below them in the parent document.
5297
  function shiftDoc(doc, distance) {
5298
    if (distance == 0) { return }
5299
    doc.first += distance;
5300
    doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
5301
      Pos(range.anchor.line + distance, range.anchor.ch),
5302
      Pos(range.head.line + distance, range.head.ch)
5303
    ); }), doc.sel.primIndex);
5304
    if (doc.cm) {
5305
      regChange(doc.cm, doc.first, doc.first - distance, distance);
5306
      for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
5307
        { regLineChange(doc.cm, l, "gutter"); }
5308
    }
5309
  }
5310
 
5311
  // More lower-level change function, handling only a single document
5312
  // (not linked ones).
5313
  function makeChangeSingleDoc(doc, change, selAfter, spans) {
5314
    if (doc.cm && !doc.cm.curOp)
5315
      { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
5316
 
5317
    if (change.to.line < doc.first) {
5318
      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
5319
      return
5320
    }
5321
    if (change.from.line > doc.lastLine()) { return }
5322
 
5323
    // Clip the change to the size of this doc
5324
    if (change.from.line < doc.first) {
5325
      var shift = change.text.length - 1 - (doc.first - change.from.line);
5326
      shiftDoc(doc, shift);
5327
      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
5328
                text: [lst(change.text)], origin: change.origin};
5329
    }
5330
    var last = doc.lastLine();
5331
    if (change.to.line > last) {
5332
      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
5333
                text: [change.text[0]], origin: change.origin};
5334
    }
5335
 
5336
    change.removed = getBetween(doc, change.from, change.to);
5337
 
5338
    if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
5339
    if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
5340
    else { updateDoc(doc, change, spans); }
5341
    setSelectionNoUndo(doc, selAfter, sel_dontScroll);
5342
  }
5343
 
5344
  // Handle the interaction of a change to a document with the editor
5345
  // that this document is part of.
5346
  function makeChangeSingleDocInEditor(cm, change, spans) {
5347
    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
5348
 
5349
    var recomputeMaxLength = false, checkWidthStart = from.line;
5350
    if (!cm.options.lineWrapping) {
5351
      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
5352
      doc.iter(checkWidthStart, to.line + 1, function (line) {
5353
        if (line == display.maxLine) {
5354
          recomputeMaxLength = true;
5355
          return true
5356
        }
5357
      });
5358
    }
5359
 
5360
    if (doc.sel.contains(change.from, change.to) > -1)
5361
      { signalCursorActivity(cm); }
5362
 
5363
    updateDoc(doc, change, spans, estimateHeight(cm));
5364
 
5365
    if (!cm.options.lineWrapping) {
5366
      doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
5367
        var len = lineLength(line);
5368
        if (len > display.maxLineLength) {
5369
          display.maxLine = line;
5370
          display.maxLineLength = len;
5371
          display.maxLineChanged = true;
5372
          recomputeMaxLength = false;
5373
        }
5374
      });
5375
      if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
5376
    }
5377
 
5378
    retreatFrontier(doc, from.line);
5379
    startWorker(cm, 400);
5380
 
5381
    var lendiff = change.text.length - (to.line - from.line) - 1;
5382
    // Remember that these lines changed, for updating the display
5383
    if (change.full)
5384
      { regChange(cm); }
5385
    else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
5386
      { regLineChange(cm, from.line, "text"); }
5387
    else
5388
      { regChange(cm, from.line, to.line + 1, lendiff); }
5389
 
5390
    var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
5391
    if (changeHandler || changesHandler) {
5392
      var obj = {
5393
        from: from, to: to,
5394
        text: change.text,
5395
        removed: change.removed,
5396
        origin: change.origin
5397
      };
5398
      if (changeHandler) { signalLater(cm, "change", cm, obj); }
5399
      if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
5400
    }
5401
    cm.display.selForContextMenu = null;
5402
  }
5403
 
5404
  function replaceRange(doc, code, from, to, origin) {
5405
    var assign;
5406
 
5407
    if (!to) { to = from; }
5408
    if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
5409
    if (typeof code == "string") { code = doc.splitLines(code); }
5410
    makeChange(doc, {from: from, to: to, text: code, origin: origin});
5411
  }
5412
 
5413
  // Rebasing/resetting history to deal with externally-sourced changes
5414
 
5415
  function rebaseHistSelSingle(pos, from, to, diff) {
5416
    if (to < pos.line) {
5417
      pos.line += diff;
5418
    } else if (from < pos.line) {
5419
      pos.line = from;
5420
      pos.ch = 0;
5421
    }
5422
  }
5423
 
5424
  // Tries to rebase an array of history events given a change in the
5425
  // document. If the change touches the same lines as the event, the
5426
  // event, and everything 'behind' it, is discarded. If the change is
5427
  // before the event, the event's positions are updated. Uses a
5428
  // copy-on-write scheme for the positions, to avoid having to
5429
  // reallocate them all on every rebase, but also avoid problems with
5430
  // shared position objects being unsafely updated.
5431
  function rebaseHistArray(array, from, to, diff) {
5432
    for (var i = 0; i < array.length; ++i) {
5433
      var sub = array[i], ok = true;
5434
      if (sub.ranges) {
5435
        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
5436
        for (var j = 0; j < sub.ranges.length; j++) {
5437
          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
5438
          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
5439
        }
5440
        continue
5441
      }
5442
      for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
5443
        var cur = sub.changes[j$1];
5444
        if (to < cur.from.line) {
5445
          cur.from = Pos(cur.from.line + diff, cur.from.ch);
5446
          cur.to = Pos(cur.to.line + diff, cur.to.ch);
5447
        } else if (from <= cur.to.line) {
5448
          ok = false;
5449
          break
5450
        }
5451
      }
5452
      if (!ok) {
5453
        array.splice(0, i + 1);
5454
        i = 0;
5455
      }
5456
    }
5457
  }
5458
 
5459
  function rebaseHist(hist, change) {
5460
    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5461
    rebaseHistArray(hist.done, from, to, diff);
5462
    rebaseHistArray(hist.undone, from, to, diff);
5463
  }
5464
 
5465
  // Utility for applying a change to a line by handle or number,
5466
  // returning the number and optionally registering the line as
5467
  // changed.
5468
  function changeLine(doc, handle, changeType, op) {
5469
    var no = handle, line = handle;
5470
    if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
5471
    else { no = lineNo(handle); }
5472
    if (no == null) { return null }
5473
    if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
5474
    return line
5475
  }
5476
 
5477
  // The document is represented as a BTree consisting of leaves, with
5478
  // chunk of lines in them, and branches, with up to ten leaves or
5479
  // other branch nodes below them. The top node is always a branch
5480
  // node, and is the document object itself (meaning it has
5481
  // additional methods and properties).
5482
  //
5483
  // All nodes have parent links. The tree is used both to go from
5484
  // line numbers to line objects, and to go from objects to numbers.
5485
  // It also indexes by height, and is used to convert between height
5486
  // and line object, and to find the total height of the document.
5487
  //
5488
  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
5489
 
5490
  function LeafChunk(lines) {
5491
    this.lines = lines;
5492
    this.parent = null;
5493
    var height = 0;
5494
    for (var i = 0; i < lines.length; ++i) {
5495
      lines[i].parent = this;
5496
      height += lines[i].height;
5497
    }
5498
    this.height = height;
5499
  }
5500
 
5501
  LeafChunk.prototype = {
5502
    chunkSize: function() { return this.lines.length },
5503
 
5504
    // Remove the n lines at offset 'at'.
5505
    removeInner: function(at, n) {
5506
      for (var i = at, e = at + n; i < e; ++i) {
5507
        var line = this.lines[i];
5508
        this.height -= line.height;
5509
        cleanUpLine(line);
5510
        signalLater(line, "delete");
5511
      }
5512
      this.lines.splice(at, n);
5513
    },
5514
 
5515
    // Helper used to collapse a small branch into a single leaf.
5516
    collapse: function(lines) {
5517
      lines.push.apply(lines, this.lines);
5518
    },
5519
 
5520
    // Insert the given array of lines at offset 'at', count them as
5521
    // having the given height.
5522
    insertInner: function(at, lines, height) {
5523
      this.height += height;
5524
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
5525
      for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
5526
    },
5527
 
5528
    // Used to iterate over a part of the tree.
5529
    iterN: function(at, n, op) {
5530
      for (var e = at + n; at < e; ++at)
5531
        { if (op(this.lines[at])) { return true } }
5532
    }
5533
  };
5534
 
5535
  function BranchChunk(children) {
5536
    this.children = children;
5537
    var size = 0, height = 0;
5538
    for (var i = 0; i < children.length; ++i) {
5539
      var ch = children[i];
5540
      size += ch.chunkSize(); height += ch.height;
5541
      ch.parent = this;
5542
    }
5543
    this.size = size;
5544
    this.height = height;
5545
    this.parent = null;
5546
  }
5547
 
5548
  BranchChunk.prototype = {
5549
    chunkSize: function() { return this.size },
5550
 
5551
    removeInner: function(at, n) {
5552
      this.size -= n;
5553
      for (var i = 0; i < this.children.length; ++i) {
5554
        var child = this.children[i], sz = child.chunkSize();
5555
        if (at < sz) {
5556
          var rm = Math.min(n, sz - at), oldHeight = child.height;
5557
          child.removeInner(at, rm);
5558
          this.height -= oldHeight - child.height;
5559
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
5560
          if ((n -= rm) == 0) { break }
5561
          at = 0;
5562
        } else { at -= sz; }
5563
      }
5564
      // If the result is smaller than 25 lines, ensure that it is a
5565
      // single leaf node.
5566
      if (this.size - n < 25 &&
5567
          (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
5568
        var lines = [];
5569
        this.collapse(lines);
5570
        this.children = [new LeafChunk(lines)];
5571
        this.children[0].parent = this;
5572
      }
5573
    },
5574
 
5575
    collapse: function(lines) {
5576
      for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
5577
    },
5578
 
5579
    insertInner: function(at, lines, height) {
5580
      this.size += lines.length;
5581
      this.height += height;
5582
      for (var i = 0; i < this.children.length; ++i) {
5583
        var child = this.children[i], sz = child.chunkSize();
5584
        if (at <= sz) {
5585
          child.insertInner(at, lines, height);
5586
          if (child.lines && child.lines.length > 50) {
5587
            // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
5588
            // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
5589
            var remaining = child.lines.length % 25 + 25;
5590
            for (var pos = remaining; pos < child.lines.length;) {
5591
              var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
5592
              child.height -= leaf.height;
5593
              this.children.splice(++i, 0, leaf);
5594
              leaf.parent = this;
5595
            }
5596
            child.lines = child.lines.slice(0, remaining);
5597
            this.maybeSpill();
5598
          }
5599
          break
5600
        }
5601
        at -= sz;
5602
      }
5603
    },
5604
 
5605
    // When a node has grown, check whether it should be split.
5606
    maybeSpill: function() {
5607
      if (this.children.length <= 10) { return }
5608
      var me = this;
5609
      do {
5610
        var spilled = me.children.splice(me.children.length - 5, 5);
5611
        var sibling = new BranchChunk(spilled);
5612
        if (!me.parent) { // Become the parent node
5613
          var copy = new BranchChunk(me.children);
5614
          copy.parent = me;
5615
          me.children = [copy, sibling];
5616
          me = copy;
5617
       } else {
5618
          me.size -= sibling.size;
5619
          me.height -= sibling.height;
5620
          var myIndex = indexOf(me.parent.children, me);
5621
          me.parent.children.splice(myIndex + 1, 0, sibling);
5622
        }
5623
        sibling.parent = me.parent;
5624
      } while (me.children.length > 10)
5625
      me.parent.maybeSpill();
5626
    },
5627
 
5628
    iterN: function(at, n, op) {
5629
      for (var i = 0; i < this.children.length; ++i) {
5630
        var child = this.children[i], sz = child.chunkSize();
5631
        if (at < sz) {
5632
          var used = Math.min(n, sz - at);
5633
          if (child.iterN(at, used, op)) { return true }
5634
          if ((n -= used) == 0) { break }
5635
          at = 0;
5636
        } else { at -= sz; }
5637
      }
5638
    }
5639
  };
5640
 
5641
  // Line widgets are block elements displayed above or below a line.
5642
 
5643
  var LineWidget = function(doc, node, options) {
5644
    if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
5645
      { this[opt] = options[opt]; } } }
5646
    this.doc = doc;
5647
    this.node = node;
5648
  };
5649
 
5650
  LineWidget.prototype.clear = function () {
5651
    var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
5652
    if (no == null || !ws) { return }
5653
    for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
5654
    if (!ws.length) { line.widgets = null; }
5655
    var height = widgetHeight(this);
5656
    updateLineHeight(line, Math.max(0, line.height - height));
5657
    if (cm) {
5658
      runInOp(cm, function () {
5659
        adjustScrollWhenAboveVisible(cm, line, -height);
5660
        regLineChange(cm, no, "widget");
5661
      });
5662
      signalLater(cm, "lineWidgetCleared", cm, this, no);
5663
    }
5664
  };
5665
 
5666
  LineWidget.prototype.changed = function () {
5667
      var this$1 = this;
5668
 
5669
    var oldH = this.height, cm = this.doc.cm, line = this.line;
5670
    this.height = null;
5671
    var diff = widgetHeight(this) - oldH;
5672
    if (!diff) { return }
5673
    if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
5674
    if (cm) {
5675
      runInOp(cm, function () {
5676
        cm.curOp.forceUpdate = true;
5677
        adjustScrollWhenAboveVisible(cm, line, diff);
5678
        signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
5679
      });
5680
    }
5681
  };
5682
  eventMixin(LineWidget);
5683
 
5684
  function adjustScrollWhenAboveVisible(cm, line, diff) {
5685
    if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
5686
      { addToScrollTop(cm, diff); }
5687
  }
5688
 
5689
  function addLineWidget(doc, handle, node, options) {
5690
    var widget = new LineWidget(doc, node, options);
5691
    var cm = doc.cm;
5692
    if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
5693
    changeLine(doc, handle, "widget", function (line) {
5694
      var widgets = line.widgets || (line.widgets = []);
5695
      if (widget.insertAt == null) { widgets.push(widget); }
5696
      else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
5697
      widget.line = line;
5698
      if (cm && !lineIsHidden(doc, line)) {
5699
        var aboveVisible = heightAtLine(line) < doc.scrollTop;
5700
        updateLineHeight(line, line.height + widgetHeight(widget));
5701
        if (aboveVisible) { addToScrollTop(cm, widget.height); }
5702
        cm.curOp.forceUpdate = true;
5703
      }
5704
      return true
5705
    });
5706
    if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
5707
    return widget
5708
  }
5709
 
5710
  // TEXTMARKERS
5711
 
5712
  // Created with markText and setBookmark methods. A TextMarker is a
5713
  // handle that can be used to clear or find a marked position in the
5714
  // document. Line objects hold arrays (markedSpans) containing
5715
  // {from, to, marker} object pointing to such marker objects, and
5716
  // indicating that such a marker is present on that line. Multiple
5717
  // lines may point to the same marker when it spans across lines.
5718
  // The spans will have null for their from/to properties when the
5719
  // marker continues beyond the start/end of the line. Markers have
5720
  // links back to the lines they currently touch.
5721
 
5722
  // Collapsed markers have unique ids, in order to be able to order
5723
  // them, which is needed for uniquely determining an outer marker
5724
  // when they overlap (they may nest, but not partially overlap).
5725
  var nextMarkerId = 0;
5726
 
5727
  var TextMarker = function(doc, type) {
5728
    this.lines = [];
5729
    this.type = type;
5730
    this.doc = doc;
5731
    this.id = ++nextMarkerId;
5732
  };
5733
 
5734
  // Clear the marker.
5735
  TextMarker.prototype.clear = function () {
5736
    if (this.explicitlyCleared) { return }
5737
    var cm = this.doc.cm, withOp = cm && !cm.curOp;
5738
    if (withOp) { startOperation(cm); }
5739
    if (hasHandler(this, "clear")) {
5740
      var found = this.find();
5741
      if (found) { signalLater(this, "clear", found.from, found.to); }
5742
    }
5743
    var min = null, max = null;
5744
    for (var i = 0; i < this.lines.length; ++i) {
5745
      var line = this.lines[i];
5746
      var span = getMarkedSpanFor(line.markedSpans, this);
5747
      if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
5748
      else if (cm) {
5749
        if (span.to != null) { max = lineNo(line); }
5750
        if (span.from != null) { min = lineNo(line); }
5751
      }
5752
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
5753
      if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
5754
        { updateLineHeight(line, textHeight(cm.display)); }
5755
    }
5756
    if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
5757
      var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
5758
      if (len > cm.display.maxLineLength) {
5759
        cm.display.maxLine = visual;
5760
        cm.display.maxLineLength = len;
5761
        cm.display.maxLineChanged = true;
5762
      }
5763
    } }
5764
 
5765
    if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
5766
    this.lines.length = 0;
5767
    this.explicitlyCleared = true;
5768
    if (this.atomic && this.doc.cantEdit) {
5769
      this.doc.cantEdit = false;
5770
      if (cm) { reCheckSelection(cm.doc); }
5771
    }
5772
    if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
5773
    if (withOp) { endOperation(cm); }
5774
    if (this.parent) { this.parent.clear(); }
5775
  };
5776
 
5777
  // Find the position of the marker in the document. Returns a {from,
5778
  // to} object by default. Side can be passed to get a specific side
5779
  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
5780
  // Pos objects returned contain a line object, rather than a line
5781
  // number (used to prevent looking up the same line twice).
5782
  TextMarker.prototype.find = function (side, lineObj) {
5783
    if (side == null && this.type == "bookmark") { side = 1; }
5784
    var from, to;
5785
    for (var i = 0; i < this.lines.length; ++i) {
5786
      var line = this.lines[i];
5787
      var span = getMarkedSpanFor(line.markedSpans, this);
5788
      if (span.from != null) {
5789
        from = Pos(lineObj ? line : lineNo(line), span.from);
5790
        if (side == -1) { return from }
5791
      }
5792
      if (span.to != null) {
5793
        to = Pos(lineObj ? line : lineNo(line), span.to);
5794
        if (side == 1) { return to }
5795
      }
5796
    }
5797
    return from && {from: from, to: to}
5798
  };
5799
 
5800
  // Signals that the marker's widget changed, and surrounding layout
5801
  // should be recomputed.
5802
  TextMarker.prototype.changed = function () {
5803
      var this$1 = this;
5804
 
5805
    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
5806
    if (!pos || !cm) { return }
5807
    runInOp(cm, function () {
5808
      var line = pos.line, lineN = lineNo(pos.line);
5809
      var view = findViewForLine(cm, lineN);
5810
      if (view) {
5811
        clearLineMeasurementCacheFor(view);
5812
        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
5813
      }
5814
      cm.curOp.updateMaxLine = true;
5815
      if (!lineIsHidden(widget.doc, line) && widget.height != null) {
5816
        var oldHeight = widget.height;
5817
        widget.height = null;
5818
        var dHeight = widgetHeight(widget) - oldHeight;
5819
        if (dHeight)
5820
          { updateLineHeight(line, line.height + dHeight); }
5821
      }
5822
      signalLater(cm, "markerChanged", cm, this$1);
5823
    });
5824
  };
5825
 
5826
  TextMarker.prototype.attachLine = function (line) {
5827
    if (!this.lines.length && this.doc.cm) {
5828
      var op = this.doc.cm.curOp;
5829
      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
5830
        { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
5831
    }
5832
    this.lines.push(line);
5833
  };
5834
 
5835
  TextMarker.prototype.detachLine = function (line) {
5836
    this.lines.splice(indexOf(this.lines, line), 1);
5837
    if (!this.lines.length && this.doc.cm) {
5838
      var op = this.doc.cm.curOp
5839
      ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
5840
    }
5841
  };
5842
  eventMixin(TextMarker);
5843
 
5844
  // Create a marker, wire it up to the right lines, and
5845
  function markText(doc, from, to, options, type) {
5846
    // Shared markers (across linked documents) are handled separately
5847
    // (markTextShared will call out to this again, once per
5848
    // document).
5849
    if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
5850
    // Ensure we are in an operation.
5851
    if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
5852
 
5853
    var marker = new TextMarker(doc, type), diff = cmp(from, to);
5854
    if (options) { copyObj(options, marker, false); }
5855
    // Don't connect empty markers unless clearWhenEmpty is false
5856
    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
5857
      { return marker }
5858
    if (marker.replacedWith) {
5859
      // Showing up as a widget implies collapsed (widget replaces text)
5860
      marker.collapsed = true;
5861
      marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
5862
      if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
5863
      if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
5864
    }
5865
    if (marker.collapsed) {
5866
      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
5867
          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
5868
        { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
5869
      seeCollapsedSpans();
5870
    }
5871
 
5872
    if (marker.addToHistory)
5873
      { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
5874
 
5875
    var curLine = from.line, cm = doc.cm, updateMaxLine;
5876
    doc.iter(curLine, to.line + 1, function (line) {
5877
      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
5878
        { updateMaxLine = true; }
5879
      if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
5880
      addMarkedSpan(line, new MarkedSpan(marker,
5881
                                         curLine == from.line ? from.ch : null,
5882
                                         curLine == to.line ? to.ch : null));
5883
      ++curLine;
5884
    });
5885
    // lineIsHidden depends on the presence of the spans, so needs a second pass
5886
    if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
5887
      if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
5888
    }); }
5889
 
5890
    if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
5891
 
5892
    if (marker.readOnly) {
5893
      seeReadOnlySpans();
5894
      if (doc.history.done.length || doc.history.undone.length)
5895
        { doc.clearHistory(); }
5896
    }
5897
    if (marker.collapsed) {
5898
      marker.id = ++nextMarkerId;
5899
      marker.atomic = true;
5900
    }
5901
    if (cm) {
5902
      // Sync editor state
5903
      if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
5904
      if (marker.collapsed)
5905
        { regChange(cm, from.line, to.line + 1); }
5906
      else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
5907
        { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
5908
      if (marker.atomic) { reCheckSelection(cm.doc); }
5909
      signalLater(cm, "markerAdded", cm, marker);
5910
    }
5911
    return marker
5912
  }
5913
 
5914
  // SHARED TEXTMARKERS
5915
 
5916
  // A shared marker spans multiple linked documents. It is
5917
  // implemented as a meta-marker-object controlling multiple normal
5918
  // markers.
5919
  var SharedTextMarker = function(markers, primary) {
5920
    this.markers = markers;
5921
    this.primary = primary;
5922
    for (var i = 0; i < markers.length; ++i)
5923
      { markers[i].parent = this; }
5924
  };
5925
 
5926
  SharedTextMarker.prototype.clear = function () {
5927
    if (this.explicitlyCleared) { return }
5928
    this.explicitlyCleared = true;
5929
    for (var i = 0; i < this.markers.length; ++i)
5930
      { this.markers[i].clear(); }
5931
    signalLater(this, "clear");
5932
  };
5933
 
5934
  SharedTextMarker.prototype.find = function (side, lineObj) {
5935
    return this.primary.find(side, lineObj)
5936
  };
5937
  eventMixin(SharedTextMarker);
5938
 
5939
  function markTextShared(doc, from, to, options, type) {
5940
    options = copyObj(options);
5941
    options.shared = false;
5942
    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
5943
    var widget = options.widgetNode;
5944
    linkedDocs(doc, function (doc) {
5945
      if (widget) { options.widgetNode = widget.cloneNode(true); }
5946
      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
5947
      for (var i = 0; i < doc.linked.length; ++i)
5948
        { if (doc.linked[i].isParent) { return } }
5949
      primary = lst(markers);
5950
    });
5951
    return new SharedTextMarker(markers, primary)
5952
  }
5953
 
5954
  function findSharedMarkers(doc) {
5955
    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
5956
  }
5957
 
5958
  function copySharedMarkers(doc, markers) {
5959
    for (var i = 0; i < markers.length; i++) {
5960
      var marker = markers[i], pos = marker.find();
5961
      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
5962
      if (cmp(mFrom, mTo)) {
5963
        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
5964
        marker.markers.push(subMark);
5965
        subMark.parent = marker;
5966
      }
5967
    }
5968
  }
5969
 
5970
  function detachSharedMarkers(markers) {
5971
    var loop = function ( i ) {
5972
      var marker = markers[i], linked = [marker.primary.doc];
5973
      linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
5974
      for (var j = 0; j < marker.markers.length; j++) {
5975
        var subMarker = marker.markers[j];
5976
        if (indexOf(linked, subMarker.doc) == -1) {
5977
          subMarker.parent = null;
5978
          marker.markers.splice(j--, 1);
5979
        }
5980
      }
5981
    };
5982
 
5983
    for (var i = 0; i < markers.length; i++) loop( i );
5984
  }
5985
 
5986
  var nextDocId = 0;
5987
  var Doc = function(text, mode, firstLine, lineSep, direction) {
5988
    if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
5989
    if (firstLine == null) { firstLine = 0; }
5990
 
5991
    BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
5992
    this.first = firstLine;
5993
    this.scrollTop = this.scrollLeft = 0;
5994
    this.cantEdit = false;
5995
    this.cleanGeneration = 1;
5996
    this.modeFrontier = this.highlightFrontier = firstLine;
5997
    var start = Pos(firstLine, 0);
5998
    this.sel = simpleSelection(start);
5999
    this.history = new History(null);
6000
    this.id = ++nextDocId;
6001
    this.modeOption = mode;
6002
    this.lineSep = lineSep;
6003
    this.direction = (direction == "rtl") ? "rtl" : "ltr";
6004
    this.extend = false;
6005
 
6006
    if (typeof text == "string") { text = this.splitLines(text); }
6007
    updateDoc(this, {from: start, to: start, text: text});
6008
    setSelection(this, simpleSelection(start), sel_dontScroll);
6009
  };
6010
 
6011
  Doc.prototype = createObj(BranchChunk.prototype, {
6012
    constructor: Doc,
6013
    // Iterate over the document. Supports two forms -- with only one
6014
    // argument, it calls that for each line in the document. With
6015
    // three, it iterates over the range given by the first two (with
6016
    // the second being non-inclusive).
6017
    iter: function(from, to, op) {
6018
      if (op) { this.iterN(from - this.first, to - from, op); }
6019
      else { this.iterN(this.first, this.first + this.size, from); }
6020
    },
6021
 
6022
    // Non-public interface for adding and removing lines.
6023
    insert: function(at, lines) {
6024
      var height = 0;
6025
      for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
6026
      this.insertInner(at - this.first, lines, height);
6027
    },
6028
    remove: function(at, n) { this.removeInner(at - this.first, n); },
6029
 
6030
    // From here, the methods are part of the public interface. Most
6031
    // are also available from CodeMirror (editor) instances.
6032
 
6033
    getValue: function(lineSep) {
6034
      var lines = getLines(this, this.first, this.first + this.size);
6035
      if (lineSep === false) { return lines }
6036
      return lines.join(lineSep || this.lineSeparator())
6037
    },
6038
    setValue: docMethodOp(function(code) {
6039
      var top = Pos(this.first, 0), last = this.first + this.size - 1;
6040
      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
6041
                        text: this.splitLines(code), origin: "setValue", full: true}, true);
6042
      if (this.cm) { scrollToCoords(this.cm, 0, 0); }
6043
      setSelection(this, simpleSelection(top), sel_dontScroll);
6044
    }),
6045
    replaceRange: function(code, from, to, origin) {
6046
      from = clipPos(this, from);
6047
      to = to ? clipPos(this, to) : from;
6048
      replaceRange(this, code, from, to, origin);
6049
    },
6050
    getRange: function(from, to, lineSep) {
6051
      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
6052
      if (lineSep === false) { return lines }
6053
      return lines.join(lineSep || this.lineSeparator())
6054
    },
6055
 
6056
    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
6057
 
6058
    getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
6059
    getLineNumber: function(line) {return lineNo(line)},
6060
 
6061
    getLineHandleVisualStart: function(line) {
6062
      if (typeof line == "number") { line = getLine(this, line); }
6063
      return visualLine(line)
6064
    },
6065
 
6066
    lineCount: function() {return this.size},
6067
    firstLine: function() {return this.first},
6068
    lastLine: function() {return this.first + this.size - 1},
6069
 
6070
    clipPos: function(pos) {return clipPos(this, pos)},
6071
 
6072
    getCursor: function(start) {
6073
      var range$$1 = this.sel.primary(), pos;
6074
      if (start == null || start == "head") { pos = range$$1.head; }
6075
      else if (start == "anchor") { pos = range$$1.anchor; }
6076
      else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
6077
      else { pos = range$$1.from(); }
6078
      return pos
6079
    },
6080
    listSelections: function() { return this.sel.ranges },
6081
    somethingSelected: function() {return this.sel.somethingSelected()},
6082
 
6083
    setCursor: docMethodOp(function(line, ch, options) {
6084
      setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
6085
    }),
6086
    setSelection: docMethodOp(function(anchor, head, options) {
6087
      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
6088
    }),
6089
    extendSelection: docMethodOp(function(head, other, options) {
6090
      extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
6091
    }),
6092
    extendSelections: docMethodOp(function(heads, options) {
6093
      extendSelections(this, clipPosArray(this, heads), options);
6094
    }),
6095
    extendSelectionsBy: docMethodOp(function(f, options) {
6096
      var heads = map(this.sel.ranges, f);
6097
      extendSelections(this, clipPosArray(this, heads), options);
6098
    }),
6099
    setSelections: docMethodOp(function(ranges, primary, options) {
6100
      if (!ranges.length) { return }
6101
      var out = [];
6102
      for (var i = 0; i < ranges.length; i++)
6103
        { out[i] = new Range(clipPos(this, ranges[i].anchor),
6104
                           clipPos(this, ranges[i].head)); }
6105
      if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
6106
      setSelection(this, normalizeSelection(this.cm, out, primary), options);
6107
    }),
6108
    addSelection: docMethodOp(function(anchor, head, options) {
6109
      var ranges = this.sel.ranges.slice(0);
6110
      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
6111
      setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
6112
    }),
6113
 
6114
    getSelection: function(lineSep) {
6115
      var ranges = this.sel.ranges, lines;
6116
      for (var i = 0; i < ranges.length; i++) {
6117
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
6118
        lines = lines ? lines.concat(sel) : sel;
6119
      }
6120
      if (lineSep === false) { return lines }
6121
      else { return lines.join(lineSep || this.lineSeparator()) }
6122
    },
6123
    getSelections: function(lineSep) {
6124
      var parts = [], ranges = this.sel.ranges;
6125
      for (var i = 0; i < ranges.length; i++) {
6126
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
6127
        if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
6128
        parts[i] = sel;
6129
      }
6130
      return parts
6131
    },
6132
    replaceSelection: function(code, collapse, origin) {
6133
      var dup = [];
6134
      for (var i = 0; i < this.sel.ranges.length; i++)
6135
        { dup[i] = code; }
6136
      this.replaceSelections(dup, collapse, origin || "+input");
6137
    },
6138
    replaceSelections: docMethodOp(function(code, collapse, origin) {
6139
      var changes = [], sel = this.sel;
6140
      for (var i = 0; i < sel.ranges.length; i++) {
6141
        var range$$1 = sel.ranges[i];
6142
        changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this.splitLines(code[i]), origin: origin};
6143
      }
6144
      var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
6145
      for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
6146
        { makeChange(this, changes[i$1]); }
6147
      if (newSel) { setSelectionReplaceHistory(this, newSel); }
6148
      else if (this.cm) { ensureCursorVisible(this.cm); }
6149
    }),
6150
    undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
6151
    redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
6152
    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
6153
    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
6154
 
6155
    setExtending: function(val) {this.extend = val;},
6156
    getExtending: function() {return this.extend},
6157
 
6158
    historySize: function() {
6159
      var hist = this.history, done = 0, undone = 0;
6160
      for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
6161
      for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
6162
      return {undo: done, redo: undone}
6163
    },
6164
    clearHistory: function() {this.history = new History(this.history.maxGeneration);},
6165
 
6166
    markClean: function() {
6167
      this.cleanGeneration = this.changeGeneration(true);
6168
    },
6169
    changeGeneration: function(forceSplit) {
6170
      if (forceSplit)
6171
        { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
6172
      return this.history.generation
6173
    },
6174
    isClean: function (gen) {
6175
      return this.history.generation == (gen || this.cleanGeneration)
6176
    },
6177
 
6178
    getHistory: function() {
6179
      return {done: copyHistoryArray(this.history.done),
6180
              undone: copyHistoryArray(this.history.undone)}
6181
    },
6182
    setHistory: function(histData) {
6183
      var hist = this.history = new History(this.history.maxGeneration);
6184
      hist.done = copyHistoryArray(histData.done.slice(0), null, true);
6185
      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
6186
    },
6187
 
6188
    setGutterMarker: docMethodOp(function(line, gutterID, value) {
6189
      return changeLine(this, line, "gutter", function (line) {
6190
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
6191
        markers[gutterID] = value;
6192
        if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
6193
        return true
6194
      })
6195
    }),
6196
 
6197
    clearGutter: docMethodOp(function(gutterID) {
6198
      var this$1 = this;
6199
 
6200
      this.iter(function (line) {
6201
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
6202
          changeLine(this$1, line, "gutter", function () {
6203
            line.gutterMarkers[gutterID] = null;
6204
            if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
6205
            return true
6206
          });
6207
        }
6208
      });
6209
    }),
6210
 
6211
    lineInfo: function(line) {
6212
      var n;
6213
      if (typeof line == "number") {
6214
        if (!isLine(this, line)) { return null }
6215
        n = line;
6216
        line = getLine(this, line);
6217
        if (!line) { return null }
6218
      } else {
6219
        n = lineNo(line);
6220
        if (n == null) { return null }
6221
      }
6222
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
6223
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
6224
              widgets: line.widgets}
6225
    },
6226
 
6227
    addLineClass: docMethodOp(function(handle, where, cls) {
6228
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6229
        var prop = where == "text" ? "textClass"
6230
                 : where == "background" ? "bgClass"
6231
                 : where == "gutter" ? "gutterClass" : "wrapClass";
6232
        if (!line[prop]) { line[prop] = cls; }
6233
        else if (classTest(cls).test(line[prop])) { return false }
6234
        else { line[prop] += " " + cls; }
6235
        return true
6236
      })
6237
    }),
6238
    removeLineClass: docMethodOp(function(handle, where, cls) {
6239
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6240
        var prop = where == "text" ? "textClass"
6241
                 : where == "background" ? "bgClass"
6242
                 : where == "gutter" ? "gutterClass" : "wrapClass";
6243
        var cur = line[prop];
6244
        if (!cur) { return false }
6245
        else if (cls == null) { line[prop] = null; }
6246
        else {
6247
          var found = cur.match(classTest(cls));
6248
          if (!found) { return false }
6249
          var end = found.index + found[0].length;
6250
          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
6251
        }
6252
        return true
6253
      })
6254
    }),
6255
 
6256
    addLineWidget: docMethodOp(function(handle, node, options) {
6257
      return addLineWidget(this, handle, node, options)
6258
    }),
6259
    removeLineWidget: function(widget) { widget.clear(); },
6260
 
6261
    markText: function(from, to, options) {
6262
      return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
6263
    },
6264
    setBookmark: function(pos, options) {
6265
      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
6266
                      insertLeft: options && options.insertLeft,
6267
                      clearWhenEmpty: false, shared: options && options.shared,
6268
                      handleMouseEvents: options && options.handleMouseEvents};
6269
      pos = clipPos(this, pos);
6270
      return markText(this, pos, pos, realOpts, "bookmark")
6271
    },
6272
    findMarksAt: function(pos) {
6273
      pos = clipPos(this, pos);
6274
      var markers = [], spans = getLine(this, pos.line).markedSpans;
6275
      if (spans) { for (var i = 0; i < spans.length; ++i) {
6276
        var span = spans[i];
6277
        if ((span.from == null || span.from <= pos.ch) &&
6278
            (span.to == null || span.to >= pos.ch))
6279
          { markers.push(span.marker.parent || span.marker); }
6280
      } }
6281
      return markers
6282
    },
6283
    findMarks: function(from, to, filter) {
6284
      from = clipPos(this, from); to = clipPos(this, to);
6285
      var found = [], lineNo$$1 = from.line;
6286
      this.iter(from.line, to.line + 1, function (line) {
6287
        var spans = line.markedSpans;
6288
        if (spans) { for (var i = 0; i < spans.length; i++) {
6289
          var span = spans[i];
6290
          if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
6291
                span.from == null && lineNo$$1 != from.line ||
6292
                span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
6293
              (!filter || filter(span.marker)))
6294
            { found.push(span.marker.parent || span.marker); }
6295
        } }
6296
        ++lineNo$$1;
6297
      });
6298
      return found
6299
    },
6300
    getAllMarks: function() {
6301
      var markers = [];
6302
      this.iter(function (line) {
6303
        var sps = line.markedSpans;
6304
        if (sps) { for (var i = 0; i < sps.length; ++i)
6305
          { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
6306
      });
6307
      return markers
6308
    },
6309
 
6310
    posFromIndex: function(off) {
6311
      var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
6312
      this.iter(function (line) {
6313
        var sz = line.text.length + sepSize;
6314
        if (sz > off) { ch = off; return true }
6315
        off -= sz;
6316
        ++lineNo$$1;
6317
      });
6318
      return clipPos(this, Pos(lineNo$$1, ch))
6319
    },
6320
    indexFromPos: function (coords) {
6321
      coords = clipPos(this, coords);
6322
      var index = coords.ch;
6323
      if (coords.line < this.first || coords.ch < 0) { return 0 }
6324
      var sepSize = this.lineSeparator().length;
6325
      this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
6326
        index += line.text.length + sepSize;
6327
      });
6328
      return index
6329
    },
6330
 
6331
    copy: function(copyHistory) {
6332
      var doc = new Doc(getLines(this, this.first, this.first + this.size),
6333
                        this.modeOption, this.first, this.lineSep, this.direction);
6334
      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
6335
      doc.sel = this.sel;
6336
      doc.extend = false;
6337
      if (copyHistory) {
6338
        doc.history.undoDepth = this.history.undoDepth;
6339
        doc.setHistory(this.getHistory());
6340
      }
6341
      return doc
6342
    },
6343
 
6344
    linkedDoc: function(options) {
6345
      if (!options) { options = {}; }
6346
      var from = this.first, to = this.first + this.size;
6347
      if (options.from != null && options.from > from) { from = options.from; }
6348
      if (options.to != null && options.to < to) { to = options.to; }
6349
      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
6350
      if (options.sharedHist) { copy.history = this.history
6351
      ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
6352
      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
6353
      copySharedMarkers(copy, findSharedMarkers(this));
6354
      return copy
6355
    },
6356
    unlinkDoc: function(other) {
6357
      if (other instanceof CodeMirror) { other = other.doc; }
6358
      if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
6359
        var link = this.linked[i];
6360
        if (link.doc != other) { continue }
6361
        this.linked.splice(i, 1);
6362
        other.unlinkDoc(this);
6363
        detachSharedMarkers(findSharedMarkers(this));
6364
        break
6365
      } }
6366
      // If the histories were shared, split them again
6367
      if (other.history == this.history) {
6368
        var splitIds = [other.id];
6369
        linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
6370
        other.history = new History(null);
6371
        other.history.done = copyHistoryArray(this.history.done, splitIds);
6372
        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
6373
      }
6374
    },
6375
    iterLinkedDocs: function(f) {linkedDocs(this, f);},
6376
 
6377
    getMode: function() {return this.mode},
6378
    getEditor: function() {return this.cm},
6379
 
6380
    splitLines: function(str) {
6381
      if (this.lineSep) { return str.split(this.lineSep) }
6382
      return splitLinesAuto(str)
6383
    },
6384
    lineSeparator: function() { return this.lineSep || "\n" },
6385
 
6386
    setDirection: docMethodOp(function (dir) {
6387
      if (dir != "rtl") { dir = "ltr"; }
6388
      if (dir == this.direction) { return }
6389
      this.direction = dir;
6390
      this.iter(function (line) { return line.order = null; });
6391
      if (this.cm) { directionChanged(this.cm); }
6392
    })
6393
  });
6394
 
6395
  // Public alias.
6396
  Doc.prototype.eachLine = Doc.prototype.iter;
6397
 
6398
  // Kludge to work around strange IE behavior where it'll sometimes
6399
  // re-fire a series of drag-related events right after the drop (#1551)
6400
  var lastDrop = 0;
6401
 
6402
  function onDrop(e) {
6403
    var cm = this;
6404
    clearDragCursor(cm);
6405
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
6406
      { return }
6407
    e_preventDefault(e);
6408
    if (ie) { lastDrop = +new Date; }
6409
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
6410
    if (!pos || cm.isReadOnly()) { return }
6411
    // Might be a file drop, in which case we simply extract the text
6412
    // and insert it.
6413
    if (files && files.length && window.FileReader && window.File) {
6414
      var n = files.length, text = Array(n), read = 0;
6415
      var loadFile = function (file, i) {
6416
        if (cm.options.allowDropFileTypes &&
6417
            indexOf(cm.options.allowDropFileTypes, file.type) == -1)
6418
          { return }
6419
 
6420
        var reader = new FileReader;
6421
        reader.onload = operation(cm, function () {
6422
          var content = reader.result;
6423
          if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
6424
          text[i] = content;
6425
          if (++read == n) {
6426
            pos = clipPos(cm.doc, pos);
6427
            var change = {from: pos, to: pos,
6428
                          text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
6429
                          origin: "paste"};
6430
            makeChange(cm.doc, change);
6431
            setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
6432
          }
6433
        });
6434
        reader.readAsText(file);
6435
      };
6436
      for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
6437
    } else { // Normal drop
6438
      // Don't do a replace if the drop happened inside of the selected text.
6439
      if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
6440
        cm.state.draggingText(e);
6441
        // Ensure the editor is re-focused
6442
        setTimeout(function () { return cm.display.input.focus(); }, 20);
6443
        return
6444
      }
6445
      try {
6446
        var text$1 = e.dataTransfer.getData("Text");
6447
        if (text$1) {
6448
          var selected;
6449
          if (cm.state.draggingText && !cm.state.draggingText.copy)
6450
            { selected = cm.listSelections(); }
6451
          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
6452
          if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
6453
            { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
6454
          cm.replaceSelection(text$1, "around", "paste");
6455
          cm.display.input.focus();
6456
        }
6457
      }
6458
      catch(e){}
6459
    }
6460
  }
6461
 
6462
  function onDragStart(cm, e) {
6463
    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
6464
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
6465
 
6466
    e.dataTransfer.setData("Text", cm.getSelection());
6467
    e.dataTransfer.effectAllowed = "copyMove";
6468
 
6469
    // Use dummy image instead of default browsers image.
6470
    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
6471
    if (e.dataTransfer.setDragImage && !safari) {
6472
      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
6473
      img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
6474
      if (presto) {
6475
        img.width = img.height = 1;
6476
        cm.display.wrapper.appendChild(img);
6477
        // Force a relayout, or Opera won't use our image for some obscure reason
6478
        img._top = img.offsetTop;
6479
      }
6480
      e.dataTransfer.setDragImage(img, 0, 0);
6481
      if (presto) { img.parentNode.removeChild(img); }
6482
    }
6483
  }
6484
 
6485
  function onDragOver(cm, e) {
6486
    var pos = posFromMouse(cm, e);
6487
    if (!pos) { return }
6488
    var frag = document.createDocumentFragment();
6489
    drawSelectionCursor(cm, pos, frag);
6490
    if (!cm.display.dragCursor) {
6491
      cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
6492
      cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
6493
    }
6494
    removeChildrenAndAdd(cm.display.dragCursor, frag);
6495
  }
6496
 
6497
  function clearDragCursor(cm) {
6498
    if (cm.display.dragCursor) {
6499
      cm.display.lineSpace.removeChild(cm.display.dragCursor);
6500
      cm.display.dragCursor = null;
6501
    }
6502
  }
6503
 
6504
  // These must be handled carefully, because naively registering a
6505
  // handler for each editor will cause the editors to never be
6506
  // garbage collected.
6507
 
6508
  function forEachCodeMirror(f) {
6509
    if (!document.getElementsByClassName) { return }
6510
    var byClass = document.getElementsByClassName("CodeMirror");
6511
    for (var i = 0; i < byClass.length; i++) {
6512
      var cm = byClass[i].CodeMirror;
6513
      if (cm) { f(cm); }
6514
    }
6515
  }
6516
 
6517
  var globalsRegistered = false;
6518
  function ensureGlobalHandlers() {
6519
    if (globalsRegistered) { return }
6520
    registerGlobalHandlers();
6521
    globalsRegistered = true;
6522
  }
6523
  function registerGlobalHandlers() {
6524
    // When the window resizes, we need to refresh active editors.
6525
    var resizeTimer;
6526
    on(window, "resize", function () {
6527
      if (resizeTimer == null) { resizeTimer = setTimeout(function () {
6528
        resizeTimer = null;
6529
        forEachCodeMirror(onResize);
6530
      }, 100); }
6531
    });
6532
    // When the window loses focus, we want to show the editor as blurred
6533
    on(window, "blur", function () { return forEachCodeMirror(onBlur); });
6534
  }
6535
  // Called when the window resizes
6536
  function onResize(cm) {
6537
    var d = cm.display;
6538
    // Might be a text scaling operation, clear size caches.
6539
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
6540
    d.scrollbarsClipped = false;
6541
    cm.setSize();
6542
  }
6543
 
6544
  var keyNames = {
6545
    3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
6546
    19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
6547
    36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
6548
    46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
6549
    106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock",
6550
    173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
6551
    221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
6552
    63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
6553
  };
6554
 
6555
  // Number keys
6556
  for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
6557
  // Alphabetic keys
6558
  for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
6559
  // Function keys
6560
  for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
6561
 
6562
  var keyMap = {};
6563
 
6564
  keyMap.basic = {
6565
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
6566
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
6567
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
6568
    "Tab": "defaultTab", "Shift-Tab": "indentAuto",
6569
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
6570
    "Esc": "singleSelection"
6571
  };
6572
  // Note that the save and find-related commands aren't defined by
6573
  // default. User code or addons can define them. Unknown commands
6574
  // are simply ignored.
6575
  keyMap.pcDefault = {
6576
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
6577
    "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
6578
    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
6579
    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
6580
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
6581
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
6582
    "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
6583
    "fallthrough": "basic"
6584
  };
6585
  // Very basic readline/emacs-style bindings, which are standard on Mac.
6586
  keyMap.emacsy = {
6587
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
6588
    "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
6589
    "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
6590
    "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
6591
    "Ctrl-O": "openLine"
6592
  };
6593
  keyMap.macDefault = {
6594
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
6595
    "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
6596
    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
6597
    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
6598
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
6599
    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
6600
    "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
6601
    "fallthrough": ["basic", "emacsy"]
6602
  };
6603
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
6604
 
6605
  // KEYMAP DISPATCH
6606
 
6607
  function normalizeKeyName(name) {
6608
    var parts = name.split(/-(?!$)/);
6609
    name = parts[parts.length - 1];
6610
    var alt, ctrl, shift, cmd;
6611
    for (var i = 0; i < parts.length - 1; i++) {
6612
      var mod = parts[i];
6613
      if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
6614
      else if (/^a(lt)?$/i.test(mod)) { alt = true; }
6615
      else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
6616
      else if (/^s(hift)?$/i.test(mod)) { shift = true; }
6617
      else { throw new Error("Unrecognized modifier name: " + mod) }
6618
    }
6619
    if (alt) { name = "Alt-" + name; }
6620
    if (ctrl) { name = "Ctrl-" + name; }
6621
    if (cmd) { name = "Cmd-" + name; }
6622
    if (shift) { name = "Shift-" + name; }
6623
    return name
6624
  }
6625
 
6626
  // This is a kludge to keep keymaps mostly working as raw objects
6627
  // (backwards compatibility) while at the same time support features
6628
  // like normalization and multi-stroke key bindings. It compiles a
6629
  // new normalized keymap, and then updates the old object to reflect
6630
  // this.
6631
  function normalizeKeyMap(keymap) {
6632
    var copy = {};
6633
    for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
6634
      var value = keymap[keyname];
6635
      if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
6636
      if (value == "...") { delete keymap[keyname]; continue }
6637
 
6638
      var keys = map(keyname.split(" "), normalizeKeyName);
6639
      for (var i = 0; i < keys.length; i++) {
6640
        var val = (void 0), name = (void 0);
6641
        if (i == keys.length - 1) {
6642
          name = keys.join(" ");
6643
          val = value;
6644
        } else {
6645
          name = keys.slice(0, i + 1).join(" ");
6646
          val = "...";
6647
        }
6648
        var prev = copy[name];
6649
        if (!prev) { copy[name] = val; }
6650
        else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
6651
      }
6652
      delete keymap[keyname];
6653
    } }
6654
    for (var prop in copy) { keymap[prop] = copy[prop]; }
6655
    return keymap
6656
  }
6657
 
6658
  function lookupKey(key, map$$1, handle, context) {
6659
    map$$1 = getKeyMap(map$$1);
6660
    var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
6661
    if (found === false) { return "nothing" }
6662
    if (found === "...") { return "multi" }
6663
    if (found != null && handle(found)) { return "handled" }
6664
 
6665
    if (map$$1.fallthrough) {
6666
      if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
6667
        { return lookupKey(key, map$$1.fallthrough, handle, context) }
6668
      for (var i = 0; i < map$$1.fallthrough.length; i++) {
6669
        var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
6670
        if (result) { return result }
6671
      }
6672
    }
6673
  }
6674
 
6675
  // Modifier key presses don't count as 'real' key presses for the
6676
  // purpose of keymap fallthrough.
6677
  function isModifierKey(value) {
6678
    var name = typeof value == "string" ? value : keyNames[value.keyCode];
6679
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
6680
  }
6681
 
6682
  function addModifierNames(name, event, noShift) {
6683
    var base = name;
6684
    if (event.altKey && base != "Alt") { name = "Alt-" + name; }
6685
    if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
6686
    if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
6687
    if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
6688
    return name
6689
  }
6690
 
6691
  // Look up the name of a key as indicated by an event object.
6692
  function keyName(event, noShift) {
6693
    if (presto && event.keyCode == 34 && event["char"]) { return false }
6694
    var name = keyNames[event.keyCode];
6695
    if (name == null || event.altGraphKey) { return false }
6696
    // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
6697
    // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
6698
    if (event.keyCode == 3 && event.code) { name = event.code; }
6699
    return addModifierNames(name, event, noShift)
6700
  }
6701
 
6702
  function getKeyMap(val) {
6703
    return typeof val == "string" ? keyMap[val] : val
6704
  }
6705
 
6706
  // Helper for deleting text near the selection(s), used to implement
6707
  // backspace, delete, and similar functionality.
6708
  function deleteNearSelection(cm, compute) {
6709
    var ranges = cm.doc.sel.ranges, kill = [];
6710
    // Build up a set of ranges to kill first, merging overlapping
6711
    // ranges.
6712
    for (var i = 0; i < ranges.length; i++) {
6713
      var toKill = compute(ranges[i]);
6714
      while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
6715
        var replaced = kill.pop();
6716
        if (cmp(replaced.from, toKill.from) < 0) {
6717
          toKill.from = replaced.from;
6718
          break
6719
        }
6720
      }
6721
      kill.push(toKill);
6722
    }
6723
    // Next, remove those actual ranges.
6724
    runInOp(cm, function () {
6725
      for (var i = kill.length - 1; i >= 0; i--)
6726
        { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
6727
      ensureCursorVisible(cm);
6728
    });
6729
  }
6730
 
6731
  function moveCharLogically(line, ch, dir) {
6732
    var target = skipExtendingChars(line.text, ch + dir, dir);
6733
    return target < 0 || target > line.text.length ? null : target
6734
  }
6735
 
6736
  function moveLogically(line, start, dir) {
6737
    var ch = moveCharLogically(line, start.ch, dir);
6738
    return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
6739
  }
6740
 
6741
  function endOfLine(visually, cm, lineObj, lineNo, dir) {
6742
    if (visually) {
6743
      var order = getOrder(lineObj, cm.doc.direction);
6744
      if (order) {
6745
        var part = dir < 0 ? lst(order) : order[0];
6746
        var moveInStorageOrder = (dir < 0) == (part.level == 1);
6747
        var sticky = moveInStorageOrder ? "after" : "before";
6748
        var ch;
6749
        // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
6750
        // it could be that the last bidi part is not on the last visual line,
6751
        // since visual lines contain content order-consecutive chunks.
6752
        // Thus, in rtl, we are looking for the first (content-order) character
6753
        // in the rtl chunk that is on the last line (that is, the same line
6754
        // as the last (content-order) character).
6755
        if (part.level > 0 || cm.doc.direction == "rtl") {
6756
          var prep = prepareMeasureForLine(cm, lineObj);
6757
          ch = dir < 0 ? lineObj.text.length - 1 : 0;
6758
          var targetTop = measureCharPrepared(cm, prep, ch).top;
6759
          ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
6760
          if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
6761
        } else { ch = dir < 0 ? part.to : part.from; }
6762
        return new Pos(lineNo, ch, sticky)
6763
      }
6764
    }
6765
    return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
6766
  }
6767
 
6768
  function moveVisually(cm, line, start, dir) {
6769
    var bidi = getOrder(line, cm.doc.direction);
6770
    if (!bidi) { return moveLogically(line, start, dir) }
6771
    if (start.ch >= line.text.length) {
6772
      start.ch = line.text.length;
6773
      start.sticky = "before";
6774
    } else if (start.ch <= 0) {
6775
      start.ch = 0;
6776
      start.sticky = "after";
6777
    }
6778
    var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
6779
    if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
6780
      // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
6781
      // nothing interesting happens.
6782
      return moveLogically(line, start, dir)
6783
    }
6784
 
6785
    var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
6786
    var prep;
6787
    var getWrappedLineExtent = function (ch) {
6788
      if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
6789
      prep = prep || prepareMeasureForLine(cm, line);
6790
      return wrappedLineExtentChar(cm, line, prep, ch)
6791
    };
6792
    var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
6793
 
6794
    if (cm.doc.direction == "rtl" || part.level == 1) {
6795
      var moveInStorageOrder = (part.level == 1) == (dir < 0);
6796
      var ch = mv(start, moveInStorageOrder ? 1 : -1);
6797
      if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
6798
        // Case 2: We move within an rtl part or in an rtl editor on the same visual line
6799
        var sticky = moveInStorageOrder ? "before" : "after";
6800
        return new Pos(start.line, ch, sticky)
6801
      }
6802
    }
6803
 
6804
    // Case 3: Could not move within this bidi part in this visual line, so leave
6805
    // the current bidi part
6806
 
6807
    var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
6808
      var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
6809
        ? new Pos(start.line, mv(ch, 1), "before")
6810
        : new Pos(start.line, ch, "after"); };
6811
 
6812
      for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
6813
        var part = bidi[partPos];
6814
        var moveInStorageOrder = (dir > 0) == (part.level != 1);
6815
        var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
6816
        if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
6817
        ch = moveInStorageOrder ? part.from : mv(part.to, -1);
6818
        if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
6819
      }
6820
    };
6821
 
6822
    // Case 3a: Look for other bidi parts on the same visual line
6823
    var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
6824
    if (res) { return res }
6825
 
6826
    // Case 3b: Look for other bidi parts on the next visual line
6827
    var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
6828
    if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
6829
      res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
6830
      if (res) { return res }
6831
    }
6832
 
6833
    // Case 4: Nowhere to move
6834
    return null
6835
  }
6836
 
6837
  // Commands are parameter-less actions that can be performed on an
6838
  // editor, mostly used for keybindings.
6839
  var commands = {
6840
    selectAll: selectAll,
6841
    singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
6842
    killLine: function (cm) { return deleteNearSelection(cm, function (range) {
6843
      if (range.empty()) {
6844
        var len = getLine(cm.doc, range.head.line).text.length;
6845
        if (range.head.ch == len && range.head.line < cm.lastLine())
6846
          { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
6847
        else
6848
          { return {from: range.head, to: Pos(range.head.line, len)} }
6849
      } else {
6850
        return {from: range.from(), to: range.to()}
6851
      }
6852
    }); },
6853
    deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
6854
      from: Pos(range.from().line, 0),
6855
      to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
6856
    }); }); },
6857
    delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
6858
      from: Pos(range.from().line, 0), to: range.from()
6859
    }); }); },
6860
    delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
6861
      var top = cm.charCoords(range.head, "div").top + 5;
6862
      var leftPos = cm.coordsChar({left: 0, top: top}, "div");
6863
      return {from: leftPos, to: range.from()}
6864
    }); },
6865
    delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
6866
      var top = cm.charCoords(range.head, "div").top + 5;
6867
      var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
6868
      return {from: range.from(), to: rightPos }
6869
    }); },
6870
    undo: function (cm) { return cm.undo(); },
6871
    redo: function (cm) { return cm.redo(); },
6872
    undoSelection: function (cm) { return cm.undoSelection(); },
6873
    redoSelection: function (cm) { return cm.redoSelection(); },
6874
    goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
6875
    goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
6876
    goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
6877
      {origin: "+move", bias: 1}
6878
    ); },
6879
    goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
6880
      {origin: "+move", bias: 1}
6881
    ); },
6882
    goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
6883
      {origin: "+move", bias: -1}
6884
    ); },
6885
    goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
6886
      var top = cm.cursorCoords(range.head, "div").top + 5;
6887
      return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
6888
    }, sel_move); },
6889
    goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
6890
      var top = cm.cursorCoords(range.head, "div").top + 5;
6891
      return cm.coordsChar({left: 0, top: top}, "div")
6892
    }, sel_move); },
6893
    goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
6894
      var top = cm.cursorCoords(range.head, "div").top + 5;
6895
      var pos = cm.coordsChar({left: 0, top: top}, "div");
6896
      if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
6897
      return pos
6898
    }, sel_move); },
6899
    goLineUp: function (cm) { return cm.moveV(-1, "line"); },
6900
    goLineDown: function (cm) { return cm.moveV(1, "line"); },
6901
    goPageUp: function (cm) { return cm.moveV(-1, "page"); },
6902
    goPageDown: function (cm) { return cm.moveV(1, "page"); },
6903
    goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
6904
    goCharRight: function (cm) { return cm.moveH(1, "char"); },
6905
    goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
6906
    goColumnRight: function (cm) { return cm.moveH(1, "column"); },
6907
    goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
6908
    goGroupRight: function (cm) { return cm.moveH(1, "group"); },
6909
    goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
6910
    goWordRight: function (cm) { return cm.moveH(1, "word"); },
6911
    delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
6912
    delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
6913
    delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
6914
    delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
6915
    delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
6916
    delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
6917
    indentAuto: function (cm) { return cm.indentSelection("smart"); },
6918
    indentMore: function (cm) { return cm.indentSelection("add"); },
6919
    indentLess: function (cm) { return cm.indentSelection("subtract"); },
6920
    insertTab: function (cm) { return cm.replaceSelection("\t"); },
6921
    insertSoftTab: function (cm) {
6922
      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
6923
      for (var i = 0; i < ranges.length; i++) {
6924
        var pos = ranges[i].from();
6925
        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
6926
        spaces.push(spaceStr(tabSize - col % tabSize));
6927
      }
6928
      cm.replaceSelections(spaces);
6929
    },
6930
    defaultTab: function (cm) {
6931
      if (cm.somethingSelected()) { cm.indentSelection("add"); }
6932
      else { cm.execCommand("insertTab"); }
6933
    },
6934
    // Swap the two chars left and right of each selection's head.
6935
    // Move cursor behind the two swapped characters afterwards.
6936
    //
6937
    // Doesn't consider line feeds a character.
6938
    // Doesn't scan more than one line above to find a character.
6939
    // Doesn't do anything on an empty line.
6940
    // Doesn't do anything with non-empty selections.
6941
    transposeChars: function (cm) { return runInOp(cm, function () {
6942
      var ranges = cm.listSelections(), newSel = [];
6943
      for (var i = 0; i < ranges.length; i++) {
6944
        if (!ranges[i].empty()) { continue }
6945
        var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
6946
        if (line) {
6947
          if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
6948
          if (cur.ch > 0) {
6949
            cur = new Pos(cur.line, cur.ch + 1);
6950
            cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
6951
                            Pos(cur.line, cur.ch - 2), cur, "+transpose");
6952
          } else if (cur.line > cm.doc.first) {
6953
            var prev = getLine(cm.doc, cur.line - 1).text;
6954
            if (prev) {
6955
              cur = new Pos(cur.line, 1);
6956
              cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
6957
                              prev.charAt(prev.length - 1),
6958
                              Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
6959
            }
6960
          }
6961
        }
6962
        newSel.push(new Range(cur, cur));
6963
      }
6964
      cm.setSelections(newSel);
6965
    }); },
6966
    newlineAndIndent: function (cm) { return runInOp(cm, function () {
6967
      var sels = cm.listSelections();
6968
      for (var i = sels.length - 1; i >= 0; i--)
6969
        { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
6970
      sels = cm.listSelections();
6971
      for (var i$1 = 0; i$1 < sels.length; i$1++)
6972
        { cm.indentLine(sels[i$1].from().line, null, true); }
6973
      ensureCursorVisible(cm);
6974
    }); },
6975
    openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
6976
    toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
6977
  };
6978
 
6979
 
6980
  function lineStart(cm, lineN) {
6981
    var line = getLine(cm.doc, lineN);
6982
    var visual = visualLine(line);
6983
    if (visual != line) { lineN = lineNo(visual); }
6984
    return endOfLine(true, cm, visual, lineN, 1)
6985
  }
6986
  function lineEnd(cm, lineN) {
6987
    var line = getLine(cm.doc, lineN);
6988
    var visual = visualLineEnd(line);
6989
    if (visual != line) { lineN = lineNo(visual); }
6990
    return endOfLine(true, cm, line, lineN, -1)
6991
  }
6992
  function lineStartSmart(cm, pos) {
6993
    var start = lineStart(cm, pos.line);
6994
    var line = getLine(cm.doc, start.line);
6995
    var order = getOrder(line, cm.doc.direction);
6996
    if (!order || order[0].level == 0) {
6997
      var firstNonWS = Math.max(0, line.text.search(/\S/));
6998
      var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
6999
      return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
7000
    }
7001
    return start
7002
  }
7003
 
7004
  // Run a handler that was bound to a key.
7005
  function doHandleBinding(cm, bound, dropShift) {
7006
    if (typeof bound == "string") {
7007
      bound = commands[bound];
7008
      if (!bound) { return false }
7009
    }
7010
    // Ensure previous input has been read, so that the handler sees a
7011
    // consistent view of the document
7012
    cm.display.input.ensurePolled();
7013
    var prevShift = cm.display.shift, done = false;
7014
    try {
7015
      if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7016
      if (dropShift) { cm.display.shift = false; }
7017
      done = bound(cm) != Pass;
7018
    } finally {
7019
      cm.display.shift = prevShift;
7020
      cm.state.suppressEdits = false;
7021
    }
7022
    return done
7023
  }
7024
 
7025
  function lookupKeyForEditor(cm, name, handle) {
7026
    for (var i = 0; i < cm.state.keyMaps.length; i++) {
7027
      var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
7028
      if (result) { return result }
7029
    }
7030
    return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
7031
      || lookupKey(name, cm.options.keyMap, handle, cm)
7032
  }
7033
 
7034
  // Note that, despite the name, this function is also used to check
7035
  // for bound mouse clicks.
7036
 
7037
  var stopSeq = new Delayed;
7038
 
7039
  function dispatchKey(cm, name, e, handle) {
7040
    var seq = cm.state.keySeq;
7041
    if (seq) {
7042
      if (isModifierKey(name)) { return "handled" }
7043
      if (/\'$/.test(name))
7044
        { cm.state.keySeq = null; }
7045
      else
7046
        { stopSeq.set(50, function () {
7047
          if (cm.state.keySeq == seq) {
7048
            cm.state.keySeq = null;
7049
            cm.display.input.reset();
7050
          }
7051
        }); }
7052
      if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
7053
    }
7054
    return dispatchKeyInner(cm, name, e, handle)
7055
  }
7056
 
7057
  function dispatchKeyInner(cm, name, e, handle) {
7058
    var result = lookupKeyForEditor(cm, name, handle);
7059
 
7060
    if (result == "multi")
7061
      { cm.state.keySeq = name; }
7062
    if (result == "handled")
7063
      { signalLater(cm, "keyHandled", cm, name, e); }
7064
 
7065
    if (result == "handled" || result == "multi") {
7066
      e_preventDefault(e);
7067
      restartBlink(cm);
7068
    }
7069
 
7070
    return !!result
7071
  }
7072
 
7073
  // Handle a key from the keydown event.
7074
  function handleKeyBinding(cm, e) {
7075
    var name = keyName(e, true);
7076
    if (!name) { return false }
7077
 
7078
    if (e.shiftKey && !cm.state.keySeq) {
7079
      // First try to resolve full name (including 'Shift-'). Failing
7080
      // that, see if there is a cursor-motion command (starting with
7081
      // 'go') bound to the keyname without 'Shift-'.
7082
      return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
7083
          || dispatchKey(cm, name, e, function (b) {
7084
               if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
7085
                 { return doHandleBinding(cm, b) }
7086
             })
7087
    } else {
7088
      return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
7089
    }
7090
  }
7091
 
7092
  // Handle a key from the keypress event
7093
  function handleCharBinding(cm, e, ch) {
7094
    return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
7095
  }
7096
 
7097
  var lastStoppedKey = null;
7098
  function onKeyDown(e) {
7099
    var cm = this;
7100
    cm.curOp.focus = activeElt();
7101
    if (signalDOMEvent(cm, e)) { return }
7102
    // IE does strange things with escape.
7103
    if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
7104
    var code = e.keyCode;
7105
    cm.display.shift = code == 16 || e.shiftKey;
7106
    var handled = handleKeyBinding(cm, e);
7107
    if (presto) {
7108
      lastStoppedKey = handled ? code : null;
7109
      // Opera has no cut event... we try to at least catch the key combo
7110
      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
7111
        { cm.replaceSelection("", null, "cut"); }
7112
    }
7113
 
7114
    // Turn mouse into crosshair when Alt is held on Mac.
7115
    if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
7116
      { showCrossHair(cm); }
7117
  }
7118
 
7119
  function showCrossHair(cm) {
7120
    var lineDiv = cm.display.lineDiv;
7121
    addClass(lineDiv, "CodeMirror-crosshair");
7122
 
7123
    function up(e) {
7124
      if (e.keyCode == 18 || !e.altKey) {
7125
        rmClass(lineDiv, "CodeMirror-crosshair");
7126
        off(document, "keyup", up);
7127
        off(document, "mouseover", up);
7128
      }
7129
    }
7130
    on(document, "keyup", up);
7131
    on(document, "mouseover", up);
7132
  }
7133
 
7134
  function onKeyUp(e) {
7135
    if (e.keyCode == 16) { this.doc.sel.shift = false; }
7136
    signalDOMEvent(this, e);
7137
  }
7138
 
7139
  function onKeyPress(e) {
7140
    var cm = this;
7141
    if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
7142
    var keyCode = e.keyCode, charCode = e.charCode;
7143
    if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
7144
    if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
7145
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
7146
    // Some browsers fire keypress events for backspace
7147
    if (ch == "\x08") { return }
7148
    if (handleCharBinding(cm, e, ch)) { return }
7149
    cm.display.input.onKeyPress(e);
7150
  }
7151
 
7152
  var DOUBLECLICK_DELAY = 400;
7153
 
7154
  var PastClick = function(time, pos, button) {
7155
    this.time = time;
7156
    this.pos = pos;
7157
    this.button = button;
7158
  };
7159
 
7160
  PastClick.prototype.compare = function (time, pos, button) {
7161
    return this.time + DOUBLECLICK_DELAY > time &&
7162
      cmp(pos, this.pos) == 0 && button == this.button
7163
  };
7164
 
7165
  var lastClick, lastDoubleClick;
7166
  function clickRepeat(pos, button) {
7167
    var now = +new Date;
7168
    if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
7169
      lastClick = lastDoubleClick = null;
7170
      return "triple"
7171
    } else if (lastClick && lastClick.compare(now, pos, button)) {
7172
      lastDoubleClick = new PastClick(now, pos, button);
7173
      lastClick = null;
7174
      return "double"
7175
    } else {
7176
      lastClick = new PastClick(now, pos, button);
7177
      lastDoubleClick = null;
7178
      return "single"
7179
    }
7180
  }
7181
 
7182
  // A mouse down can be a single click, double click, triple click,
7183
  // start of selection drag, start of text drag, new cursor
7184
  // (ctrl-click), rectangle drag (alt-drag), or xwin
7185
  // middle-click-paste. Or it might be a click on something we should
7186
  // not interfere with, such as a scrollbar or widget.
7187
  function onMouseDown(e) {
7188
    var cm = this, display = cm.display;
7189
    if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
7190
    display.input.ensurePolled();
7191
    display.shift = e.shiftKey;
7192
 
7193
    if (eventInWidget(display, e)) {
7194
      if (!webkit) {
7195
        // Briefly turn off draggability, to allow widgets to do
7196
        // normal dragging things.
7197
        display.scroller.draggable = false;
7198
        setTimeout(function () { return display.scroller.draggable = true; }, 100);
7199
      }
7200
      return
7201
    }
7202
    if (clickInGutter(cm, e)) { return }
7203
    var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
7204
    window.focus();
7205
 
7206
    // #3261: make sure, that we're not starting a second selection
7207
    if (button == 1 && cm.state.selectingText)
7208
      { cm.state.selectingText(e); }
7209
 
7210
    if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
7211
 
7212
    if (button == 1) {
7213
      if (pos) { leftButtonDown(cm, pos, repeat, e); }
7214
      else if (e_target(e) == display.scroller) { e_preventDefault(e); }
7215
    } else if (button == 2) {
7216
      if (pos) { extendSelection(cm.doc, pos); }
7217
      setTimeout(function () { return display.input.focus(); }, 20);
7218
    } else if (button == 3) {
7219
      if (captureRightClick) { cm.display.input.onContextMenu(e); }
7220
      else { delayBlurEvent(cm); }
7221
    }
7222
  }
7223
 
7224
  function handleMappedButton(cm, button, pos, repeat, event) {
7225
    var name = "Click";
7226
    if (repeat == "double") { name = "Double" + name; }
7227
    else if (repeat == "triple") { name = "Triple" + name; }
7228
    name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
7229
 
7230
    return dispatchKey(cm,  addModifierNames(name, event), event, function (bound) {
7231
      if (typeof bound == "string") { bound = commands[bound]; }
7232
      if (!bound) { return false }
7233
      var done = false;
7234
      try {
7235
        if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7236
        done = bound(cm, pos) != Pass;
7237
      } finally {
7238
        cm.state.suppressEdits = false;
7239
      }
7240
      return done
7241
    })
7242
  }
7243
 
7244
  function configureMouse(cm, repeat, event) {
7245
    var option = cm.getOption("configureMouse");
7246
    var value = option ? option(cm, repeat, event) : {};
7247
    if (value.unit == null) {
7248
      var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
7249
      value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
7250
    }
7251
    if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
7252
    if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
7253
    if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
7254
    return value
7255
  }
7256
 
7257
  function leftButtonDown(cm, pos, repeat, event) {
7258
    if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
7259
    else { cm.curOp.focus = activeElt(); }
7260
 
7261
    var behavior = configureMouse(cm, repeat, event);
7262
 
7263
    var sel = cm.doc.sel, contained;
7264
    if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
7265
        repeat == "single" && (contained = sel.contains(pos)) > -1 &&
7266
        (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
7267
        (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
7268
      { leftButtonStartDrag(cm, event, pos, behavior); }
7269
    else
7270
      { leftButtonSelect(cm, event, pos, behavior); }
7271
  }
7272
 
7273
  // Start a text drag. When it ends, see if any dragging actually
7274
  // happen, and treat as a click if it didn't.
7275
  function leftButtonStartDrag(cm, event, pos, behavior) {
7276
    var display = cm.display, moved = false;
7277
    var dragEnd = operation(cm, function (e) {
7278
      if (webkit) { display.scroller.draggable = false; }
7279
      cm.state.draggingText = false;
7280
      off(display.wrapper.ownerDocument, "mouseup", dragEnd);
7281
      off(display.wrapper.ownerDocument, "mousemove", mouseMove);
7282
      off(display.scroller, "dragstart", dragStart);
7283
      off(display.scroller, "drop", dragEnd);
7284
      if (!moved) {
7285
        e_preventDefault(e);
7286
        if (!behavior.addNew)
7287
          { extendSelection(cm.doc, pos, null, null, behavior.extend); }
7288
        // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
7289
        if (webkit || ie && ie_version == 9)
7290
          { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }
7291
        else
7292
          { display.input.focus(); }
7293
      }
7294
    });
7295
    var mouseMove = function(e2) {
7296
      moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
7297
    };
7298
    var dragStart = function () { return moved = true; };
7299
    // Let the drag handler handle this.
7300
    if (webkit) { display.scroller.draggable = true; }
7301
    cm.state.draggingText = dragEnd;
7302
    dragEnd.copy = !behavior.moveOnDrag;
7303
    // IE's approach to draggable
7304
    if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
7305
    on(display.wrapper.ownerDocument, "mouseup", dragEnd);
7306
    on(display.wrapper.ownerDocument, "mousemove", mouseMove);
7307
    on(display.scroller, "dragstart", dragStart);
7308
    on(display.scroller, "drop", dragEnd);
7309
 
7310
    delayBlurEvent(cm);
7311
    setTimeout(function () { return display.input.focus(); }, 20);
7312
  }
7313
 
7314
  function rangeForUnit(cm, pos, unit) {
7315
    if (unit == "char") { return new Range(pos, pos) }
7316
    if (unit == "word") { return cm.findWordAt(pos) }
7317
    if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
7318
    var result = unit(cm, pos);
7319
    return new Range(result.from, result.to)
7320
  }
7321
 
7322
  // Normal selection, as opposed to text dragging.
7323
  function leftButtonSelect(cm, event, start, behavior) {
7324
    var display = cm.display, doc = cm.doc;
7325
    e_preventDefault(event);
7326
 
7327
    var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
7328
    if (behavior.addNew && !behavior.extend) {
7329
      ourIndex = doc.sel.contains(start);
7330
      if (ourIndex > -1)
7331
        { ourRange = ranges[ourIndex]; }
7332
      else
7333
        { ourRange = new Range(start, start); }
7334
    } else {
7335
      ourRange = doc.sel.primary();
7336
      ourIndex = doc.sel.primIndex;
7337
    }
7338
 
7339
    if (behavior.unit == "rectangle") {
7340
      if (!behavior.addNew) { ourRange = new Range(start, start); }
7341
      start = posFromMouse(cm, event, true, true);
7342
      ourIndex = -1;
7343
    } else {
7344
      var range$$1 = rangeForUnit(cm, start, behavior.unit);
7345
      if (behavior.extend)
7346
        { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
7347
      else
7348
        { ourRange = range$$1; }
7349
    }
7350
 
7351
    if (!behavior.addNew) {
7352
      ourIndex = 0;
7353
      setSelection(doc, new Selection([ourRange], 0), sel_mouse);
7354
      startSel = doc.sel;
7355
    } else if (ourIndex == -1) {
7356
      ourIndex = ranges.length;
7357
      setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
7358
                   {scroll: false, origin: "*mouse"});
7359
    } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
7360
      setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
7361
                   {scroll: false, origin: "*mouse"});
7362
      startSel = doc.sel;
7363
    } else {
7364
      replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
7365
    }
7366
 
7367
    var lastPos = start;
7368
    function extendTo(pos) {
7369
      if (cmp(lastPos, pos) == 0) { return }
7370
      lastPos = pos;
7371
 
7372
      if (behavior.unit == "rectangle") {
7373
        var ranges = [], tabSize = cm.options.tabSize;
7374
        var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
7375
        var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
7376
        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
7377
        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
7378
             line <= end; line++) {
7379
          var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
7380
          if (left == right)
7381
            { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
7382
          else if (text.length > leftPos)
7383
            { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
7384
        }
7385
        if (!ranges.length) { ranges.push(new Range(start, start)); }
7386
        setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
7387
                     {origin: "*mouse", scroll: false});
7388
        cm.scrollIntoView(pos);
7389
      } else {
7390
        var oldRange = ourRange;
7391
        var range$$1 = rangeForUnit(cm, pos, behavior.unit);
7392
        var anchor = oldRange.anchor, head;
7393
        if (cmp(range$$1.anchor, anchor) > 0) {
7394
          head = range$$1.head;
7395
          anchor = minPos(oldRange.from(), range$$1.anchor);
7396
        } else {
7397
          head = range$$1.anchor;
7398
          anchor = maxPos(oldRange.to(), range$$1.head);
7399
        }
7400
        var ranges$1 = startSel.ranges.slice(0);
7401
        ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
7402
        setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
7403
      }
7404
    }
7405
 
7406
    var editorSize = display.wrapper.getBoundingClientRect();
7407
    // Used to ensure timeout re-tries don't fire when another extend
7408
    // happened in the meantime (clearTimeout isn't reliable -- at
7409
    // least on Chrome, the timeouts still happen even when cleared,
7410
    // if the clear happens after their scheduled firing time).
7411
    var counter = 0;
7412
 
7413
    function extend(e) {
7414
      var curCount = ++counter;
7415
      var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
7416
      if (!cur) { return }
7417
      if (cmp(cur, lastPos) != 0) {
7418
        cm.curOp.focus = activeElt();
7419
        extendTo(cur);
7420
        var visible = visibleLines(display, doc);
7421
        if (cur.line >= visible.to || cur.line < visible.from)
7422
          { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
7423
      } else {
7424
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
7425
        if (outside) { setTimeout(operation(cm, function () {
7426
          if (counter != curCount) { return }
7427
          display.scroller.scrollTop += outside;
7428
          extend(e);
7429
        }), 50); }
7430
      }
7431
    }
7432
 
7433
    function done(e) {
7434
      cm.state.selectingText = false;
7435
      counter = Infinity;
7436
      e_preventDefault(e);
7437
      display.input.focus();
7438
      off(display.wrapper.ownerDocument, "mousemove", move);
7439
      off(display.wrapper.ownerDocument, "mouseup", up);
7440
      doc.history.lastSelOrigin = null;
7441
    }
7442
 
7443
    var move = operation(cm, function (e) {
7444
      if (e.buttons === 0 || !e_button(e)) { done(e); }
7445
      else { extend(e); }
7446
    });
7447
    var up = operation(cm, done);
7448
    cm.state.selectingText = up;
7449
    on(display.wrapper.ownerDocument, "mousemove", move);
7450
    on(display.wrapper.ownerDocument, "mouseup", up);
7451
  }
7452
 
7453
  // Used when mouse-selecting to adjust the anchor to the proper side
7454
  // of a bidi jump depending on the visual position of the head.
7455
  function bidiSimplify(cm, range$$1) {
7456
    var anchor = range$$1.anchor;
7457
    var head = range$$1.head;
7458
    var anchorLine = getLine(cm.doc, anchor.line);
7459
    if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
7460
    var order = getOrder(anchorLine);
7461
    if (!order) { return range$$1 }
7462
    var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
7463
    if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
7464
    var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
7465
    if (boundary == 0 || boundary == order.length) { return range$$1 }
7466
 
7467
    // Compute the relative visual position of the head compared to the
7468
    // anchor (<0 is to the left, >0 to the right)
7469
    var leftSide;
7470
    if (head.line != anchor.line) {
7471
      leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
7472
    } else {
7473
      var headIndex = getBidiPartAt(order, head.ch, head.sticky);
7474
      var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
7475
      if (headIndex == boundary - 1 || headIndex == boundary)
7476
        { leftSide = dir < 0; }
7477
      else
7478
        { leftSide = dir > 0; }
7479
    }
7480
 
7481
    var usePart = order[boundary + (leftSide ? -1 : 0)];
7482
    var from = leftSide == (usePart.level == 1);
7483
    var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
7484
    return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
7485
  }
7486
 
7487
 
7488
  // Determines whether an event happened in the gutter, and fires the
7489
  // handlers for the corresponding event.
7490
  function gutterEvent(cm, e, type, prevent) {
7491
    var mX, mY;
7492
    if (e.touches) {
7493
      mX = e.touches[0].clientX;
7494
      mY = e.touches[0].clientY;
7495
    } else {
7496
      try { mX = e.clientX; mY = e.clientY; }
7497
      catch(e) { return false }
7498
    }
7499
    if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
7500
    if (prevent) { e_preventDefault(e); }
7501
 
7502
    var display = cm.display;
7503
    var lineBox = display.lineDiv.getBoundingClientRect();
7504
 
7505
    if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
7506
    mY -= lineBox.top - display.viewOffset;
7507
 
7508
    for (var i = 0; i < cm.options.gutters.length; ++i) {
7509
      var g = display.gutters.childNodes[i];
7510
      if (g && g.getBoundingClientRect().right >= mX) {
7511
        var line = lineAtHeight(cm.doc, mY);
7512
        var gutter = cm.options.gutters[i];
7513
        signal(cm, type, cm, line, gutter, e);
7514
        return e_defaultPrevented(e)
7515
      }
7516
    }
7517
  }
7518
 
7519
  function clickInGutter(cm, e) {
7520
    return gutterEvent(cm, e, "gutterClick", true)
7521
  }
7522
 
7523
  // CONTEXT MENU HANDLING
7524
 
7525
  // To make the context menu work, we need to briefly unhide the
7526
  // textarea (making it as unobtrusive as possible) to let the
7527
  // right-click take effect on it.
7528
  function onContextMenu(cm, e) {
7529
    if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
7530
    if (signalDOMEvent(cm, e, "contextmenu")) { return }
7531
    if (!captureRightClick) { cm.display.input.onContextMenu(e); }
7532
  }
7533
 
7534
  function contextMenuInGutter(cm, e) {
7535
    if (!hasHandler(cm, "gutterContextMenu")) { return false }
7536
    return gutterEvent(cm, e, "gutterContextMenu", false)
7537
  }
7538
 
7539
  function themeChanged(cm) {
7540
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
7541
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
7542
    clearCaches(cm);
7543
  }
7544
 
7545
  var Init = {toString: function(){return "CodeMirror.Init"}};
7546
 
7547
  var defaults = {};
7548
  var optionHandlers = {};
7549
 
7550
  function defineOptions(CodeMirror) {
7551
    var optionHandlers = CodeMirror.optionHandlers;
7552
 
7553
    function option(name, deflt, handle, notOnInit) {
7554
      CodeMirror.defaults[name] = deflt;
7555
      if (handle) { optionHandlers[name] =
7556
        notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
7557
    }
7558
 
7559
    CodeMirror.defineOption = option;
7560
 
7561
    // Passed to option handlers when there is no old value.
7562
    CodeMirror.Init = Init;
7563
 
7564
    // These two are, on init, called from the constructor because they
7565
    // have to be initialized before the editor can start at all.
7566
    option("value", "", function (cm, val) { return cm.setValue(val); }, true);
7567
    option("mode", null, function (cm, val) {
7568
      cm.doc.modeOption = val;
7569
      loadMode(cm);
7570
    }, true);
7571
 
7572
    option("indentUnit", 2, loadMode, true);
7573
    option("indentWithTabs", false);
7574
    option("smartIndent", true);
7575
    option("tabSize", 4, function (cm) {
7576
      resetModeState(cm);
7577
      clearCaches(cm);
7578
      regChange(cm);
7579
    }, true);
7580
 
7581
    option("lineSeparator", null, function (cm, val) {
7582
      cm.doc.lineSep = val;
7583
      if (!val) { return }
7584
      var newBreaks = [], lineNo = cm.doc.first;
7585
      cm.doc.iter(function (line) {
7586
        for (var pos = 0;;) {
7587
          var found = line.text.indexOf(val, pos);
7588
          if (found == -1) { break }
7589
          pos = found + val.length;
7590
          newBreaks.push(Pos(lineNo, found));
7591
        }
7592
        lineNo++;
7593
      });
7594
      for (var i = newBreaks.length - 1; i >= 0; i--)
7595
        { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
7596
    });
7597
    option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
7598
      cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
7599
      if (old != Init) { cm.refresh(); }
7600
    });
7601
    option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
7602
    option("electricChars", true);
7603
    option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
7604
      throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
7605
    }, true);
7606
    option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
7607
    option("rtlMoveVisually", !windows);
7608
    option("wholeLineUpdateBefore", true);
7609
 
7610
    option("theme", "default", function (cm) {
7611
      themeChanged(cm);
7612
      guttersChanged(cm);
7613
    }, true);
7614
    option("keyMap", "default", function (cm, val, old) {
7615
      var next = getKeyMap(val);
7616
      var prev = old != Init && getKeyMap(old);
7617
      if (prev && prev.detach) { prev.detach(cm, next); }
7618
      if (next.attach) { next.attach(cm, prev || null); }
7619
    });
7620
    option("extraKeys", null);
7621
    option("configureMouse", null);
7622
 
7623
    option("lineWrapping", false, wrappingChanged, true);
7624
    option("gutters", [], function (cm) {
7625
      setGuttersForLineNumbers(cm.options);
7626
      guttersChanged(cm);
7627
    }, true);
7628
    option("fixedGutter", true, function (cm, val) {
7629
      cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
7630
      cm.refresh();
7631
    }, true);
7632
    option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
7633
    option("scrollbarStyle", "native", function (cm) {
7634
      initScrollbars(cm);
7635
      updateScrollbars(cm);
7636
      cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
7637
      cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
7638
    }, true);
7639
    option("lineNumbers", false, function (cm) {
7640
      setGuttersForLineNumbers(cm.options);
7641
      guttersChanged(cm);
7642
    }, true);
7643
    option("firstLineNumber", 1, guttersChanged, true);
7644
    option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
7645
    option("showCursorWhenSelecting", false, updateSelection, true);
7646
 
7647
    option("resetSelectionOnContextMenu", true);
7648
    option("lineWiseCopyCut", true);
7649
    option("pasteLinesPerSelection", true);
7650
    option("selectionsMayTouch", false);
7651
 
7652
    option("readOnly", false, function (cm, val) {
7653
      if (val == "nocursor") {
7654
        onBlur(cm);
7655
        cm.display.input.blur();
7656
      }
7657
      cm.display.input.readOnlyChanged(val);
7658
    });
7659
    option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
7660
    option("dragDrop", true, dragDropChanged);
7661
    option("allowDropFileTypes", null);
7662
 
7663
    option("cursorBlinkRate", 530);
7664
    option("cursorScrollMargin", 0);
7665
    option("cursorHeight", 1, updateSelection, true);
7666
    option("singleCursorHeightPerLine", true, updateSelection, true);
7667
    option("workTime", 100);
7668
    option("workDelay", 100);
7669
    option("flattenSpans", true, resetModeState, true);
7670
    option("addModeClass", false, resetModeState, true);
7671
    option("pollInterval", 100);
7672
    option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
7673
    option("historyEventDelay", 1250);
7674
    option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
7675
    option("maxHighlightLength", 10000, resetModeState, true);
7676
    option("moveInputWithCursor", true, function (cm, val) {
7677
      if (!val) { cm.display.input.resetPosition(); }
7678
    });
7679
 
7680
    option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
7681
    option("autofocus", null);
7682
    option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
7683
    option("phrases", null);
7684
  }
7685
 
7686
  function guttersChanged(cm) {
7687
    updateGutters(cm);
7688
    regChange(cm);
7689
    alignHorizontally(cm);
7690
  }
7691
 
7692
  function dragDropChanged(cm, value, old) {
7693
    var wasOn = old && old != Init;
7694
    if (!value != !wasOn) {
7695
      var funcs = cm.display.dragFunctions;
7696
      var toggle = value ? on : off;
7697
      toggle(cm.display.scroller, "dragstart", funcs.start);
7698
      toggle(cm.display.scroller, "dragenter", funcs.enter);
7699
      toggle(cm.display.scroller, "dragover", funcs.over);
7700
      toggle(cm.display.scroller, "dragleave", funcs.leave);
7701
      toggle(cm.display.scroller, "drop", funcs.drop);
7702
    }
7703
  }
7704
 
7705
  function wrappingChanged(cm) {
7706
    if (cm.options.lineWrapping) {
7707
      addClass(cm.display.wrapper, "CodeMirror-wrap");
7708
      cm.display.sizer.style.minWidth = "";
7709
      cm.display.sizerWidth = null;
7710
    } else {
7711
      rmClass(cm.display.wrapper, "CodeMirror-wrap");
7712
      findMaxLine(cm);
7713
    }
7714
    estimateLineHeights(cm);
7715
    regChange(cm);
7716
    clearCaches(cm);
7717
    setTimeout(function () { return updateScrollbars(cm); }, 100);
7718
  }
7719
 
7720
  // A CodeMirror instance represents an editor. This is the object
7721
  // that user code is usually dealing with.
7722
 
7723
  function CodeMirror(place, options) {
7724
    var this$1 = this;
7725
 
7726
    if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
7727
 
7728
    this.options = options = options ? copyObj(options) : {};
7729
    // Determine effective options based on given values and defaults.
7730
    copyObj(defaults, options, false);
7731
    setGuttersForLineNumbers(options);
7732
 
7733
    var doc = options.value;
7734
    if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
7735
    else if (options.mode) { doc.modeOption = options.mode; }
7736
    this.doc = doc;
7737
 
7738
    var input = new CodeMirror.inputStyles[options.inputStyle](this);
7739
    var display = this.display = new Display(place, doc, input);
7740
    display.wrapper.CodeMirror = this;
7741
    updateGutters(this);
7742
    themeChanged(this);
7743
    if (options.lineWrapping)
7744
      { this.display.wrapper.className += " CodeMirror-wrap"; }
7745
    initScrollbars(this);
7746
 
7747
    this.state = {
7748
      keyMaps: [],  // stores maps added by addKeyMap
7749
      overlays: [], // highlighting overlays, as added by addOverlay
7750
      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
7751
      overwrite: false,
7752
      delayingBlurEvent: false,
7753
      focused: false,
7754
      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
7755
      pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
7756
      selectingText: false,
7757
      draggingText: false,
7758
      highlight: new Delayed(), // stores highlight worker timeout
7759
      keySeq: null,  // Unfinished key sequence
7760
      specialChars: null
7761
    };
7762
 
7763
    if (options.autofocus && !mobile) { display.input.focus(); }
7764
 
7765
    // Override magic textarea content restore that IE sometimes does
7766
    // on our hidden textarea on reload
7767
    if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
7768
 
7769
    registerEventHandlers(this);
7770
    ensureGlobalHandlers();
7771
 
7772
    startOperation(this);
7773
    this.curOp.forceUpdate = true;
7774
    attachDoc(this, doc);
7775
 
7776
    if ((options.autofocus && !mobile) || this.hasFocus())
7777
      { setTimeout(bind(onFocus, this), 20); }
7778
    else
7779
      { onBlur(this); }
7780
 
7781
    for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
7782
      { optionHandlers[opt](this, options[opt], Init); } }
7783
    maybeUpdateLineNumberWidth(this);
7784
    if (options.finishInit) { options.finishInit(this); }
7785
    for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
7786
    endOperation(this);
7787
    // Suppress optimizelegibility in Webkit, since it breaks text
7788
    // measuring on line wrapping boundaries.
7789
    if (webkit && options.lineWrapping &&
7790
        getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
7791
      { display.lineDiv.style.textRendering = "auto"; }
7792
  }
7793
 
7794
  // The default configuration options.
7795
  CodeMirror.defaults = defaults;
7796
  // Functions to run when options are changed.
7797
  CodeMirror.optionHandlers = optionHandlers;
7798
 
7799
  // Attach the necessary event handlers when initializing the editor
7800
  function registerEventHandlers(cm) {
7801
    var d = cm.display;
7802
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
7803
    // Older IE's will not fire a second mousedown for a double click
7804
    if (ie && ie_version < 11)
7805
      { on(d.scroller, "dblclick", operation(cm, function (e) {
7806
        if (signalDOMEvent(cm, e)) { return }
7807
        var pos = posFromMouse(cm, e);
7808
        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
7809
        e_preventDefault(e);
7810
        var word = cm.findWordAt(pos);
7811
        extendSelection(cm.doc, word.anchor, word.head);
7812
      })); }
7813
    else
7814
      { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
7815
    // Some browsers fire contextmenu *after* opening the menu, at
7816
    // which point we can't mess with it anymore. Context menu is
7817
    // handled in onMouseDown for these browsers.
7818
    on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
7819
 
7820
    // Used to suppress mouse event handling when a touch happens
7821
    var touchFinished, prevTouch = {end: 0};
7822
    function finishTouch() {
7823
      if (d.activeTouch) {
7824
        touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
7825
        prevTouch = d.activeTouch;
7826
        prevTouch.end = +new Date;
7827
      }
7828
    }
7829
    function isMouseLikeTouchEvent(e) {
7830
      if (e.touches.length != 1) { return false }
7831
      var touch = e.touches[0];
7832
      return touch.radiusX <= 1 && touch.radiusY <= 1
7833
    }
7834
    function farAway(touch, other) {
7835
      if (other.left == null) { return true }
7836
      var dx = other.left - touch.left, dy = other.top - touch.top;
7837
      return dx * dx + dy * dy > 20 * 20
7838
    }
7839
    on(d.scroller, "touchstart", function (e) {
7840
      if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
7841
        d.input.ensurePolled();
7842
        clearTimeout(touchFinished);
7843
        var now = +new Date;
7844
        d.activeTouch = {start: now, moved: false,
7845
                         prev: now - prevTouch.end <= 300 ? prevTouch : null};
7846
        if (e.touches.length == 1) {
7847
          d.activeTouch.left = e.touches[0].pageX;
7848
          d.activeTouch.top = e.touches[0].pageY;
7849
        }
7850
      }
7851
    });
7852
    on(d.scroller, "touchmove", function () {
7853
      if (d.activeTouch) { d.activeTouch.moved = true; }
7854
    });
7855
    on(d.scroller, "touchend", function (e) {
7856
      var touch = d.activeTouch;
7857
      if (touch && !eventInWidget(d, e) && touch.left != null &&
7858
          !touch.moved && new Date - touch.start < 300) {
7859
        var pos = cm.coordsChar(d.activeTouch, "page"), range;
7860
        if (!touch.prev || farAway(touch, touch.prev)) // Single tap
7861
          { range = new Range(pos, pos); }
7862
        else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
7863
          { range = cm.findWordAt(pos); }
7864
        else // Triple tap
7865
          { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
7866
        cm.setSelection(range.anchor, range.head);
7867
        cm.focus();
7868
        e_preventDefault(e);
7869
      }
7870
      finishTouch();
7871
    });
7872
    on(d.scroller, "touchcancel", finishTouch);
7873
 
7874
    // Sync scrolling between fake scrollbars and real scrollable
7875
    // area, ensure viewport is updated when scrolling.
7876
    on(d.scroller, "scroll", function () {
7877
      if (d.scroller.clientHeight) {
7878
        updateScrollTop(cm, d.scroller.scrollTop);
7879
        setScrollLeft(cm, d.scroller.scrollLeft, true);
7880
        signal(cm, "scroll", cm);
7881
      }
7882
    });
7883
 
7884
    // Listen to wheel events in order to try and update the viewport on time.
7885
    on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
7886
    on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
7887
 
7888
    // Prevent wrapper from ever scrolling
7889
    on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
7890
 
7891
    d.dragFunctions = {
7892
      enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
7893
      over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
7894
      start: function (e) { return onDragStart(cm, e); },
7895
      drop: operation(cm, onDrop),
7896
      leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
7897
    };
7898
 
7899
    var inp = d.input.getField();
7900
    on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
7901
    on(inp, "keydown", operation(cm, onKeyDown));
7902
    on(inp, "keypress", operation(cm, onKeyPress));
7903
    on(inp, "focus", function (e) { return onFocus(cm, e); });
7904
    on(inp, "blur", function (e) { return onBlur(cm, e); });
7905
  }
7906
 
7907
  var initHooks = [];
7908
  CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
7909
 
7910
  // Indent the given line. The how parameter can be "smart",
7911
  // "add"/null, "subtract", or "prev". When aggressive is false
7912
  // (typically set to true for forced single-line indents), empty
7913
  // lines are not indented, and places where the mode returns Pass
7914
  // are left alone.
7915
  function indentLine(cm, n, how, aggressive) {
7916
    var doc = cm.doc, state;
7917
    if (how == null) { how = "add"; }
7918
    if (how == "smart") {
7919
      // Fall back to "prev" when the mode doesn't have an indentation
7920
      // method.
7921
      if (!doc.mode.indent) { how = "prev"; }
7922
      else { state = getContextBefore(cm, n).state; }
7923
    }
7924
 
7925
    var tabSize = cm.options.tabSize;
7926
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
7927
    if (line.stateAfter) { line.stateAfter = null; }
7928
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
7929
    if (!aggressive && !/\S/.test(line.text)) {
7930
      indentation = 0;
7931
      how = "not";
7932
    } else if (how == "smart") {
7933
      indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
7934
      if (indentation == Pass || indentation > 150) {
7935
        if (!aggressive) { return }
7936
        how = "prev";
7937
      }
7938
    }
7939
    if (how == "prev") {
7940
      if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
7941
      else { indentation = 0; }
7942
    } else if (how == "add") {
7943
      indentation = curSpace + cm.options.indentUnit;
7944
    } else if (how == "subtract") {
7945
      indentation = curSpace - cm.options.indentUnit;
7946
    } else if (typeof how == "number") {
7947
      indentation = curSpace + how;
7948
    }
7949
    indentation = Math.max(0, indentation);
7950
 
7951
    var indentString = "", pos = 0;
7952
    if (cm.options.indentWithTabs)
7953
      { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
7954
    if (pos < indentation) { indentString += spaceStr(indentation - pos); }
7955
 
7956
    if (indentString != curSpaceString) {
7957
      replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
7958
      line.stateAfter = null;
7959
      return true
7960
    } else {
7961
      // Ensure that, if the cursor was in the whitespace at the start
7962
      // of the line, it is moved to the end of that space.
7963
      for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
7964
        var range = doc.sel.ranges[i$1];
7965
        if (range.head.line == n && range.head.ch < curSpaceString.length) {
7966
          var pos$1 = Pos(n, curSpaceString.length);
7967
          replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
7968
          break
7969
        }
7970
      }
7971
    }
7972
  }
7973
 
7974
  // This will be set to a {lineWise: bool, text: [string]} object, so
7975
  // that, when pasting, we know what kind of selections the copied
7976
  // text was made out of.
7977
  var lastCopied = null;
7978
 
7979
  function setLastCopied(newLastCopied) {
7980
    lastCopied = newLastCopied;
7981
  }
7982
 
7983
  function applyTextInput(cm, inserted, deleted, sel, origin) {
7984
    var doc = cm.doc;
7985
    cm.display.shift = false;
7986
    if (!sel) { sel = doc.sel; }
7987
 
7988
    var paste = cm.state.pasteIncoming || origin == "paste";
7989
    var textLines = splitLinesAuto(inserted), multiPaste = null;
7990
    // When pasting N lines into N selections, insert one line per selection
7991
    if (paste && sel.ranges.length > 1) {
7992
      if (lastCopied && lastCopied.text.join("\n") == inserted) {
7993
        if (sel.ranges.length % lastCopied.text.length == 0) {
7994
          multiPaste = [];
7995
          for (var i = 0; i < lastCopied.text.length; i++)
7996
            { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
7997
        }
7998
      } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
7999
        multiPaste = map(textLines, function (l) { return [l]; });
8000
      }
8001
    }
8002
 
8003
    var updateInput;
8004
    // Normal behavior is to insert the new text into every selection
8005
    for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
8006
      var range$$1 = sel.ranges[i$1];
8007
      var from = range$$1.from(), to = range$$1.to();
8008
      if (range$$1.empty()) {
8009
        if (deleted && deleted > 0) // Handle deletion
8010
          { from = Pos(from.line, from.ch - deleted); }
8011
        else if (cm.state.overwrite && !paste) // Handle overwrite
8012
          { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
8013
        else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
8014
          { from = to = Pos(from.line, 0); }
8015
      }
8016
      updateInput = cm.curOp.updateInput;
8017
      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
8018
                         origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
8019
      makeChange(cm.doc, changeEvent);
8020
      signalLater(cm, "inputRead", cm, changeEvent);
8021
    }
8022
    if (inserted && !paste)
8023
      { triggerElectric(cm, inserted); }
8024
 
8025
    ensureCursorVisible(cm);
8026
    cm.curOp.updateInput = updateInput;
8027
    cm.curOp.typing = true;
8028
    cm.state.pasteIncoming = cm.state.cutIncoming = false;
8029
  }
8030
 
8031
  function handlePaste(e, cm) {
8032
    var pasted = e.clipboardData && e.clipboardData.getData("Text");
8033
    if (pasted) {
8034
      e.preventDefault();
8035
      if (!cm.isReadOnly() && !cm.options.disableInput)
8036
        { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
8037
      return true
8038
    }
8039
  }
8040
 
8041
  function triggerElectric(cm, inserted) {
8042
    // When an 'electric' character is inserted, immediately trigger a reindent
8043
    if (!cm.options.electricChars || !cm.options.smartIndent) { return }
8044
    var sel = cm.doc.sel;
8045
 
8046
    for (var i = sel.ranges.length - 1; i >= 0; i--) {
8047
      var range$$1 = sel.ranges[i];
8048
      if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
8049
      var mode = cm.getModeAt(range$$1.head);
8050
      var indented = false;
8051
      if (mode.electricChars) {
8052
        for (var j = 0; j < mode.electricChars.length; j++)
8053
          { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
8054
            indented = indentLine(cm, range$$1.head.line, "smart");
8055
            break
8056
          } }
8057
      } else if (mode.electricInput) {
8058
        if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
8059
          { indented = indentLine(cm, range$$1.head.line, "smart"); }
8060
      }
8061
      if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
8062
    }
8063
  }
8064
 
8065
  function copyableRanges(cm) {
8066
    var text = [], ranges = [];
8067
    for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
8068
      var line = cm.doc.sel.ranges[i].head.line;
8069
      var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
8070
      ranges.push(lineRange);
8071
      text.push(cm.getRange(lineRange.anchor, lineRange.head));
8072
    }
8073
    return {text: text, ranges: ranges}
8074
  }
8075
 
8076
  function disableBrowserMagic(field, spellcheck) {
8077
    field.setAttribute("autocorrect", "off");
8078
    field.setAttribute("autocapitalize", "off");
8079
    field.setAttribute("spellcheck", !!spellcheck);
8080
  }
8081
 
8082
  function hiddenTextarea() {
8083
    var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
8084
    var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
8085
    // The textarea is kept positioned near the cursor to prevent the
8086
    // fact that it'll be scrolled into view on input from scrolling
8087
    // our fake cursor out of view. On webkit, when wrap=off, paste is
8088
    // very slow. So make the area wide instead.
8089
    if (webkit) { te.style.width = "1000px"; }
8090
    else { te.setAttribute("wrap", "off"); }
8091
    // If border: 0; -- iOS fails to open keyboard (issue #1287)
8092
    if (ios) { te.style.border = "1px solid black"; }
8093
    disableBrowserMagic(te);
8094
    return div
8095
  }
8096
 
8097
  // The publicly visible API. Note that methodOp(f) means
8098
  // 'wrap f in an operation, performed on its `this` parameter'.
8099
 
8100
  // This is not the complete set of editor methods. Most of the
8101
  // methods defined on the Doc type are also injected into
8102
  // CodeMirror.prototype, for backwards compatibility and
8103
  // convenience.
8104
 
8105
  function addEditorMethods(CodeMirror) {
8106
    var optionHandlers = CodeMirror.optionHandlers;
8107
 
8108
    var helpers = CodeMirror.helpers = {};
8109
 
8110
    CodeMirror.prototype = {
8111
      constructor: CodeMirror,
8112
      focus: function(){window.focus(); this.display.input.focus();},
8113
 
8114
      setOption: function(option, value) {
8115
        var options = this.options, old = options[option];
8116
        if (options[option] == value && option != "mode") { return }
8117
        options[option] = value;
8118
        if (optionHandlers.hasOwnProperty(option))
8119
          { operation(this, optionHandlers[option])(this, value, old); }
8120
        signal(this, "optionChange", this, option);
8121
      },
8122
 
8123
      getOption: function(option) {return this.options[option]},
8124
      getDoc: function() {return this.doc},
8125
 
8126
      addKeyMap: function(map$$1, bottom) {
8127
        this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
8128
      },
8129
      removeKeyMap: function(map$$1) {
8130
        var maps = this.state.keyMaps;
8131
        for (var i = 0; i < maps.length; ++i)
8132
          { if (maps[i] == map$$1 || maps[i].name == map$$1) {
8133
            maps.splice(i, 1);
8134
            return true
8135
          } }
8136
      },
8137
 
8138
      addOverlay: methodOp(function(spec, options) {
8139
        var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
8140
        if (mode.startState) { throw new Error("Overlays may not be stateful.") }
8141
        insertSorted(this.state.overlays,
8142
                     {mode: mode, modeSpec: spec, opaque: options && options.opaque,
8143
                      priority: (options && options.priority) || 0},
8144
                     function (overlay) { return overlay.priority; });
8145
        this.state.modeGen++;
8146
        regChange(this);
8147
      }),
8148
      removeOverlay: methodOp(function(spec) {
8149
        var overlays = this.state.overlays;
8150
        for (var i = 0; i < overlays.length; ++i) {
8151
          var cur = overlays[i].modeSpec;
8152
          if (cur == spec || typeof spec == "string" && cur.name == spec) {
8153
            overlays.splice(i, 1);
8154
            this.state.modeGen++;
8155
            regChange(this);
8156
            return
8157
          }
8158
        }
8159
      }),
8160
 
8161
      indentLine: methodOp(function(n, dir, aggressive) {
8162
        if (typeof dir != "string" && typeof dir != "number") {
8163
          if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
8164
          else { dir = dir ? "add" : "subtract"; }
8165
        }
8166
        if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
8167
      }),
8168
      indentSelection: methodOp(function(how) {
8169
        var ranges = this.doc.sel.ranges, end = -1;
8170
        for (var i = 0; i < ranges.length; i++) {
8171
          var range$$1 = ranges[i];
8172
          if (!range$$1.empty()) {
8173
            var from = range$$1.from(), to = range$$1.to();
8174
            var start = Math.max(end, from.line);
8175
            end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
8176
            for (var j = start; j < end; ++j)
8177
              { indentLine(this, j, how); }
8178
            var newRanges = this.doc.sel.ranges;
8179
            if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
8180
              { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
8181
          } else if (range$$1.head.line > end) {
8182
            indentLine(this, range$$1.head.line, how, true);
8183
            end = range$$1.head.line;
8184
            if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
8185
          }
8186
        }
8187
      }),
8188
 
8189
      // Fetch the parser token for a given character. Useful for hacks
8190
      // that want to inspect the mode state (say, for completion).
8191
      getTokenAt: function(pos, precise) {
8192
        return takeToken(this, pos, precise)
8193
      },
8194
 
8195
      getLineTokens: function(line, precise) {
8196
        return takeToken(this, Pos(line), precise, true)
8197
      },
8198
 
8199
      getTokenTypeAt: function(pos) {
8200
        pos = clipPos(this.doc, pos);
8201
        var styles = getLineStyles(this, getLine(this.doc, pos.line));
8202
        var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
8203
        var type;
8204
        if (ch == 0) { type = styles[2]; }
8205
        else { for (;;) {
8206
          var mid = (before + after) >> 1;
8207
          if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
8208
          else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
8209
          else { type = styles[mid * 2 + 2]; break }
8210
        } }
8211
        var cut = type ? type.indexOf("overlay ") : -1;
8212
        return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
8213
      },
8214
 
8215
      getModeAt: function(pos) {
8216
        var mode = this.doc.mode;
8217
        if (!mode.innerMode) { return mode }
8218
        return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
8219
      },
8220
 
8221
      getHelper: function(pos, type) {
8222
        return this.getHelpers(pos, type)[0]
8223
      },
8224
 
8225
      getHelpers: function(pos, type) {
8226
        var found = [];
8227
        if (!helpers.hasOwnProperty(type)) { return found }
8228
        var help = helpers[type], mode = this.getModeAt(pos);
8229
        if (typeof mode[type] == "string") {
8230
          if (help[mode[type]]) { found.push(help[mode[type]]); }
8231
        } else if (mode[type]) {
8232
          for (var i = 0; i < mode[type].length; i++) {
8233
            var val = help[mode[type][i]];
8234
            if (val) { found.push(val); }
8235
          }
8236
        } else if (mode.helperType && help[mode.helperType]) {
8237
          found.push(help[mode.helperType]);
8238
        } else if (help[mode.name]) {
8239
          found.push(help[mode.name]);
8240
        }
8241
        for (var i$1 = 0; i$1 < help._global.length; i$1++) {
8242
          var cur = help._global[i$1];
8243
          if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
8244
            { found.push(cur.val); }
8245
        }
8246
        return found
8247
      },
8248
 
8249
      getStateAfter: function(line, precise) {
8250
        var doc = this.doc;
8251
        line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
8252
        return getContextBefore(this, line + 1, precise).state
8253
      },
8254
 
8255
      cursorCoords: function(start, mode) {
8256
        var pos, range$$1 = this.doc.sel.primary();
8257
        if (start == null) { pos = range$$1.head; }
8258
        else if (typeof start == "object") { pos = clipPos(this.doc, start); }
8259
        else { pos = start ? range$$1.from() : range$$1.to(); }
8260
        return cursorCoords(this, pos, mode || "page")
8261
      },
8262
 
8263
      charCoords: function(pos, mode) {
8264
        return charCoords(this, clipPos(this.doc, pos), mode || "page")
8265
      },
8266
 
8267
      coordsChar: function(coords, mode) {
8268
        coords = fromCoordSystem(this, coords, mode || "page");
8269
        return coordsChar(this, coords.left, coords.top)
8270
      },
8271
 
8272
      lineAtHeight: function(height, mode) {
8273
        height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
8274
        return lineAtHeight(this.doc, height + this.display.viewOffset)
8275
      },
8276
      heightAtLine: function(line, mode, includeWidgets) {
8277
        var end = false, lineObj;
8278
        if (typeof line == "number") {
8279
          var last = this.doc.first + this.doc.size - 1;
8280
          if (line < this.doc.first) { line = this.doc.first; }
8281
          else if (line > last) { line = last; end = true; }
8282
          lineObj = getLine(this.doc, line);
8283
        } else {
8284
          lineObj = line;
8285
        }
8286
        return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
8287
          (end ? this.doc.height - heightAtLine(lineObj) : 0)
8288
      },
8289
 
8290
      defaultTextHeight: function() { return textHeight(this.display) },
8291
      defaultCharWidth: function() { return charWidth(this.display) },
8292
 
8293
      getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
8294
 
8295
      addWidget: function(pos, node, scroll, vert, horiz) {
8296
        var display = this.display;
8297
        pos = cursorCoords(this, clipPos(this.doc, pos));
8298
        var top = pos.bottom, left = pos.left;
8299
        node.style.position = "absolute";
8300
        node.setAttribute("cm-ignore-events", "true");
8301
        this.display.input.setUneditable(node);
8302
        display.sizer.appendChild(node);
8303
        if (vert == "over") {
8304
          top = pos.top;
8305
        } else if (vert == "above" || vert == "near") {
8306
          var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
8307
          hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
8308
          // Default to positioning above (if specified and possible); otherwise default to positioning below
8309
          if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
8310
            { top = pos.top - node.offsetHeight; }
8311
          else if (pos.bottom + node.offsetHeight <= vspace)
8312
            { top = pos.bottom; }
8313
          if (left + node.offsetWidth > hspace)
8314
            { left = hspace - node.offsetWidth; }
8315
        }
8316
        node.style.top = top + "px";
8317
        node.style.left = node.style.right = "";
8318
        if (horiz == "right") {
8319
          left = display.sizer.clientWidth - node.offsetWidth;
8320
          node.style.right = "0px";
8321
        } else {
8322
          if (horiz == "left") { left = 0; }
8323
          else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
8324
          node.style.left = left + "px";
8325
        }
8326
        if (scroll)
8327
          { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
8328
      },
8329
 
8330
      triggerOnKeyDown: methodOp(onKeyDown),
8331
      triggerOnKeyPress: methodOp(onKeyPress),
8332
      triggerOnKeyUp: onKeyUp,
8333
      triggerOnMouseDown: methodOp(onMouseDown),
8334
 
8335
      execCommand: function(cmd) {
8336
        if (commands.hasOwnProperty(cmd))
8337
          { return commands[cmd].call(null, this) }
8338
      },
8339
 
8340
      triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
8341
 
8342
      findPosH: function(from, amount, unit, visually) {
8343
        var dir = 1;
8344
        if (amount < 0) { dir = -1; amount = -amount; }
8345
        var cur = clipPos(this.doc, from);
8346
        for (var i = 0; i < amount; ++i) {
8347
          cur = findPosH(this.doc, cur, dir, unit, visually);
8348
          if (cur.hitSide) { break }
8349
        }
8350
        return cur
8351
      },
8352
 
8353
      moveH: methodOp(function(dir, unit) {
8354
        var this$1 = this;
8355
 
8356
        this.extendSelectionsBy(function (range$$1) {
8357
          if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
8358
            { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
8359
          else
8360
            { return dir < 0 ? range$$1.from() : range$$1.to() }
8361
        }, sel_move);
8362
      }),
8363
 
8364
      deleteH: methodOp(function(dir, unit) {
8365
        var sel = this.doc.sel, doc = this.doc;
8366
        if (sel.somethingSelected())
8367
          { doc.replaceSelection("", null, "+delete"); }
8368
        else
8369
          { deleteNearSelection(this, function (range$$1) {
8370
            var other = findPosH(doc, range$$1.head, dir, unit, false);
8371
            return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
8372
          }); }
8373
      }),
8374
 
8375
      findPosV: function(from, amount, unit, goalColumn) {
8376
        var dir = 1, x = goalColumn;
8377
        if (amount < 0) { dir = -1; amount = -amount; }
8378
        var cur = clipPos(this.doc, from);
8379
        for (var i = 0; i < amount; ++i) {
8380
          var coords = cursorCoords(this, cur, "div");
8381
          if (x == null) { x = coords.left; }
8382
          else { coords.left = x; }
8383
          cur = findPosV(this, coords, dir, unit);
8384
          if (cur.hitSide) { break }
8385
        }
8386
        return cur
8387
      },
8388
 
8389
      moveV: methodOp(function(dir, unit) {
8390
        var this$1 = this;
8391
 
8392
        var doc = this.doc, goals = [];
8393
        var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
8394
        doc.extendSelectionsBy(function (range$$1) {
8395
          if (collapse)
8396
            { return dir < 0 ? range$$1.from() : range$$1.to() }
8397
          var headPos = cursorCoords(this$1, range$$1.head, "div");
8398
          if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
8399
          goals.push(headPos.left);
8400
          var pos = findPosV(this$1, headPos, dir, unit);
8401
          if (unit == "page" && range$$1 == doc.sel.primary())
8402
            { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
8403
          return pos
8404
        }, sel_move);
8405
        if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
8406
          { doc.sel.ranges[i].goalColumn = goals[i]; } }
8407
      }),
8408
 
8409
      // Find the word at the given position (as returned by coordsChar).
8410
      findWordAt: function(pos) {
8411
        var doc = this.doc, line = getLine(doc, pos.line).text;
8412
        var start = pos.ch, end = pos.ch;
8413
        if (line) {
8414
          var helper = this.getHelper(pos, "wordChars");
8415
          if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
8416
          var startChar = line.charAt(start);
8417
          var check = isWordChar(startChar, helper)
8418
            ? function (ch) { return isWordChar(ch, helper); }
8419
            : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
8420
            : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
8421
          while (start > 0 && check(line.charAt(start - 1))) { --start; }
8422
          while (end < line.length && check(line.charAt(end))) { ++end; }
8423
        }
8424
        return new Range(Pos(pos.line, start), Pos(pos.line, end))
8425
      },
8426
 
8427
      toggleOverwrite: function(value) {
8428
        if (value != null && value == this.state.overwrite) { return }
8429
        if (this.state.overwrite = !this.state.overwrite)
8430
          { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8431
        else
8432
          { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8433
 
8434
        signal(this, "overwriteToggle", this, this.state.overwrite);
8435
      },
8436
      hasFocus: function() { return this.display.input.getField() == activeElt() },
8437
      isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
8438
 
8439
      scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
8440
      getScrollInfo: function() {
8441
        var scroller = this.display.scroller;
8442
        return {left: scroller.scrollLeft, top: scroller.scrollTop,
8443
                height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
8444
                width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
8445
                clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
8446
      },
8447
 
8448
      scrollIntoView: methodOp(function(range$$1, margin) {
8449
        if (range$$1 == null) {
8450
          range$$1 = {from: this.doc.sel.primary().head, to: null};
8451
          if (margin == null) { margin = this.options.cursorScrollMargin; }
8452
        } else if (typeof range$$1 == "number") {
8453
          range$$1 = {from: Pos(range$$1, 0), to: null};
8454
        } else if (range$$1.from == null) {
8455
          range$$1 = {from: range$$1, to: null};
8456
        }
8457
        if (!range$$1.to) { range$$1.to = range$$1.from; }
8458
        range$$1.margin = margin || 0;
8459
 
8460
        if (range$$1.from.line != null) {
8461
          scrollToRange(this, range$$1);
8462
        } else {
8463
          scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
8464
        }
8465
      }),
8466
 
8467
      setSize: methodOp(function(width, height) {
8468
        var this$1 = this;
8469
 
8470
        var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
8471
        if (width != null) { this.display.wrapper.style.width = interpret(width); }
8472
        if (height != null) { this.display.wrapper.style.height = interpret(height); }
8473
        if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
8474
        var lineNo$$1 = this.display.viewFrom;
8475
        this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
8476
          if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
8477
            { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
8478
          ++lineNo$$1;
8479
        });
8480
        this.curOp.forceUpdate = true;
8481
        signal(this, "refresh", this);
8482
      }),
8483
 
8484
      operation: function(f){return runInOp(this, f)},
8485
      startOperation: function(){return startOperation(this)},
8486
      endOperation: function(){return endOperation(this)},
8487
 
8488
      refresh: methodOp(function() {
8489
        var oldHeight = this.display.cachedTextHeight;
8490
        regChange(this);
8491
        this.curOp.forceUpdate = true;
8492
        clearCaches(this);
8493
        scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
8494
        updateGutterSpace(this);
8495
        if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
8496
          { estimateLineHeights(this); }
8497
        signal(this, "refresh", this);
8498
      }),
8499
 
8500
      swapDoc: methodOp(function(doc) {
8501
        var old = this.doc;
8502
        old.cm = null;
8503
        attachDoc(this, doc);
8504
        clearCaches(this);
8505
        this.display.input.reset();
8506
        scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
8507
        this.curOp.forceScroll = true;
8508
        signalLater(this, "swapDoc", this, old);
8509
        return old
8510
      }),
8511
 
8512
      phrase: function(phraseText) {
8513
        var phrases = this.options.phrases;
8514
        return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
8515
      },
8516
 
8517
      getInputField: function(){return this.display.input.getField()},
8518
      getWrapperElement: function(){return this.display.wrapper},
8519
      getScrollerElement: function(){return this.display.scroller},
8520
      getGutterElement: function(){return this.display.gutters}
8521
    };
8522
    eventMixin(CodeMirror);
8523
 
8524
    CodeMirror.registerHelper = function(type, name, value) {
8525
      if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
8526
      helpers[type][name] = value;
8527
    };
8528
    CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
8529
      CodeMirror.registerHelper(type, name, value);
8530
      helpers[type]._global.push({pred: predicate, val: value});
8531
    };
8532
  }
8533
 
8534
  // Used for horizontal relative motion. Dir is -1 or 1 (left or
8535
  // right), unit can be "char", "column" (like char, but doesn't
8536
  // cross line boundaries), "word" (across next word), or "group" (to
8537
  // the start of next group of word or non-word-non-whitespace
8538
  // chars). The visually param controls whether, in right-to-left
8539
  // text, direction 1 means to move towards the next index in the
8540
  // string, or towards the character to the right of the current
8541
  // position. The resulting position will have a hitSide=true
8542
  // property if it reached the end of the document.
8543
  function findPosH(doc, pos, dir, unit, visually) {
8544
    var oldPos = pos;
8545
    var origDir = dir;
8546
    var lineObj = getLine(doc, pos.line);
8547
    function findNextLine() {
8548
      var l = pos.line + dir;
8549
      if (l < doc.first || l >= doc.first + doc.size) { return false }
8550
      pos = new Pos(l, pos.ch, pos.sticky);
8551
      return lineObj = getLine(doc, l)
8552
    }
8553
    function moveOnce(boundToLine) {
8554
      var next;
8555
      if (visually) {
8556
        next = moveVisually(doc.cm, lineObj, pos, dir);
8557
      } else {
8558
        next = moveLogically(lineObj, pos, dir);
8559
      }
8560
      if (next == null) {
8561
        if (!boundToLine && findNextLine())
8562
          { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
8563
        else
8564
          { return false }
8565
      } else {
8566
        pos = next;
8567
      }
8568
      return true
8569
    }
8570
 
8571
    if (unit == "char") {
8572
      moveOnce();
8573
    } else if (unit == "column") {
8574
      moveOnce(true);
8575
    } else if (unit == "word" || unit == "group") {
8576
      var sawType = null, group = unit == "group";
8577
      var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
8578
      for (var first = true;; first = false) {
8579
        if (dir < 0 && !moveOnce(!first)) { break }
8580
        var cur = lineObj.text.charAt(pos.ch) || "\n";
8581
        var type = isWordChar(cur, helper) ? "w"
8582
          : group && cur == "\n" ? "n"
8583
          : !group || /\s/.test(cur) ? null
8584
          : "p";
8585
        if (group && !first && !type) { type = "s"; }
8586
        if (sawType && sawType != type) {
8587
          if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
8588
          break
8589
        }
8590
 
8591
        if (type) { sawType = type; }
8592
        if (dir > 0 && !moveOnce(!first)) { break }
8593
      }
8594
    }
8595
    var result = skipAtomic(doc, pos, oldPos, origDir, true);
8596
    if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
8597
    return result
8598
  }
8599
 
8600
  // For relative vertical movement. Dir may be -1 or 1. Unit can be
8601
  // "page" or "line". The resulting position will have a hitSide=true
8602
  // property if it reached the end of the document.
8603
  function findPosV(cm, pos, dir, unit) {
8604
    var doc = cm.doc, x = pos.left, y;
8605
    if (unit == "page") {
8606
      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
8607
      var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
8608
      y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
8609
 
8610
    } else if (unit == "line") {
8611
      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
8612
    }
8613
    var target;
8614
    for (;;) {
8615
      target = coordsChar(cm, x, y);
8616
      if (!target.outside) { break }
8617
      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
8618
      y += dir * 5;
8619
    }
8620
    return target
8621
  }
8622
 
8623
  // CONTENTEDITABLE INPUT STYLE
8624
 
8625
  var ContentEditableInput = function(cm) {
8626
    this.cm = cm;
8627
    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
8628
    this.polling = new Delayed();
8629
    this.composing = null;
8630
    this.gracePeriod = false;
8631
    this.readDOMTimeout = null;
8632
  };
8633
 
8634
  ContentEditableInput.prototype.init = function (display) {
8635
      var this$1 = this;
8636
 
8637
    var input = this, cm = input.cm;
8638
    var div = input.div = display.lineDiv;
8639
    disableBrowserMagic(div, cm.options.spellcheck);
8640
 
8641
    on(div, "paste", function (e) {
8642
      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
8643
      // IE doesn't fire input events, so we schedule a read for the pasted content in this way
8644
      if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
8645
    });
8646
 
8647
    on(div, "compositionstart", function (e) {
8648
      this$1.composing = {data: e.data, done: false};
8649
    });
8650
    on(div, "compositionupdate", function (e) {
8651
      if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
8652
    });
8653
    on(div, "compositionend", function (e) {
8654
      if (this$1.composing) {
8655
        if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
8656
        this$1.composing.done = true;
8657
      }
8658
    });
8659
 
8660
    on(div, "touchstart", function () { return input.forceCompositionEnd(); });
8661
 
8662
    on(div, "input", function () {
8663
      if (!this$1.composing) { this$1.readFromDOMSoon(); }
8664
    });
8665
 
8666
    function onCopyCut(e) {
8667
      if (signalDOMEvent(cm, e)) { return }
8668
      if (cm.somethingSelected()) {
8669
        setLastCopied({lineWise: false, text: cm.getSelections()});
8670
        if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
8671
      } else if (!cm.options.lineWiseCopyCut) {
8672
        return
8673
      } else {
8674
        var ranges = copyableRanges(cm);
8675
        setLastCopied({lineWise: true, text: ranges.text});
8676
        if (e.type == "cut") {
8677
          cm.operation(function () {
8678
            cm.setSelections(ranges.ranges, 0, sel_dontScroll);
8679
            cm.replaceSelection("", null, "cut");
8680
          });
8681
        }
8682
      }
8683
      if (e.clipboardData) {
8684
        e.clipboardData.clearData();
8685
        var content = lastCopied.text.join("\n");
8686
        // iOS exposes the clipboard API, but seems to discard content inserted into it
8687
        e.clipboardData.setData("Text", content);
8688
        if (e.clipboardData.getData("Text") == content) {
8689
          e.preventDefault();
8690
          return
8691
        }
8692
      }
8693
      // Old-fashioned briefly-focus-a-textarea hack
8694
      var kludge = hiddenTextarea(), te = kludge.firstChild;
8695
      cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
8696
      te.value = lastCopied.text.join("\n");
8697
      var hadFocus = document.activeElement;
8698
      selectInput(te);
8699
      setTimeout(function () {
8700
        cm.display.lineSpace.removeChild(kludge);
8701
        hadFocus.focus();
8702
        if (hadFocus == div) { input.showPrimarySelection(); }
8703
      }, 50);
8704
    }
8705
    on(div, "copy", onCopyCut);
8706
    on(div, "cut", onCopyCut);
8707
  };
8708
 
8709
  ContentEditableInput.prototype.prepareSelection = function () {
8710
    var result = prepareSelection(this.cm, false);
8711
    result.focus = this.cm.state.focused;
8712
    return result
8713
  };
8714
 
8715
  ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
8716
    if (!info || !this.cm.display.view.length) { return }
8717
    if (info.focus || takeFocus) { this.showPrimarySelection(); }
8718
    this.showMultipleSelections(info);
8719
  };
8720
 
8721
  ContentEditableInput.prototype.getSelection = function () {
8722
    return this.cm.display.wrapper.ownerDocument.getSelection()
8723
  };
8724
 
8725
  ContentEditableInput.prototype.showPrimarySelection = function () {
8726
    var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
8727
    var from = prim.from(), to = prim.to();
8728
 
8729
    if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
8730
      sel.removeAllRanges();
8731
      return
8732
    }
8733
 
8734
    var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
8735
    var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
8736
    if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
8737
        cmp(minPos(curAnchor, curFocus), from) == 0 &&
8738
        cmp(maxPos(curAnchor, curFocus), to) == 0)
8739
      { return }
8740
 
8741
    var view = cm.display.view;
8742
    var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
8743
        {node: view[0].measure.map[2], offset: 0};
8744
    var end = to.line < cm.display.viewTo && posToDOM(cm, to);
8745
    if (!end) {
8746
      var measure = view[view.length - 1].measure;
8747
      var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
8748
      end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
8749
    }
8750
 
8751
    if (!start || !end) {
8752
      sel.removeAllRanges();
8753
      return
8754
    }
8755
 
8756
    var old = sel.rangeCount && sel.getRangeAt(0), rng;
8757
    try { rng = range(start.node, start.offset, end.offset, end.node); }
8758
    catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
8759
    if (rng) {
8760
      if (!gecko && cm.state.focused) {
8761
        sel.collapse(start.node, start.offset);
8762
        if (!rng.collapsed) {
8763
          sel.removeAllRanges();
8764
          sel.addRange(rng);
8765
        }
8766
      } else {
8767
        sel.removeAllRanges();
8768
        sel.addRange(rng);
8769
      }
8770
      if (old && sel.anchorNode == null) { sel.addRange(old); }
8771
      else if (gecko) { this.startGracePeriod(); }
8772
    }
8773
    this.rememberSelection();
8774
  };
8775
 
8776
  ContentEditableInput.prototype.startGracePeriod = function () {
8777
      var this$1 = this;
8778
 
8779
    clearTimeout(this.gracePeriod);
8780
    this.gracePeriod = setTimeout(function () {
8781
      this$1.gracePeriod = false;
8782
      if (this$1.selectionChanged())
8783
        { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
8784
    }, 20);
8785
  };
8786
 
8787
  ContentEditableInput.prototype.showMultipleSelections = function (info) {
8788
    removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
8789
    removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
8790
  };
8791
 
8792
  ContentEditableInput.prototype.rememberSelection = function () {
8793
    var sel = this.getSelection();
8794
    this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
8795
    this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
8796
  };
8797
 
8798
  ContentEditableInput.prototype.selectionInEditor = function () {
8799
    var sel = this.getSelection();
8800
    if (!sel.rangeCount) { return false }
8801
    var node = sel.getRangeAt(0).commonAncestorContainer;
8802
    return contains(this.div, node)
8803
  };
8804
 
8805
  ContentEditableInput.prototype.focus = function () {
8806
    if (this.cm.options.readOnly != "nocursor") {
8807
      if (!this.selectionInEditor())
8808
        { this.showSelection(this.prepareSelection(), true); }
8809
      this.div.focus();
8810
    }
8811
  };
8812
  ContentEditableInput.prototype.blur = function () { this.div.blur(); };
8813
  ContentEditableInput.prototype.getField = function () { return this.div };
8814
 
8815
  ContentEditableInput.prototype.supportsTouch = function () { return true };
8816
 
8817
  ContentEditableInput.prototype.receivedFocus = function () {
8818
    var input = this;
8819
    if (this.selectionInEditor())
8820
      { this.pollSelection(); }
8821
    else
8822
      { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
8823
 
8824
    function poll() {
8825
      if (input.cm.state.focused) {
8826
        input.pollSelection();
8827
        input.polling.set(input.cm.options.pollInterval, poll);
8828
      }
8829
    }
8830
    this.polling.set(this.cm.options.pollInterval, poll);
8831
  };
8832
 
8833
  ContentEditableInput.prototype.selectionChanged = function () {
8834
    var sel = this.getSelection();
8835
    return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
8836
      sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
8837
  };
8838
 
8839
  ContentEditableInput.prototype.pollSelection = function () {
8840
    if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
8841
    var sel = this.getSelection(), cm = this.cm;
8842
    // On Android Chrome (version 56, at least), backspacing into an
8843
    // uneditable block element will put the cursor in that element,
8844
    // and then, because it's not editable, hide the virtual keyboard.
8845
    // Because Android doesn't allow us to actually detect backspace
8846
    // presses in a sane way, this code checks for when that happens
8847
    // and simulates a backspace press in this case.
8848
    if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
8849
      this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
8850
      this.blur();
8851
      this.focus();
8852
      return
8853
    }
8854
    if (this.composing) { return }
8855
    this.rememberSelection();
8856
    var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
8857
    var head = domToPos(cm, sel.focusNode, sel.focusOffset);
8858
    if (anchor && head) { runInOp(cm, function () {
8859
      setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
8860
      if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
8861
    }); }
8862
  };
8863
 
8864
  ContentEditableInput.prototype.pollContent = function () {
8865
    if (this.readDOMTimeout != null) {
8866
      clearTimeout(this.readDOMTimeout);
8867
      this.readDOMTimeout = null;
8868
    }
8869
 
8870
    var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
8871
    var from = sel.from(), to = sel.to();
8872
    if (from.ch == 0 && from.line > cm.firstLine())
8873
      { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
8874
    if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
8875
      { to = Pos(to.line + 1, 0); }
8876
    if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
8877
 
8878
    var fromIndex, fromLine, fromNode;
8879
    if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
8880
      fromLine = lineNo(display.view[0].line);
8881
      fromNode = display.view[0].node;
8882
    } else {
8883
      fromLine = lineNo(display.view[fromIndex].line);
8884
      fromNode = display.view[fromIndex - 1].node.nextSibling;
8885
    }
8886
    var toIndex = findViewIndex(cm, to.line);
8887
    var toLine, toNode;
8888
    if (toIndex == display.view.length - 1) {
8889
      toLine = display.viewTo - 1;
8890
      toNode = display.lineDiv.lastChild;
8891
    } else {
8892
      toLine = lineNo(display.view[toIndex + 1].line) - 1;
8893
      toNode = display.view[toIndex + 1].node.previousSibling;
8894
    }
8895
 
8896
    if (!fromNode) { return false }
8897
    var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
8898
    var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
8899
    while (newText.length > 1 && oldText.length > 1) {
8900
      if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
8901
      else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
8902
      else { break }
8903
    }
8904
 
8905
    var cutFront = 0, cutEnd = 0;
8906
    var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
8907
    while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
8908
      { ++cutFront; }
8909
    var newBot = lst(newText), oldBot = lst(oldText);
8910
    var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
8911
                             oldBot.length - (oldText.length == 1 ? cutFront : 0));
8912
    while (cutEnd < maxCutEnd &&
8913
           newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
8914
      { ++cutEnd; }
8915
    // Try to move start of change to start of selection if ambiguous
8916
    if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
8917
      while (cutFront && cutFront > from.ch &&
8918
             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
8919
        cutFront--;
8920
        cutEnd++;
8921
      }
8922
    }
8923
 
8924
    newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
8925
    newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
8926
 
8927
    var chFrom = Pos(fromLine, cutFront);
8928
    var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
8929
    if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
8930
      replaceRange(cm.doc, newText, chFrom, chTo, "+input");
8931
      return true
8932
    }
8933
  };
8934
 
8935
  ContentEditableInput.prototype.ensurePolled = function () {
8936
    this.forceCompositionEnd();
8937
  };
8938
  ContentEditableInput.prototype.reset = function () {
8939
    this.forceCompositionEnd();
8940
  };
8941
  ContentEditableInput.prototype.forceCompositionEnd = function () {
8942
    if (!this.composing) { return }
8943
    clearTimeout(this.readDOMTimeout);
8944
    this.composing = null;
8945
    this.updateFromDOM();
8946
    this.div.blur();
8947
    this.div.focus();
8948
  };
8949
  ContentEditableInput.prototype.readFromDOMSoon = function () {
8950
      var this$1 = this;
8951
 
8952
    if (this.readDOMTimeout != null) { return }
8953
    this.readDOMTimeout = setTimeout(function () {
8954
      this$1.readDOMTimeout = null;
8955
      if (this$1.composing) {
8956
        if (this$1.composing.done) { this$1.composing = null; }
8957
        else { return }
8958
      }
8959
      this$1.updateFromDOM();
8960
    }, 80);
8961
  };
8962
 
8963
  ContentEditableInput.prototype.updateFromDOM = function () {
8964
      var this$1 = this;
8965
 
8966
    if (this.cm.isReadOnly() || !this.pollContent())
8967
      { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
8968
  };
8969
 
8970
  ContentEditableInput.prototype.setUneditable = function (node) {
8971
    node.contentEditable = "false";
8972
  };
8973
 
8974
  ContentEditableInput.prototype.onKeyPress = function (e) {
8975
    if (e.charCode == 0 || this.composing) { return }
8976
    e.preventDefault();
8977
    if (!this.cm.isReadOnly())
8978
      { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
8979
  };
8980
 
8981
  ContentEditableInput.prototype.readOnlyChanged = function (val) {
8982
    this.div.contentEditable = String(val != "nocursor");
8983
  };
8984
 
8985
  ContentEditableInput.prototype.onContextMenu = function () {};
8986
  ContentEditableInput.prototype.resetPosition = function () {};
8987
 
8988
  ContentEditableInput.prototype.needsContentAttribute = true;
8989
 
8990
  function posToDOM(cm, pos) {
8991
    var view = findViewForLine(cm, pos.line);
8992
    if (!view || view.hidden) { return null }
8993
    var line = getLine(cm.doc, pos.line);
8994
    var info = mapFromLineView(view, line, pos.line);
8995
 
8996
    var order = getOrder(line, cm.doc.direction), side = "left";
8997
    if (order) {
8998
      var partPos = getBidiPartAt(order, pos.ch);
8999
      side = partPos % 2 ? "right" : "left";
9000
    }
9001
    var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
9002
    result.offset = result.collapse == "right" ? result.end : result.start;
9003
    return result
9004
  }
9005
 
9006
  function isInGutter(node) {
9007
    for (var scan = node; scan; scan = scan.parentNode)
9008
      { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
9009
    return false
9010
  }
9011
 
9012
  function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
9013
 
9014
  function domTextBetween(cm, from, to, fromLine, toLine) {
9015
    var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
9016
    function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
9017
    function close() {
9018
      if (closing) {
9019
        text += lineSep;
9020
        if (extraLinebreak) { text += lineSep; }
9021
        closing = extraLinebreak = false;
9022
      }
9023
    }
9024
    function addText(str) {
9025
      if (str) {
9026
        close();
9027
        text += str;
9028
      }
9029
    }
9030
    function walk(node) {
9031
      if (node.nodeType == 1) {
9032
        var cmText = node.getAttribute("cm-text");
9033
        if (cmText) {
9034
          addText(cmText);
9035
          return
9036
        }
9037
        var markerID = node.getAttribute("cm-marker"), range$$1;
9038
        if (markerID) {
9039
          var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
9040
          if (found.length && (range$$1 = found[0].find(0)))
9041
            { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
9042
          return
9043
        }
9044
        if (node.getAttribute("contenteditable") == "false") { return }
9045
        var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
9046
        if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
9047
 
9048
        if (isBlock) { close(); }
9049
        for (var i = 0; i < node.childNodes.length; i++)
9050
          { walk(node.childNodes[i]); }
9051
 
9052
        if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
9053
        if (isBlock) { closing = true; }
9054
      } else if (node.nodeType == 3) {
9055
        addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
9056
      }
9057
    }
9058
    for (;;) {
9059
      walk(from);
9060
      if (from == to) { break }
9061
      from = from.nextSibling;
9062
      extraLinebreak = false;
9063
    }
9064
    return text
9065
  }
9066
 
9067
  function domToPos(cm, node, offset) {
9068
    var lineNode;
9069
    if (node == cm.display.lineDiv) {
9070
      lineNode = cm.display.lineDiv.childNodes[offset];
9071
      if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
9072
      node = null; offset = 0;
9073
    } else {
9074
      for (lineNode = node;; lineNode = lineNode.parentNode) {
9075
        if (!lineNode || lineNode == cm.display.lineDiv) { return null }
9076
        if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
9077
      }
9078
    }
9079
    for (var i = 0; i < cm.display.view.length; i++) {
9080
      var lineView = cm.display.view[i];
9081
      if (lineView.node == lineNode)
9082
        { return locateNodeInLineView(lineView, node, offset) }
9083
    }
9084
  }
9085
 
9086
  function locateNodeInLineView(lineView, node, offset) {
9087
    var wrapper = lineView.text.firstChild, bad = false;
9088
    if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
9089
    if (node == wrapper) {
9090
      bad = true;
9091
      node = wrapper.childNodes[offset];
9092
      offset = 0;
9093
      if (!node) {
9094
        var line = lineView.rest ? lst(lineView.rest) : lineView.line;
9095
        return badPos(Pos(lineNo(line), line.text.length), bad)
9096
      }
9097
    }
9098
 
9099
    var textNode = node.nodeType == 3 ? node : null, topNode = node;
9100
    if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
9101
      textNode = node.firstChild;
9102
      if (offset) { offset = textNode.nodeValue.length; }
9103
    }
9104
    while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
9105
    var measure = lineView.measure, maps = measure.maps;
9106
 
9107
    function find(textNode, topNode, offset) {
9108
      for (var i = -1; i < (maps ? maps.length : 0); i++) {
9109
        var map$$1 = i < 0 ? measure.map : maps[i];
9110
        for (var j = 0; j < map$$1.length; j += 3) {
9111
          var curNode = map$$1[j + 2];
9112
          if (curNode == textNode || curNode == topNode) {
9113
            var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
9114
            var ch = map$$1[j] + offset;
9115
            if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
9116
            return Pos(line, ch)
9117
          }
9118
        }
9119
      }
9120
    }
9121
    var found = find(textNode, topNode, offset);
9122
    if (found) { return badPos(found, bad) }
9123
 
9124
    // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
9125
    for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
9126
      found = find(after, after.firstChild, 0);
9127
      if (found)
9128
        { return badPos(Pos(found.line, found.ch - dist), bad) }
9129
      else
9130
        { dist += after.textContent.length; }
9131
    }
9132
    for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
9133
      found = find(before, before.firstChild, -1);
9134
      if (found)
9135
        { return badPos(Pos(found.line, found.ch + dist$1), bad) }
9136
      else
9137
        { dist$1 += before.textContent.length; }
9138
    }
9139
  }
9140
 
9141
  // TEXTAREA INPUT STYLE
9142
 
9143
  var TextareaInput = function(cm) {
9144
    this.cm = cm;
9145
    // See input.poll and input.reset
9146
    this.prevInput = "";
9147
 
9148
    // Flag that indicates whether we expect input to appear real soon
9149
    // now (after some event like 'keypress' or 'input') and are
9150
    // polling intensively.
9151
    this.pollingFast = false;
9152
    // Self-resetting timeout for the poller
9153
    this.polling = new Delayed();
9154
    // Used to work around IE issue with selection being forgotten when focus moves away from textarea
9155
    this.hasSelection = false;
9156
    this.composing = null;
9157
  };
9158
 
9159
  TextareaInput.prototype.init = function (display) {
9160
      var this$1 = this;
9161
 
9162
    var input = this, cm = this.cm;
9163
    this.createField(display);
9164
    var te = this.textarea;
9165
 
9166
    display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
9167
 
9168
    // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
9169
    if (ios) { te.style.width = "0px"; }
9170
 
9171
    on(te, "input", function () {
9172
      if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
9173
      input.poll();
9174
    });
9175
 
9176
    on(te, "paste", function (e) {
9177
      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
9178
 
9179
      cm.state.pasteIncoming = true;
9180
      input.fastPoll();
9181
    });
9182
 
9183
    function prepareCopyCut(e) {
9184
      if (signalDOMEvent(cm, e)) { return }
9185
      if (cm.somethingSelected()) {
9186
        setLastCopied({lineWise: false, text: cm.getSelections()});
9187
      } else if (!cm.options.lineWiseCopyCut) {
9188
        return
9189
      } else {
9190
        var ranges = copyableRanges(cm);
9191
        setLastCopied({lineWise: true, text: ranges.text});
9192
        if (e.type == "cut") {
9193
          cm.setSelections(ranges.ranges, null, sel_dontScroll);
9194
        } else {
9195
          input.prevInput = "";
9196
          te.value = ranges.text.join("\n");
9197
          selectInput(te);
9198
        }
9199
      }
9200
      if (e.type == "cut") { cm.state.cutIncoming = true; }
9201
    }
9202
    on(te, "cut", prepareCopyCut);
9203
    on(te, "copy", prepareCopyCut);
9204
 
9205
    on(display.scroller, "paste", function (e) {
9206
      if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
9207
      cm.state.pasteIncoming = true;
9208
      input.focus();
9209
    });
9210
 
9211
    // Prevent normal selection in the editor (we handle our own)
9212
    on(display.lineSpace, "selectstart", function (e) {
9213
      if (!eventInWidget(display, e)) { e_preventDefault(e); }
9214
    });
9215
 
9216
    on(te, "compositionstart", function () {
9217
      var start = cm.getCursor("from");
9218
      if (input.composing) { input.composing.range.clear(); }
9219
      input.composing = {
9220
        start: start,
9221
        range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
9222
      };
9223
    });
9224
    on(te, "compositionend", function () {
9225
      if (input.composing) {
9226
        input.poll();
9227
        input.composing.range.clear();
9228
        input.composing = null;
9229
      }
9230
    });
9231
  };
9232
 
9233
  TextareaInput.prototype.createField = function (_display) {
9234
    // Wraps and hides input textarea
9235
    this.wrapper = hiddenTextarea();
9236
    // The semihidden textarea that is focused when the editor is
9237
    // focused, and receives input.
9238
    this.textarea = this.wrapper.firstChild;
9239
  };
9240
 
9241
  TextareaInput.prototype.prepareSelection = function () {
9242
    // Redraw the selection and/or cursor
9243
    var cm = this.cm, display = cm.display, doc = cm.doc;
9244
    var result = prepareSelection(cm);
9245
 
9246
    // Move the hidden textarea near the cursor to prevent scrolling artifacts
9247
    if (cm.options.moveInputWithCursor) {
9248
      var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
9249
      var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
9250
      result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
9251
                                          headPos.top + lineOff.top - wrapOff.top));
9252
      result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
9253
                                           headPos.left + lineOff.left - wrapOff.left));
9254
    }
9255
 
9256
    return result
9257
  };
9258
 
9259
  TextareaInput.prototype.showSelection = function (drawn) {
9260
    var cm = this.cm, display = cm.display;
9261
    removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
9262
    removeChildrenAndAdd(display.selectionDiv, drawn.selection);
9263
    if (drawn.teTop != null) {
9264
      this.wrapper.style.top = drawn.teTop + "px";
9265
      this.wrapper.style.left = drawn.teLeft + "px";
9266
    }
9267
  };
9268
 
9269
  // Reset the input to correspond to the selection (or to be empty,
9270
  // when not typing and nothing is selected)
9271
  TextareaInput.prototype.reset = function (typing) {
9272
    if (this.contextMenuPending || this.composing) { return }
9273
    var cm = this.cm;
9274
    if (cm.somethingSelected()) {
9275
      this.prevInput = "";
9276
      var content = cm.getSelection();
9277
      this.textarea.value = content;
9278
      if (cm.state.focused) { selectInput(this.textarea); }
9279
      if (ie && ie_version >= 9) { this.hasSelection = content; }
9280
    } else if (!typing) {
9281
      this.prevInput = this.textarea.value = "";
9282
      if (ie && ie_version >= 9) { this.hasSelection = null; }
9283
    }
9284
  };
9285
 
9286
  TextareaInput.prototype.getField = function () { return this.textarea };
9287
 
9288
  TextareaInput.prototype.supportsTouch = function () { return false };
9289
 
9290
  TextareaInput.prototype.focus = function () {
9291
    if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
9292
      try { this.textarea.focus(); }
9293
      catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
9294
    }
9295
  };
9296
 
9297
  TextareaInput.prototype.blur = function () { this.textarea.blur(); };
9298
 
9299
  TextareaInput.prototype.resetPosition = function () {
9300
    this.wrapper.style.top = this.wrapper.style.left = 0;
9301
  };
9302
 
9303
  TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
9304
 
9305
  // Poll for input changes, using the normal rate of polling. This
9306
  // runs as long as the editor is focused.
9307
  TextareaInput.prototype.slowPoll = function () {
9308
      var this$1 = this;
9309
 
9310
    if (this.pollingFast) { return }
9311
    this.polling.set(this.cm.options.pollInterval, function () {
9312
      this$1.poll();
9313
      if (this$1.cm.state.focused) { this$1.slowPoll(); }
9314
    });
9315
  };
9316
 
9317
  // When an event has just come in that is likely to add or change
9318
  // something in the input textarea, we poll faster, to ensure that
9319
  // the change appears on the screen quickly.
9320
  TextareaInput.prototype.fastPoll = function () {
9321
    var missed = false, input = this;
9322
    input.pollingFast = true;
9323
    function p() {
9324
      var changed = input.poll();
9325
      if (!changed && !missed) {missed = true; input.polling.set(60, p);}
9326
      else {input.pollingFast = false; input.slowPoll();}
9327
    }
9328
    input.polling.set(20, p);
9329
  };
9330
 
9331
  // Read input from the textarea, and update the document to match.
9332
  // When something is selected, it is present in the textarea, and
9333
  // selected (unless it is huge, in which case a placeholder is
9334
  // used). When nothing is selected, the cursor sits after previously
9335
  // seen text (can be empty), which is stored in prevInput (we must
9336
  // not reset the textarea when typing, because that breaks IME).
9337
  TextareaInput.prototype.poll = function () {
9338
      var this$1 = this;
9339
 
9340
    var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
9341
    // Since this is called a *lot*, try to bail out as cheaply as
9342
    // possible when it is clear that nothing happened. hasSelection
9343
    // will be the case when there is a lot of text in the textarea,
9344
    // in which case reading its value would be expensive.
9345
    if (this.contextMenuPending || !cm.state.focused ||
9346
        (hasSelection(input) && !prevInput && !this.composing) ||
9347
        cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
9348
      { return false }
9349
 
9350
    var text = input.value;
9351
    // If nothing changed, bail.
9352
    if (text == prevInput && !cm.somethingSelected()) { return false }
9353
    // Work around nonsensical selection resetting in IE9/10, and
9354
    // inexplicable appearance of private area unicode characters on
9355
    // some key combos in Mac (#2689).
9356
    if (ie && ie_version >= 9 && this.hasSelection === text ||
9357
        mac && /[\uf700-\uf7ff]/.test(text)) {
9358
      cm.display.input.reset();
9359
      return false
9360
    }
9361
 
9362
    if (cm.doc.sel == cm.display.selForContextMenu) {
9363
      var first = text.charCodeAt(0);
9364
      if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
9365
      if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
9366
    }
9367
    // Find the part of the input that is actually new
9368
    var same = 0, l = Math.min(prevInput.length, text.length);
9369
    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
9370
 
9371
    runInOp(cm, function () {
9372
      applyTextInput(cm, text.slice(same), prevInput.length - same,
9373
                     null, this$1.composing ? "*compose" : null);
9374
 
9375
      // Don't leave long text in the textarea, since it makes further polling slow
9376
      if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
9377
      else { this$1.prevInput = text; }
9378
 
9379
      if (this$1.composing) {
9380
        this$1.composing.range.clear();
9381
        this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
9382
                                           {className: "CodeMirror-composing"});
9383
      }
9384
    });
9385
    return true
9386
  };
9387
 
9388
  TextareaInput.prototype.ensurePolled = function () {
9389
    if (this.pollingFast && this.poll()) { this.pollingFast = false; }
9390
  };
9391
 
9392
  TextareaInput.prototype.onKeyPress = function () {
9393
    if (ie && ie_version >= 9) { this.hasSelection = null; }
9394
    this.fastPoll();
9395
  };
9396
 
9397
  TextareaInput.prototype.onContextMenu = function (e) {
9398
    var input = this, cm = input.cm, display = cm.display, te = input.textarea;
9399
    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
9400
    if (!pos || presto) { return } // Opera is difficult.
9401
 
9402
    // Reset the current text selection only if the click is done outside of the selection
9403
    // and 'resetSelectionOnContextMenu' option is true.
9404
    var reset = cm.options.resetSelectionOnContextMenu;
9405
    if (reset && cm.doc.sel.contains(pos) == -1)
9406
      { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
9407
 
9408
    var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
9409
    input.wrapper.style.cssText = "position: absolute";
9410
    var wrapperBox = input.wrapper.getBoundingClientRect();
9411
    te.style.cssText = "position: absolute; width: 30px; height: 30px;\n      top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n      z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
9412
    var oldScrollY;
9413
    if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
9414
    display.input.focus();
9415
    if (webkit) { window.scrollTo(null, oldScrollY); }
9416
    display.input.reset();
9417
    // Adds "Select all" to context menu in FF
9418
    if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
9419
    input.contextMenuPending = true;
9420
    display.selForContextMenu = cm.doc.sel;
9421
    clearTimeout(display.detectingSelectAll);
9422
 
9423
    // Select-all will be greyed out if there's nothing to select, so
9424
    // this adds a zero-width space so that we can later check whether
9425
    // it got selected.
9426
    function prepareSelectAllHack() {
9427
      if (te.selectionStart != null) {
9428
        var selected = cm.somethingSelected();
9429
        var extval = "\u200b" + (selected ? te.value : "");
9430
        te.value = "\u21da"; // Used to catch context-menu undo
9431
        te.value = extval;
9432
        input.prevInput = selected ? "" : "\u200b";
9433
        te.selectionStart = 1; te.selectionEnd = extval.length;
9434
        // Re-set this, in case some other handler touched the
9435
        // selection in the meantime.
9436
        display.selForContextMenu = cm.doc.sel;
9437
      }
9438
    }
9439
    function rehide() {
9440
      input.contextMenuPending = false;
9441
      input.wrapper.style.cssText = oldWrapperCSS;
9442
      te.style.cssText = oldCSS;
9443
      if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
9444
 
9445
      // Try to detect the user choosing select-all
9446
      if (te.selectionStart != null) {
9447
        if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
9448
        var i = 0, poll = function () {
9449
          if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
9450
              te.selectionEnd > 0 && input.prevInput == "\u200b") {
9451
            operation(cm, selectAll)(cm);
9452
          } else if (i++ < 10) {
9453
            display.detectingSelectAll = setTimeout(poll, 500);
9454
          } else {
9455
            display.selForContextMenu = null;
9456
            display.input.reset();
9457
          }
9458
        };
9459
        display.detectingSelectAll = setTimeout(poll, 200);
9460
      }
9461
    }
9462
 
9463
    if (ie && ie_version >= 9) { prepareSelectAllHack(); }
9464
    if (captureRightClick) {
9465
      e_stop(e);
9466
      var mouseup = function () {
9467
        off(window, "mouseup", mouseup);
9468
        setTimeout(rehide, 20);
9469
      };
9470
      on(window, "mouseup", mouseup);
9471
    } else {
9472
      setTimeout(rehide, 50);
9473
    }
9474
  };
9475
 
9476
  TextareaInput.prototype.readOnlyChanged = function (val) {
9477
    if (!val) { this.reset(); }
9478
    this.textarea.disabled = val == "nocursor";
9479
  };
9480
 
9481
  TextareaInput.prototype.setUneditable = function () {};
9482
 
9483
  TextareaInput.prototype.needsContentAttribute = false;
9484
 
9485
  function fromTextArea(textarea, options) {
9486
    options = options ? copyObj(options) : {};
9487
    options.value = textarea.value;
9488
    if (!options.tabindex && textarea.tabIndex)
9489
      { options.tabindex = textarea.tabIndex; }
9490
    if (!options.placeholder && textarea.placeholder)
9491
      { options.placeholder = textarea.placeholder; }
9492
    // Set autofocus to true if this textarea is focused, or if it has
9493
    // autofocus and no other element is focused.
9494
    if (options.autofocus == null) {
9495
      var hasFocus = activeElt();
9496
      options.autofocus = hasFocus == textarea ||
9497
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
9498
    }
9499
 
9500
    function save() {textarea.value = cm.getValue();}
9501
 
9502
    var realSubmit;
9503
    if (textarea.form) {
9504
      on(textarea.form, "submit", save);
9505
      // Deplorable hack to make the submit method do the right thing.
9506
      if (!options.leaveSubmitMethodAlone) {
9507
        var form = textarea.form;
9508
        realSubmit = form.submit;
9509
        try {
9510
          var wrappedSubmit = form.submit = function () {
9511
            save();
9512
            form.submit = realSubmit;
9513
            form.submit();
9514
            form.submit = wrappedSubmit;
9515
          };
9516
        } catch(e) {}
9517
      }
9518
    }
9519
 
9520
    options.finishInit = function (cm) {
9521
      cm.save = save;
9522
      cm.getTextArea = function () { return textarea; };
9523
      cm.toTextArea = function () {
9524
        cm.toTextArea = isNaN; // Prevent this from being ran twice
9525
        save();
9526
        textarea.parentNode.removeChild(cm.getWrapperElement());
9527
        textarea.style.display = "";
9528
        if (textarea.form) {
9529
          off(textarea.form, "submit", save);
9530
          if (typeof textarea.form.submit == "function")
9531
            { textarea.form.submit = realSubmit; }
9532
        }
9533
      };
9534
    };
9535
 
9536
    textarea.style.display = "none";
9537
    var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
9538
      options);
9539
    return cm
9540
  }
9541
 
9542
  function addLegacyProps(CodeMirror) {
9543
    CodeMirror.off = off;
9544
    CodeMirror.on = on;
9545
    CodeMirror.wheelEventPixels = wheelEventPixels;
9546
    CodeMirror.Doc = Doc;
9547
    CodeMirror.splitLines = splitLinesAuto;
9548
    CodeMirror.countColumn = countColumn;
9549
    CodeMirror.findColumn = findColumn;
9550
    CodeMirror.isWordChar = isWordCharBasic;
9551
    CodeMirror.Pass = Pass;
9552
    CodeMirror.signal = signal;
9553
    CodeMirror.Line = Line;
9554
    CodeMirror.changeEnd = changeEnd;
9555
    CodeMirror.scrollbarModel = scrollbarModel;
9556
    CodeMirror.Pos = Pos;
9557
    CodeMirror.cmpPos = cmp;
9558
    CodeMirror.modes = modes;
9559
    CodeMirror.mimeModes = mimeModes;
9560
    CodeMirror.resolveMode = resolveMode;
9561
    CodeMirror.getMode = getMode;
9562
    CodeMirror.modeExtensions = modeExtensions;
9563
    CodeMirror.extendMode = extendMode;
9564
    CodeMirror.copyState = copyState;
9565
    CodeMirror.startState = startState;
9566
    CodeMirror.innerMode = innerMode;
9567
    CodeMirror.commands = commands;
9568
    CodeMirror.keyMap = keyMap;
9569
    CodeMirror.keyName = keyName;
9570
    CodeMirror.isModifierKey = isModifierKey;
9571
    CodeMirror.lookupKey = lookupKey;
9572
    CodeMirror.normalizeKeyMap = normalizeKeyMap;
9573
    CodeMirror.StringStream = StringStream;
9574
    CodeMirror.SharedTextMarker = SharedTextMarker;
9575
    CodeMirror.TextMarker = TextMarker;
9576
    CodeMirror.LineWidget = LineWidget;
9577
    CodeMirror.e_preventDefault = e_preventDefault;
9578
    CodeMirror.e_stopPropagation = e_stopPropagation;
9579
    CodeMirror.e_stop = e_stop;
9580
    CodeMirror.addClass = addClass;
9581
    CodeMirror.contains = contains;
9582
    CodeMirror.rmClass = rmClass;
9583
    CodeMirror.keyNames = keyNames;
9584
  }
9585
 
9586
  // EDITOR CONSTRUCTOR
9587
 
9588
  defineOptions(CodeMirror);
9589
 
9590
  addEditorMethods(CodeMirror);
9591
 
9592
  // Set up methods on CodeMirror's prototype to redirect to the editor's document.
9593
  var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
9594
  for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
9595
    { CodeMirror.prototype[prop] = (function(method) {
9596
      return function() {return method.apply(this.doc, arguments)}
9597
    })(Doc.prototype[prop]); } }
9598
 
9599
  eventMixin(Doc);
9600
  CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
9601
 
9602
  // Extra arguments are stored as the mode's dependencies, which is
9603
  // used by (legacy) mechanisms like loadmode.js to automatically
9604
  // load a mode. (Preferred mechanism is the require/define calls.)
9605
  CodeMirror.defineMode = function(name/*, mode, …*/) {
9606
    if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
9607
    defineMode.apply(this, arguments);
9608
  };
9609
 
9610
  CodeMirror.defineMIME = defineMIME;
9611
 
9612
  // Minimal default mode.
9613
  CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
9614
  CodeMirror.defineMIME("text/plain", "null");
9615
 
9616
  // EXTENSIONS
9617
 
9618
  CodeMirror.defineExtension = function (name, func) {
9619
    CodeMirror.prototype[name] = func;
9620
  };
9621
  CodeMirror.defineDocExtension = function (name, func) {
9622
    Doc.prototype[name] = func;
9623
  };
9624
 
9625
  CodeMirror.fromTextArea = fromTextArea;
9626
 
9627
  addLegacyProps(CodeMirror);
9628
 
9629
  CodeMirror.version = "5.41.0";
9630
 
9631
  return CodeMirror;
9632
 
9633
})));